text
stringlengths
54
60.6k
<commit_before>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read Secretfile // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; printf("before read secretfile \n"); init_time_at(time,"# read Secret file",t); Secret=read_Secretfile(F.Secretfile,F); printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str()); print_time(time,"# ... took :"); std::vector<int> count; count=count_galaxies(Secret); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n"); for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);} //read the three input files init_time_at(time,"# read target, SS, SF files",t); MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); print_time(time,"# ... took :"); //combine the three input files M=Targ; printf(" M size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d \n",M.size()); F.Ngal=M.size(); assign_priority_class(M); //establish priority classes init_time_at(time,"# establish priority clasess",t); std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } print_time(time,"# ... took :"); for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); //P is original list of plates Plates P = read_plate_centers(F); printf(" future plates %d\n",P.size()); F.Nplate=P.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs simple_assign(M,P,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list //and inverse map A.inv_order=initList(F.Nplate,0); for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){ A.suborder.push_back(j); not_done=false; } } } F.NUsedplate=A.suborder.size(); printf(" Plates after screening %d \n",F.NUsedplate); //if(F.diagnose)diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly for (int i=0; i<1; i++) { improve(M,P,pp,F,A,0); redistribute_tf(M,P,pp,F,A,0); } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); //try assigning SF and SS before real time assignment for (int j=0;j<F.NUsedplate;++j){ int js=A.suborder[j]; assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(js,M,P,pp,F,A); } //if(F.diagnose)diagnostic(M,Secret,F,A); init_time_at(time,"# Begin real time assignment",t); //Execute plan, updating targets at intervals for(int i=0;i<F.pass_intervals.size();i++)printf(" i=%d interval %d \n",i,F.pass_intervals[i]); std::vector <int> update_intervals=F.pass_intervals; printf("before push back\n"); update_intervals.push_back(F.NUsedplate);//to end intervals at last plate printf("made update_intervals\n"); for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate int starter=update_intervals[i]; printf(" before pass = %d at %d tiles\n",i,starter); //display_results("doc/figs/",G,P,pp,F,A,true); //plan whole survey from this point out for (int jj=starter; jj<F.NUsedplate; jj++) { int js = A.suborder[jj]; assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF assign_unused(js,M,P,pp,F,A); } //update target information for interval i //A.next_plate=F.pass_intervals[i]; for (int jj=starter; jj<update_intervals[i]; jj++) { // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=jj-F.Analysis) update_plan_from_one_obs(jj,Secret,M,P,pp,F,A,F.Nplate-1); else printf("\n"); //A.next_plate++; } redistribute_tf(M,P,pp,F,A,starter); redistribute_tf(M,P,pp,F,A,starter); improve(M,P,pp,F,A,starter); redistribute_tf(M,P,pp,F,A,starter); //} //if(F.diagnose)diagnostic(M,Secret,F,A); // check on SS and SF /* for(int j=0;j<F.NUsedplate;++j){ int js=A.suborder[j]; printf("\n js = %d\n",js); for (int p=0;p<F.Npetal;++p){ int count_SS=0; int count_SF=0; for (int k=0;k<F.Nfbp;++k){ int kk=pp.fibers_of_sp[p][k]; int g=A.TF[js][kk]; if(g!=-1 && M[g].SS)count_SS++; if(g!=-1 && M[g].SF)count_SF++; } printf(" %d %d ",count_SS,count_SF); } printf("\n"); } */ } // Results ------------------------------------------------------- if (F.PrintAscii) for (int j=0; j<F.NUsedplate; j++){ write_FAtile_ascii(A.suborder[j],F.outDir,M,P,pp,F,A); } if (F.PrintFits) for (int j=0; j<F.NUsedplate; j++){ fa_write(A.suborder[j],F.outDir,M,P,pp,F,A); // Write output } display_results("doc/figs/",Secret,M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <commit_msg>silly<commit_after>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read Secretfile // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; printf("before read secretfile \n"); init_time_at(time,"# read Secret file",t); Secret=read_Secretfile(F.Secretfile,F); printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str()); print_time(time,"# ... took :"); std::vector<int> count; count=count_galaxies(Secret); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n"); for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);} //read the three input files init_time_at(time,"# read target, SS, SF files",t); MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); print_time(time,"# ... took :"); //combine the three input files M=Targ; printf(" M size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d \n",M.size()); F.Ngal=M.size(); assign_priority_class(M); //establish priority classes init_time_at(time,"# establish priority clasess",t); std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } print_time(time,"# ... took :"); for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); //P is original list of plates Plates P = read_plate_centers(F); printf(" future plates %d\n",P.size()); F.Nplate=P.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs simple_assign(M,P,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list //and inverse map A.inv_order=initList(F.Nplate,0); for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){ A.suborder.push_back(j); not_done=false; } } } F.NUsedplate=A.suborder.size(); printf(" Plates after screening %d \n",F.NUsedplate); //if(F.diagnose)diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly for (int i=0; i<1; i++) { improve(M,P,pp,F,A,0); redistribute_tf(M,P,pp,F,A,0); } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); //try assigning SF and SS before real time assignment for (int j=0;j<F.NUsedplate;++j){ int js=A.suborder[j]; assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(js,M,P,pp,F,A); } if(F.diagnose)diagnostic(M,Secret,F,A); init_time_at(time,"# Begin real time assignment",t); //Execute plan, updating targets at intervals for(int i=0;i<F.pass_intervals.size();i++)printf(" i=%d interval %d \n",i,F.pass_intervals[i]); std::vector <int> update_intervals=F.pass_intervals; printf("before push back\n"); update_intervals.push_back(F.NUsedplate);//to end intervals at last plate printf("made update_intervals\n"); for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate int starter=update_intervals[i]; printf(" before pass = %d at %d tiles\n",i,starter); //display_results("doc/figs/",G,P,pp,F,A,true); //plan whole survey from this point out for (int jj=starter; jj<F.NUsedplate; jj++) { int js = A.suborder[jj]; assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF assign_unused(js,M,P,pp,F,A); } //update target information for interval i //A.next_plate=F.pass_intervals[i]; for (int jj=starter; jj<update_intervals[i]; jj++) { // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=jj-F.Analysis) update_plan_from_one_obs(jj,Secret,M,P,pp,F,A,F.Nplate-1); else printf("\n"); //A.next_plate++; } //redistribute_tf(M,P,pp,F,A,starter); redistribute_tf(M,P,pp,F,A,starter); improve(M,P,pp,F,A,starter); redistribute_tf(M,P,pp,F,A,starter); //} if(F.diagnose)diagnostic(M,Secret,F,A); // check on SS and SF /* for(int j=0;j<F.NUsedplate;++j){ int js=A.suborder[j]; printf("\n js = %d\n",js); for (int p=0;p<F.Npetal;++p){ int count_SS=0; int count_SF=0; for (int k=0;k<F.Nfbp;++k){ int kk=pp.fibers_of_sp[p][k]; int g=A.TF[js][kk]; if(g!=-1 && M[g].SS)count_SS++; if(g!=-1 && M[g].SF)count_SF++; } printf(" %d %d ",count_SS,count_SF); } printf("\n"); } */ } // Results ------------------------------------------------------- if (F.PrintAscii) for (int j=0; j<F.NUsedplate; j++){ write_FAtile_ascii(A.suborder[j],F.outDir,M,P,pp,F,A); } if (F.PrintFits) for (int j=0; j<F.NUsedplate; j++){ fa_write(A.suborder[j],F.outDir,M,P,pp,F,A); // Write output } display_results("doc/figs/",Secret,M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <|endoftext|>
<commit_before>// Copyright (c) 2017 nyorain // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt /// \file Various operations for real vectors. /// Over the whole files, template types names V or V* must fulfil the /// vector concept specified in doc/vec.md #pragma once #ifndef NYTL_INCLUDE_VEC_OPS #define NYTL_INCLUDE_VEC_OPS #include <nytl/tmpUtil.hpp> // nytl::templatize #include <nytl/scalar.hpp> // nytl::accumulate #include <functional> // std::plus, std::multiplies #include <stdexcept> // std::invalid_argument #include <cmath> // std::acos #include <iosfwd> // std::ostream namespace nytl::vec { namespace detail { /// \brief Helper that asserts that the given vectors have the same dimension. template<typename V1, typename V2> struct AssertSameDimensions { static constexpr void call(const V1& a, const V2& b) { if constexpr(V1::staticSized && V2::staticSized) { static_assert(V1::size() == V2::size(), "nytl::vec: vectors must have same dimension"); } else { if(a.size() != b.size()) throw std::invalid_argument("nytl::vec: vectors must have same dimension"); } } }; /// \brief Helper that asserts that a vector of type V1 has dimension Dim. template<unsigned int Dim, typename V> struct AssertDimension { static constexpr void call(const V& a) { if constexpr(V::staticSized) { static_assert(V::size() == Dim, "nytl::vec: vector must have specified dimension"); } else { if(a.size() != Dim) throw std::invalid_argument("nytl::vec: vector must have specified dimension"); } } }; /// \brief Asserts that the both given vectors have the same dimension. /// Will result in a compile time error if possible, otherwise throws /// std::invalid_argument. template<typename V1, typename V2> constexpr void assertSameDimensions(const V1& a, const V2& b) { AssertSameDimensions<V1, V2>::call(a, b); } /// \brief Asserts that the given vector has dimension Dim. /// Will result in a compile time error if possible, otherwise throws /// std::invalid_argument. template<unsigned int Dim, typename V> constexpr void assertDimension(const V& a) { AssertDimension<Dim, V>::call(a); } /// \brief Creates a new vector from implementation 'V' with value type 'T' /// and size 'S' template<typename V, typename T, std::size_t S> auto createVector() { if constexpr(V::staticSized) return V::template Rebind<T>::template create<S>(); else return V::template Rebind<T>::create(S); } /// \brief Creates a new vector from the same implementation and size as the given vector /// with value type T. template<typename T, typename V> auto createVector(const V& v) { if constexpr(V::staticSized) return V::template Rebind<T>::template create<V::size()>(); else return V::template Rebind<T>::create(v.size()); } } // namespace detail /// Vec operations without argument checking /// Useful for extra performance gains when things like /// vector dimension are known. namespace nocheck { /// \brief Like dot, but no sanity checks are performed. template<typename V1, typename V2> constexpr auto dot(const V1& a, const V2& b) { using RetType = decltype(a[0] * b[0] + a[0] * b[0]); auto ret = RetType {}; for(auto i = 0u; i < a.size(); ++i) ret += a[i] * b[i]; return ret; } /// \brief Like angle, but no sanity checks are performed. /// There might be unexpected results e.g. when both vectors are /// equal due to rounding errors. template<typename V1, typename V2> constexpr auto angle(const V1& a, const V2& b) { return std::acos(nocheck::dot(a, b) / (length(a) * length(b))); } /// \brief Like cross, but no sanity checks are performed. template<typename V1, typename V2> constexpr auto cross(const V1& a, const V2& b) { auto ret = detail::createVector<V1, decltype(a[0] * b[0] - a[0] * b[0]), 3>(); ret[0] = (a[1] * b[2]) - (a[2] * b[1]); ret[1] = (a[2] * b[0]) - (a[0] * b[2]); ret[2] = (a[0] * b[1]) - (a[1] * b[0]); return ret; } /// \brief Like normalize, but no sanity checks are performed. template<typename V> constexpr auto normalize(const V& a) { return (1.0 / length(a)) * a; } } // namespace nocheck /// \brief Sums up all values of the given vector using the + operator. template<typename V> constexpr auto sum(const V& a) { return accumulate(a.begin(), a.end(), 0.0, std::plus<>()); } /// \brief Multiplies all values of the given vector using the * operator. template<typename V> constexpr auto multiply(const V& a) { return accumulate(a.begin(), a.end(), 1.0, std::multiplies<>()); } /// \brief Calculates the default dot product for the given vectors. /// Note that this follows the dot definition for real numbers and does /// not automatically handle the dot definition for complex numbers. /// \throws std::invalid_argument if the size of the input vectors differs. template<typename V1, typename V2> constexpr auto dot(const V1& a, const V2& b) { detail::assertSameDimensions(a, b); return nocheck::dot(a, b); } /// \brief Returns the euclidean norm (or length) of the given vector. template<typename V> constexpr auto length(const V& a) { return std::sqrt(nocheck::dot(a, a)); } /// \brief Returns the euclidean distance between two vectors. /// Another way to describe this operation is the length between the /// difference of the given vectors. /// \requires The both given vectors shall have the same dimension. /// Will not check for this and simply subtract them from each other. template<typename V1, typename V2> constexpr auto distance(const V1& a, const V2& b) { return length(a - b); } /// \brief Calculates the angle in radians between two vectors using the dot product. /// Therefore it will always return the smaller between the both vectors on a /// plane in which both vectors lay. /// For two equal vectors, it will return always 0.0. /// Does only work for real numbers and does not handle complex vectors. /// \throws std::invalid_argument if the size of the input vectors differs. /// \throws std::domain_error if at least one of the given vectors has a length of 0. template<typename V1, typename V2> constexpr auto angle(const V1& a, const V2& b) { detail::assertSameDimensions(a, b); auto la = length(a); auto lb = length(b); if(la == 0.0 || lb == 0.0) throw std::domain_error("nytl::vec::angle: both vectors are null"); // We do this check here to output 0 for angle(a, a). // This might produce nan somtimes due to rounding errors. auto div = nocheck::dot(a, b) / (la * lb); if(div > 1.0) return 0.0; return std::acos(div); } /// \brief Calculates the cross product for two 3-dimensional vectors. /// \requires The given vectors shall be in the 3-dimensional space. /// \throws std::domain_error if at least on of the input vectors does not have a size of 3. template<typename V1, typename V2> constexpr auto cross(const V1& a, const V2& b) { detail::assertDimension<3>(a); detail::assertDimension<3>(b); return nocheck::cross(a, b); } /// \brief Returns a normalization of the given vector for the euclidean norm. /// \throws std::domain_error if the vector has the length 0. template<typename V> constexpr auto normalize(const V& a) { auto la = length(a); if(la == 0.0) throw std::domain_error("nytl::vec::normalize: vector has length 0"); return (1.0 / la) * a; } /// \brief Prints the given vector to the given ostream. /// If this function is used, header <ostream> must be included. /// This function does not implement operator<< since this operator should only implemented /// for the Vector implementation types. /// \requires There must be an implementation of operator<<(std::ostream&, V::Value). template<typename V> std::ostream& print(std::ostream& os, const V& vec) { auto& tos = templatize<V>(os); // we don't want to include ostream tos << "("; auto it = vec.begin(); tos << *it; while(++it != vec.end()) tos << ", " << *it; tos << ")"; return os; } namespace cw { // component-wise operations namespace ip { // inplace operations /// \brief Applies the given function to every value in the given vector. template<typename V, typename F> constexpr void apply(V& vec, F&& func) { for(auto i = 0u; i < vec.size(); ++i) func(vec[i]); } // Various utility functions. // Always modify the given vector in place and simply apply the similar // named stl or nytl function on all components. template<typename V> constexpr void abs(V& vec) { apply(vec, [](auto& x){ x = std::abs(x); }); } template<typename V> constexpr void degrees(V& vec) { apply(vec, [](auto& x){ x = nytl::degrees(x); }); } template<typename V> constexpr void radians(V& vec) { apply(vec, [](auto& x){ x = nytl::radians(x); }); } template<typename V> constexpr void sin(V& vec) { apply(vec, [](auto& x){ x = std::sin(x); }); } template<typename V> constexpr void cos(V& vec) { apply(vec, [](auto& x){ x = std::cos(x); }); } template<typename V> constexpr void tan(V& vec) { apply(vec, [](auto& x){ x = std::cos(x); }); } template<typename V> constexpr void asin(V& vec) { apply(vec, [](auto& x){ x = std::asin(x); }); } template<typename V> constexpr void acos(V& vec) { apply(vec, [](auto& x){ x = std::acos(x); }); } template<typename V> constexpr void atan(V& vec) { apply(vec, [](auto& x){ x = std::atan(x); }); } template<typename V> constexpr void exp(V& vec) { apply(vec, [](auto& x){ x = std::exp(x); }); } template<typename V> constexpr void log(V& vec) { apply(vec, [](auto& x){ x = std::log(x); }); } template<typename V> constexpr void sqrt(V& vec) { apply(vec, [](auto& x){ x = std::sqrt(x); }); } template<typename V> constexpr void exp2(V& vec) { apply(vec, [](auto& x){ x = std::exp2(x); }); } template<typename V> constexpr void floor(V& vec) { apply(vec, [](auto& x){ x = std::floor(x); }); } template<typename V> constexpr void ceil(V& vec) { apply(vec, [](auto& x){ x = std::ceil(x); }); } template<typename V, typename T> constexpr void pow(V& vec, const T& e) { apply(vec, [&e](auto& x){ x = std::pow(x, e); }); } } // namespace ip /// \brief Returns a vector holding the component-wise maximum of the given Vectors. /// \requires Type 'V' shall be a Vector type. /// \requires The both given vectors shall have the same dimension. template<typename V> constexpr auto max(V a, const V& b) { detail::assertSameDimensions(a, b); for(auto i = 0u; i < a.size(); ++i) if(b[i] > a[i]) a[i] = b[i]; return a; } /// \brief Returns a vector holding the component-wise maximum of the given Vectors. /// \requires Type 'V' shall be a Vector type. /// \requires The both given vectors shall have the same dimension. template<typename V> constexpr auto min(V a, const V& b) { detail::assertSameDimensions(a, b); for(auto i = 0u; i < a.size(); ++i) if(b[i] < a[i]) a[i] = b[i]; return a; } /// \brief Multiplies the two vectors component wise /// \requires Types 'V1', 'V2' shall be Vector types over the same space. template<typename V1, typename V2> constexpr auto multiply(const V1& a, const V2& b) { detail::assertSameDimensions(a, b); auto ret = detail::createVector<decltype(a[0] * b[0])>(a); for(auto i = 0u; i < a.size(); ++i) ret[i] = a[i] * b[i]; return ret; } /// \brief Component-wise divides the first vector by the second one. /// Will not perform any zero checks. /// \requires Types 'V1', 'V2' shall be Vector types over the same space. template<typename V1, typename V2> constexpr auto divide(const V1& a, const V2& b) { detail::assertSameDimensions(a, b); auto ret = detail::createVector<decltype(a[0] / b[0])>(a); for(auto i = 0u; i < a.size(); ++i) ret[i] = a[i] / b[i]; return ret; } } // namespace cw } // namespace nytl::vec #endif // header guard <commit_msg>Fix type conversions in vecOps<commit_after>// Copyright (c) 2017 nyorain // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt /// \file Various operations for real vectors. /// Over the whole files, template types names V or V* must fulfil the /// vector concept specified in doc/vec.md #pragma once #ifndef NYTL_INCLUDE_VEC_OPS #define NYTL_INCLUDE_VEC_OPS #include <nytl/tmpUtil.hpp> // nytl::templatize #include <nytl/scalar.hpp> // nytl::accumulate #include <functional> // std::plus, std::multiplies #include <stdexcept> // std::invalid_argument #include <cmath> // std::acos #include <iosfwd> // std::ostream namespace nytl::vec { namespace detail { /// \brief Helper that asserts that the given vectors have the same dimension. template<typename V1, typename V2> struct AssertSameDimensions { static constexpr void call(const V1& a, const V2& b) { if constexpr(V1::staticSized && V2::staticSized) { static_assert(V1::size() == V2::size(), "nytl::vec: vectors must have same dimension"); } else { if(a.size() != b.size()) throw std::invalid_argument("nytl::vec: vectors must have same dimension"); } } }; /// \brief Helper that asserts that a vector of type V1 has dimension Dim. template<unsigned int Dim, typename V> struct AssertDimension { static constexpr void call(const V& a) { if constexpr(V::staticSized) { static_assert(V::size() == Dim, "nytl::vec: vector must have specified dimension"); } else { if(a.size() != Dim) throw std::invalid_argument("nytl::vec: vector must have specified dimension"); } } }; /// \brief Asserts that the both given vectors have the same dimension. /// Will result in a compile time error if possible, otherwise throws /// std::invalid_argument. template<typename V1, typename V2> constexpr void assertSameDimensions(const V1& a, const V2& b) { AssertSameDimensions<V1, V2>::call(a, b); } /// \brief Asserts that the given vector has dimension Dim. /// Will result in a compile time error if possible, otherwise throws /// std::invalid_argument. template<unsigned int Dim, typename V> constexpr void assertDimension(const V& a) { AssertDimension<Dim, V>::call(a); } /// \brief Creates a new vector from implementation 'V' with value type 'T' /// and size 'S' template<typename V, typename T, std::size_t S> auto createVector() { if constexpr(V::staticSized) return V::template Rebind<T>::template create<S>(); else return V::template Rebind<T>::create(S); } /// \brief Creates a new vector from the same implementation and size as the given vector /// with value type T. template<typename T, typename V> auto createVector(const V& v) { if constexpr(V::staticSized) return V::template Rebind<T>::template create<V::size()>(); else return V::template Rebind<T>::create(v.size()); } } // namespace detail /// Vec operations without argument checking /// Useful for extra performance gains when things like /// vector dimension are known. namespace nocheck { /// \brief Like dot, but no sanity checks are performed. template<typename V1, typename V2> constexpr auto dot(const V1& a, const V2& b) { using RetType = decltype(a[0] * b[0] + a[0] * b[0]); auto ret = RetType {}; for(auto i = 0u; i < a.size(); ++i) ret += a[i] * b[i]; return ret; } /// \brief Like angle, but no sanity checks are performed. /// There might be unexpected results e.g. when both vectors are /// equal due to rounding errors. template<typename V1, typename V2> constexpr auto angle(const V1& a, const V2& b) { return std::acos(nocheck::dot(a, b) / (length(a) * length(b))); } /// \brief Like cross, but no sanity checks are performed. template<typename V1, typename V2> constexpr auto cross(const V1& a, const V2& b) { auto ret = detail::createVector<V1, decltype(a[0] * b[0] - a[0] * b[0]), 3>(); ret[0] = (a[1] * b[2]) - (a[2] * b[1]); ret[1] = (a[2] * b[0]) - (a[0] * b[2]); ret[2] = (a[0] * b[1]) - (a[1] * b[0]); return ret; } /// \brief Like normalize, but no sanity checks are performed. template<typename V> constexpr auto normalize(const V& a) { return (typename V::Value {1} / length(a)) * a; } } // namespace nocheck /// \brief Sums up all values of the given vector using the + operator. template<typename V> constexpr auto sum(const V& a) { return accumulate(a.begin(), a.end(), typename V::Value{0}, std::plus<>()); } /// \brief Multiplies all values of the given vector using the * operator. template<typename V> constexpr auto multiply(const V& a) { return accumulate(a.begin(), a.end(), typename V::Value {1}, std::multiplies<>()); } /// \brief Calculates the default dot product for the given vectors. /// Note that this follows the dot definition for real numbers and does /// not automatically handle the dot definition for complex numbers. /// \throws std::invalid_argument if the size of the input vectors differs. template<typename V1, typename V2> constexpr auto dot(const V1& a, const V2& b) { detail::assertSameDimensions(a, b); return nocheck::dot(a, b); } /// \brief Returns the euclidean norm (or length) of the given vector. template<typename V> constexpr auto length(const V& a) { return std::sqrt(nocheck::dot(a, a)); } /// \brief Returns the euclidean distance between two vectors. /// Another way to describe this operation is the length between the /// difference of the given vectors. /// \requires The both given vectors shall have the same dimension. /// Will not check for this and simply subtract them from each other. template<typename V1, typename V2> constexpr auto distance(const V1& a, const V2& b) { return length(a - b); } /// \brief Calculates the angle in radians between two vectors using the dot product. /// Therefore it will always return the smaller between the both vectors on a /// plane in which both vectors lay. /// For two equal vectors, it will return always 0.0. /// Does only work for real numbers and does not handle complex vectors. /// \throws std::invalid_argument if the size of the input vectors differs. /// \throws std::domain_error if at least one of the given vectors has a length of 0. template<typename V1, typename V2> constexpr auto angle(const V1& a, const V2& b) { detail::assertSameDimensions(a, b); auto la = length(a); auto lb = length(b); if(la == 0.0 || lb == 0.0) throw std::domain_error("nytl::vec::angle: both vectors are null"); // We do this check here to output 0 for angle(a, a). // This might produce nan somtimes due to rounding errors. auto div = nocheck::dot(a, b) / (la * lb); if(div > 1.0) return 0.0; return std::acos(div); } /// \brief Calculates the cross product for two 3-dimensional vectors. /// \requires The given vectors shall be in the 3-dimensional space. /// \throws std::domain_error if at least on of the input vectors does not have a size of 3. template<typename V1, typename V2> constexpr auto cross(const V1& a, const V2& b) { detail::assertDimension<3>(a); detail::assertDimension<3>(b); return nocheck::cross(a, b); } /// \brief Returns a normalization of the given vector for the euclidean norm. /// \throws std::domain_error if the vector has the length 0. template<typename V> constexpr auto normalize(const V& a) { auto la = length(a); if(la == typename V::Value{0}) throw std::domain_error("nytl::vec::normalize: vector has length 0"); return (typename V::Value {1} / la) * a; } /// \brief Prints the given vector to the given ostream. /// If this function is used, header <ostream> must be included. /// This function does not implement operator<< since this operator should only implemented /// for the Vector implementation types. /// \requires There must be an implementation of operator<<(std::ostream&, V::Value). template<typename V> std::ostream& print(std::ostream& os, const V& vec) { auto& tos = templatize<V>(os); // we don't want to include ostream tos << "("; auto it = vec.begin(); tos << *it; while(++it != vec.end()) tos << ", " << *it; tos << ")"; return os; } namespace cw { // component-wise operations namespace ip { // inplace operations /// \brief Applies the given function to every value in the given vector. template<typename V, typename F> constexpr void apply(V& vec, F&& func) { for(auto i = 0u; i < vec.size(); ++i) func(vec[i]); } // Various utility functions. // Always modify the given vector in place and simply apply the similar // named stl or nytl function on all components. template<typename V> constexpr void abs(V& vec) { apply(vec, [](auto& x){ x = std::abs(x); }); } template<typename V> constexpr void degrees(V& vec) { apply(vec, [](auto& x){ x = nytl::degrees(x); }); } template<typename V> constexpr void radians(V& vec) { apply(vec, [](auto& x){ x = nytl::radians(x); }); } template<typename V> constexpr void sin(V& vec) { apply(vec, [](auto& x){ x = std::sin(x); }); } template<typename V> constexpr void cos(V& vec) { apply(vec, [](auto& x){ x = std::cos(x); }); } template<typename V> constexpr void tan(V& vec) { apply(vec, [](auto& x){ x = std::cos(x); }); } template<typename V> constexpr void asin(V& vec) { apply(vec, [](auto& x){ x = std::asin(x); }); } template<typename V> constexpr void acos(V& vec) { apply(vec, [](auto& x){ x = std::acos(x); }); } template<typename V> constexpr void atan(V& vec) { apply(vec, [](auto& x){ x = std::atan(x); }); } template<typename V> constexpr void exp(V& vec) { apply(vec, [](auto& x){ x = std::exp(x); }); } template<typename V> constexpr void log(V& vec) { apply(vec, [](auto& x){ x = std::log(x); }); } template<typename V> constexpr void sqrt(V& vec) { apply(vec, [](auto& x){ x = std::sqrt(x); }); } template<typename V> constexpr void exp2(V& vec) { apply(vec, [](auto& x){ x = std::exp2(x); }); } template<typename V> constexpr void floor(V& vec) { apply(vec, [](auto& x){ x = std::floor(x); }); } template<typename V> constexpr void ceil(V& vec) { apply(vec, [](auto& x){ x = std::ceil(x); }); } template<typename V, typename T> constexpr void pow(V& vec, const T& e) { apply(vec, [&e](auto& x){ x = std::pow(x, e); }); } } // namespace ip /// \brief Returns a vector holding the component-wise maximum of the given Vectors. /// \requires Type 'V' shall be a Vector type. /// \requires The both given vectors shall have the same dimension. template<typename V> constexpr auto max(V a, const V& b) { detail::assertSameDimensions(a, b); for(auto i = 0u; i < a.size(); ++i) if(b[i] > a[i]) a[i] = b[i]; return a; } /// \brief Returns a vector holding the component-wise maximum of the given Vectors. /// \requires Type 'V' shall be a Vector type. /// \requires The both given vectors shall have the same dimension. template<typename V> constexpr auto min(V a, const V& b) { detail::assertSameDimensions(a, b); for(auto i = 0u; i < a.size(); ++i) if(b[i] < a[i]) a[i] = b[i]; return a; } /// \brief Multiplies the two vectors component wise /// \requires Types 'V1', 'V2' shall be Vector types over the same space. template<typename V1, typename V2> constexpr auto multiply(const V1& a, const V2& b) { detail::assertSameDimensions(a, b); auto ret = detail::createVector<decltype(a[0] * b[0])>(a); for(auto i = 0u; i < a.size(); ++i) ret[i] = a[i] * b[i]; return ret; } /// \brief Component-wise divides the first vector by the second one. /// Will not perform any zero checks. /// \requires Types 'V1', 'V2' shall be Vector types over the same space. template<typename V1, typename V2> constexpr auto divide(const V1& a, const V2& b) { detail::assertSameDimensions(a, b); auto ret = detail::createVector<decltype(a[0] / b[0])>(a); for(auto i = 0u; i < a.size(); ++i) ret[i] = a[i] / b[i]; return ret; } } // namespace cw } // namespace nytl::vec #endif // header guard <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2017) #include <set> #include <dune/geometry/type.hh> #include <dune/grid/common/mcmgmapper.hh> #include <dune/xt/common/numeric_cast.hh> #include <dune/xt/grid/type_traits.hh> #include <dune/xt/functions/interfaces/local-functions.hh> #include <dune/gdt/exceptions.hh> #include <dune/gdt/local/finite-elements/interfaces.hh> #include <dune/gdt/spaces/mapper/interfaces.hh> #ifndef DUNE_GDT_SPACES_MAPPER_CONTINUOUS_HH #define DUNE_GDT_SPACES_MAPPER_CONTINUOUS_HH namespace Dune { namespace GDT { // forward, required for the traits template <class GL, class R = double, size_t r = 1, size_t rC = 1, class F = R> class FixedOrderMultipleCodimMultipleGeomTypeMapper; namespace internal { template <class GL, class R, size_t r, size_t rC, class F> class FixedOrderMultipleCodimMultipleGeomTypeMapperTraits { static_assert(XT::Grid::is_layer<GL>::value, ""); template <int dim_> struct GeometryTypeLayout { GeometryTypeLayout(std::set<GeometryType>&& types) : types_(std::move(types)) { } GeometryTypeLayout(const GeometryTypeLayout<dim_>&) = default; GeometryTypeLayout(GeometryTypeLayout<dim_>&&) = default; bool contains(const GeometryType& gt) const { return types_.count(gt) > 0; } const std::set<GeometryType> types_; }; public: using derived_type = FixedOrderMultipleCodimMultipleGeomTypeMapper<GL, R, r, rC, F>; using BackendType = MultipleCodimMultipleGeomTypeMapper<GL, GeometryTypeLayout>; using EntityType = XT::Grid::extract_entity_t<GL>; private: friend class FixedOrderMultipleCodimMultipleGeomTypeMapper<GL, R, r, rC, F>; }; // class FixedOrderMultipleCodimMultipleGeomTypeMapperTraits } // namespace internal template <class GL, class R, size_t r, size_t rC, class F> class FixedOrderMultipleCodimMultipleGeomTypeMapper : public MapperInterface<internal::FixedOrderMultipleCodimMultipleGeomTypeMapperTraits<GL, R, r, rC, F>> { public: using Traits = internal::FixedOrderMultipleCodimMultipleGeomTypeMapperTraits<GL, R, r, rC, F>; private: using ThisType = FixedOrderMultipleCodimMultipleGeomTypeMapper<GL, R, r, rC, F>; using BaseType = MapperInterface<Traits>; using D = typename GL::ctype; static const constexpr size_t d = GL::dimension; public: using typename BaseType::EntityType; using typename BaseType::BackendType; using FiniteElementType = LocalFiniteElementInterface<D, d, R, r, rC, F>; FixedOrderMultipleCodimMultipleGeomTypeMapper( const GL& grid_layer, const std::shared_ptr<std::map<GeometryType, std::shared_ptr<FiniteElementType>>>& finite_elements) : finite_elements_(finite_elements) , mapper_(nullptr) { if (d == 3 && finite_elements_->size() != 1) DUNE_THROW(mapper_error, "The mapper does not seem to work with multiple finite elements in 3d!"); std::set<GeometryType> all_DoF_attached_geometry_types; // collect all entities (for all codims) which are used to attach DoFs to for (auto&& geometry_type : grid_layer.indexSet().types(0)) { // get the finite element for this geometry type const auto finite_element_search_result = finite_elements_->find(geometry_type); if (finite_element_search_result == finite_elements_->end()) DUNE_THROW(mapper_error, "Missing finite element for the required geometry type " << geometry_type << "!"); const auto& finite_element = *finite_element_search_result->second; // loop over all keys of this finite element const auto& reference_element = ReferenceElements<D, d>::general(geometry_type); const auto& coeffs = finite_element.coefficients(); for (size_t ii = 0; ii < coeffs.size(); ++ii) { const auto& local_key = coeffs.local_key(ii); if (local_key.index() != 0) // Would require twisting of DoFs and possibly more knowledge from the FE DUNE_THROW(mapper_error, "This case is not covered yet, when we have more than one DoF per (sub)entity!"); // find the (sub)entity for this key const auto sub_entity = local_key.subEntity(); const auto codim = local_key.codim(); const auto& subentity_geometry_type = reference_element.type(sub_entity, codim); // and add the respective geometry type all_DoF_attached_geometry_types.insert(subentity_geometry_type); } } if (all_DoF_attached_geometry_types.size() == 0) DUNE_THROW(mapper_error, "This must not happen, the finite elements report no DoFs attached to (sub)entities!"); mapper_ = std::make_shared<BackendType>( grid_layer, std::move(typename Traits::template GeometryTypeLayout<d>(std::move(all_DoF_attached_geometry_types)))); } // ... FixedOrderMultipleCodimMultipleGeomTypeMapper(...) FixedOrderMultipleCodimMultipleGeomTypeMapper(const ThisType&) = default; FixedOrderMultipleCodimMultipleGeomTypeMapper(ThisType&&) = default; FixedOrderMultipleCodimMultipleGeomTypeMapper& operator=(const ThisType&) = delete; FixedOrderMultipleCodimMultipleGeomTypeMapper& operator=(ThisType&&) = delete; const BackendType& backend() const { return *mapper_; } size_t size() const { return mapper_->size(); } size_t maxNumDofs() const { size_t ret = 0; for (const auto& geometry_type_and_finite_element_pair : *finite_elements_) { const auto& finite_element = *geometry_type_and_finite_element_pair.second; ret = std::max(ret, XT::Common::numeric_cast<size_t>(finite_element.size())); } return ret; } // ... maxNumDofs(...) size_t numDofs(const EntityType& entity) const { const auto finite_element_search_result = finite_elements_->find(entity.geometry().type()); if (finite_element_search_result == finite_elements_->end()) DUNE_THROW(XT::Common::Exceptions::internal_error, "This must not happen after the checks in the ctor, the grid layer did not report all geometry types!" "\n entity.geometry().type() = " << entity.geometry().type()); const auto& finite_element = *finite_element_search_result->second; return finite_element.size(); } // ... numDofs(...) template <int cd, class GridImp, template <int, int, class> class EntityImp> typename std::enable_if<cd != EntityType::codimension, size_t>::type numDofs(const Entity<cd, EntityType::dimension, GridImp, EntityImp>& entity) const { return 0; } using BaseType::globalIndices; void globalIndices(const EntityType& entity, DynamicVector<size_t>& ret) const { const auto finite_element_search_result = finite_elements_->find(entity.geometry().type()); if (finite_element_search_result == finite_elements_->end()) DUNE_THROW(XT::Common::Exceptions::internal_error, "This must not happen after the checks in the ctor, the grid layer did not report all geometry types!" "\n entity.geometry().type() = " << entity.geometry().type()); const auto& finite_element = *finite_element_search_result->second; const auto& local_coefficients = finite_element.coefficients(); const auto local_size = local_coefficients.size(); if (ret.size() < local_size) ret.resize(local_size, 0); for (size_t ii = 0; ii < local_size; ++ii) { const auto& local_key = local_coefficients.local_key(ii); // No need to assert local_key.index() == 0, has been checked in the ctor! ret[ii] = mapper_->subIndex(entity, local_key.subEntity(), local_key.codim()); } } // ... globalIndices(...) size_t mapToGlobal(const EntityType& entity, const size_t local_index) const { const auto finite_element_search_result = finite_elements_->find(entity.geometry().type()); if (finite_element_search_result == finite_elements_->end()) DUNE_THROW(XT::Common::Exceptions::internal_error, "This must not happen after the checks in the ctor, the grid layer did not report all geometry types!" "\n entity.geometry().type() = " << entity.geometry().type()); const auto& finite_element = *finite_element_search_result->second; const auto& local_coefficients = finite_element.coefficients(); if (local_index >= local_coefficients.size()) DUNE_THROW(Exception, "finite_element.coefficients().size() = " << local_coefficients.size() << "\n local_index = " << local_index); const auto& local_key = local_coefficients.local_key(local_index); // No need to assert local_key.index() == 0, has been checked in the ctor! return mapper_->subIndex(entity, local_key.subEntity(), local_key.codim()); } // ... mapToGlobal(...) private: const std::shared_ptr<std::map<GeometryType, std::shared_ptr<FiniteElementType>>> finite_elements_; std::shared_ptr<BackendType> mapper_; }; // class FixedOrderMultipleCodimMultipleGeomTypeMapper } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_MAPPER_CONTINUOUS_HH <commit_msg>[mapper.continuous] implement new interface<commit_after>// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2017 - 2018) #ifndef DUNE_GDT_SPACES_MAPPER_CONTINUOUS_HH #define DUNE_GDT_SPACES_MAPPER_CONTINUOUS_HH #include <set> #include <dune/geometry/type.hh> #include <dune/grid/common/mcmgmapper.hh> #include <dune/xt/grid/type_traits.hh> #include <dune/gdt/exceptions.hh> #include <dune/gdt/type_traits.hh> #include <dune/gdt/local/finite-elements/interfaces.hh> #include "interfaces.hh" namespace Dune { namespace GDT { template <class GV, class FiniteElement> class ContinuousMapper : public MapperInterface<GV> { static_assert(is_local_finite_element<FiniteElement>::value, ""); using ThisType = ContinuousMapper<GV, FiniteElement>; using BaseType = MapperInterface<GV>; template <int d> struct GeometryTypeLayout { GeometryTypeLayout(std::set<GeometryType>&& types) : types_(std::move(types)) { } GeometryTypeLayout(const GeometryTypeLayout<d>&) = default; GeometryTypeLayout(GeometryTypeLayout<d>&&) = default; bool contains(const GeometryType& gt) const { return types_.count(gt) > 0; } const std::set<GeometryType> types_; }; using Implementation = MultipleCodimMultipleGeomTypeMapper<GV, GeometryTypeLayout>; using D = typename GV::ctype; static const constexpr size_t d = GV::dimension; public: using typename BaseType::GridViewType; using typename BaseType::ElementType; ContinuousMapper(const GridViewType& grd_vw, const std::shared_ptr<std::map<GeometryType, std::shared_ptr<FiniteElement>>>& finite_elements) : grid_view_(grd_vw) , finite_elements_(finite_elements) , max_local_size_(0) , mapper_(nullptr) { if (d == 3 && finite_elements_->size() != 1) // Probably due to non-conforming intersections. DUNE_THROW(mapper_error, "The mapper does not seem to work with multiple finite elements in 3d!"); std::set<GeometryType> all_DoF_attached_geometry_types; // collect all entities (for all codims) which are used to attach DoFs to for (auto&& geometry_type : grid_view_.indexSet().types(0)) { // get the finite element for this geometry type const auto finite_element_search_result = finite_elements_->find(geometry_type); if (finite_element_search_result == finite_elements_->end()) DUNE_THROW(mapper_error, "Missing finite element for the required geometry type " << geometry_type << "!"); const auto& finite_element = *finite_element_search_result->second; max_local_size_ = std::max(max_local_size_, finite_element.size()); // loop over all keys of this finite element const auto& reference_element = ReferenceElements<D, d>::general(geometry_type); const auto& coeffs = finite_element.coefficients(); for (size_t ii = 0; ii < coeffs.size(); ++ii) { const auto& local_key = coeffs.local_key(ii); if (local_key.index() != 0) // Would require twisting of DoFs and possibly more knowledge from the FE DUNE_THROW(mapper_error, "This case is not covered yet, when we have more than one DoF per (sub)entity!"); // find the (sub)entity for this key const auto sub_entity = local_key.subEntity(); const auto codim = local_key.codim(); const auto& subentity_geometry_type = reference_element.type(sub_entity, codim); // and add the respective geometry type all_DoF_attached_geometry_types.insert(subentity_geometry_type); } } if (all_DoF_attached_geometry_types.size() == 0) DUNE_THROW(mapper_error, "This must not happen, the finite elements report no DoFs attached to (sub)entities!"); mapper_ = std::make_shared<Implementation>( grid_view_, std::move(GeometryTypeLayout<d>(std::move(all_DoF_attached_geometry_types)))); } // ... ContinuousMapper(...) ContinuousMapper(const ThisType&) = default; ContinuousMapper(ThisType&&) = default; ContinuousMapper& operator=(const ThisType&) = delete; ContinuousMapper& operator=(ThisType&&) = delete; const GridViewType& grid_view() const override final { return grid_view_; } const LocalFiniteElementCoefficientsInterface& local_coefficients(const GeometryType& geometry_type) const override final { const auto finite_element_search_result = finite_elements_->find(geometry_type); if (finite_element_search_result == finite_elements_->end()) DUNE_THROW(XT::Common::Exceptions::internal_error, "This must not happen, the grid view did not report all geometry types!" << "\n geometry_type = " << geometry_type); return finite_element_search_result->second->coefficients(); } size_t size() const override final { return mapper_->size(); } size_t max_local_size() const override final { return max_local_size_; } size_t local_size(const ElementType& element) const override final { return local_coefficients(element.geometry().type()).size(); } size_t global_index(const ElementType& element, const size_t local_index) const override final { const auto& coeffs = local_coefficients(element.geometry().type()); if (local_index >= coeffs.size()) DUNE_THROW(mapper_error, "local_size(element) = " << coeffs.size() << "\n local_index = " << local_index); const auto& local_key = coeffs.local_key(local_index); // No need to assert local_key.index() == 0, has been checked in the ctor! return mapper_->subIndex(element, local_key.subEntity(), local_key.codim()); } // ... mapToGlobal(...) using BaseType::global_indices; void global_indices(const ElementType& element, DynamicVector<size_t>& indices) const override final { const auto& coeffs = local_coefficients(element.geometry().type()); const auto local_sz = coeffs.size(); if (indices.size() < local_sz) indices.resize(local_sz, 0); for (size_t ii = 0; ii < local_sz; ++ii) { const auto& local_key = coeffs.local_key(ii); // No need to assert local_key.index() == 0, has been checked in the ctor! indices[ii] = mapper_->subIndex(element, local_key.subEntity(), local_key.codim()); } } // ... globalIndices(...) private: const GridViewType& grid_view_; const std::shared_ptr<std::map<GeometryType, std::shared_ptr<FiniteElement>>> finite_elements_; size_t max_local_size_; std::shared_ptr<Implementation> mapper_; }; // class ContinuousMapper } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_MAPPER_CONTINUOUS_HH <|endoftext|>
<commit_before>#ifndef DUNE_STUFF_LA_CONTAINER_INTERFACE_HH #define DUNE_STUFF_LA_CONTAINER_INTERFACE_HH #include <dune/common/bartonnackmanifcheck.hh> namespace Dune { namespace Stuff { namespace LA { namespace Container { template< class Traits > class Interface { public: typedef typename Traits::BackendType BackendType; virtual BackendType& backend() = 0; virtual const BackendType& backend() const = 0; }; // class Interface template< class Traits > class MatrixInterface : public Interface< Traits > { public: typedef MatrixInterface< Traits > ThisType; typedef typename Traits::derived_type derived_type; typedef typename Traits::BackendType BackendType; typedef typename Traits::ElementType ElementType; typedef typename Traits::size_type size_type; size_type rows() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().rows()); return asImp().rows(); } size_type cols() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().cols()); return asImp().cols(); } void add(const size_type i, const size_type j, const ElementType& val) { CHECK_INTERFACE_IMPLEMENTATION(asImp().add(i, j, val)); asImp().add(i, j, val); } void set(const size_type i, const size_type j, const ElementType& val) { CHECK_INTERFACE_IMPLEMENTATION(asImp().set(i, j, val)); asImp().set(i, j, val); } const ElementType get(const size_type i, const size_type j) const { CHECK_INTERFACE_IMPLEMENTATION(asImp().get(i, j)); return asImp().get(i, j); } derived_type& asImp() { return static_cast< derived_type& >(*this); } const derived_type& asImp() const { return static_cast< const derived_type& >(*this); } }; // class MatrixInterface template< class Traits > class VectorInterface : public Interface< Traits > { public: typedef VectorInterface< Traits > ThisType; typedef typename Traits::derived_type derived_type; typedef typename Traits::BackendType BackendType; typedef typename Traits::ElementType ElementType; typedef typename Traits::size_type size_type; size_type size() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().rows()); return asImp().size(); } void add(const size_type i, const ElementType& val) { CHECK_INTERFACE_IMPLEMENTATION(asImp().add(i, val)); asImp().add(i, val); } void set(const size_type i, const ElementType& val) { CHECK_INTERFACE_IMPLEMENTATION(asImp().set(i, val)); asImp().set(i, val); } const ElementType get(const size_type i) const { CHECK_INTERFACE_IMPLEMENTATION(asImp().get(i)); return asImp().get(i); } derived_type& asImp() { return static_cast< derived_type& >(*this); } const derived_type& asImp() const { return static_cast< const derived_type& >(*this); } }; // class VectorInterface } // namespace Container } // namespace LA } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_LA_CONTAINER_INTERFACE_HH <commit_msg>[la.container] yet another virtual base class with no virtual dtor<commit_after>#ifndef DUNE_STUFF_LA_CONTAINER_INTERFACE_HH #define DUNE_STUFF_LA_CONTAINER_INTERFACE_HH #include <dune/common/bartonnackmanifcheck.hh> namespace Dune { namespace Stuff { namespace LA { namespace Container { template< class Traits > class Interface { public: typedef typename Traits::BackendType BackendType; virtual BackendType& backend() = 0; virtual ~Interface() {} virtual const BackendType& backend() const = 0; }; // class Interface template< class Traits > class MatrixInterface : public Interface< Traits > { public: typedef MatrixInterface< Traits > ThisType; typedef typename Traits::derived_type derived_type; typedef typename Traits::BackendType BackendType; typedef typename Traits::ElementType ElementType; typedef typename Traits::size_type size_type; size_type rows() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().rows()); return asImp().rows(); } size_type cols() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().cols()); return asImp().cols(); } void add(const size_type i, const size_type j, const ElementType& val) { CHECK_INTERFACE_IMPLEMENTATION(asImp().add(i, j, val)); asImp().add(i, j, val); } void set(const size_type i, const size_type j, const ElementType& val) { CHECK_INTERFACE_IMPLEMENTATION(asImp().set(i, j, val)); asImp().set(i, j, val); } const ElementType get(const size_type i, const size_type j) const { CHECK_INTERFACE_IMPLEMENTATION(asImp().get(i, j)); return asImp().get(i, j); } derived_type& asImp() { return static_cast< derived_type& >(*this); } const derived_type& asImp() const { return static_cast< const derived_type& >(*this); } }; // class MatrixInterface template< class Traits > class VectorInterface : public Interface< Traits > { public: typedef VectorInterface< Traits > ThisType; typedef typename Traits::derived_type derived_type; typedef typename Traits::BackendType BackendType; typedef typename Traits::ElementType ElementType; typedef typename Traits::size_type size_type; size_type size() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().rows()); return asImp().size(); } void add(const size_type i, const ElementType& val) { CHECK_INTERFACE_IMPLEMENTATION(asImp().add(i, val)); asImp().add(i, val); } void set(const size_type i, const ElementType& val) { CHECK_INTERFACE_IMPLEMENTATION(asImp().set(i, val)); asImp().set(i, val); } const ElementType get(const size_type i) const { CHECK_INTERFACE_IMPLEMENTATION(asImp().get(i)); return asImp().get(i); } derived_type& asImp() { return static_cast< derived_type& >(*this); } const derived_type& asImp() const { return static_cast< const derived_type& >(*this); } }; // class VectorInterface } // namespace Container } // namespace LA } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_LA_CONTAINER_INTERFACE_HH <|endoftext|>
<commit_before>#pragma once #include <iostream> #include <stdexcept> #include <string> #include <vector> #include <algorithm> #include "acmacs-base/string.hh" #include "acmacs-base/rapidjson.hh" // ---------------------------------------------------------------------- namespace from_json { using ConstArray = rapidjson::Value::ConstArray; inline const rapidjson::Value& get_raw(const rapidjson::Value& aValue, const char* aName) { return aValue[aName]; } template <typename Value> Value get(const rapidjson::Value& aValue, const char* aName); template<> inline std::string get(const rapidjson::Value& aValue, const char* aName) { return aValue[aName].GetString(); } template<> inline size_t get(const rapidjson::Value& aValue, const char* aName) { return aValue[aName].GetUint(); } template<> inline unsigned get(const rapidjson::Value& aValue, const char* aName) { return aValue[aName].GetUint(); } template<> inline int get(const rapidjson::Value& aValue, const char* aName) { return aValue[aName].GetInt(); } template<> inline bool get(const rapidjson::Value& aValue, const char* aName) { return aValue[aName].GetBool(); } template<> inline ConstArray get(const rapidjson::Value& aValue, const char* aName) { return aValue[aName].GetArray(); } inline const char* get_string(const rapidjson::Value& aValue) { return aValue.GetString(); } inline std::string get_string_uppercase(const rapidjson::Value& aValue) { return string::upper(aValue.GetString()); } inline std::string get_string_lowercase(const rapidjson::Value& aValue) { return string::lower(aValue.GetString()); } template<> inline std::vector<std::string> get(const rapidjson::Value& aValue, const char* aName) { std::vector<std::string> result; const auto value = get<ConstArray>(aValue, aName); //std::transform(value.begin(), value.end(), std::back_inserter(result), [](const auto& elt) { return elt.GetString(); }); std::transform(value.begin(), value.end(), std::back_inserter(result), &get_string); return result; } template <typename Value> inline Value get(const rapidjson::Value& aValue, const char* aName, const Value& aDefault) { try { return get<Value>(aValue, aName); } catch (rapidjson_assert&) { return aDefault; } } inline std::string to_string(const rapidjson::Value& value) { rapidjson::StringBuffer buffer; buffer.Clear(); rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); value.Accept(writer); return buffer.GetString(); } // ---------------------------------------------------------------------- class object { public: object(std::string aSrc) { mDoc.Parse(aSrc.c_str(), aSrc.size()); } object(object&& aSrc) : mDoc{std::move(aSrc.mDoc)} {} object(std::istream&& aInput, std::string aFilename = "istream") { if (!aInput) throw std::runtime_error{"cannot read json input from " + aFilename }; rapidjson::IStreamWrapper wrapper{aInput}; mDoc.ParseStream(wrapper); } virtual ~object() = default; // const rapidjson::Value& get_raw(const char* aName) const { return from_json::get_raw(mDoc, aName); } template <typename Value> Value get(const char* aName) const { return from_json::get<Value>(mDoc, aName); } template <typename Value> Value get(const char* aName, const Value& aDefault) const { return from_json::get(mDoc, aName, aDefault); } std::string get_string(const char* aName) const { return get(aName, std::string{}); } ConstArray get_array(const char* aName) const { return from_json::get<ConstArray>(mDoc, aName); } // throws rapidjson_assert std::string get_as_string(const char* aName) const { try { return from_json::to_string(from_json::get_raw(mDoc, aName)); } catch (rapidjson_assert&) { return {}; } } // const rapidjson::Document& doc() const { return mDoc; } std::string to_json() const { rapidjson::StringBuffer buffer; rapidjson::Writer<decltype(buffer)> writer(buffer); mDoc.Accept(writer); return buffer.GetString(); } private: rapidjson::Document mDoc; }; // class Object } // namespace from_json // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>rapidjson is obsolete<commit_after>#pragma once #error Obsolete, use rjson #include <iostream> #include <stdexcept> #include <string> #include <vector> #include <algorithm> #include "acmacs-base/string.hh" #include "acmacs-base/rapidjson.hh" // ---------------------------------------------------------------------- namespace from_json { using ConstArray = rapidjson::Value::ConstArray; inline const rapidjson::Value& get_raw(const rapidjson::Value& aValue, const char* aName) { return aValue[aName]; } template <typename Value> Value get(const rapidjson::Value& aValue, const char* aName); template<> inline std::string get(const rapidjson::Value& aValue, const char* aName) { return aValue[aName].GetString(); } template<> inline size_t get(const rapidjson::Value& aValue, const char* aName) { return aValue[aName].GetUint(); } template<> inline unsigned get(const rapidjson::Value& aValue, const char* aName) { return aValue[aName].GetUint(); } template<> inline int get(const rapidjson::Value& aValue, const char* aName) { return aValue[aName].GetInt(); } template<> inline bool get(const rapidjson::Value& aValue, const char* aName) { return aValue[aName].GetBool(); } template<> inline ConstArray get(const rapidjson::Value& aValue, const char* aName) { return aValue[aName].GetArray(); } inline const char* get_string(const rapidjson::Value& aValue) { return aValue.GetString(); } inline std::string get_string_uppercase(const rapidjson::Value& aValue) { return string::upper(aValue.GetString()); } inline std::string get_string_lowercase(const rapidjson::Value& aValue) { return string::lower(aValue.GetString()); } template<> inline std::vector<std::string> get(const rapidjson::Value& aValue, const char* aName) { std::vector<std::string> result; const auto value = get<ConstArray>(aValue, aName); //std::transform(value.begin(), value.end(), std::back_inserter(result), [](const auto& elt) { return elt.GetString(); }); std::transform(value.begin(), value.end(), std::back_inserter(result), &get_string); return result; } template <typename Value> inline Value get(const rapidjson::Value& aValue, const char* aName, const Value& aDefault) { try { return get<Value>(aValue, aName); } catch (rapidjson_assert&) { return aDefault; } } inline std::string to_string(const rapidjson::Value& value) { rapidjson::StringBuffer buffer; buffer.Clear(); rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); value.Accept(writer); return buffer.GetString(); } // ---------------------------------------------------------------------- class object { public: object(std::string aSrc) { mDoc.Parse(aSrc.c_str(), aSrc.size()); } object(object&& aSrc) : mDoc{std::move(aSrc.mDoc)} {} object(std::istream&& aInput, std::string aFilename = "istream") { if (!aInput) throw std::runtime_error{"cannot read json input from " + aFilename }; rapidjson::IStreamWrapper wrapper{aInput}; mDoc.ParseStream(wrapper); } virtual ~object() = default; // const rapidjson::Value& get_raw(const char* aName) const { return from_json::get_raw(mDoc, aName); } template <typename Value> Value get(const char* aName) const { return from_json::get<Value>(mDoc, aName); } template <typename Value> Value get(const char* aName, const Value& aDefault) const { return from_json::get(mDoc, aName, aDefault); } std::string get_string(const char* aName) const { return get(aName, std::string{}); } ConstArray get_array(const char* aName) const { return from_json::get<ConstArray>(mDoc, aName); } // throws rapidjson_assert std::string get_as_string(const char* aName) const { try { return from_json::to_string(from_json::get_raw(mDoc, aName)); } catch (rapidjson_assert&) { return {}; } } // const rapidjson::Document& doc() const { return mDoc; } std::string to_json() const { rapidjson::StringBuffer buffer; rapidjson::Writer<decltype(buffer)> writer(buffer); mDoc.Accept(writer); return buffer.GetString(); } private: rapidjson::Document mDoc; }; // class Object } // namespace from_json // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>// Copyright 2004-present Facebook. All Rights Reserved. #include "ProxyExecutor.h" #include <fb/assert.h> #include <fb/Environment.h> #include <jni/LocalReference.h> #include <jni/LocalString.h> #include <folly/json.h> #include <folly/Memory.h> #include <cxxreact/SystraceSection.h> #include <cxxreact/ModuleRegistry.h> namespace facebook { namespace react { const auto EXECUTOR_BASECLASS = "com/facebook/react/bridge/JavaJSExecutor"; static std::string executeJSCallWithProxy( jobject executor, const std::string& methodName, const folly::dynamic& arguments) { static auto executeJSCall = jni::findClassStatic(EXECUTOR_BASECLASS)->getMethod<jstring(jstring, jstring)>("executeJSCall"); auto result = executeJSCall( executor, jni::make_jstring(methodName).get(), jni::make_jstring(folly::toJson(arguments).c_str()).get()); return result->toString(); } std::unique_ptr<JSExecutor> ProxyExecutorOneTimeFactory::createJSExecutor( std::shared_ptr<ExecutorDelegate> delegate, std::shared_ptr<MessageQueueThread>) { return folly::make_unique<ProxyExecutor>(std::move(m_executor), delegate); } ProxyExecutor::ProxyExecutor(jni::global_ref<jobject>&& executorInstance, std::shared_ptr<ExecutorDelegate> delegate) : m_executor(std::move(executorInstance)) , m_delegate(delegate) { folly::dynamic nativeModuleConfig = folly::dynamic::array; { SystraceSection s("collectNativeModuleDescriptions"); auto moduleRegistry = delegate->getModuleRegistry(); for (const auto& name : moduleRegistry->moduleNames()) { auto config = moduleRegistry->getConfig(name); nativeModuleConfig.push_back(config ? config->config : nullptr); } } folly::dynamic config = folly::dynamic::object ("remoteModuleConfig", std::move(nativeModuleConfig)); SystraceSection t("setGlobalVariable"); setGlobalVariable( "__fbBatchedBridgeConfig", folly::make_unique<JSBigStdString>(folly::toJson(config))); } ProxyExecutor::~ProxyExecutor() { m_executor.reset(); } void ProxyExecutor::loadApplicationScript( std::unique_ptr<const JSBigString>, std::string sourceURL) { static auto loadApplicationScript = jni::findClassStatic(EXECUTOR_BASECLASS)->getMethod<void(jstring)>("loadApplicationScript"); // The proxy ignores the script data passed in. loadApplicationScript( m_executor.get(), jni::make_jstring(sourceURL).get()); // We can get pending calls here to native but the queue will be drained when // we launch the application. } void ProxyExecutor::setJSModulesUnbundle(std::unique_ptr<JSModulesUnbundle>) { jni::throwNewJavaException( "java/lang/UnsupportedOperationException", "Loading application unbundles is not supported for proxy executors"); } void ProxyExecutor::callFunction(const std::string& moduleId, const std::string& methodId, const folly::dynamic& arguments) { auto call = folly::dynamic::array(moduleId, methodId, std::move(arguments)); std::string result = executeJSCallWithProxy(m_executor.get(), "callFunctionReturnFlushedQueue", std::move(call)); m_delegate->callNativeModules(*this, folly::parseJson(result), true); } void ProxyExecutor::invokeCallback(const double callbackId, const folly::dynamic& arguments) { auto call = folly::dynamic::array(callbackId, std::move(arguments)); std::string result = executeJSCallWithProxy(m_executor.get(), "invokeCallbackAndReturnFlushedQueue", std::move(call)); m_delegate->callNativeModules(*this, folly::parseJson(result), true); } void ProxyExecutor::setGlobalVariable(std::string propName, std::unique_ptr<const JSBigString> jsonValue) { static auto setGlobalVariable = jni::findClassStatic(EXECUTOR_BASECLASS)->getMethod<void(jstring, jstring)>("setGlobalVariable"); setGlobalVariable( m_executor.get(), jni::make_jstring(propName).get(), jni::make_jstring(jsonValue->c_str()).get()); } } } <commit_msg>Delaying native module config collection.<commit_after>// Copyright 2004-present Facebook. All Rights Reserved. #include "ProxyExecutor.h" #include <fb/assert.h> #include <fb/Environment.h> #include <jni/LocalReference.h> #include <jni/LocalString.h> #include <folly/json.h> #include <folly/Memory.h> #include <cxxreact/SystraceSection.h> #include <cxxreact/ModuleRegistry.h> namespace facebook { namespace react { const auto EXECUTOR_BASECLASS = "com/facebook/react/bridge/JavaJSExecutor"; static std::string executeJSCallWithProxy( jobject executor, const std::string& methodName, const folly::dynamic& arguments) { static auto executeJSCall = jni::findClassStatic(EXECUTOR_BASECLASS)->getMethod<jstring(jstring, jstring)>("executeJSCall"); auto result = executeJSCall( executor, jni::make_jstring(methodName).get(), jni::make_jstring(folly::toJson(arguments).c_str()).get()); return result->toString(); } std::unique_ptr<JSExecutor> ProxyExecutorOneTimeFactory::createJSExecutor( std::shared_ptr<ExecutorDelegate> delegate, std::shared_ptr<MessageQueueThread>) { return folly::make_unique<ProxyExecutor>(std::move(m_executor), delegate); } ProxyExecutor::ProxyExecutor(jni::global_ref<jobject>&& executorInstance, std::shared_ptr<ExecutorDelegate> delegate) : m_executor(std::move(executorInstance)) , m_delegate(delegate) {} ProxyExecutor::~ProxyExecutor() { m_executor.reset(); } void ProxyExecutor::loadApplicationScript( std::unique_ptr<const JSBigString>, std::string sourceURL) { folly::dynamic nativeModuleConfig = folly::dynamic::array; { SystraceSection s("collectNativeModuleDescriptions"); auto moduleRegistry = m_delegate->getModuleRegistry(); for (const auto& name : moduleRegistry->moduleNames()) { auto config = moduleRegistry->getConfig(name); nativeModuleConfig.push_back(config ? config->config : nullptr); } } folly::dynamic config = folly::dynamic::object ("remoteModuleConfig", std::move(nativeModuleConfig)); { SystraceSection t("setGlobalVariable"); setGlobalVariable( "__fbBatchedBridgeConfig", folly::make_unique<JSBigStdString>(folly::toJson(config))); } static auto loadApplicationScript = jni::findClassStatic(EXECUTOR_BASECLASS)->getMethod<void(jstring)>("loadApplicationScript"); // The proxy ignores the script data passed in. loadApplicationScript( m_executor.get(), jni::make_jstring(sourceURL).get()); // We can get pending calls here to native but the queue will be drained when // we launch the application. } void ProxyExecutor::setJSModulesUnbundle(std::unique_ptr<JSModulesUnbundle>) { jni::throwNewJavaException( "java/lang/UnsupportedOperationException", "Loading application unbundles is not supported for proxy executors"); } void ProxyExecutor::callFunction(const std::string& moduleId, const std::string& methodId, const folly::dynamic& arguments) { auto call = folly::dynamic::array(moduleId, methodId, std::move(arguments)); std::string result = executeJSCallWithProxy(m_executor.get(), "callFunctionReturnFlushedQueue", std::move(call)); m_delegate->callNativeModules(*this, folly::parseJson(result), true); } void ProxyExecutor::invokeCallback(const double callbackId, const folly::dynamic& arguments) { auto call = folly::dynamic::array(callbackId, std::move(arguments)); std::string result = executeJSCallWithProxy(m_executor.get(), "invokeCallbackAndReturnFlushedQueue", std::move(call)); m_delegate->callNativeModules(*this, folly::parseJson(result), true); } void ProxyExecutor::setGlobalVariable(std::string propName, std::unique_ptr<const JSBigString> jsonValue) { static auto setGlobalVariable = jni::findClassStatic(EXECUTOR_BASECLASS)->getMethod<void(jstring, jstring)>("setGlobalVariable"); setGlobalVariable( m_executor.get(), jni::make_jstring(propName).get(), jni::make_jstring(jsonValue->c_str()).get()); } } } <|endoftext|>
<commit_before>#include "CameraImageWrapper.h" #include <QColor> #include <QApplication> #include <QDesktopWidget> CameraImageWrapper::CameraImageWrapper() : LuminanceSource(0,0), image(NULL) { } CameraImageWrapper::CameraImageWrapper(const QImage &sourceImage) : LuminanceSource(sourceImage.width(), sourceImage.height()) { image = grayScaleImage( &sourceImage ); } CameraImageWrapper::CameraImageWrapper(CameraImageWrapper& otherInstance) : LuminanceSource(otherInstance.getWidth(), otherInstance.getHeight()) { image = new QImage(otherInstance.getOriginalImage()); } CameraImageWrapper::~CameraImageWrapper() { if(image) delete image; } CameraImageWrapper *CameraImageWrapper::Factory(const QImage &sourceImage, int maxWidth, int maxHeight, bool smoothTransformation) { if((maxWidth != 1 || maxHeight != 1) && (sourceImage.width() > maxWidth || sourceImage.height() > maxHeight)) { QImage image; image = sourceImage.scaled( maxWidth != -1 ? maxWidth : sourceImage.width(), maxHeight != -1 ? maxHeight : sourceImage.height(), Qt::KeepAspectRatio, smoothTransformation ? Qt::SmoothTransformation : Qt::FastTransformation); return new CameraImageWrapper(image); } else return new CameraImageWrapper(sourceImage); } int CameraImageWrapper::getWidth() const { return image->width(); } int CameraImageWrapper::getHeight() const { return image->height(); } unsigned char CameraImageWrapper::getPixel(int x, int y) const { return image->pixel(x,y); } unsigned char* CameraImageWrapper::copyMatrix() const { unsigned char* newMatrix = (unsigned char*)malloc(image->width() * image->height() * sizeof(unsigned char)); int cnt = 0; for(int i=0; i<image->width(); i++) for(int j=0; j<image->height(); j++) newMatrix[cnt++] = getPixel(i,j); return newMatrix; } QImage* CameraImageWrapper::grayScaleImage(const QImage *origin) { QImage *tmp = new QImage(origin->width(), origin->height(), QImage::Format_Grayscale8); for(int i=0; i<origin->width(); i++) { for(int j=0; j<origin->height(); j++) { int pix = qGray(origin->pixel(QPoint(i,j))); tmp->setPixel(i,j, qRgb(pix ,pix,pix)); } } return tmp; } QImage CameraImageWrapper::getOriginalImage() { return *image; } ArrayRef<char> CameraImageWrapper::getRow(int y, ArrayRef<char> row) const { int width = getWidth(); if (row->size() != width) row.reset(ArrayRef<char>(width)); for (int x = 0; x < width; x++) row[x] = getPixel(x,y); return row; } ArrayRef<char> CameraImageWrapper::getMatrix() const { int width = getWidth(); int height = getHeight(); char* matrix = new char[width*height]; char* m = matrix; ArrayRef<char> tmpRow(0); for(int y=0; y<height; y++) { tmpRow = getRow(y, tmpRow); #if __cplusplus > 199711L memcpy(m, tmpRow->values().data(), width); #else memcpy(m, &tmpRow[0], width); #endif m += width * sizeof(unsigned char); } ArrayRef<char> arr = ArrayRef<char>(matrix, width*height); if (matrix) { delete matrix; } return arr; } QImage *CameraImageWrapper::sharpen(const QImage *origin) { QImage * newImage = new QImage(* origin); int kernel [3][3]= {{0,-1,0}, {-1,5,-1}, {0,-1,0}}; int kernelSize = 3; int sumKernel = 1; int r,g,b; QColor color; for(int x=kernelSize/2; x<newImage->width()-(kernelSize/2); x++){ for(int y=kernelSize/2; y<newImage->height()-(kernelSize/2); y++){ r = 0; g = 0; b = 0; for(int i = -kernelSize/2; i<= kernelSize/2; i++){ for(int j = -kernelSize/2; j<= kernelSize/2; j++){ color = QColor(origin->pixel(x+i, y+j)); r += color.red()*kernel[kernelSize/2+i][kernelSize/2+j]; g += color.green()*kernel[kernelSize/2+i][kernelSize/2+j]; b += color.blue()*kernel[kernelSize/2+i][kernelSize/2+j]; } } r = qBound(0, r/sumKernel, 255); g = qBound(0, g/sumKernel, 255); b = qBound(0, b/sumKernel, 255); newImage->setPixel(x,y, qRgb(r,g,b)); } } return newImage; } <commit_msg>optimized CameraImageWrapper::getMatrix by removing an extra (uneeded) image copy<commit_after>#include "CameraImageWrapper.h" #include <QColor> #include <QApplication> #include <QDesktopWidget> CameraImageWrapper::CameraImageWrapper() : LuminanceSource(0,0), image(NULL) { } CameraImageWrapper::CameraImageWrapper(const QImage &sourceImage) : LuminanceSource(sourceImage.width(), sourceImage.height()) { image = grayScaleImage( &sourceImage ); } CameraImageWrapper::CameraImageWrapper(CameraImageWrapper& otherInstance) : LuminanceSource(otherInstance.getWidth(), otherInstance.getHeight()) { image = new QImage(otherInstance.getOriginalImage()); } CameraImageWrapper::~CameraImageWrapper() { if(image) delete image; } CameraImageWrapper *CameraImageWrapper::Factory(const QImage &sourceImage, int maxWidth, int maxHeight, bool smoothTransformation) { if((maxWidth != 1 || maxHeight != 1) && (sourceImage.width() > maxWidth || sourceImage.height() > maxHeight)) { QImage image; image = sourceImage.scaled( maxWidth != -1 ? maxWidth : sourceImage.width(), maxHeight != -1 ? maxHeight : sourceImage.height(), Qt::KeepAspectRatio, smoothTransformation ? Qt::SmoothTransformation : Qt::FastTransformation); return new CameraImageWrapper(image); } else return new CameraImageWrapper(sourceImage); } int CameraImageWrapper::getWidth() const { return image->width(); } int CameraImageWrapper::getHeight() const { return image->height(); } unsigned char CameraImageWrapper::getPixel(int x, int y) const { return image->pixel(x,y); } unsigned char* CameraImageWrapper::copyMatrix() const { unsigned char* newMatrix = (unsigned char*)malloc(image->width() * image->height() * sizeof(unsigned char)); int cnt = 0; for(int i=0; i<image->width(); i++) for(int j=0; j<image->height(); j++) newMatrix[cnt++] = getPixel(i,j); return newMatrix; } QImage* CameraImageWrapper::grayScaleImage(const QImage *origin) { QImage *tmp = new QImage(origin->width(), origin->height(), QImage::Format_Grayscale8); for(int i=0; i<origin->width(); i++) { for(int j=0; j<origin->height(); j++) { int pix = qGray(origin->pixel(QPoint(i,j))); tmp->setPixel(i,j, qRgb(pix ,pix,pix)); } } return tmp; } QImage CameraImageWrapper::getOriginalImage() { return *image; } ArrayRef<char> CameraImageWrapper::getRow(int y, ArrayRef<char> row) const { int width = getWidth(); if (row->size() != width) row.reset(ArrayRef<char>(width)); for (int x = 0; x < width; x++) row[x] = getPixel(x,y); return row; } ArrayRef<char> CameraImageWrapper::getMatrix() const { int width = getWidth(); int height = getHeight(); ArrayRef<char> tmpRow(0); ArrayRef<char> arr(width*height); char* m = &arr[0]; for(int y=0; y<height; y++) { tmpRow = getRow(y, tmpRow); #if __cplusplus > 199711L memcpy(m, tmpRow->values().data(), width); #else memcpy(m, &tmpRow[0], width); #endif m += width * sizeof(unsigned char); } return arr; } QImage *CameraImageWrapper::sharpen(const QImage *origin) { QImage * newImage = new QImage(* origin); int kernel [3][3]= {{0,-1,0}, {-1,5,-1}, {0,-1,0}}; int kernelSize = 3; int sumKernel = 1; int r,g,b; QColor color; for(int x=kernelSize/2; x<newImage->width()-(kernelSize/2); x++){ for(int y=kernelSize/2; y<newImage->height()-(kernelSize/2); y++){ r = 0; g = 0; b = 0; for(int i = -kernelSize/2; i<= kernelSize/2; i++){ for(int j = -kernelSize/2; j<= kernelSize/2; j++){ color = QColor(origin->pixel(x+i, y+j)); r += color.red()*kernel[kernelSize/2+i][kernelSize/2+j]; g += color.green()*kernel[kernelSize/2+i][kernelSize/2+j]; b += color.blue()*kernel[kernelSize/2+i][kernelSize/2+j]; } } r = qBound(0, r/sumKernel, 255); g = qBound(0, g/sumKernel, 255); b = qBound(0, b/sumKernel, 255); newImage->setPixel(x,y, qRgb(r,g,b)); } } return newImage; } <|endoftext|>
<commit_before>#include <silicium/config.hpp> #include <silicium/bounded_int.hpp> #include <silicium/variant.hpp> #include <silicium/array_view.hpp> #include <silicium/arithmetic/add.hpp> #include <boost/test/unit_test.hpp> namespace Si { namespace m3 { template <class T> void trivial_copy(T &destination, T const &source) { std::memcpy(&destination, &source, sizeof(source)); } template <class T> struct val { val() BOOST_NOEXCEPT : m_is_set(false) { } template <class... Args> explicit val(Args &&... args) : m_is_set(true) { new (static_cast<void *>(&get())) T(std::forward<Args>(args)...); } ~val() BOOST_NOEXCEPT { if (!m_is_set) { return; } get().~T(); } val(val &&other) BOOST_NOEXCEPT : m_is_set(other.m_is_set) { if (m_is_set) { trivial_copy(get(), other.get()); other.m_is_set = false; } } val &operator=(val &&other) BOOST_NOEXCEPT { if (m_is_set) { if (other.m_is_set) { get().~T(); trivial_copy(get(), other.get()); other.m_is_set = false; } else { get().~T(); m_is_set = false; } } else { if (other.m_is_set) { trivial_copy(get(), other.get()); other.m_is_set = false; m_is_set = true; } else { // nothing to do } } return *this; } void release() BOOST_NOEXCEPT { m_is_set = false; } T &require() { if (!m_is_set) { boost::throw_exception(std::logic_error("expected non-empty val")); } return get(); } void transfer(T &destination) BOOST_NOEXCEPT { trivial_copy(destination, require()); release(); } static val steal(T const &from) { val result; trivial_copy(result.get(), from); result.m_is_set = true; return result; } private: bool m_is_set; typename std::aligned_storage<sizeof(T), alignof(T)>::type m_storage; T &get() { return reinterpret_cast<T &>(reinterpret_cast<char &>(m_storage)); } }; template <class T> val<T> steal(T const &stolen) { return val<T>::steal(stolen); } template <class T, class Deleter> struct unique_ref : private Deleter { explicit unique_ref(T &ref, Deleter deleter) BOOST_NOEXCEPT : Deleter(deleter), m_ptr(&ref) { } explicit unique_ref(val<unique_ref> other) BOOST_NOEXCEPT { other.transfer(*this); } ~unique_ref() BOOST_NOEXCEPT { Deleter::operator()(*m_ptr); } SILICIUM_DISABLE_COPY(unique_ref) T &ref() const BOOST_NOEXCEPT { return *m_ptr; } private: T *m_ptr; }; struct new_deleter { new_deleter() BOOST_NOEXCEPT { } template <class T> void operator()(T &deleted) const BOOST_NOEXCEPT { delete &deleted; } }; struct malloc_deleter { malloc_deleter() BOOST_NOEXCEPT { } template <class T> void operator()(T &deleted) const BOOST_NOEXCEPT { std::free(&deleted); } }; template <class T, class... Args> val<unique_ref<T, new_deleter>> make_unique(Args &&... args) { return val<unique_ref<T, new_deleter>>(*new T(std::forward<Args>(args)...), new_deleter()); } template <class T> val<unique_ref<T, malloc_deleter>> allocate_array_storage(std::size_t length) { void *const storage = std::calloc(length, sizeof(T)); if (!storage) { boost::throw_exception(std::bad_alloc()); } return val<unique_ref<T, malloc_deleter>>(*static_cast<T *>(storage), malloc_deleter()); } template <class T, class Length> struct dynamic_array : private Length { template <class ElementGenerator> dynamic_array(Length length, ElementGenerator &&generate_elements) BOOST_NOEXCEPT : Length(length), m_elements(allocate_array_storage<T>(length.value())) { for (typename Length::value_type i = 0, c = this->length().value(); i < c; ++i) { generate_elements().transfer((&m_elements.ref())[i]); } } explicit dynamic_array(val<dynamic_array> other) BOOST_NOEXCEPT : Length(other.require()), m_elements(steal(other.require().m_elements)) { other.release(); } ~dynamic_array() BOOST_NOEXCEPT { for (typename Length::value_type i = 0, c = length().value(); i < c; ++i) { (&m_elements.ref())[c - i - 1].~T(); } } Length length() const BOOST_NOEXCEPT { return *this; } array_view<T, Length> as_view() const BOOST_NOEXCEPT { return array_view<T, Length>(m_elements.ref(), length()); } SILICIUM_DISABLE_COPY(dynamic_array) private: unique_ref<T, malloc_deleter> m_elements; }; template <std::size_t I, class... T> struct type_at; template <class Head, class... Tail> struct type_at<0, Head, Tail...> { typedef Head type; }; template <std::size_t I, class Head, class... Tail> struct type_at<I, Head, Tail...> { typedef typename type_at<I - 1, Tail...>::type type; }; template <class... T> struct tuple_impl; template <> struct tuple_impl<> { tuple_impl() BOOST_NOEXCEPT { } explicit tuple_impl(tuple_impl const &) BOOST_NOEXCEPT { } }; template <class Head, class... Tail> struct tuple_impl<Head, Tail...> : private tuple_impl<Tail...> { template <class First, class... Rest> explicit tuple_impl(First &&first, Rest &&... rest) BOOST_NOEXCEPT : base(std::forward<Rest>(rest)...), m_head(std::forward<First>(first)) { } explicit tuple_impl(tuple_impl<Head, Tail...> const &stolen) BOOST_NOEXCEPT : base(static_cast<base const &>(stolen)), m_head(steal(stolen.m_head)) { } Head &get(std::integral_constant<std::size_t, 0>) { return m_head; } template <std::size_t I> typename type_at<I - 1, Tail...>::type &get(std::integral_constant<std::size_t, I>) { return base::template get(std::integral_constant<std::size_t, I - 1>()); } private: typedef tuple_impl<Tail...> base; Head m_head; }; template <class... T> struct tuple : private tuple_impl<T...> { template <class... Elements> explicit tuple(Elements &&... elements) BOOST_NOEXCEPT : base(std::forward<Elements>(elements)...) { } explicit tuple(val<tuple> other) BOOST_NOEXCEPT : base(static_cast<base const &>(other.require())) { other.release(); } template <std::size_t I> typename type_at<I, T...>::type &get() { return base::template get(std::integral_constant<std::size_t, I>()); } private: typedef tuple_impl<T...> base; }; template <std::size_t I, class... T> typename type_at<I, T...>::type &get(tuple<T...> &from) { return from.template get<I>(); } template <class T> struct make_tuple_decay { typedef T type; }; template <class T> struct make_tuple_decay<val<T>> { typedef T type; }; template <class... T> auto make_tuple(T &&... elements) { return val<tuple<typename make_tuple_decay<typename std::decay<T>::type>::type>...>( std::forward<T>(elements)...); } } } BOOST_AUTO_TEST_CASE(move3_val) { Si::m3::val<Si::m3::unique_ref<int, Si::m3::new_deleter>> r = Si::m3::make_unique<int>(23); BOOST_CHECK_EQUAL(23, r.require().ref()); Si::m3::val<Si::m3::unique_ref<int, Si::m3::new_deleter>> s = std::move(r); BOOST_CHECK_EQUAL(23, s.require().ref()); s.require().ref() = 24; r = std::move(s); BOOST_CHECK_EQUAL(24, r.require().ref()); Si::m3::unique_ref<int, Si::m3::new_deleter> t(std::move(r)); BOOST_CHECK_EQUAL(24, t.ref()); } BOOST_AUTO_TEST_CASE(move3_vector_ref_emplace_back) { typedef Si::bounded_int<std::size_t, 1, 2> length_type; Si::m3::dynamic_array<Si::m3::unique_ref<int, Si::m3::new_deleter>, length_type> const v( length_type::literal<1>(), []() { return Si::m3::make_unique<int>(23); }); BOOST_REQUIRE_EQUAL(length_type::literal<1>(), v.length()); Si::array_view<Si::m3::unique_ref<int, Si::m3::new_deleter>, length_type> const range = v.as_view(); BOOST_REQUIRE_EQUAL(length_type::literal<1>(), range.length()); Si::m3::unique_ref<int, Si::m3::new_deleter> const &element = range[Si::literal<std::size_t, 0>()]; BOOST_CHECK_EQUAL(element.ref(), 23); } BOOST_AUTO_TEST_CASE(move3_val_of_vector) { typedef Si::bounded_int<std::size_t, 1, 2> length_type; auto create_array = []() { return Si::m3::val<Si::m3::dynamic_array<Si::m3::unique_ref<int, Si::m3::new_deleter>, length_type>>( length_type::literal<1>(), []() { return Si::m3::make_unique<int>(23); }); }; Si::m3::val<Si::m3::dynamic_array<Si::m3::unique_ref<int, Si::m3::new_deleter>, length_type>> a = create_array(); Si::m3::dynamic_array<Si::m3::unique_ref<int, Si::m3::new_deleter>, length_type> const v(std::move(a)); BOOST_REQUIRE_EQUAL(length_type::literal<1>(), v.length()); Si::array_view<Si::m3::unique_ref<int, Si::m3::new_deleter>, length_type> const range = v.as_view(); BOOST_REQUIRE_EQUAL(length_type::literal<1>(), range.length()); Si::m3::unique_ref<int, Si::m3::new_deleter> const &element = range[Si::literal<std::size_t, 0>()]; BOOST_CHECK_EQUAL(element.ref(), 23); } BOOST_AUTO_TEST_CASE(move3_make_tuple) { using namespace Si::m3; val<tuple<unique_ref<int, new_deleter>>> t = make_tuple(make_unique<int>(23)); tuple<unique_ref<int, new_deleter>> u(std::move(t)); unique_ref<int, new_deleter> &element = get<0>(u); BOOST_CHECK_EQUAL(23, element.ref()); } <commit_msg>using namespace for better readability<commit_after>#include <silicium/config.hpp> #include <silicium/bounded_int.hpp> #include <silicium/variant.hpp> #include <silicium/array_view.hpp> #include <silicium/arithmetic/add.hpp> #include <boost/test/unit_test.hpp> namespace Si { namespace m3 { template <class T> void trivial_copy(T &destination, T const &source) { std::memcpy(&destination, &source, sizeof(source)); } template <class T> struct val { val() BOOST_NOEXCEPT : m_is_set(false) { } template <class... Args> explicit val(Args &&... args) : m_is_set(true) { new (static_cast<void *>(&get())) T(std::forward<Args>(args)...); } ~val() BOOST_NOEXCEPT { if (!m_is_set) { return; } get().~T(); } val(val &&other) BOOST_NOEXCEPT : m_is_set(other.m_is_set) { if (m_is_set) { trivial_copy(get(), other.get()); other.m_is_set = false; } } val &operator=(val &&other) BOOST_NOEXCEPT { if (m_is_set) { if (other.m_is_set) { get().~T(); trivial_copy(get(), other.get()); other.m_is_set = false; } else { get().~T(); m_is_set = false; } } else { if (other.m_is_set) { trivial_copy(get(), other.get()); other.m_is_set = false; m_is_set = true; } else { // nothing to do } } return *this; } void release() BOOST_NOEXCEPT { m_is_set = false; } T &require() { if (!m_is_set) { boost::throw_exception(std::logic_error("expected non-empty val")); } return get(); } void transfer(T &destination) BOOST_NOEXCEPT { trivial_copy(destination, require()); release(); } static val steal(T const &from) { val result; trivial_copy(result.get(), from); result.m_is_set = true; return result; } private: bool m_is_set; typename std::aligned_storage<sizeof(T), alignof(T)>::type m_storage; T &get() { return reinterpret_cast<T &>(reinterpret_cast<char &>(m_storage)); } }; template <class T> val<T> steal(T const &stolen) { return val<T>::steal(stolen); } template <class T, class Deleter> struct unique_ref : private Deleter { explicit unique_ref(T &ref, Deleter deleter) BOOST_NOEXCEPT : Deleter(deleter), m_ptr(&ref) { } explicit unique_ref(val<unique_ref> other) BOOST_NOEXCEPT { other.transfer(*this); } ~unique_ref() BOOST_NOEXCEPT { Deleter::operator()(*m_ptr); } SILICIUM_DISABLE_COPY(unique_ref) T &ref() const BOOST_NOEXCEPT { return *m_ptr; } private: T *m_ptr; }; struct new_deleter { new_deleter() BOOST_NOEXCEPT { } template <class T> void operator()(T &deleted) const BOOST_NOEXCEPT { delete &deleted; } }; struct malloc_deleter { malloc_deleter() BOOST_NOEXCEPT { } template <class T> void operator()(T &deleted) const BOOST_NOEXCEPT { std::free(&deleted); } }; template <class T, class... Args> val<unique_ref<T, new_deleter>> make_unique(Args &&... args) { return val<unique_ref<T, new_deleter>>(*new T(std::forward<Args>(args)...), new_deleter()); } template <class T> val<unique_ref<T, malloc_deleter>> allocate_array_storage(std::size_t length) { void *const storage = std::calloc(length, sizeof(T)); if (!storage) { boost::throw_exception(std::bad_alloc()); } return val<unique_ref<T, malloc_deleter>>(*static_cast<T *>(storage), malloc_deleter()); } template <class T, class Length> struct dynamic_array : private Length { template <class ElementGenerator> dynamic_array(Length length, ElementGenerator &&generate_elements) BOOST_NOEXCEPT : Length(length), m_elements(allocate_array_storage<T>(length.value())) { for (typename Length::value_type i = 0, c = this->length().value(); i < c; ++i) { generate_elements().transfer((&m_elements.ref())[i]); } } explicit dynamic_array(val<dynamic_array> other) BOOST_NOEXCEPT : Length(other.require()), m_elements(steal(other.require().m_elements)) { other.release(); } ~dynamic_array() BOOST_NOEXCEPT { for (typename Length::value_type i = 0, c = length().value(); i < c; ++i) { (&m_elements.ref())[c - i - 1].~T(); } } Length length() const BOOST_NOEXCEPT { return *this; } array_view<T, Length> as_view() const BOOST_NOEXCEPT { return array_view<T, Length>(m_elements.ref(), length()); } SILICIUM_DISABLE_COPY(dynamic_array) private: unique_ref<T, malloc_deleter> m_elements; }; template <std::size_t I, class... T> struct type_at; template <class Head, class... Tail> struct type_at<0, Head, Tail...> { typedef Head type; }; template <std::size_t I, class Head, class... Tail> struct type_at<I, Head, Tail...> { typedef typename type_at<I - 1, Tail...>::type type; }; template <class... T> struct tuple_impl; template <> struct tuple_impl<> { tuple_impl() BOOST_NOEXCEPT { } explicit tuple_impl(tuple_impl const &) BOOST_NOEXCEPT { } }; template <class Head, class... Tail> struct tuple_impl<Head, Tail...> : private tuple_impl<Tail...> { template <class First, class... Rest> explicit tuple_impl(First &&first, Rest &&... rest) BOOST_NOEXCEPT : base(std::forward<Rest>(rest)...), m_head(std::forward<First>(first)) { } explicit tuple_impl(tuple_impl<Head, Tail...> const &stolen) BOOST_NOEXCEPT : base(static_cast<base const &>(stolen)), m_head(steal(stolen.m_head)) { } Head &get(std::integral_constant<std::size_t, 0>) { return m_head; } template <std::size_t I> typename type_at<I - 1, Tail...>::type &get(std::integral_constant<std::size_t, I>) { return base::template get(std::integral_constant<std::size_t, I - 1>()); } private: typedef tuple_impl<Tail...> base; Head m_head; }; template <class... T> struct tuple : private tuple_impl<T...> { template <class... Elements> explicit tuple(Elements &&... elements) BOOST_NOEXCEPT : base(std::forward<Elements>(elements)...) { } explicit tuple(val<tuple> other) BOOST_NOEXCEPT : base(static_cast<base const &>(other.require())) { other.release(); } template <std::size_t I> typename type_at<I, T...>::type &get() { return base::template get(std::integral_constant<std::size_t, I>()); } private: typedef tuple_impl<T...> base; }; template <std::size_t I, class... T> typename type_at<I, T...>::type &get(tuple<T...> &from) { return from.template get<I>(); } template <class T> struct make_tuple_decay { typedef T type; }; template <class T> struct make_tuple_decay<val<T>> { typedef T type; }; template <class... T> auto make_tuple(T &&... elements) { return val<tuple<typename make_tuple_decay<typename std::decay<T>::type>::type>...>( std::forward<T>(elements)...); } } } using namespace Si::m3; BOOST_AUTO_TEST_CASE(move3_val) { val<unique_ref<int, new_deleter>> r = make_unique<int>(23); BOOST_CHECK_EQUAL(23, r.require().ref()); val<unique_ref<int, new_deleter>> s = std::move(r); BOOST_CHECK_EQUAL(23, s.require().ref()); s.require().ref() = 24; r = std::move(s); BOOST_CHECK_EQUAL(24, r.require().ref()); unique_ref<int, new_deleter> t(std::move(r)); BOOST_CHECK_EQUAL(24, t.ref()); } BOOST_AUTO_TEST_CASE(move3_vector_ref_emplace_back) { typedef Si::bounded_int<std::size_t, 1, 2> length_type; dynamic_array<unique_ref<int, new_deleter>, length_type> const v(length_type::literal<1>(), []() { return make_unique<int>(23); }); BOOST_REQUIRE_EQUAL(length_type::literal<1>(), v.length()); Si::array_view<unique_ref<int, new_deleter>, length_type> const range = v.as_view(); BOOST_REQUIRE_EQUAL(length_type::literal<1>(), range.length()); unique_ref<int, new_deleter> const &element = range[Si::literal<std::size_t, 0>()]; BOOST_CHECK_EQUAL(element.ref(), 23); } BOOST_AUTO_TEST_CASE(move3_val_of_vector) { typedef Si::bounded_int<std::size_t, 1, 2> length_type; auto create_array = []() { return val<dynamic_array<unique_ref<int, new_deleter>, length_type>>(length_type::literal<1>(), []() { return make_unique<int>(23); }); }; val<dynamic_array<unique_ref<int, new_deleter>, length_type>> a = create_array(); dynamic_array<unique_ref<int, new_deleter>, length_type> const v(std::move(a)); BOOST_REQUIRE_EQUAL(length_type::literal<1>(), v.length()); Si::array_view<unique_ref<int, new_deleter>, length_type> const range = v.as_view(); BOOST_REQUIRE_EQUAL(length_type::literal<1>(), range.length()); unique_ref<int, new_deleter> const &element = range[Si::literal<std::size_t, 0>()]; BOOST_CHECK_EQUAL(element.ref(), 23); } BOOST_AUTO_TEST_CASE(move3_make_tuple) { val<tuple<unique_ref<int, new_deleter>>> t = make_tuple(make_unique<int>(23)); tuple<unique_ref<int, new_deleter>> u(std::move(t)); unique_ref<int, new_deleter> &element = get<0>(u); BOOST_CHECK_EQUAL(23, element.ref()); } <|endoftext|>
<commit_before>#undef NDEBUG //because we are using assert to check actual operations that cannot be skipped in release mode testing #include <cassert> #include <exodus/program.h> programinit() var xo_dict = "xo_dict"; var dict_xo_test = "dict.xo_test"; var default_conn; var xo_dict_conn; function main() { printl("\n --- clear any existing EXO_DATA/DICT env ---\n"); assert(ossetenv("EXO_DATA", "")); assert(ossetenv("EXO_DICT", "")); printl("\n --- default connection first thing before anything else to ensure clean ---\n"); printl("\n --- quit (pass test) if no default database connection ---\n"); if (not default_conn.connect()) { printl("\n --- No default db connection to perform db testing. Test passed ---\n"); return 0; } TRACE(default_conn) //Skip if fast testing required if (osgetenv("EXO_FAST_TEST")) { printl("EXO_FAST_TEST - skipping test."); printl("Test passed"); return 0; } gosub cleanup(); printl("\n --- create a specific database for dicts ---\n"); assert(dbcreate(xo_dict)); printl("\n --- test with EXO_DICT ---\n"); if (true) { printl("\n --- connect to the specific database ---\n"); assert(xo_dict_conn.connect(xo_dict)); printl("\n --- say that dicts are on the specific database " ^ xo_dict ^ " ---\n"); assert(ossetenv("EXO_DICT", xo_dict)); assert(var(getenv("EXO_DICT")) eq xo_dict); printl("\n --- create a dict on the specific database implicitly ---\n"); assert(createfile(dict_xo_test)); printl("\n --- ensure new dict IS on the right database implicitly ---\n"); var dicttest; assert(dicttest.open(dict_xo_test)); printl("\n --- ensure new dict IS on the right database specifically ---\n"); var dicttest2; assert(dicttest2.open(dict_xo_test, xo_dict_conn)); printl("\n --- ensure dict IS NOT on the default connection ---\n"); assert(not dicttest.open(dict_xo_test, default_conn)); printl("\n --- delete the dict on the specific database implicitly ---\n"); assert(deletefile(dict_xo_test)); printl("\n --- ensure new dict IS NO LONGER on the right database implicitly ---\n"); var dicttest3; assert(not dicttest3.open(dict_xo_test)); printl("\n --- ensure new dict IS NO LONGER on the specific database ---\n"); var dicttest4; assert(not dicttest4.open(dict_xo_test, xo_dict_conn)); printl("\n --- disconnect specific connection ---\n"); xo_dict_conn.disconnect(); } printl("\n --- test without EXO_DICT ---\n"); if (true) { printl("\n --- connect to the specific database (although not used for dict here) ---\n"); printl("\n --- say that dicts are on the default database ---\n"); assert(ossetenv("EXO_DICT", "")); assert(var(getenv("EXO_DICT")) eq ""); printl("\n --- needed to remove default dict connection ---\n"); disconnectall(); printl("\n --- specific connection to the dic database ---\n"); assert(xo_dict_conn.connect(xo_dict)); printl("\n --- create a dict on the default database implicitly ---\n"); assert(createfile(dict_xo_test)); printl("\n --- ensure new dict IS on the right database implicitly ---\n"); var dicttest; assert(dicttest.open(dict_xo_test)); printl("\n --- ensure new dict IS on the right database specifically ---\n"); var dicttest2; assert(dicttest2.open(dict_xo_test, default_conn)); printl("\n --- ensure dict IS NOT on the test database ---\n"); var dicttest3; assert(not dicttest3.open(dict_xo_test, xo_dict_conn)); printl("\n --- delete the dict on the default database implicitly ---\n"); assert(deletefile(dict_xo_test)); printl("\n --- ensure new dict IS NO LONGER on the default database implicitly ---\n"); var dicttest4; assert(not dicttest4.open(dict_xo_test)); printl("\n --- ensure new dict IS NO LONGER on the default database specifically ---\n"); var dicttest5; assert(not dicttest5.open(dict_xo_test, default_conn)); printl("\n --- ensure new dict IS NO LONGER on the special database ---\n"); var dicttest6; assert(not dicttest6.open(dict_xo_test, xo_dict_conn)); printl("\n --- disconnect specific connection ---\n"); xo_dict_conn.disconnect(); } gosub cleanup(); printl(elapsedtimetext()); printl("\nTest passed"); return 0; } subroutine cleanup() { dbdelete(xo_dict); printl("\n --- delete the dict file from the default connection just in case, to be clean ---\n"); default_conn.deletefile(dict_xo_test); } programexit() <commit_msg>use osgetenv instead of getenv in test_dict<commit_after>#undef NDEBUG //because we are using assert to check actual operations that cannot be skipped in release mode testing #include <cassert> #include <exodus/program.h> programinit() var xo_dict = "xo_dict"; var dict_xo_test = "dict.xo_test"; var default_conn; var xo_dict_conn; function main() { printl("\n --- clear any existing EXO_DATA/DICT env ---\n"); assert(ossetenv("EXO_DATA", "")); assert(ossetenv("EXO_DICT", "")); printl("\n --- default connection first thing before anything else to ensure clean ---\n"); printl("\n --- quit (pass test) if no default database connection ---\n"); if (not default_conn.connect()) { printl("\n --- No default db connection to perform db testing. Test passed ---\n"); return 0; } TRACE(default_conn) //Skip if fast testing required if (osgetenv("EXO_FAST_TEST")) { printl("EXO_FAST_TEST - skipping test."); printl("Test passed"); return 0; } gosub cleanup(); printl("\n --- create a specific database for dicts ---\n"); assert(dbcreate(xo_dict)); printl("\n --- test with EXO_DICT ---\n"); if (true) { printl("\n --- connect to the specific database ---\n"); assert(xo_dict_conn.connect(xo_dict)); printl("\n --- say that dicts are on the specific database " ^ xo_dict ^ " ---\n"); assert(ossetenv("EXO_DICT", xo_dict)); assert(var(osgetenv("EXO_DICT")) eq xo_dict); printl("\n --- create a dict on the specific database implicitly ---\n"); assert(createfile(dict_xo_test)); printl("\n --- ensure new dict IS on the right database implicitly ---\n"); var dicttest; assert(dicttest.open(dict_xo_test)); printl("\n --- ensure new dict IS on the right database specifically ---\n"); var dicttest2; assert(dicttest2.open(dict_xo_test, xo_dict_conn)); printl("\n --- ensure dict IS NOT on the default connection ---\n"); assert(not dicttest.open(dict_xo_test, default_conn)); printl("\n --- delete the dict on the specific database implicitly ---\n"); assert(deletefile(dict_xo_test)); printl("\n --- ensure new dict IS NO LONGER on the right database implicitly ---\n"); var dicttest3; assert(not dicttest3.open(dict_xo_test)); printl("\n --- ensure new dict IS NO LONGER on the specific database ---\n"); var dicttest4; assert(not dicttest4.open(dict_xo_test, xo_dict_conn)); printl("\n --- disconnect specific connection ---\n"); xo_dict_conn.disconnect(); } printl("\n --- test without EXO_DICT ---\n"); if (true) { printl("\n --- connect to the specific database (although not used for dict here) ---\n"); printl("\n --- say that dicts are on the default database ---\n"); assert(ossetenv("EXO_DICT", "")); assert(var(osgetenv("EXO_DICT")) eq ""); printl("\n --- needed to remove default dict connection ---\n"); disconnectall(); printl("\n --- specific connection to the dic database ---\n"); assert(xo_dict_conn.connect(xo_dict)); printl("\n --- create a dict on the default database implicitly ---\n"); assert(createfile(dict_xo_test)); printl("\n --- ensure new dict IS on the right database implicitly ---\n"); var dicttest; assert(dicttest.open(dict_xo_test)); printl("\n --- ensure new dict IS on the right database specifically ---\n"); var dicttest2; assert(dicttest2.open(dict_xo_test, default_conn)); printl("\n --- ensure dict IS NOT on the test database ---\n"); var dicttest3; assert(not dicttest3.open(dict_xo_test, xo_dict_conn)); printl("\n --- delete the dict on the default database implicitly ---\n"); assert(deletefile(dict_xo_test)); printl("\n --- ensure new dict IS NO LONGER on the default database implicitly ---\n"); var dicttest4; assert(not dicttest4.open(dict_xo_test)); printl("\n --- ensure new dict IS NO LONGER on the default database specifically ---\n"); var dicttest5; assert(not dicttest5.open(dict_xo_test, default_conn)); printl("\n --- ensure new dict IS NO LONGER on the special database ---\n"); var dicttest6; assert(not dicttest6.open(dict_xo_test, xo_dict_conn)); printl("\n --- disconnect specific connection ---\n"); xo_dict_conn.disconnect(); } gosub cleanup(); printl(elapsedtimetext()); printl("\nTest passed"); return 0; } subroutine cleanup() { dbdelete(xo_dict); printl("\n --- delete the dict file from the default connection just in case, to be clean ---\n"); default_conn.deletefile(dict_xo_test); } programexit() <|endoftext|>
<commit_before>#include "PackTexture.h" #include "check_params.h" #include <drag2d.h> #include <easytexpacker.h> namespace edb { std::string PackTexture::Command() const { return "pack-tex"; } std::string PackTexture::Description() const { return "pack texture"; } std::string PackTexture::Usage() const { std::string cmd0 = Command() + " [cfg file]"; std::string cmd1 = Command() + " [src dir] [dst dir] [min size] [max size]"; return cmd0 + " or " + cmd1; } void PackTexture::Run(int argc, char *argv[]) { if (!check_number(this, argc, 3)) return; if (argc == 3) { RunFromConfig(argv[2]); } else { RunFromCmd(NULL, argv[2], argv[3], -1, atof(argv[5]), atof(argv[4]), 1, 1); } } void PackTexture::RunFromConfig(const std::string& cfg_file) { Json::Value value; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(cfg_file.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, value); fin.close(); std::string dir = d2d::FilenameTools::getFileDir(cfg_file); std::string src_dir = d2d::FilenameTools::getAbsolutePath(dir, value["src"].asString()); std::string dst_file = d2d::FilenameTools::getAbsolutePath(dir, value["dst"].asString()); libtexpacker::ImageTrimData* trim = NULL; if (!value["trim file"].isNull()) { std::string trim_file = d2d::FilenameTools::getAbsolutePath(dir, value["trim file"].asString()); trim = new libtexpacker::ImageTrimData(trim_file); } int static_size = value["static size"].asInt(), max_size = value["max size"].asInt(), min_size = value["min size"].asInt(); int extrude_min = value["extrude min"].asInt(), extrude_max = value["extrude max"].asInt(); RunFromCmd(trim, src_dir, dst_file, static_size, max_size, min_size, extrude_min, extrude_max); delete trim; } void PackTexture::RunFromCmd(libtexpacker::ImageTrimData* trim, const std::string& src_dir, const std::string& dst_file, int static_size, int max_size, int min_size, int extrude_min, int extrude_max) { std::vector<std::string> images; wxArrayString files; d2d::FilenameTools::fetchAllFiles(src_dir, files); for (int i = 0, n = files.size(); i < n; ++i) { if (d2d::FileNameParser::isType(files[i], d2d::FileNameParser::e_image)) { std::string filepath = d2d::FilenameTools::FormatFilepathAbsolute(files[i].ToStdString()); images.push_back(filepath); } } std::string dst_dir = d2d::FilenameTools::getFileDir(dst_file); d2d::mk_dir(dst_dir); d2d::SettingData& sd = d2d::Config::Instance()->GetSettings(); bool ori_cfg = sd.open_image_edge_clip; sd.open_image_edge_clip = false; libtexpacker::NormalPack tex_packer(images, trim, extrude_min, extrude_max); tex_packer.Pack(static_size, max_size, min_size); tex_packer.OutputInfo(src_dir, dst_file + ".json"); tex_packer.OutputImage(dst_file + ".png"); sd.open_image_edge_clip = ori_cfg; } }<commit_msg>[FIXED] tp传trim file参数<commit_after>#include "PackTexture.h" #include "check_params.h" #include <drag2d.h> #include <easytexpacker.h> namespace edb { std::string PackTexture::Command() const { return "pack-tex"; } std::string PackTexture::Description() const { return "pack texture"; } std::string PackTexture::Usage() const { std::string cmd0 = Command() + " [cfg file]"; std::string cmd1 = Command() + " [src dir] [dst dir] [min size] [max size] [trim file]"; return cmd0 + " or " + cmd1; } void PackTexture::Run(int argc, char *argv[]) { if (!check_number(this, argc, 3)) return; if (argc == 3) { RunFromConfig(argv[2]); } else { libtexpacker::ImageTrimData* trim = NULL; if (argc > 6) { trim = new libtexpacker::ImageTrimData(argv[6]); } RunFromCmd(trim, argv[2], argv[3], -1, atof(argv[5]), atof(argv[4]), 1, 1); } } void PackTexture::RunFromConfig(const std::string& cfg_file) { Json::Value value; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(cfg_file.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, value); fin.close(); std::string dir = d2d::FilenameTools::getFileDir(cfg_file); std::string src_dir = d2d::FilenameTools::getAbsolutePath(dir, value["src"].asString()); std::string dst_file = d2d::FilenameTools::getAbsolutePath(dir, value["dst"].asString()); libtexpacker::ImageTrimData* trim = NULL; if (!value["trim file"].isNull()) { std::string trim_file = d2d::FilenameTools::getAbsolutePath(dir, value["trim file"].asString()); trim = new libtexpacker::ImageTrimData(trim_file); } int static_size = value["static size"].asInt(), max_size = value["max size"].asInt(), min_size = value["min size"].asInt(); int extrude_min = value["extrude min"].asInt(), extrude_max = value["extrude max"].asInt(); RunFromCmd(trim, src_dir, dst_file, static_size, max_size, min_size, extrude_min, extrude_max); delete trim; } void PackTexture::RunFromCmd(libtexpacker::ImageTrimData* trim, const std::string& src_dir, const std::string& dst_file, int static_size, int max_size, int min_size, int extrude_min, int extrude_max) { std::vector<std::string> images; wxArrayString files; d2d::FilenameTools::fetchAllFiles(src_dir, files); for (int i = 0, n = files.size(); i < n; ++i) { if (d2d::FileNameParser::isType(files[i], d2d::FileNameParser::e_image)) { std::string filepath = d2d::FilenameTools::FormatFilepathAbsolute(files[i].ToStdString()); images.push_back(filepath); } } std::string dst_dir = d2d::FilenameTools::getFileDir(dst_file); d2d::mk_dir(dst_dir); d2d::SettingData& sd = d2d::Config::Instance()->GetSettings(); bool ori_cfg = sd.open_image_edge_clip; sd.open_image_edge_clip = false; libtexpacker::NormalPack tex_packer(images, trim, extrude_min, extrude_max); tex_packer.Pack(static_size, max_size, min_size); tex_packer.OutputInfo(src_dir, dst_file + ".json"); tex_packer.OutputImage(dst_file + ".png"); sd.open_image_edge_clip = ori_cfg; } }<|endoftext|>
<commit_before>/* * Copyright 2015 Twitter, 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 <iostream> #include <thread> #include <vector> #include <chrono> #include "network/unittests.pb.h" #include "network/host_unittest.h" #include "network/client_unittest.h" #include "network/server_unittest.h" #include "gtest/gtest.h" #include "basics/basics.h" #include "errors/errors.h" #include "threads/threads.h" #include "threads/spcountdownlatch.h" #include "network/network.h" #include "basics/modinit.h" #include "errors/modinit.h" #include "threads/modinit.h" #include "network/modinit.h" class Terminate : public Client { public: Terminate(EventLoopImpl* eventLoop, const NetworkOptions& _options) : Client(eventLoop, _options) { // Setup the call back function to be invoked when retrying retry_cb_ = [this]() { this->Retry(); }; } ~Terminate() {} protected: void Retry() { Start(); } virtual void HandleConnect(NetworkErrorCode _status) { if (_status == OK) { TerminateMessage message; SendMessage(message); return; } AddTimer(retry_cb_, 1000); } virtual void HandleClose(NetworkErrorCode) { Stop(); getEventLoop()->loopExit(); } private: VCallback<> retry_cb_; }; static TestServer* server_; void start_server(sp_uint32* port, CountDownLatch* latch) { NetworkOptions options; options.set_host(LOCALHOST); options.set_port(*port); options.set_max_packet_size(1024 * 1024); options.set_socket_family(PF_INET); EventLoopImpl ss; server_ = new TestServer(&ss, options); EXPECT_EQ(0, server_->get_serveroptions().get_port()); if (server_->Start() != 0) GTEST_FAIL(); *port = server_->get_serveroptions().get_port(); latch->countDown(); ss.loop(); } void start_client(sp_uint32 port, sp_uint64 requests) { NetworkOptions options; options.set_host(LOCALHOST); options.set_port(port); options.set_max_packet_size(1024 * 1024); options.set_socket_family(PF_INET); EventLoopImpl ss; TestClient client(&ss, options, requests); client.Start(); ss.loop(); } void terminate_server(sp_uint32 port) { NetworkOptions options; options.set_host(LOCALHOST); options.set_port(port); options.set_max_packet_size(1024 * 1024); options.set_socket_family(PF_INET); EventLoopImpl ss; Terminate ts(&ss, options); ts.Start(); ss.loop(); } void start_test(sp_int32 nclients, sp_uint64 requests) { sp_uint32 server_port = 0; CountDownLatch* latch = new CountDownLatch(1); // start the server thread std::thread sthread(start_server, &server_port, latch); latch->wait(); std::cout << "server port " << server_port << std::endl; auto start = std::chrono::high_resolution_clock::now(); // start the client threads std::vector<std::thread> cthreads; for (sp_int32 i = 0; i < nclients; i++) { cthreads.push_back(std::thread(start_client, server_port, requests)); } // wait for the client threads to terminate for (auto& thread : cthreads) { thread.join(); } auto stop = std::chrono::high_resolution_clock::now(); // now send a terminate message to server terminate_server(server_port); sthread.join(); ASSERT_TRUE(server_->sent_pkts() == server_->recv_pkts()); ASSERT_TRUE(server_->sent_pkts() == nclients * requests); std::cout << nclients << " client(s) exchanged a total of " << requests << " in " << std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count() << " ms." << std::endl; delete server_; } TEST(NetworkTest, test_switch_1) { start_test(1, 100); } TEST(NetworkTest, test_switch_2) { start_test(1, 1000); } TEST(NetworkTest, test_switch_3) { start_test(1, 10000); } int main(int argc, char** argv) { heron::common::Initialize(argv[0]); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>delete latch<commit_after>/* * Copyright 2015 Twitter, 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 <iostream> #include <thread> #include <vector> #include <chrono> #include "network/unittests.pb.h" #include "network/host_unittest.h" #include "network/client_unittest.h" #include "network/server_unittest.h" #include "gtest/gtest.h" #include "basics/basics.h" #include "errors/errors.h" #include "threads/threads.h" #include "threads/spcountdownlatch.h" #include "network/network.h" #include "basics/modinit.h" #include "errors/modinit.h" #include "threads/modinit.h" #include "network/modinit.h" class Terminate : public Client { public: Terminate(EventLoopImpl* eventLoop, const NetworkOptions& _options) : Client(eventLoop, _options) { // Setup the call back function to be invoked when retrying retry_cb_ = [this]() { this->Retry(); }; } ~Terminate() {} protected: void Retry() { Start(); } virtual void HandleConnect(NetworkErrorCode _status) { if (_status == OK) { TerminateMessage message; SendMessage(message); return; } AddTimer(retry_cb_, 1000); } virtual void HandleClose(NetworkErrorCode) { Stop(); getEventLoop()->loopExit(); } private: VCallback<> retry_cb_; }; static TestServer* server_; void start_server(sp_uint32* port, CountDownLatch* latch) { NetworkOptions options; options.set_host(LOCALHOST); options.set_port(*port); options.set_max_packet_size(1024 * 1024); options.set_socket_family(PF_INET); EventLoopImpl ss; server_ = new TestServer(&ss, options); EXPECT_EQ(0, server_->get_serveroptions().get_port()); if (server_->Start() != 0) GTEST_FAIL(); *port = server_->get_serveroptions().get_port(); latch->countDown(); ss.loop(); } void start_client(sp_uint32 port, sp_uint64 requests) { NetworkOptions options; options.set_host(LOCALHOST); options.set_port(port); options.set_max_packet_size(1024 * 1024); options.set_socket_family(PF_INET); EventLoopImpl ss; TestClient client(&ss, options, requests); client.Start(); ss.loop(); } void terminate_server(sp_uint32 port) { NetworkOptions options; options.set_host(LOCALHOST); options.set_port(port); options.set_max_packet_size(1024 * 1024); options.set_socket_family(PF_INET); EventLoopImpl ss; Terminate ts(&ss, options); ts.Start(); ss.loop(); } void start_test(sp_int32 nclients, sp_uint64 requests) { sp_uint32 server_port = 0; CountDownLatch* latch = new CountDownLatch(1); // start the server thread std::thread sthread(start_server, &server_port, latch); latch->wait(); std::cout << "server port " << server_port << std::endl; auto start = std::chrono::high_resolution_clock::now(); // start the client threads std::vector<std::thread> cthreads; for (sp_int32 i = 0; i < nclients; i++) { cthreads.push_back(std::thread(start_client, server_port, requests)); } // wait for the client threads to terminate for (auto& thread : cthreads) { thread.join(); } auto stop = std::chrono::high_resolution_clock::now(); // now send a terminate message to server terminate_server(server_port); sthread.join(); ASSERT_TRUE(server_->sent_pkts() == server_->recv_pkts()); ASSERT_TRUE(server_->sent_pkts() == nclients * requests); std::cout << nclients << " client(s) exchanged a total of " << requests << " in " << std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count() << " ms." << std::endl; delete server_; delete latch; } TEST(NetworkTest, test_switch_1) { start_test(1, 100); } TEST(NetworkTest, test_switch_2) { start_test(1, 1000); } TEST(NetworkTest, test_switch_3) { start_test(1, 10000); } int main(int argc, char** argv) { heron::common::Initialize(argv[0]); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: localedatawrapper.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: er $ $Date: 2000-11-04 21:46:24 $ * * 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 _UNOTOOLS_LOCALEDATAWRAPPER_HXX #define _UNOTOOLS_LOCALEDATAWRAPPER_HXX #ifndef _TOOLS_INTN_HXX #include <tools/intn.hxx> // enum MeasurementSystem #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _COM_SUN_STAR_I18N_XLOCALEDATA_HPP_ #include <com/sun/star/i18n/XLocaleData.hpp> #endif #ifndef _COM_SUN_STAR_I18N_LOCALEITEM_HPP_ #include <com/sun/star/i18n/LocaleItem.hpp> #endif #ifndef _COM_SUN_STAR_I18N_RESERVEDWORDS_HPP_ #include <com/sun/star/i18n/reservedWords.hpp> #endif namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } }}} class LocaleDataWrapper { ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xSMgr; ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XLocaleData > xLD; ::com::sun::star::lang::Locale aLocale; ::com::sun::star::i18n::LocaleDataItem aLocaleDataItem; ::com::sun::star::uno::Sequence< ::rtl::OUString > aReservedWordSeq; // cached items String aLocaleItem[::com::sun::star::i18n::LocaleItem::COUNT]; String aReservedWord[::com::sun::star::i18n::reservedWords::COUNT]; String aCurrSymbol; String aCurrBankSymbol; USHORT nCurrPositiveFormat; USHORT nCurrNegativeFormat; USHORT nCurrDigits; BOOL bLocaleDataItemValid; BOOL bReservedWordValid; // dummies, to be implemented or provided by XML locale data String aLongDateDayOfWeekSep; sal_Unicode cCurrZeroChar; // not implemented, prevent usage LocaleDataWrapper( const LocaleDataWrapper& ); LocaleDataWrapper& operator=( const LocaleDataWrapper& ); // whenever Locale changes void invalidateData(); void getOneLocaleItemImpl( sal_Int16 nItem ); const String& getOneLocaleItem( sal_Int16 nItem ) const; void getOneReservedWordImpl( sal_Int16 nWord ); const String& getOneReservedWord( sal_Int16 nWord ) const; void getCurrSymbolsImpl(); void getCurrFormatsImpl(); void scanCurrFormat( const String& rCode, xub_StrLen nStart, xub_StrLen& nSign, xub_StrLen& nPar, xub_StrLen& nNum, xub_StrLen& nBlank, xub_StrLen& nSym ); public: LocaleDataWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSF, const ::com::sun::star::lang::Locale& rLocale ); ~LocaleDataWrapper(); /// set a new Locale to request void setLocale( const ::com::sun::star::lang::Locale& rLocale ); /// get current requested Locale const ::com::sun::star::lang::Locale& getLocale() const { return aLocale; } /// get current loaded Locale, which might differ from the requested Locale ::com::sun::star::lang::Locale getLoadedLocale() const; // Wrapper implementations of class LocaleData ::com::sun::star::i18n::LanguageCountryInfo getLanguageCountryInfo() const; ::com::sun::star::i18n::LocaleDataItem getLocaleItem() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Calendar > getAllCalendars() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Currency > getAllCurrencies() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::FormatElement > getAllFormats() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Implementation > getCollatorImplementations() const; ::com::sun::star::uno::Sequence< ::rtl::OUString > getTransliterations() const; ::com::sun::star::i18n::ForbiddenCharacters getForbiddenCharacters() const; ::com::sun::star::uno::Sequence< ::rtl::OUString > getReservedWord() const; /// maps the LocaleData string to the International enum MeasurementSystem mapMeasurementStringToEnum( const String& rMS ) const; // Functionality of class International methods, LocaleItem inline const String& getDateSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DATE_SEPARATOR ); } inline const String& getNumThousandSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::THOUSAND_SEPARATOR ); } inline const String& getNumDecimalSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DECIMAL_SEPARATOR ); } inline const String& getTimeSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_SEPARATOR ); } inline const String& getTime100SecSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_100SEC_SEPARATOR ); } inline const String& getListSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LIST_SEPARATOR ); } inline const String& getQuotationMarkStart() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::SINGLE_QUOTATION_START ); } inline const String& getQuotationMarkEnd() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::SINGLE_QUOTATION_END ); } inline const String& getDoubleQuotationMarkStart() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DOUBLE_QUOTATION_START ); } inline const String& getDoubleQuotationMarkEnd() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DOUBLE_QUOTATION_END ); } inline const String& getMeasurementSystem() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::MEASUREMENT_SYSTEM ); } inline MeasurementSystem getMeasurementSystemEnum() const { return mapMeasurementStringToEnum( getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::MEASUREMENT_SYSTEM ) ); } inline const String& getTimeAM() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_AM ); } inline const String& getTimePM() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_PM ); } const String& getCurrSymbol() const; const String& getCurrBankSymbol() const; USHORT getCurrPositiveFormat() const; USHORT getCurrNegativeFormat() const; USHORT getCurrDigits() const; // dummy returns inline const String& getLongDateDayOfWeekSep() const { return aLongDateDayOfWeekSep; } inline sal_Unicode getCurrZeroChar() const { return cCurrZeroChar; } // reserved words inline const String& getTrueWord() const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::TRUE_WORD ); } inline const String& getFalseWord() const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::FALSE_WORD ); } #ifndef PRODUCT ByteString& AppendLocaleInfo( ByteString& rDebugMsg ) const; #endif }; #endif // _UNOTOOLS_LOCALEDATAWRAPPER_HXX <commit_msg>add: getLongDate separators, getDateFormat, getQuarterWord<commit_after>/************************************************************************* * * $RCSfile: localedatawrapper.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: er $ $Date: 2000-11-18 18:53:10 $ * * 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 _UNOTOOLS_LOCALEDATAWRAPPER_HXX #define _UNOTOOLS_LOCALEDATAWRAPPER_HXX #ifndef _TOOLS_INTN_HXX #include <tools/intn.hxx> // enum MeasurementSystem, enum DateFormat #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _COM_SUN_STAR_I18N_XLOCALEDATA_HPP_ #include <com/sun/star/i18n/XLocaleData.hpp> #endif #ifndef _COM_SUN_STAR_I18N_LOCALEITEM_HPP_ #include <com/sun/star/i18n/LocaleItem.hpp> #endif #ifndef _COM_SUN_STAR_I18N_RESERVEDWORDS_HPP_ #include <com/sun/star/i18n/reservedWords.hpp> #endif namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } }}} class LocaleDataWrapper { ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xSMgr; ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XLocaleData > xLD; ::com::sun::star::lang::Locale aLocale; ::com::sun::star::i18n::LocaleDataItem aLocaleDataItem; ::com::sun::star::uno::Sequence< ::rtl::OUString > aReservedWordSeq; // cached items String aLocaleItem[::com::sun::star::i18n::LocaleItem::COUNT]; String aReservedWord[::com::sun::star::i18n::reservedWords::COUNT]; String aCurrSymbol; String aCurrBankSymbol; int nDateFormat; int nLongDateFormat; USHORT nCurrPositiveFormat; USHORT nCurrNegativeFormat; USHORT nCurrDigits; BOOL bLocaleDataItemValid; BOOL bReservedWordValid; // dummies, to be implemented or provided by XML locale data sal_Unicode cCurrZeroChar; // not implemented, prevent usage LocaleDataWrapper( const LocaleDataWrapper& ); LocaleDataWrapper& operator=( const LocaleDataWrapper& ); // whenever Locale changes void invalidateData(); void getOneLocaleItemImpl( sal_Int16 nItem ); const String& getOneLocaleItem( sal_Int16 nItem ) const; void getOneReservedWordImpl( sal_Int16 nWord ); const String& getOneReservedWord( sal_Int16 nWord ) const; void getCurrSymbolsImpl(); void getCurrFormatsImpl(); void scanCurrFormat( const String& rCode, xub_StrLen nStart, xub_StrLen& nSign, xub_StrLen& nPar, xub_StrLen& nNum, xub_StrLen& nBlank, xub_StrLen& nSym ); void getDateFormatsImpl(); DateFormat scanDateFormat( const String& rCode ); public: LocaleDataWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSF, const ::com::sun::star::lang::Locale& rLocale ); ~LocaleDataWrapper(); /// set a new Locale to request void setLocale( const ::com::sun::star::lang::Locale& rLocale ); /// get current requested Locale const ::com::sun::star::lang::Locale& getLocale() const { return aLocale; } /// get current loaded Locale, which might differ from the requested Locale ::com::sun::star::lang::Locale getLoadedLocale() const; // Wrapper implementations of class LocaleData ::com::sun::star::i18n::LanguageCountryInfo getLanguageCountryInfo() const; ::com::sun::star::i18n::LocaleDataItem getLocaleItem() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Calendar > getAllCalendars() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Currency > getAllCurrencies() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::FormatElement > getAllFormats() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Implementation > getCollatorImplementations() const; ::com::sun::star::uno::Sequence< ::rtl::OUString > getTransliterations() const; ::com::sun::star::i18n::ForbiddenCharacters getForbiddenCharacters() const; ::com::sun::star::uno::Sequence< ::rtl::OUString > getReservedWord() const; /// maps the LocaleData string to the International enum MeasurementSystem mapMeasurementStringToEnum( const String& rMS ) const; // Functionality of class International methods, LocaleItem inline const String& getDateSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DATE_SEPARATOR ); } inline const String& getNumThousandSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::THOUSAND_SEPARATOR ); } inline const String& getNumDecimalSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DECIMAL_SEPARATOR ); } inline const String& getTimeSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_SEPARATOR ); } inline const String& getTime100SecSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_100SEC_SEPARATOR ); } inline const String& getListSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LIST_SEPARATOR ); } inline const String& getQuotationMarkStart() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::SINGLE_QUOTATION_START ); } inline const String& getQuotationMarkEnd() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::SINGLE_QUOTATION_END ); } inline const String& getDoubleQuotationMarkStart() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DOUBLE_QUOTATION_START ); } inline const String& getDoubleQuotationMarkEnd() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DOUBLE_QUOTATION_END ); } inline const String& getMeasurementSystem() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::MEASUREMENT_SYSTEM ); } inline MeasurementSystem getMeasurementSystemEnum() const { return mapMeasurementStringToEnum( getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::MEASUREMENT_SYSTEM ) ); } inline const String& getTimeAM() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_AM ); } inline const String& getTimePM() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_PM ); } inline const String& getLongDateDayOfWeekSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LONG_DATE_DAY_OF_WEEK_SEPARATOR ); } inline const String& getLongDateDaySep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LONG_DATE_DAY_SEPARATOR ); } inline const String& getLongDateMonthSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LONG_DATE_MONTH_SEPARATOR ); } inline const String& getLongDateYearSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LONG_DATE_YEAR_SEPARATOR ); } const String& getCurrSymbol() const; const String& getCurrBankSymbol() const; USHORT getCurrPositiveFormat() const; USHORT getCurrNegativeFormat() const; USHORT getCurrDigits() const; DateFormat getDateFormat() const; DateFormat getLongDateFormat() const; // dummy returns inline sal_Unicode getCurrZeroChar() const { return cCurrZeroChar; } // reserved words inline const String& getTrueWord() const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::TRUE_WORD ); } inline const String& getFalseWord() const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::FALSE_WORD ); } inline const String& getQuarterWord() const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::QUARTER_WORD ); } #ifndef PRODUCT ByteString& AppendLocaleInfo( ByteString& rDebugMsg ) const; #endif }; #endif // _UNOTOOLS_LOCALEDATAWRAPPER_HXX <|endoftext|>
<commit_before><commit_msg>Fixed: Fail on HTTP codes >=400<commit_after><|endoftext|>
<commit_before>/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION 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 "http/server/Public.hxx" #include "http/server/Handler.hxx" #include "http/IncomingRequest.hxx" #include "http/Client.hxx" #include "http/Headers.hxx" #include "http/ResponseHandler.hxx" #include "lease.hxx" #include "PInstance.hxx" #include "pool/pool.hxx" #include "pool/Holder.hxx" #include "pool/UniquePtr.hxx" #include "istream/UnusedPtr.hxx" #include "istream/UnusedHoldPtr.hxx" #include "istream/HeadIstream.hxx" #include "istream/BlockIstream.hxx" #include "istream/ZeroIstream.hxx" #include "istream/istream_string.hxx" #include "istream/Sink.hxx" #include "memory/fb_pool.hxx" #include "fs/FilteredSocket.hxx" #include "event/FineTimerEvent.hxx" #include "net/UniqueSocketDescriptor.hxx" #include "system/Error.hxx" #include "io/SpliceSupport.hxx" #include "util/Cancellable.hxx" #include "util/PrintException.hxx" #include "util/RuntimeError.hxx" #include "stopwatch.hxx" #include <functional> #include <stdio.h> #include <stdlib.h> class Server final : PoolHolder, HttpServerConnectionHandler, HttpServerRequestHandler, Lease, BufferedSocketHandler { HttpServerConnection *connection = nullptr; std::function<void(IncomingHttpRequest &request, CancellablePointer &cancel_ptr)> request_handler; FilteredSocket client_fs; bool client_fs_released = false; public: Server(struct pool &_pool, EventLoop &event_loop); ~Server() noexcept { CloseClientSocket(); CheckCloseConnection(); } using PoolHolder::GetPool; auto &GetEventLoop() noexcept { return client_fs.GetEventLoop(); } template<typename T> void SetRequestHandler(T &&handler) noexcept { request_handler = std::forward<T>(handler); } void CloseConnection() noexcept { http_server_connection_close(connection); connection = nullptr; } void CheckCloseConnection() noexcept { if (connection != nullptr) CloseConnection(); } void SendRequest(http_method_t method, const char *uri, const StringMap &headers, UnusedIstreamPtr body, bool expect_100, HttpResponseHandler &handler, CancellablePointer &cancel_ptr) noexcept { http_client_request(*pool, nullptr, client_fs, *this, "foo", method, uri, headers, {}, std::move(body), expect_100, handler, cancel_ptr); } void CloseClientSocket() noexcept { if (client_fs.IsValid() && client_fs.IsConnected()) { client_fs.Close(); client_fs.Destroy(); } } private: /* virtual methods from class HttpServerConnectionHandler */ void HandleHttpRequest(IncomingHttpRequest &request, const StopwatchPtr &parent_stopwatch, CancellablePointer &cancel_ptr) noexcept override; void HttpConnectionError(std::exception_ptr e) noexcept override; void HttpConnectionClosed() noexcept override; /* virtual methods from class Lease */ void ReleaseLease(bool reuse) noexcept override { client_fs_released = true; if (reuse && client_fs.IsValid() && client_fs.IsConnected()) { client_fs.Reinit(Event::Duration(-1), Event::Duration(-1), *this); client_fs.UnscheduleWrite(); } else { CloseClientSocket(); } } /* virtual methods from class BufferedSocketHandler */ BufferedResult OnBufferedData() override { fprintf(stderr, "unexpected data in idle TCP connection"); CloseClientSocket(); return BufferedResult::CLOSED; } bool OnBufferedClosed() noexcept override { CloseClientSocket(); return false; } gcc_noreturn bool OnBufferedWrite() override { /* should never be reached because we never schedule writing */ gcc_unreachable(); } void OnBufferedError(std::exception_ptr e) noexcept override { PrintException(e); CloseClientSocket(); } }; class Client final : HttpResponseHandler, IstreamSink { CancellablePointer client_cancel_ptr; std::exception_ptr response_error; std::string response_body; http_status_t status{}; bool response_eof = false; public: void SendRequest(Server &server, http_method_t method, const char *uri, const StringMap &headers, UnusedIstreamPtr body, bool expect_100=false) noexcept { server.SendRequest(method, uri, headers, std::move(body), expect_100, *this, client_cancel_ptr); } bool IsClientDone() const noexcept { return response_error || response_eof; } void WaitDone(Server &server) { auto &event_loop = server.GetEventLoop(); while (!IsClientDone()) event_loop.LoopOnce(); } void RethrowResponseError() const { if (response_error) std::rethrow_exception(response_error); } void ExpectResponse(Server &server, http_status_t expected_status, const char *expected_body) { WaitDone(server); RethrowResponseError(); if (status != expected_status) throw FormatRuntimeError("Got status %d, expected %d\n", int(status), int(expected_status)); if (response_body != expected_body) throw FormatRuntimeError("Got response body '%s', expected '%s'\n", response_body.c_str(), expected_body); } private: /* virtual methods from class HttpResponseHandler */ void OnHttpResponse(http_status_t _status, StringMap &&headers, UnusedIstreamPtr body) noexcept override { status = _status; (void)headers; IstreamSink::SetInput(std::move(body)); input.Read(); } void OnHttpError(std::exception_ptr ep) noexcept override { response_error = std::move(ep); } /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) noexcept override { response_body.append((const char *)data, length); return length; } void OnEof() noexcept override { IstreamSink::ClearInput(); response_eof = true; } void OnError(std::exception_ptr ep) noexcept override { IstreamSink::ClearInput(); response_error = std::move(ep); } }; Server::Server(struct pool &_pool, EventLoop &event_loop) :PoolHolder(pool_new_libc(&_pool, "catch")), client_fs(event_loop) { UniqueSocketDescriptor client_socket, server_socket; if (!UniqueSocketDescriptor::CreateSocketPair(AF_LOCAL, SOCK_STREAM, 0, client_socket, server_socket)) throw MakeErrno("socketpair() failed"); connection = http_server_connection_new(pool, UniquePoolPtr<FilteredSocket>::Make(pool, event_loop, std::move(server_socket), FdType::FD_SOCKET), nullptr, nullptr, true, *this, *this); client_fs.InitDummy(client_socket.Release(), FdType::FD_SOCKET); } void Server::HandleHttpRequest(IncomingHttpRequest &request, const StopwatchPtr &, CancellablePointer &cancel_ptr) noexcept { request_handler(request, cancel_ptr); } void Server::HttpConnectionError(std::exception_ptr e) noexcept { connection = nullptr; PrintException(e); } void Server::HttpConnectionClosed() noexcept { connection = nullptr; } static void TestSimple(Server &server) { server.SetRequestHandler([](IncomingHttpRequest &request, CancellablePointer &) noexcept { request.SendResponse(HTTP_STATUS_OK, {}, istream_string_new(request.pool, "foo")); }); Client client; client.SendRequest(server, HTTP_METHOD_GET, "/", {}, nullptr); client.ExpectResponse(server, HTTP_STATUS_OK, "foo"); } static void TestMirror(Server &server) { server.SetRequestHandler([](IncomingHttpRequest &request, CancellablePointer &) noexcept { request.SendResponse(HTTP_STATUS_OK, {}, std::move(request.body)); }); Client client; client.SendRequest(server, HTTP_METHOD_POST, "/", {}, istream_string_new(server.GetPool(), "foo")); client.ExpectResponse(server, HTTP_STATUS_OK, "foo"); } static void TestDiscardTinyRequestBody(Server &server) { server.SetRequestHandler([](IncomingHttpRequest &request, CancellablePointer &) noexcept { request.body.Clear(); request.SendResponse(HTTP_STATUS_OK, {}, istream_string_new(request.pool, "foo")); }); Client client; client.SendRequest(server, HTTP_METHOD_POST, "/", {}, istream_string_new(server.GetPool(), "foo")); client.ExpectResponse(server, HTTP_STATUS_OK, "foo"); } /** * Send a huge request body which will be discarded by the server; the * server then disables keepalive, sends the response and closes the * connection. */ static void TestDiscardedHugeRequestBody(Server &server) { class RespondLater { FineTimerEvent timer; IncomingHttpRequest *request; UnusedHoldIstreamPtr body; public: explicit RespondLater(EventLoop &event_loop) noexcept :timer(event_loop, BIND_THIS_METHOD(OnTimer)) {} void Schedule(IncomingHttpRequest &_request) noexcept { request = &_request; body = UnusedHoldIstreamPtr(request->pool, std::move(request->body)); timer.Schedule(std::chrono::milliseconds(10)); } private: void OnTimer() noexcept { body.Clear(); request->SendResponse(HTTP_STATUS_OK, {}, istream_string_new(request->pool, "foo")); } } respond_later(server.GetEventLoop()); server.SetRequestHandler([&respond_later](IncomingHttpRequest &request, CancellablePointer &) noexcept { respond_later.Schedule(request); }); Client client; client.SendRequest(server, HTTP_METHOD_POST, "/", {}, istream_zero_new(server.GetPool())); client.ExpectResponse(server, HTTP_STATUS_OK, "foo"); } int main(int argc, char **argv) noexcept try { (void)argc; (void)argv; direct_global_init(); const ScopeFbPoolInit fb_pool_init; PInstance instance; { Server server(instance.root_pool, instance.event_loop); TestSimple(server); TestMirror(server); TestDiscardTinyRequestBody(server); TestDiscardedHugeRequestBody(server); server.CloseClientSocket(); instance.event_loop.Dispatch(); } } catch (...) { PrintException(std::current_exception()); return EXIT_FAILURE; } <commit_msg>test/t_http_server: add buffered mirror test<commit_after>/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION 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 "http/server/Public.hxx" #include "http/server/Handler.hxx" #include "http/IncomingRequest.hxx" #include "http/Client.hxx" #include "http/Headers.hxx" #include "http/ResponseHandler.hxx" #include "lease.hxx" #include "PInstance.hxx" #include "pool/pool.hxx" #include "pool/Holder.hxx" #include "pool/UniquePtr.hxx" #include "istream/UnusedPtr.hxx" #include "istream/UnusedHoldPtr.hxx" #include "istream/HeadIstream.hxx" #include "istream/BlockIstream.hxx" #include "istream/ZeroIstream.hxx" #include "istream/istream_string.hxx" #include "istream/Sink.hxx" #include "memory/fb_pool.hxx" #include "memory/GrowingBuffer.hxx" #include "memory/SinkGrowingBuffer.hxx" #include "memory/istream_gb.hxx" #include "fs/FilteredSocket.hxx" #include "event/FineTimerEvent.hxx" #include "net/UniqueSocketDescriptor.hxx" #include "system/Error.hxx" #include "io/SpliceSupport.hxx" #include "util/Cancellable.hxx" #include "util/Exception.hxx" #include "util/PrintException.hxx" #include "util/RuntimeError.hxx" #include "stopwatch.hxx" #include <functional> #include <stdio.h> #include <stdlib.h> class Server final : PoolHolder, HttpServerConnectionHandler, HttpServerRequestHandler, Lease, BufferedSocketHandler { HttpServerConnection *connection = nullptr; std::function<void(IncomingHttpRequest &request, CancellablePointer &cancel_ptr)> request_handler; FilteredSocket client_fs; bool client_fs_released = false; public: Server(struct pool &_pool, EventLoop &event_loop); ~Server() noexcept { CloseClientSocket(); CheckCloseConnection(); } using PoolHolder::GetPool; auto &GetEventLoop() noexcept { return client_fs.GetEventLoop(); } template<typename T> void SetRequestHandler(T &&handler) noexcept { request_handler = std::forward<T>(handler); } void CloseConnection() noexcept { http_server_connection_close(connection); connection = nullptr; } void CheckCloseConnection() noexcept { if (connection != nullptr) CloseConnection(); } void SendRequest(http_method_t method, const char *uri, const StringMap &headers, UnusedIstreamPtr body, bool expect_100, HttpResponseHandler &handler, CancellablePointer &cancel_ptr) noexcept { http_client_request(*pool, nullptr, client_fs, *this, "foo", method, uri, headers, {}, std::move(body), expect_100, handler, cancel_ptr); } void CloseClientSocket() noexcept { if (client_fs.IsValid() && client_fs.IsConnected()) { client_fs.Close(); client_fs.Destroy(); } } private: /* virtual methods from class HttpServerConnectionHandler */ void HandleHttpRequest(IncomingHttpRequest &request, const StopwatchPtr &parent_stopwatch, CancellablePointer &cancel_ptr) noexcept override; void HttpConnectionError(std::exception_ptr e) noexcept override; void HttpConnectionClosed() noexcept override; /* virtual methods from class Lease */ void ReleaseLease(bool reuse) noexcept override { client_fs_released = true; if (reuse && client_fs.IsValid() && client_fs.IsConnected()) { client_fs.Reinit(Event::Duration(-1), Event::Duration(-1), *this); client_fs.UnscheduleWrite(); } else { CloseClientSocket(); } } /* virtual methods from class BufferedSocketHandler */ BufferedResult OnBufferedData() override { fprintf(stderr, "unexpected data in idle TCP connection"); CloseClientSocket(); return BufferedResult::CLOSED; } bool OnBufferedClosed() noexcept override { CloseClientSocket(); return false; } gcc_noreturn bool OnBufferedWrite() override { /* should never be reached because we never schedule writing */ gcc_unreachable(); } void OnBufferedError(std::exception_ptr e) noexcept override { PrintException(e); CloseClientSocket(); } }; class Client final : HttpResponseHandler, IstreamSink { CancellablePointer client_cancel_ptr; std::exception_ptr response_error; std::string response_body; http_status_t status{}; bool response_eof = false; public: void SendRequest(Server &server, http_method_t method, const char *uri, const StringMap &headers, UnusedIstreamPtr body, bool expect_100=false) noexcept { server.SendRequest(method, uri, headers, std::move(body), expect_100, *this, client_cancel_ptr); } bool IsClientDone() const noexcept { return response_error || response_eof; } void WaitDone(Server &server) { auto &event_loop = server.GetEventLoop(); while (!IsClientDone()) event_loop.LoopOnce(); } void RethrowResponseError() const { if (response_error) std::rethrow_exception(response_error); } void ExpectResponse(Server &server, http_status_t expected_status, const char *expected_body) { WaitDone(server); RethrowResponseError(); if (status != expected_status) throw FormatRuntimeError("Got status %d, expected %d\n", int(status), int(expected_status)); if (response_body != expected_body) throw FormatRuntimeError("Got response body '%s', expected '%s'\n", response_body.c_str(), expected_body); } private: /* virtual methods from class HttpResponseHandler */ void OnHttpResponse(http_status_t _status, StringMap &&headers, UnusedIstreamPtr body) noexcept override { status = _status; (void)headers; IstreamSink::SetInput(std::move(body)); input.Read(); } void OnHttpError(std::exception_ptr ep) noexcept override { response_error = std::move(ep); } /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) noexcept override { response_body.append((const char *)data, length); return length; } void OnEof() noexcept override { IstreamSink::ClearInput(); response_eof = true; } void OnError(std::exception_ptr ep) noexcept override { IstreamSink::ClearInput(); response_error = std::move(ep); } }; Server::Server(struct pool &_pool, EventLoop &event_loop) :PoolHolder(pool_new_libc(&_pool, "catch")), client_fs(event_loop) { UniqueSocketDescriptor client_socket, server_socket; if (!UniqueSocketDescriptor::CreateSocketPair(AF_LOCAL, SOCK_STREAM, 0, client_socket, server_socket)) throw MakeErrno("socketpair() failed"); connection = http_server_connection_new(pool, UniquePoolPtr<FilteredSocket>::Make(pool, event_loop, std::move(server_socket), FdType::FD_SOCKET), nullptr, nullptr, true, *this, *this); client_fs.InitDummy(client_socket.Release(), FdType::FD_SOCKET); } void Server::HandleHttpRequest(IncomingHttpRequest &request, const StopwatchPtr &, CancellablePointer &cancel_ptr) noexcept { request_handler(request, cancel_ptr); } void Server::HttpConnectionError(std::exception_ptr e) noexcept { connection = nullptr; PrintException(e); } void Server::HttpConnectionClosed() noexcept { connection = nullptr; } static void TestSimple(Server &server) { server.SetRequestHandler([](IncomingHttpRequest &request, CancellablePointer &) noexcept { request.SendResponse(HTTP_STATUS_OK, {}, istream_string_new(request.pool, "foo")); }); Client client; client.SendRequest(server, HTTP_METHOD_GET, "/", {}, nullptr); client.ExpectResponse(server, HTTP_STATUS_OK, "foo"); } static void TestMirror(Server &server) { server.SetRequestHandler([](IncomingHttpRequest &request, CancellablePointer &) noexcept { request.SendResponse(HTTP_STATUS_OK, {}, std::move(request.body)); }); Client client; client.SendRequest(server, HTTP_METHOD_POST, "/", {}, istream_string_new(server.GetPool(), "foo")); client.ExpectResponse(server, HTTP_STATUS_OK, "foo"); } class BufferedMirror final : GrowingBufferSinkHandler, Cancellable { IncomingHttpRequest &request; GrowingBufferSink sink; public: BufferedMirror(IncomingHttpRequest &_request, CancellablePointer &cancel_ptr) noexcept :request(_request), sink(std::move(request.body), *this) { cancel_ptr = *this; } private: void Destroy() noexcept { this->~BufferedMirror(); } void Cancel() noexcept override { Destroy(); } /* virtual methods from class GrowingBufferSinkHandler */ void OnGrowingBufferSinkEof(GrowingBuffer buffer) noexcept { request.SendResponse(HTTP_STATUS_OK, {}, istream_gb_new(request.pool, std::move(buffer))); } void OnGrowingBufferSinkError(std::exception_ptr error) noexcept { const char *msg = p_strdup(request.pool, GetFullMessage(error).c_str()); request.SendResponse(HTTP_STATUS_INTERNAL_SERVER_ERROR, {}, istream_string_new(request.pool, msg)); } }; static char * RandomString(AllocatorPtr alloc, std::size_t length) noexcept { char *p = alloc.NewArray<char>(length + 1), *q = p; for (std::size_t i = 0; i < length; ++i) *q++ = 'A' + (i % 26); *q = 0; return p; } static void TestBufferedMirror(Server &server) { server.SetRequestHandler([](IncomingHttpRequest &request, CancellablePointer &cancel_ptr) noexcept { NewFromPool<BufferedMirror>(request.pool, request, cancel_ptr); }); char *data = RandomString(server.GetPool(), 65536); Client client; client.SendRequest(server, HTTP_METHOD_POST, "/buffered", {}, istream_string_new(server.GetPool(), data)); client.ExpectResponse(server, HTTP_STATUS_OK, data); } static void TestDiscardTinyRequestBody(Server &server) { server.SetRequestHandler([](IncomingHttpRequest &request, CancellablePointer &) noexcept { request.body.Clear(); request.SendResponse(HTTP_STATUS_OK, {}, istream_string_new(request.pool, "foo")); }); Client client; client.SendRequest(server, HTTP_METHOD_POST, "/", {}, istream_string_new(server.GetPool(), "foo")); client.ExpectResponse(server, HTTP_STATUS_OK, "foo"); } /** * Send a huge request body which will be discarded by the server; the * server then disables keepalive, sends the response and closes the * connection. */ static void TestDiscardedHugeRequestBody(Server &server) { class RespondLater { FineTimerEvent timer; IncomingHttpRequest *request; UnusedHoldIstreamPtr body; public: explicit RespondLater(EventLoop &event_loop) noexcept :timer(event_loop, BIND_THIS_METHOD(OnTimer)) {} void Schedule(IncomingHttpRequest &_request) noexcept { request = &_request; body = UnusedHoldIstreamPtr(request->pool, std::move(request->body)); timer.Schedule(std::chrono::milliseconds(10)); } private: void OnTimer() noexcept { body.Clear(); request->SendResponse(HTTP_STATUS_OK, {}, istream_string_new(request->pool, "foo")); } } respond_later(server.GetEventLoop()); server.SetRequestHandler([&respond_later](IncomingHttpRequest &request, CancellablePointer &) noexcept { respond_later.Schedule(request); }); Client client; client.SendRequest(server, HTTP_METHOD_POST, "/", {}, istream_zero_new(server.GetPool())); client.ExpectResponse(server, HTTP_STATUS_OK, "foo"); } int main(int argc, char **argv) noexcept try { (void)argc; (void)argv; direct_global_init(); const ScopeFbPoolInit fb_pool_init; PInstance instance; { Server server(instance.root_pool, instance.event_loop); TestSimple(server); TestMirror(server); TestBufferedMirror(server); TestDiscardTinyRequestBody(server); TestDiscardedHugeRequestBody(server); server.CloseClientSocket(); instance.event_loop.Dispatch(); } } catch (...) { PrintException(std::current_exception()); return EXIT_FAILURE; } <|endoftext|>
<commit_before>#pragma once #include "includes.hpp" #define TAGLIB_STATIC #include <taglib/fileref.h> #include <taglib/tag.h> #include <taglib/tpropertymap.h> class playlist : public Component, public FileDragAndDropTarget { struct playlistModel : public TableListBoxModel { base::string paths, talbum, tartist, ttitle; std::vector<uint32> tyear, ttrack; std::vector<uint32> paths_i, talbum_i, tartist_i, ttitle_i; // persistent user defined tags map std::map<base::string, std::vector<base::cell>> tags; void init() { paths_i.clear(); // this one first (getNumRows) paths_i.push_back(0); paths.clear(); talbum.clear(); tartist.clear(); tyear.clear(); ttitle.clear(); ttrack.clear(); talbum_i.clear(); talbum_i.push_back(0); tartist_i.clear(); tartist_i.push_back(0); ttitle_i.clear(); ttitle_i.push_back(0); } void addItem(const String &path) { paths.append(path.toStdString()); paths_i.push_back(paths.size()); // read tags from file TagLib::FileRef file(path.toRawUTF8()); if (!file.isNull() && file.tag()) { talbum.append(file.tag()->album().toCString()); tartist.append(file.tag()->artist().toCString()); ttitle.append(file.tag()->title().toCString()); tyear.push_back(file.tag()->year()); ttrack.push_back(file.tag()->track()); } else { tyear.push_back(0); ttrack.push_back(0); } talbum_i.push_back(talbum.size()); tartist_i.push_back(tartist.size()); ttitle_i.push_back(ttitle.size()); } base::string getItemPath(size_t index) { return base::string(paths.begin() + paths_i[index], paths.begin() + paths_i[index + 1]); } uint getItemTrack(size_t index) { return ttrack[index]; } uint getItemYear(size_t index) { return tyear[index]; } base::string getItemAlbum(size_t index) { return base::string(talbum.begin() + talbum_i[index], talbum.begin() + talbum_i[index + 1]); } base::string getItemArtist(size_t index) { return base::string(tartist.begin() + tartist_i[index], tartist.begin() + tartist_i[index + 1]); } base::string getItemTitle(size_t index) { return base::string(ttitle.begin() + ttitle_i[index], ttitle.begin() + ttitle_i[index + 1]); } // GUI int getNumRows() override { return paths_i.size() - 1; } // This is overloaded from TableListBoxModel, and should fill in the background of the whole row void paintRowBackground(Graphics& g, int rowNumber, int /*width*/, int /*height*/, bool rowIsSelected) override { if (rowIsSelected) g.fillAll(Colours::lightblue); else if (rowNumber % 2) g.fillAll(Colour(0xffeeeeee)); } // This is overloaded from TableListBoxModel, and must paint any cells that aren't using custom // components. void paintCell(Graphics& g, int rowNumber, int columnId, int width, int height, bool /*rowIsSelected*/) override { g.setColour(Colours::black); g.setFont(height * 0.7f); if (columnId == 0) g.drawText(base::toStr(getItemTrack(rowNumber)), 5, 0, width, height, Justification::centredLeft, true); else if (columnId == 1) g.drawText(getItemAlbum(rowNumber), 5, 0, width, height, Justification::centredLeft, true); else if (columnId == 2) g.drawText(getItemArtist(rowNumber), 5, 0, width, height, Justification::centredLeft, true); else if (columnId == 3) g.drawText(getItemTitle(rowNumber), 5, 0, width, height, Justification::centredLeft, true); else if (columnId == 4) g.drawText(base::toStr(getItemYear(rowNumber)), 5, 0, width, height, Justification::centredLeft, true); g.setColour(Colours::black.withAlpha(0.2f)); g.fillRect(width - 1, 0, 1, height); } }; // progress dialog class progress : public ThreadWithProgressWindow { playlistModel &m; StringArray files; std::function<void()> onFinish; public: progress(playlistModel &model, const StringArray &_files, std::function<void()> _onFinish) : ThreadWithProgressWindow("Importing music", true, true), m(model), files(_files), onFinish(_onFinish) { setStatusMessage("Importing music"); } // TODO: system codecs? bool isFileSupported(const String &fname) { return fname.endsWith(".mp3") || fname.endsWith(".wav") || fname.endsWith(".wma") || fname.endsWith(".flac") || fname.endsWith(".ogg") || fname.endsWith(".ape"); } void run() override { setProgress(-1.0); int nth = 0; for (auto &fileName : files) { if (File(fileName).isDirectory()) { // recursively scan for files DirectoryIterator i(File(fileName), true, "*.mp3;*.wav;*.wma;*.flac;*.ogg;*.ape"); while (i.next()) { m.addItem(i.getFile().getFullPathName()); if (nth++ == 50) { nth = 0; setStatusMessage(i.getFile().getFullPathName()); } } } else { // single file if (isFileSupported(fileName)) m.addItem(fileName); } } setStatusMessage("Done."); } void threadComplete(bool/* userPressedCancel*/) override { onFinish(); delete this; } }; TableListBox box; playlistModel model; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(playlist); public: playlist() : box("playlist-box", nullptr) { model.init(); box.setModel(&model); box.setMultipleSelectionEnabled(true); box.getHeader().setStretchToFitActive(true); addAndMakeVisible(box); box.getHeader().addColumn("track", 0, 50, 20, 1000, TableHeaderComponent::defaultFlags); box.getHeader().addColumn("album", 1, 200, 150, 1000, TableHeaderComponent::defaultFlags); box.getHeader().addColumn("artist", 2, 200, 150, 1000, TableHeaderComponent::defaultFlags); box.getHeader().addColumn("title", 3, 200, 150, 1000, TableHeaderComponent::defaultFlags); box.getHeader().addColumn("year", 4, 70, 50, 1000, TableHeaderComponent::defaultFlags); box.setMultipleSelectionEnabled(true); } void resized() override { box.setBounds(getLocalBounds().reduced(0)); } bool isInterestedInFileDrag(const StringArray& /*files*/) override { return true; } void fileDragEnter(const StringArray& /*files*/, int /*x*/, int /*y*/) override { repaint(); } void fileDragMove (const StringArray& /*files*/, int /*x*/, int /*y*/) override {} void fileDragExit (const StringArray& /*files*/) override { repaint(); } void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override { (new progress(model, files, [this](){ box.updateContent(); repaint(); }))->launchThread(); } base::string getSelectedRowString() { return model.getItemPath(box.getSelectedRow()); } bool store(const base::string &f) { base::stream s; s.write(model.paths); s.write(model.talbum); s.write(model.tartist); s.write(model.ttitle); s.write(model.tyear); s.write(model.ttrack); s.write(model.paths_i); s.write(model.talbum_i); s.write(model.tartist_i); s.write(model.ttitle_i); return base::fs::store(f, s); } bool load(const base::string &f) { base::stream s = base::fs::load(f); bool result = s.read(model.paths) > 0 && s.read(model.talbum) > 0 && s.read(model.tartist) > 0 && s.read(model.ttitle) > 0 && s.read(model.tyear) > 0 && s.read(model.ttrack) > 0 && s.read(model.paths_i) > 0 && s.read(model.talbum_i) > 0 && s.read(model.tartist_i) > 0 && s.read(model.ttitle_i) > 0; box.updateContent(); repaint(); return result; } bool storeTags(const base::string &f) { base::stream s; s.write((uint32)model.tags.size()); for (const auto &e : model.tags) { s.write(e.first); // TODO: write returns / estimate size / write documentation on writing vectors? s.write(sizeof(uint32) + sizeof(base::cell) * e.second.size()); s.write(e.second); } return base::fs::store(f, s); } bool loadTags(const base::string &f) { model.tags.clear(); base::stream s = base::fs::load(f); uint32 mapSize; if (s.read(mapSize) == 0) return false; for (uint32 i = 0; i < mapSize; ++i) { base::string key; if (s.read(key) == 0) return false; auto &c = model.tags[key]; uint32 cellsSize; if (s.read(cellsSize) == 0) return false; if (s.read(c) != cellsSize) return false; } return true; } }; <commit_msg>+ set/get custom tag, tags init<commit_after>#pragma once #include "includes.hpp" #define TAGLIB_STATIC #include <taglib/fileref.h> #include <taglib/tag.h> #include <taglib/tpropertymap.h> class playlist : public Component, public FileDragAndDropTarget { struct playlistModel : public TableListBoxModel { base::string paths, talbum, tartist, ttitle; std::vector<uint32> tyear, ttrack; std::vector<uint32> paths_i, talbum_i, tartist_i, ttitle_i; // persistent user defined tags map std::map<base::string, std::vector<base::cell>> tags; uint32 tagsCount; void init() { paths_i.clear(); // this one first (getNumRows) paths_i.push_back(0); paths.clear(); talbum.clear(); tartist.clear(); tyear.clear(); ttitle.clear(); ttrack.clear(); talbum_i.clear(); talbum_i.push_back(0); tartist_i.clear(); tartist_i.push_back(0); ttitle_i.clear(); ttitle_i.push_back(0); } void addItem(const String &path) { paths.append(path.toStdString()); paths_i.push_back(paths.size()); // read tags from file TagLib::FileRef file(path.toRawUTF8()); if (!file.isNull() && file.tag()) { talbum.append(file.tag()->album().toCString()); tartist.append(file.tag()->artist().toCString()); ttitle.append(file.tag()->title().toCString()); tyear.push_back(file.tag()->year()); ttrack.push_back(file.tag()->track()); } else { tyear.push_back(0); ttrack.push_back(0); } talbum_i.push_back(talbum.size()); tartist_i.push_back(tartist.size()); ttitle_i.push_back(ttitle.size()); } base::string getItemPath(size_t index) { return base::string(paths.begin() + paths_i[index], paths.begin() + paths_i[index + 1]); } uint getItemTrack(size_t index) { return ttrack[index]; } uint getItemYear(size_t index) { return tyear[index]; } base::string getItemAlbum(size_t index) { return base::string(talbum.begin() + talbum_i[index], talbum.begin() + talbum_i[index + 1]); } base::string getItemArtist(size_t index) { return base::string(tartist.begin() + tartist_i[index], tartist.begin() + tartist_i[index + 1]); } base::string getItemTitle(size_t index) { return base::string(ttitle.begin() + ttitle_i[index], ttitle.begin() + ttitle_i[index + 1]); } // GUI int getNumRows() override { return paths_i.size() - 1; } // This is overloaded from TableListBoxModel, and should fill in the background of the whole row void paintRowBackground(Graphics& g, int rowNumber, int /*width*/, int /*height*/, bool rowIsSelected) override { if (rowIsSelected) g.fillAll(Colours::lightblue); else if (rowNumber % 2) g.fillAll(Colour(0xffeeeeee)); } // This is overloaded from TableListBoxModel, and must paint any cells that aren't using custom // components. void paintCell(Graphics& g, int rowNumber, int columnId, int width, int height, bool /*rowIsSelected*/) override { g.setColour(Colours::black); g.setFont(height * 0.7f); if (columnId == 0) g.drawText(base::toStr(getItemTrack(rowNumber)), 5, 0, width, height, Justification::centredLeft, true); else if (columnId == 1) g.drawText(getItemAlbum(rowNumber), 5, 0, width, height, Justification::centredLeft, true); else if (columnId == 2) g.drawText(getItemArtist(rowNumber), 5, 0, width, height, Justification::centredLeft, true); else if (columnId == 3) g.drawText(getItemTitle(rowNumber), 5, 0, width, height, Justification::centredLeft, true); else if (columnId == 4) g.drawText(base::toStr(getItemYear(rowNumber)), 5, 0, width, height, Justification::centredLeft, true); g.setColour(Colours::black.withAlpha(0.2f)); g.fillRect(width - 1, 0, 1, height); } }; // progress dialog class progress : public ThreadWithProgressWindow { playlistModel &m; StringArray files; std::function<void()> onFinish; public: progress(playlistModel &model, const StringArray &_files, std::function<void()> _onFinish) : ThreadWithProgressWindow("Importing music", true, true), m(model), files(_files), onFinish(_onFinish) { setStatusMessage("Importing music"); } // TODO: system codecs? bool isFileSupported(const String &fname) { return fname.endsWith(".mp3") || fname.endsWith(".wav") || fname.endsWith(".wma") || fname.endsWith(".flac") || fname.endsWith(".ogg") || fname.endsWith(".ape"); } void run() override { setProgress(-1.0); int nth = 0; for (auto &fileName : files) { if (File(fileName).isDirectory()) { // recursively scan for files DirectoryIterator i(File(fileName), true, "*.mp3;*.wav;*.wma;*.flac;*.ogg;*.ape"); while (i.next()) { m.addItem(i.getFile().getFullPathName()); if (nth++ == 50) { nth = 0; setStatusMessage(i.getFile().getFullPathName()); } } } else { // single file if (isFileSupported(fileName)) m.addItem(fileName); } } setStatusMessage("Done."); } void threadComplete(bool/* userPressedCancel*/) override { onFinish(); delete this; } }; TableListBox box; playlistModel model; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(playlist); public: playlist() : box("playlist-box", nullptr) { model.init(); box.setModel(&model); box.setMultipleSelectionEnabled(true); box.getHeader().setStretchToFitActive(true); addAndMakeVisible(box); box.getHeader().addColumn("track", 0, 50, 20, 1000, TableHeaderComponent::defaultFlags); box.getHeader().addColumn("album", 1, 200, 150, 1000, TableHeaderComponent::defaultFlags); box.getHeader().addColumn("artist", 2, 200, 150, 1000, TableHeaderComponent::defaultFlags); box.getHeader().addColumn("title", 3, 200, 150, 1000, TableHeaderComponent::defaultFlags); box.getHeader().addColumn("year", 4, 70, 50, 1000, TableHeaderComponent::defaultFlags); box.setMultipleSelectionEnabled(true); model.tagsCount = 0; } void resized() override { box.setBounds(getLocalBounds().reduced(0)); } bool isInterestedInFileDrag(const StringArray& /*files*/) override { return true; } void fileDragEnter(const StringArray& /*files*/, int /*x*/, int /*y*/) override { repaint(); } void fileDragMove (const StringArray& /*files*/, int /*x*/, int /*y*/) override {} void fileDragExit (const StringArray& /*files*/) override { repaint(); } void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override { (new progress(model, files, [this](){ box.updateContent(); repaint(); }))->launchThread(); } base::string getSelectedRowString() { return model.getItemPath(box.getSelectedRow()); } void initTags(uint32 count) { model.tagsCount = count; // TODO: resizing? } base::cell getCustomTag(const base::string &id, uint32 index) { auto e = model.tags.find(id); if (e != model.tags.end() && e->second.size() <= index) { return e->second[index]; } return base::cell::nil; } void setCustomTag(const base::string &id, uint32 index, base::cell c) { if (model.tagsCount > 0) { auto &e = model.tags[id]; if (e.size() <= index) e[index] = c; // update else { e.resize(4, base::cell::nil); // initialize e[index] = c; } } } bool store(const base::string &f) { base::stream s; s.write(model.paths); s.write(model.talbum); s.write(model.tartist); s.write(model.ttitle); s.write(model.tyear); s.write(model.ttrack); s.write(model.paths_i); s.write(model.talbum_i); s.write(model.tartist_i); s.write(model.ttitle_i); return base::fs::store(f, s); } bool load(const base::string &f) { base::stream s = base::fs::load(f); bool result = s.read(model.paths) > 0 && s.read(model.talbum) > 0 && s.read(model.tartist) > 0 && s.read(model.ttitle) > 0 && s.read(model.tyear) > 0 && s.read(model.ttrack) > 0 && s.read(model.paths_i) > 0 && s.read(model.talbum_i) > 0 && s.read(model.tartist_i) > 0 && s.read(model.ttitle_i) > 0; box.updateContent(); repaint(); return result; } bool storeTags(const base::string &f) { base::stream s; s.write((uint32)model.tags.size()); for (const auto &e : model.tags) { s.write(e.first); // TODO: write returns / estimate size / write documentation on writing vectors? s.write(sizeof(uint32) + sizeof(base::cell) * e.second.size()); s.write(e.second); } return base::fs::store(f, s); } bool loadTags(const base::string &f) { model.tags.clear(); base::stream s = base::fs::load(f); uint32 mapSize; if (s.read(mapSize) == 0) return false; for (uint32 i = 0; i < mapSize; ++i) { base::string key; if (s.read(key) == 0) return false; auto &c = model.tags[key]; uint32 cellsSize; if (s.read(cellsSize) == 0) return false; if (s.read(c) != cellsSize) return false; } return true; } }; <|endoftext|>
<commit_before>//------------------------------------------- // // Example of the use of Adaptors // to get access to the red component // of an RGB image // //------------------------------------------- #include <itkImage.h> #include <itkIndex.h> #include <itkImageRegionSimpleIterator.h> #include <itkImageAdaptor.h> #include <itkDataAccessorRGBtoRed.h> #include <itkFilterImageAdd.h> int main() { //------------------------------------------------------------- // Typedefs //------------------------------------------------------------- // Float Image typedefs typedef float myFloatPixelType; typedef itk::Image<myFloatPixelType, 3> myFloatImageType; typedef myFloatImageType::SizeType mySizeType; typedef myFloatImageType::IndexType myIndexType; typedef myFloatImageType::RegionType myRegionType; // RGB Image typedefs typedef itk::RGB<myFloatPixelType> myRGBPixelType; typedef itk::Image<myRGBPixelType, 3> myRGBImageType; typedef itk::DataAccessorRGBtoRed<myFloatPixelType> myAccessorType; typedef itk::ImageAdaptor<myRGBImageType, myAccessorType> myAdaptorType; typedef itk::ImageRegionSimpleIterator< myFloatImageType > myFloatIteratorType; typedef itk::ImageRegionSimpleIterator< myRGBImageType > myRGBIteratorType; typedef itk::FilterImageAdd< myAdaptorType, myFloatImageType, myFloatImageType > myFilterType; //------------------------------------------------------------- // Create and Allocate the image //------------------------------------------------------------- // Define their size, and start index mySizeType size; size[0] = 2; size[1] = 2; size[2] = 2; // Small size, because we are printing it myIndexType start; start[0]= 0; start[1]= 0; start[2]= 0; myRegionType region; region.SetIndex( start ); region.SetSize( size ); float spacing[3]; spacing[0] = 1.0; spacing[1] = 1.0; spacing[2] = 1.0; //------------------------------------------------------------- // Create and Initialize the RGB image //------------------------------------------------------------- myRGBImageType::Pointer myRGBImage = myRGBImageType::New(); myRGBImage->SetLargestPossibleRegion( region ); myRGBImage->SetBufferedRegion( region ); myRGBImage->SetRequestedRegion( region ); myRGBImage->Allocate(); myRGBImage->SetSpacing( spacing ); myRGBIteratorType it( myRGBImage, myRGBImage->GetRequestedRegion() ); myRGBPixelType initialRGBValue; initialRGBValue.SetRed( 10 ); initialRGBValue.SetBlue( 30 ); initialRGBValue.SetGreen( 20 ); it.Begin(); while( !it.IsAtEnd() ) { it.Set( initialRGBValue ); ++it; } std::cout << "Initial RGB Image Values : " << std::endl; it.Begin(); while( !it.IsAtEnd() ) { myIndexType index = it.GetIndex(); std::cout << "["; std::cout.width(3); std::cout << index[0] << ","; std::cout.width(3); std::cout << index[1] << ","; std::cout.width(3); std::cout << index[2] << "] = "; std::cout.width(4); std::cout << it.Get().GetRed() << ","; std::cout.width(4); std::cout << it.Get().GetGreen() << ","; std::cout.width(4); std::cout << it.Get().GetBlue() << std::endl; ++it; } std::cout << "RGB Image Initializaed" << std::endl; //------------------------------------------------------------- // Create and Initialize the Float image //------------------------------------------------------------- myFloatImageType::Pointer myFloatImage = myFloatImageType::New(); myFloatImage->SetLargestPossibleRegion( region ); myFloatImage->SetBufferedRegion( region ); myFloatImage->SetRequestedRegion( region ); myFloatImage->Allocate(); myFloatImage->SetSpacing( spacing ); myFloatIteratorType itf( myFloatImage, myFloatImage->GetRequestedRegion() ); myFloatPixelType initialFloatValue = 5.0; itf.Begin(); while( !itf.IsAtEnd() ) { itf.Set( initialFloatValue ); ++itf; } std::cout << "Initial Float Image Values : " << std::endl; itf.Begin(); while( !itf.IsAtEnd() ) { myIndexType index = itf.GetIndex(); std::cout << "["; std::cout.width(3); std::cout << index[0] << ","; std::cout.width(3); std::cout << index[1] << ","; std::cout.width(3); std::cout << index[2] << "] = "; std::cout.width(8); std::cout << itf.Get() << std::endl; ++itf; } std::cout << "Float Image Initializaed" << std::endl; //------------------------------------------------------------- // Create the adaptor and connect the image //------------------------------------------------------------- myAdaptorType::Pointer myAdaptor = myAdaptorType::New(); myAdaptor->SetImage( myRGBImage ); //------------------------------------------------------------- // Create the filter and connect the inputs //------------------------------------------------------------- myFilterType::Pointer filter = myFilterType::New(); filter->SetInput1( myAdaptor ); filter->SetInput2( myFloatImage ); //------------------------------------------------------------- // Set the requested region of the Output image //------------------------------------------------------------- myFloatImageType::Pointer myFloatOutputImage = filter->GetOutput(); myFloatOutputImage->SetLargestPossibleRegion( region ); myFloatOutputImage->SetRequestedRegion( region ); myFloatOutputImage->SetBufferedRegion( region ); myFloatOutputImage->Allocate(); myFloatOutputImage->SetSpacing( spacing ); std::cout << "Float Output Image Initializaed" << std::endl; //------------------------------------------------------------- // Force the execution of the filter //------------------------------------------------------------- std::cout << "Calling filter Update" << std::endl; filter->Update(); std::cout << "Filter Updated" << std::endl; //------------------------------------------------------------- // Force the execution of the filter //------------------------------------------------------------- myFloatOutputImage = filter->GetOutput(); myFloatIteratorType ito( myFloatOutputImage, myFloatOutputImage->GetRequestedRegion() ); std::cout << std::endl; std::cout << "Filter Output :" << std::endl; ito.Begin(); while( !ito.IsAtEnd() ) { myIndexType index = ito.GetIndex(); std::cout << "["; std::cout.width(3); std::cout << index[0] << ","; std::cout.width(3); std::cout << index[1] << ","; std::cout.width(3); std::cout << index[2] << "] = "; std::cout.width(8); std::cout << ito.Get() << std::endl; ++ito; } return 0; } <commit_msg>ENH: Allocation for Output image was removed. It should be done inside Add Filter.<commit_after>//------------------------------------------- // // Example of the use of Adaptors // to get access to the red component // of an RGB image // //------------------------------------------- #include <itkImage.h> #include <itkIndex.h> #include <itkImageRegionSimpleIterator.h> #include <itkImageAdaptor.h> #include <itkDataAccessorRGBtoRed.h> #include <itkFilterImageAdd.h> int main() { //------------------------------------------------------------- // Typedefs //------------------------------------------------------------- // Float Image typedefs typedef float myFloatPixelType; typedef itk::Image<myFloatPixelType, 3> myFloatImageType; typedef myFloatImageType::SizeType mySizeType; typedef myFloatImageType::IndexType myIndexType; typedef myFloatImageType::RegionType myRegionType; // RGB Image typedefs typedef itk::RGB<myFloatPixelType> myRGBPixelType; typedef itk::Image<myRGBPixelType, 3> myRGBImageType; typedef itk::DataAccessorRGBtoRed<myFloatPixelType> myAccessorType; typedef itk::ImageAdaptor<myRGBImageType, myAccessorType> myAdaptorType; typedef itk::ImageRegionSimpleIterator< myFloatImageType > myFloatIteratorType; typedef itk::ImageRegionSimpleIterator< myRGBImageType > myRGBIteratorType; typedef itk::FilterImageAdd< myAdaptorType, myFloatImageType, myFloatImageType > myFilterType; //------------------------------------------------------------- // Create and Allocate the image //------------------------------------------------------------- // Define their size, and start index mySizeType size; size[0] = 2; size[1] = 2; size[2] = 2; // Small size, because we are printing it myIndexType start; start[0]= 0; start[1]= 0; start[2]= 0; myRegionType region; region.SetIndex( start ); region.SetSize( size ); float spacing[3]; spacing[0] = 1.0; spacing[1] = 1.0; spacing[2] = 1.0; //------------------------------------------------------------- // Create and Initialize the RGB image //------------------------------------------------------------- myRGBImageType::Pointer myRGBImage = myRGBImageType::New(); myRGBImage->SetLargestPossibleRegion( region ); myRGBImage->SetBufferedRegion( region ); myRGBImage->SetRequestedRegion( region ); myRGBImage->Allocate(); myRGBImage->SetSpacing( spacing ); myRGBIteratorType it( myRGBImage, myRGBImage->GetRequestedRegion() ); myRGBPixelType initialRGBValue; initialRGBValue.SetRed( 10 ); initialRGBValue.SetBlue( 30 ); initialRGBValue.SetGreen( 20 ); it.Begin(); while( !it.IsAtEnd() ) { it.Set( initialRGBValue ); ++it; } std::cout << "Initial RGB Image Values : " << std::endl; it.Begin(); while( !it.IsAtEnd() ) { myIndexType index = it.GetIndex(); std::cout << "["; std::cout.width(3); std::cout << index[0] << ","; std::cout.width(3); std::cout << index[1] << ","; std::cout.width(3); std::cout << index[2] << "] = "; std::cout.width(4); std::cout << it.Get().GetRed() << ","; std::cout.width(4); std::cout << it.Get().GetGreen() << ","; std::cout.width(4); std::cout << it.Get().GetBlue() << std::endl; ++it; } std::cout << "RGB Image Initializaed" << std::endl; //------------------------------------------------------------- // Create and Initialize the Float image //------------------------------------------------------------- myFloatImageType::Pointer myFloatImage = myFloatImageType::New(); myFloatImage->SetLargestPossibleRegion( region ); myFloatImage->SetBufferedRegion( region ); myFloatImage->SetRequestedRegion( region ); myFloatImage->Allocate(); myFloatImage->SetSpacing( spacing ); myFloatIteratorType itf( myFloatImage, myFloatImage->GetRequestedRegion() ); myFloatPixelType initialFloatValue = 5.0; itf.Begin(); while( !itf.IsAtEnd() ) { itf.Set( initialFloatValue ); ++itf; } std::cout << "Initial Float Image Values : " << std::endl; itf.Begin(); while( !itf.IsAtEnd() ) { myIndexType index = itf.GetIndex(); std::cout << "["; std::cout.width(3); std::cout << index[0] << ","; std::cout.width(3); std::cout << index[1] << ","; std::cout.width(3); std::cout << index[2] << "] = "; std::cout.width(8); std::cout << itf.Get() << std::endl; ++itf; } std::cout << "Float Image Initializaed" << std::endl; //------------------------------------------------------------- // Create the adaptor and connect the image //------------------------------------------------------------- myAdaptorType::Pointer myAdaptor = myAdaptorType::New(); myAdaptor->SetImage( myRGBImage ); //------------------------------------------------------------- // Create the filter and connect the inputs //------------------------------------------------------------- myFilterType::Pointer filter = myFilterType::New(); filter->SetInput1( myAdaptor ); filter->SetInput2( myFloatImage ); //------------------------------------------------------------- // Set the requested region of the Output image //------------------------------------------------------------- myFloatImageType::Pointer myFloatOutputImage = filter->GetOutput(); myFloatOutputImage->SetSpacing( spacing ); std::cout << "Float Output Image Initializaed" << std::endl; //------------------------------------------------------------- // Force the execution of the filter //------------------------------------------------------------- std::cout << "Calling filter Update" << std::endl; filter->Update(); std::cout << "Filter Updated" << std::endl; //------------------------------------------------------------- // Force the execution of the filter //------------------------------------------------------------- myFloatOutputImage = filter->GetOutput(); myFloatIteratorType ito( myFloatOutputImage, myFloatOutputImage->GetRequestedRegion() ); std::cout << std::endl; std::cout << "Filter Output :" << std::endl; ito.Begin(); while( !ito.IsAtEnd() ) { myIndexType index = ito.GetIndex(); std::cout << "["; std::cout.width(3); std::cout << index[0] << ","; std::cout.width(3); std::cout << index[1] << ","; std::cout.width(3); std::cout << index[2] << "] = "; std::cout.width(8); std::cout << ito.Get() << std::endl; ++ito; } return 0; } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include <Utils/TestUtils.h> #include <Tasks/BasicTasks/BriefTask.h> using namespace Hearthstonepp; TEST(BriefTask, GetTaskID) { BasicTasks::BriefTask brief; EXPECT_EQ(brief.GetTaskID(), +TaskID::BRIEF); } TEST(BriefTask, Run) { BasicTasks::BriefTask brief; TestUtils::GenPlayer gen(CardClass::DRUID, CardClass::ROGUE); gen.player1.id = 100; MetaData result = brief.Run(gen.player1, gen.player2); EXPECT_EQ(result, MetaData::BRIEF); TaskMeta meta; result = brief.Run(gen.player1, gen.player2, meta); EXPECT_EQ(result, MetaData::BRIEF); EXPECT_EQ(meta.id, +TaskID::BRIEF); EXPECT_EQ(meta.status, MetaData::BRIEF); EXPECT_EQ(meta.userID, gen.player1.id); }<commit_msg>Update BriefTaskTests - Add newline to eof<commit_after>#include "gtest/gtest.h" #include <Utils/TestUtils.h> #include <Tasks/BasicTasks/BriefTask.h> using namespace Hearthstonepp; TEST(BriefTask, GetTaskID) { BasicTasks::BriefTask brief; EXPECT_EQ(brief.GetTaskID(), +TaskID::BRIEF); } TEST(BriefTask, Run) { BasicTasks::BriefTask brief; TestUtils::GenPlayer gen(CardClass::DRUID, CardClass::ROGUE); gen.player1.id = 100; MetaData result = brief.Run(gen.player1, gen.player2); EXPECT_EQ(result, MetaData::BRIEF); TaskMeta meta; result = brief.Run(gen.player1, gen.player2, meta); EXPECT_EQ(result, MetaData::BRIEF); EXPECT_EQ(meta.id, +TaskID::BRIEF); EXPECT_EQ(meta.status, MetaData::BRIEF); EXPECT_EQ(meta.userID, gen.player1.id); } <|endoftext|>
<commit_before> #include "DynamixelInterface.h" #include <SoftwareSerial.h> // define TXEN, RXEN and RXCIE #if !defined(TXEN) #if defined(TXEN0) #define TXEN TXEN0 #define RXEN RXEN0 #define RXCIE RXCIE0 #elif defined(TXEN1) // Some devices have uart1 but no uart0 (leonardo) #define TXEN TXEN1 #define RXEN RXEN1 #define RXCIE RXCIE1 #endif #endif DynamixelInterface *createSerialInterface(HardwareSerial &aSerial) { return new DynamixelInterfaceImpl<HardwareSerial>(aSerial); } DynamixelInterface *createSerialInterface(HardwareSerial &aSerial, uint8_t aDirectionPin) { return new DynamixelInterfaceImpl<HardwareSerial>(aSerial, aDirectionPin); } namespace { class DynSoftwareSerial:public SoftwareSerial { public: DynSoftwareSerial(uint8_t aRxPin, uint8_t aTxPin): SoftwareSerial(aRxPin, aTxPin), mTxPin(aTxPin) {} void enableTx(){pinMode(mTxPin, OUTPUT);} void disableTx(){pinMode(mTxPin, INPUT);} private: uint8_t mTxPin; }; } DynamixelInterface *createSoftSerialInterface(uint8_t aRxPin, uint8_t aTxPin) { DynSoftwareSerial &serial=*new DynSoftwareSerial(aRxPin, aTxPin); return new DynamixelInterfaceImpl<DynSoftwareSerial>(serial, DynamixelInterfaceImpl<DynSoftwareSerial>::NO_DIR_PORT, true); } DynamixelInterface *createSoftSerialInterface(uint8_t aRxPin, uint8_t aTxPin, uint8_t aDirectionPin) { DynSoftwareSerial &serial=*new DynSoftwareSerial(aRxPin, aTxPin); return new DynamixelInterfaceImpl<DynSoftwareSerial>(serial, aDirectionPin, true); } namespace { //dirty trick to access protected member class HardwareSerialAccess:public HardwareSerial { public: volatile uint8_t * const ucsrb(){return _ucsrb;} }; } template<> void setReadMode<HardwareSerial>(HardwareSerial &aStream) { HardwareSerialAccess &stream=reinterpret_cast<HardwareSerialAccess&>(aStream); *(stream.ucsrb()) &= ~_BV(TXEN); *(stream.ucsrb()) |= _BV(RXEN); *(stream.ucsrb()) |= _BV(RXCIE); } template<> void setWriteMode<HardwareSerial>(HardwareSerial &aStream) { HardwareSerialAccess &stream=reinterpret_cast<HardwareSerialAccess&>(aStream); *(stream.ucsrb()) &= ~_BV(RXEN); *(stream.ucsrb()) |= _BV(RXCIE); *(stream.ucsrb()) |= _BV(TXEN); } template<> void setReadMode<DynSoftwareSerial>(DynSoftwareSerial &aStream) { aStream.disableTx(); aStream.listen(); } template<> void setWriteMode<DynSoftwareSerial>(DynSoftwareSerial &aStream) { aStream.stopListening(); aStream.enableTx(); } <commit_msg>Add experimental support for Arduino 101<commit_after> #include "DynamixelInterface.h" #include <SoftwareSerial.h> #if __AVR__ // define TXEN, RXEN and RXCIE #if !defined(TXEN) #if defined(TXEN0) #define TXEN TXEN0 #define RXEN RXEN0 #define RXCIE RXCIE0 #elif defined(TXEN1) // Some devices have uart1 but no uart0 (leonardo) #define TXEN TXEN1 #define RXEN RXEN1 #define RXCIE RXCIE1 #endif #endif #endif //__AVR__ DynamixelInterface *createSerialInterface(HardwareSerial &aSerial) { return new DynamixelInterfaceImpl<HardwareSerial>(aSerial); } DynamixelInterface *createSerialInterface(HardwareSerial &aSerial, uint8_t aDirectionPin) { return new DynamixelInterfaceImpl<HardwareSerial>(aSerial, aDirectionPin); } namespace { class DynSoftwareSerial:public SoftwareSerial { public: DynSoftwareSerial(uint8_t aRxPin, uint8_t aTxPin): SoftwareSerial(aRxPin, aTxPin), mTxPin(aTxPin) {} void enableTx(){pinMode(mTxPin, OUTPUT);} void disableTx(){pinMode(mTxPin, INPUT);} private: uint8_t mTxPin; }; } DynamixelInterface *createSoftSerialInterface(uint8_t aRxPin, uint8_t aTxPin) { DynSoftwareSerial &serial=*new DynSoftwareSerial(aRxPin, aTxPin); return new DynamixelInterfaceImpl<DynSoftwareSerial>(serial, DynamixelInterfaceImpl<DynSoftwareSerial>::NO_DIR_PORT, true); } DynamixelInterface *createSoftSerialInterface(uint8_t aRxPin, uint8_t aTxPin, uint8_t aDirectionPin) { DynSoftwareSerial &serial=*new DynSoftwareSerial(aRxPin, aTxPin); return new DynamixelInterfaceImpl<DynSoftwareSerial>(serial, aDirectionPin, true); } #if __AVR__ namespace { //dirty trick to access protected member class HardwareSerialAccess:public HardwareSerial { public: volatile uint8_t * const ucsrb(){return _ucsrb;} }; } template<> void setReadMode<HardwareSerial>(HardwareSerial &aStream) { HardwareSerialAccess &stream=reinterpret_cast<HardwareSerialAccess&>(aStream); *(stream.ucsrb()) &= ~_BV(TXEN); *(stream.ucsrb()) |= _BV(RXEN); *(stream.ucsrb()) |= _BV(RXCIE); } template<> void setWriteMode<HardwareSerial>(HardwareSerial &aStream) { HardwareSerialAccess &stream=reinterpret_cast<HardwareSerialAccess&>(aStream); *(stream.ucsrb()) &= ~_BV(RXEN); *(stream.ucsrb()) |= _BV(RXCIE); *(stream.ucsrb()) |= _BV(TXEN); } #elif __arc__ //Arduino 101 specific code template<> void setReadMode<HardwareSerial>(HardwareSerial &aStream) { //enable pull up to avoid noise on the line pinMode(1, INPUT); digitalWrite(1, HIGH); // disconnect UART TX and connect UART RX SET_PIN_MODE(16, GPIO_MUX_MODE); SET_PIN_MODE(17, UART_MUX_MODE); } template<> void setWriteMode<HardwareSerial>(HardwareSerial &aStream) { // disconnect UART RX and connect UART TX SET_PIN_MODE(17, GPIO_MUX_MODE); SET_PIN_MODE(16, UART_MUX_MODE); } #endif template<> void setReadMode<DynSoftwareSerial>(DynSoftwareSerial &aStream) { aStream.disableTx(); aStream.listen(); } template<> void setWriteMode<DynSoftwareSerial>(DynSoftwareSerial &aStream) { aStream.stopListening(); aStream.enableTx(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: cclass_unicode.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2004-09-08 15:25: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): _______________________________________ * * ************************************************************************/ #include <cclass_unicode.hxx> #include <com/sun/star/i18n/UnicodeScript.hpp> #include <com/sun/star/i18n/UnicodeType.hpp> #include <i18nutil/unicode.hxx> #include <i18nutil/x_rtl_ustring.h> #include <breakiteratorImpl.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::rtl; namespace com { namespace sun { namespace star { namespace i18n { // ---------------------------------------------------- // class cclass_Unicode // ----------------------------------------------------; cclass_Unicode::cclass_Unicode( uno::Reference < XMultiServiceFactory > xSMgr ) : xMSF( xSMgr ), pTable( NULL ), pStart( NULL ), pCont( NULL ), nStartTypes( 0 ), nContTypes( 0 ), eState( ssGetChar ), cGroupSep( ',' ), cDecimalSep( '.' ) { trans = new Transliteration_casemapping(); cClass = "com.sun.star.i18n.CharacterClassification_Unicode"; } cclass_Unicode::~cclass_Unicode() { destroyParserTable(); delete trans; } OUString SAL_CALL cclass_Unicode::toUpper( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { sal_Int32 len = Text.getLength(); if (nPos >= len) return OUString(); if (nCount + nPos > len) nCount = len - nPos; trans->setMappingType(MappingTypeToUpper, rLocale); return trans->transliterateString2String(Text, nPos, nCount); } OUString SAL_CALL cclass_Unicode::toLower( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { sal_Int32 len = Text.getLength(); if (nPos >= len) return OUString(); if (nCount + nPos > len) nCount = len - nPos; trans->setMappingType(MappingTypeToLower, rLocale); return trans->transliterateString2String(Text, nPos, nCount); } OUString SAL_CALL cclass_Unicode::toTitle( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { sal_Int32 len = Text.getLength(); if (nPos >= len) return OUString(); if (nCount + nPos > len) nCount = len - nPos; trans->setMappingType(MappingTypeToTitle, rLocale); rtl_uString* pStr = x_rtl_uString_new_WithLength( nCount, 1 ); sal_Unicode* out = pStr->buffer; BreakIteratorImpl brk(xMSF); Boundary bdy = brk.getWordBoundary(Text, nPos, rLocale, WordType::ANYWORD_IGNOREWHITESPACES, sal_True); for (sal_Int32 i = nPos; i < nCount + nPos; i++, out++) { if (i >= bdy.endPos) bdy = brk.nextWord(Text, bdy.endPos, rLocale, WordType::ANYWORD_IGNOREWHITESPACES); *out = (i == bdy.startPos) ? trans->transliterateChar2Char(Text[i]) : Text[i]; } *out = 0; return OUString( pStr, SAL_NO_ACQUIRE ); } sal_Int16 SAL_CALL cclass_Unicode::getType( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getUnicodeType(Text[nPos]); } sal_Int16 SAL_CALL cclass_Unicode::getCharacterDirection( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getUnicodeDirection(Text[nPos]); } sal_Int16 SAL_CALL cclass_Unicode::getScript( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getUnicodeScriptType(Text[nPos], (ScriptTypeList*) 0, 0); } sal_Int32 SAL_CALL cclass_Unicode::getCharacterType( const OUString& Text, sal_Int32 nPos, const Locale& rLocale ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getCharType(Text[nPos]); } sal_Int32 SAL_CALL cclass_Unicode::getStringType( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; if ( Text.getLength() < nPos + nCount ) nCount = Text.getLength() - nPos; sal_Int32 result = 0; for (int i = 0; i < nCount; i++) result |= unicode::getCharType(Text[nPos+i]); return result; } ParseResult SAL_CALL cclass_Unicode::parseAnyToken( const OUString& Text, sal_Int32 nPos, const Locale& rLocale, sal_Int32 startCharTokenType, const OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType, const OUString& userDefinedCharactersCont ) throw(RuntimeException) { ParseResult r; if ( Text.getLength() <= nPos ) return r; setupParserTable( rLocale, startCharTokenType, userDefinedCharactersStart, contCharTokenType, userDefinedCharactersCont ); parseText( r, Text, nPos ); return r; } ParseResult SAL_CALL cclass_Unicode::parsePredefinedToken( sal_Int32 nTokenType, const OUString& Text, sal_Int32 nPos, const Locale& rLocale, sal_Int32 startCharTokenType, const OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType, const OUString& userDefinedCharactersCont ) throw(RuntimeException) { ParseResult r; if ( Text.getLength() <= nPos ) return r; setupParserTable( rLocale, startCharTokenType, userDefinedCharactersStart, contCharTokenType, userDefinedCharactersCont ); parseText( r, Text, nPos, nTokenType ); return r; } OUString SAL_CALL cclass_Unicode::getImplementationName() throw( RuntimeException ) { return OUString::createFromAscii(cClass); } sal_Bool SAL_CALL cclass_Unicode::supportsService(const OUString& rServiceName) throw( RuntimeException ) { return !rServiceName.compareToAscii(cClass); } Sequence< OUString > SAL_CALL cclass_Unicode::getSupportedServiceNames() throw( RuntimeException ) { Sequence< OUString > aRet(1); aRet[0] = OUString::createFromAscii(cClass); return aRet; } } } } } <commit_msg>INTEGRATION: CWS ooo19126 (1.7.50); FILE MERGED 2005/09/05 17:47:34 rt 1.7.50.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cclass_unicode.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-07 17:04:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <cclass_unicode.hxx> #include <com/sun/star/i18n/UnicodeScript.hpp> #include <com/sun/star/i18n/UnicodeType.hpp> #include <i18nutil/unicode.hxx> #include <i18nutil/x_rtl_ustring.h> #include <breakiteratorImpl.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::rtl; namespace com { namespace sun { namespace star { namespace i18n { // ---------------------------------------------------- // class cclass_Unicode // ----------------------------------------------------; cclass_Unicode::cclass_Unicode( uno::Reference < XMultiServiceFactory > xSMgr ) : xMSF( xSMgr ), pTable( NULL ), pStart( NULL ), pCont( NULL ), nStartTypes( 0 ), nContTypes( 0 ), eState( ssGetChar ), cGroupSep( ',' ), cDecimalSep( '.' ) { trans = new Transliteration_casemapping(); cClass = "com.sun.star.i18n.CharacterClassification_Unicode"; } cclass_Unicode::~cclass_Unicode() { destroyParserTable(); delete trans; } OUString SAL_CALL cclass_Unicode::toUpper( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { sal_Int32 len = Text.getLength(); if (nPos >= len) return OUString(); if (nCount + nPos > len) nCount = len - nPos; trans->setMappingType(MappingTypeToUpper, rLocale); return trans->transliterateString2String(Text, nPos, nCount); } OUString SAL_CALL cclass_Unicode::toLower( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { sal_Int32 len = Text.getLength(); if (nPos >= len) return OUString(); if (nCount + nPos > len) nCount = len - nPos; trans->setMappingType(MappingTypeToLower, rLocale); return trans->transliterateString2String(Text, nPos, nCount); } OUString SAL_CALL cclass_Unicode::toTitle( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { sal_Int32 len = Text.getLength(); if (nPos >= len) return OUString(); if (nCount + nPos > len) nCount = len - nPos; trans->setMappingType(MappingTypeToTitle, rLocale); rtl_uString* pStr = x_rtl_uString_new_WithLength( nCount, 1 ); sal_Unicode* out = pStr->buffer; BreakIteratorImpl brk(xMSF); Boundary bdy = brk.getWordBoundary(Text, nPos, rLocale, WordType::ANYWORD_IGNOREWHITESPACES, sal_True); for (sal_Int32 i = nPos; i < nCount + nPos; i++, out++) { if (i >= bdy.endPos) bdy = brk.nextWord(Text, bdy.endPos, rLocale, WordType::ANYWORD_IGNOREWHITESPACES); *out = (i == bdy.startPos) ? trans->transliterateChar2Char(Text[i]) : Text[i]; } *out = 0; return OUString( pStr, SAL_NO_ACQUIRE ); } sal_Int16 SAL_CALL cclass_Unicode::getType( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getUnicodeType(Text[nPos]); } sal_Int16 SAL_CALL cclass_Unicode::getCharacterDirection( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getUnicodeDirection(Text[nPos]); } sal_Int16 SAL_CALL cclass_Unicode::getScript( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getUnicodeScriptType(Text[nPos], (ScriptTypeList*) 0, 0); } sal_Int32 SAL_CALL cclass_Unicode::getCharacterType( const OUString& Text, sal_Int32 nPos, const Locale& rLocale ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getCharType(Text[nPos]); } sal_Int32 SAL_CALL cclass_Unicode::getStringType( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; if ( Text.getLength() < nPos + nCount ) nCount = Text.getLength() - nPos; sal_Int32 result = 0; for (int i = 0; i < nCount; i++) result |= unicode::getCharType(Text[nPos+i]); return result; } ParseResult SAL_CALL cclass_Unicode::parseAnyToken( const OUString& Text, sal_Int32 nPos, const Locale& rLocale, sal_Int32 startCharTokenType, const OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType, const OUString& userDefinedCharactersCont ) throw(RuntimeException) { ParseResult r; if ( Text.getLength() <= nPos ) return r; setupParserTable( rLocale, startCharTokenType, userDefinedCharactersStart, contCharTokenType, userDefinedCharactersCont ); parseText( r, Text, nPos ); return r; } ParseResult SAL_CALL cclass_Unicode::parsePredefinedToken( sal_Int32 nTokenType, const OUString& Text, sal_Int32 nPos, const Locale& rLocale, sal_Int32 startCharTokenType, const OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType, const OUString& userDefinedCharactersCont ) throw(RuntimeException) { ParseResult r; if ( Text.getLength() <= nPos ) return r; setupParserTable( rLocale, startCharTokenType, userDefinedCharactersStart, contCharTokenType, userDefinedCharactersCont ); parseText( r, Text, nPos, nTokenType ); return r; } OUString SAL_CALL cclass_Unicode::getImplementationName() throw( RuntimeException ) { return OUString::createFromAscii(cClass); } sal_Bool SAL_CALL cclass_Unicode::supportsService(const OUString& rServiceName) throw( RuntimeException ) { return !rServiceName.compareToAscii(cClass); } Sequence< OUString > SAL_CALL cclass_Unicode::getSupportedServiceNames() throw( RuntimeException ) { Sequence< OUString > aRet(1); aRet[0] = OUString::createFromAscii(cClass); return aRet; } } } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: transliteration_Ignore.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: khong $ $Date: 2002-09-16 16:31:37 $ * * 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): _______________________________________ * * ************************************************************************/ // prevent internal compiler error with MSVC6SP3 #include <utility> #include <transliteration_Ignore.hxx> using namespace com::sun::star::uno; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { inline sal_Int32 Min( sal_Int32 a, sal_Int32 b ) { return a > b ? b : a; } sal_Bool SAL_CALL transliteration_Ignore::equals(const OUString& str1, sal_Int32 pos1, sal_Int32 nCount1, sal_Int32& nMatch1, const OUString& str2, sal_Int32 pos2, sal_Int32 nCount2, sal_Int32& nMatch2 ) throw(RuntimeException) { Sequence< sal_Int32 > offset1; Sequence< sal_Int32 > offset2; // The method folding is defined in a sub class. OUString s1 = this->folding( str1, pos1, nCount1, offset1); OUString s2 = this->folding( str2, pos2, nCount2, offset2); const sal_Unicode * p1 = s1.getStr(); const sal_Unicode * p2 = s2.getStr(); sal_Int32 length = Min(s1.getLength(), s2.getLength()); for (sal_Int32 nmatch = 0; nmatch < length; nmatch++) if (*p1++ != *p2++) break; if (nmatch > 0) { nMatch1 = offset1[ nmatch - 1 ] + 1; // Subtract 1 from nmatch because the index starts from zero. nMatch2 = offset2[ nmatch - 1 ] + 1; // And then, add 1 to position because it means the number of character matched. } else { nMatch1 = 0; // No character was matched. nMatch2 = 0; } return (nmatch == s1.getLength()) && (nmatch == s2.getLength()); } Sequence< OUString > SAL_CALL transliteration_Ignore::transliterateRange( const OUString& str1, const OUString& str2 ) throw(RuntimeException) { if (str1.getLength() < 1 || str2.getLength() < 1) throw RuntimeException(); Sequence< OUString > r(2); r[0] = str1.copy(0, 1); r[1] = str2.copy(0, 1); return r; } sal_Int16 SAL_CALL transliteration_Ignore::getType() throw(RuntimeException) { // The type is also defined in com/sun/star/util/TransliterationType.hdl return TransliterationType::IGNORE; } OUString SAL_CALL transliteration_Ignore::transliterate( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset ) throw(RuntimeException) { // The method folding is defined in a sub class. return this->folding( inStr, startPos, nCount, offset); } Sequence< OUString > SAL_CALL transliteration_Ignore::transliterateRange( const OUString& str1, const OUString& str2, XTransliteration& t1, XTransliteration& t2 ) throw(RuntimeException) { if (str1.getLength() < 1 || str2.getLength() < 1) throw RuntimeException(); Sequence< sal_Int32 > offset; OUString s11 = t1.transliterate( str1, 0, 1, offset ); OUString s12 = t1.transliterate( str2, 0, 1, offset ); OUString s21 = t2.transliterate( str1, 0, 1, offset ); OUString s22 = t2.transliterate( str2, 0, 1, offset ); if ( (s11 == s21) && (s12 == s22) ) { Sequence< OUString > r(2); r[0] = s11; r[1] = s12; return r; } Sequence< OUString > r(4); r[0] = s11; r[1] = s12; r[2] = s21; r[3] = s22; return r; } OUString SAL_CALL transliteration_Ignore::transliterate( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset, oneToOneMapping& table ) throw(RuntimeException) { // Create a string buffer which can hold nCount + 1 characters. // The reference count is 0 now. rtl_uString * newStr = x_rtl_uString_new_WithLength( nCount ); // defined in x_rtl_ustring.h sal_Unicode * dst = newStr->buffer; const sal_Unicode * src = inStr.getStr() + startPos; // Allocate nCount length to offset argument. offset.realloc( nCount ); sal_Int32 *p = offset.getArray(); sal_Int32 position = startPos; sal_Int32 count = 0; // Translation while (nCount -- > 0) { sal_Unicode c = table[ *src++ ]; // if the "func" returns 0xffff, skip the character. if (c != 0xffff) { *dst ++ = c; *p ++ = position; count++; } position ++; } *dst = (sal_Unicode) 0; offset.realloc(count); return OUString( newStr->buffer, count); // defined in rtl/usrting. The reference count is increased from 0 to 1. } OUString SAL_CALL transliteration_Ignore::transliterate( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset, sal_Unicode (*func)(const sal_Unicode) ) throw(RuntimeException) { // Create a string buffer which can hold nCount + 1 characters. // The reference count is 0 now. rtl_uString * newStr = x_rtl_uString_new_WithLength( nCount ); // defined in x_rtl_ustring.h sal_Unicode * dst = newStr->buffer; const sal_Unicode * src = inStr.getStr() + startPos; // Allocate nCount length to offset argument. offset.realloc( nCount ); sal_Int32 *p = offset.getArray(); sal_Int32 position = startPos; sal_Int32 count = 0; // Translation while (nCount -- > 0) { sal_Unicode c = func( *src++ ); // if the "func" returns 0xffff, skip the character. if (c != 0xffff) { *dst ++ = c; *p ++ = position; count++; } position ++; } *dst = (sal_Unicode) 0; offset.realloc(count); return OUString( newStr->buffer, count ); // defined in rtl/usrting. The reference count is increased from 0 to 1. } } } } } <commit_msg>INTEGRATION: CWS calc06 (1.4.36); FILE MERGED 2003/03/21 22:08:16 khong 1.4.36.1: #106680# Implementing new XExtendedTransliteration interface<commit_after>/************************************************************************* * * $RCSfile: transliteration_Ignore.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2003-04-08 16:06:57 $ * * 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): _______________________________________ * * ************************************************************************/ // prevent internal compiler error with MSVC6SP3 #include <utility> #include <transliteration_Ignore.hxx> using namespace drafts::com::sun::star::i18n; using namespace com::sun::star::uno; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { inline sal_Int32 Min( sal_Int32 a, sal_Int32 b ) { return a > b ? b : a; } sal_Bool SAL_CALL transliteration_Ignore::equals(const OUString& str1, sal_Int32 pos1, sal_Int32 nCount1, sal_Int32& nMatch1, const OUString& str2, sal_Int32 pos2, sal_Int32 nCount2, sal_Int32& nMatch2 ) throw(RuntimeException) { Sequence< sal_Int32 > offset1; Sequence< sal_Int32 > offset2; // The method folding is defined in a sub class. OUString s1 = this->folding( str1, pos1, nCount1, offset1); OUString s2 = this->folding( str2, pos2, nCount2, offset2); const sal_Unicode * p1 = s1.getStr(); const sal_Unicode * p2 = s2.getStr(); sal_Int32 length = Min(s1.getLength(), s2.getLength()); for (sal_Int32 nmatch = 0; nmatch < length; nmatch++) if (*p1++ != *p2++) break; if (nmatch > 0) { nMatch1 = offset1[ nmatch - 1 ] + 1; // Subtract 1 from nmatch because the index starts from zero. nMatch2 = offset2[ nmatch - 1 ] + 1; // And then, add 1 to position because it means the number of character matched. } else { nMatch1 = 0; // No character was matched. nMatch2 = 0; } return (nmatch == s1.getLength()) && (nmatch == s2.getLength()); } Sequence< OUString > SAL_CALL transliteration_Ignore::transliterateRange( const OUString& str1, const OUString& str2 ) throw(RuntimeException) { if (str1.getLength() < 1 || str2.getLength() < 1) throw RuntimeException(); Sequence< OUString > r(2); r[0] = str1.copy(0, 1); r[1] = str2.copy(0, 1); return r; } sal_Int16 SAL_CALL transliteration_Ignore::getType() throw(RuntimeException) { // The type is also defined in com/sun/star/util/TransliterationType.hdl return TransliterationType::IGNORE; } OUString SAL_CALL transliteration_Ignore::transliterate( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset ) throw(RuntimeException) { // The method folding is defined in a sub class. return this->folding( inStr, startPos, nCount, offset); } Sequence< OUString > SAL_CALL transliteration_Ignore::transliterateRange( const OUString& str1, const OUString& str2, XTransliteration& t1, XTransliteration& t2 ) throw(RuntimeException) { if (str1.getLength() < 1 || str2.getLength() < 1) throw RuntimeException(); Sequence< sal_Int32 > offset; OUString s11 = t1.transliterate( str1, 0, 1, offset ); OUString s12 = t1.transliterate( str2, 0, 1, offset ); OUString s21 = t2.transliterate( str1, 0, 1, offset ); OUString s22 = t2.transliterate( str2, 0, 1, offset ); if ( (s11 == s21) && (s12 == s22) ) { Sequence< OUString > r(2); r[0] = s11; r[1] = s12; return r; } Sequence< OUString > r(4); r[0] = s11; r[1] = s12; r[2] = s21; r[3] = s22; return r; } OUString SAL_CALL transliteration_Ignore::folding( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset) throw(RuntimeException) { // Create a string buffer which can hold nCount + 1 characters. // The reference count is 0 now. rtl_uString * newStr = x_rtl_uString_new_WithLength( nCount ); // defined in x_rtl_ustring.h sal_Unicode * dst = newStr->buffer; const sal_Unicode * src = inStr.getStr() + startPos; // Allocate nCount length to offset argument. sal_Int32 *p, position; if (useOffset) { offset.realloc( nCount ); p = offset.getArray(); position = startPos; } if (map) { sal_Unicode previousChar = *src ++; sal_Unicode currentChar; // Translation while (-- nCount > 0) { currentChar = *src ++; Mapping *m; for (m = map; m->replaceChar; m++) { if (previousChar == m->previousChar && currentChar == m->currentChar ) { if (useOffset) { position++; *p++ = position++; } *dst++ = m->replaceChar;\ previousChar = *src++; nCount--; break; } } if (! m->replaceChar) { if (useOffset) *p ++ = position ++; *dst ++ = previousChar; previousChar = currentChar; } } if (nCount == 0) { if (useOffset) *p = position; *dst ++ = previousChar; } newStr->length = sal_Int32(dst - newStr->buffer); if (useOffset) offset.realloc(newStr->length); } else { // Translation while (nCount -- > 0) { sal_Unicode c = *src++; *dst ++ = func ? func( c) : (*table)[ c ]; if (useOffset) *p ++ = position ++; } } *dst = (sal_Unicode) 0; return OUString( newStr ); // defined in rtl/usrting. The reference count is increased from 0 to 1. } sal_Unicode SAL_CALL transliteration_Ignore::transliterateChar2Char( sal_Unicode inChar) throw(RuntimeException, MultipleCharsOutputException) { return func ? func( inChar) : table ? (*table)[ inChar ] : inChar; } } } } } <|endoftext|>
<commit_before>// // CompositeTileImageProvider.cpp // G3MiOSSDK // // Created by Diego Gomez Deck on 4/23/14. // // #include "CompositeTileImageProvider.hpp" #include "TileImageListener.hpp" #include "Tile.hpp" #include "CompositeTileImageContribution.hpp" #include "IFactory.hpp" #include "ICanvas.hpp" #include "IImage.hpp" #include "FrameTasksExecutor.hpp" CompositeTileImageProvider::~CompositeTileImageProvider() { for (int i = 0; i < _childrenSize; i++) { TileImageProvider* child = _children[i]; child->_release(); } #ifdef JAVA_CODE super.dispose(); #endif } const TileImageContribution* CompositeTileImageProvider::contribution(const Tile* tile) { std::vector<const CompositeTileImageContribution::ChildContribution*> childrenContributions; for (int i = 0; i < _childrenSize; i++) { TileImageProvider* child = _children[i]; const TileImageContribution* childContribution = child->contribution(tile); if (childContribution != NULL) { // ignore previous contributions, they are covered by the current fullCoverage & Opaque contribution. const int childrenContributionsSize = childrenContributions.size(); if ((childrenContributionsSize > 0) && childContribution->isFullCoverageAndOpaque()) { for (int j = 0; j < childrenContributionsSize; j++) { const CompositeTileImageContribution::ChildContribution* previousContribution = childrenContributions[j]; #ifdef C_CODE delete previousContribution; #endif #ifdef JAVA_CODE previousContribution.dispose(); #endif } childrenContributions.clear(); } childrenContributions.push_back( new CompositeTileImageContribution::ChildContribution(i, childContribution) ); } } return CompositeTileImageContribution::create(childrenContributions); } CompositeTileImageProvider::ChildResult::ChildResult(const bool isError, const bool isCanceled, const IImage* image, const std::string& imageId, const TileImageContribution* contribution, const std::string& error) : _isError(isError), _isCanceled(isCanceled), _image(image), _imageId(imageId), _contribution(contribution), _error(error) { // TileImageContribution::retainContribution(_contribution); } CompositeTileImageProvider::ChildResult::~ChildResult() { delete _image; // TileImageContribution::releaseContribution(_contribution); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::image(const IImage* image, const std::string& imageId, const TileImageContribution* contribution) { return new CompositeTileImageProvider::ChildResult(false , // isError false, // isCanceled image, imageId, contribution, "" // error ); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::error(const std::string& error) { return new CompositeTileImageProvider::ChildResult(true, // isError false, // isCanceled NULL, // image "", // imageId NULL, // contribution error); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::cancelation() { return new CompositeTileImageProvider::ChildResult(false, // isError true, // isCanceled NULL, // image "", // imageId NULL, // contribution "" // error ); } CompositeTileImageProvider::Composer::Composer(int width, int height, CompositeTileImageProvider* compositeTileImageProvider, const std::string& tileId, const Sector& tileSector, TileImageListener* listener, bool deleteListener, const CompositeTileImageContribution* compositeContribution, FrameTasksExecutor* frameTasksExecutor) : _width(width), _height(height), _compositeTileImageProvider(compositeTileImageProvider), _tileId(tileId), _listener(listener), _deleteListener(deleteListener), _compositeContribution(compositeContribution), _contributionsSize( compositeContribution->size() ), _frameTasksExecutor(frameTasksExecutor), _stepsDone(0), _anyError(false), _anyCancelation(false), _canceled(false), _tileSector(tileSector) { #warning DEBUG MEMORY // TileImageContribution::retainContribution(_compositeContribution); for (int i = 0; i < _contributionsSize; i++) { _results.push_back( NULL ); } } CompositeTileImageProvider::Composer::~Composer() { for (int i = 0; i < _contributionsSize; i++) { const ChildResult* result = _results[i]; delete result; } TileImageContribution::releaseContribution(_compositeContribution); #ifdef JAVA_CODE super.dispose(); #endif } void CompositeTileImageProvider::Composer::cleanUp() { if (_deleteListener) { delete _listener; _listener = NULL; } _compositeTileImageProvider->composerDone(this); } void CompositeTileImageProvider::Composer::done() { if (_canceled) { cleanUp(); return; } if (_contributionsSize == 1) { const ChildResult* singleResult = _results[0]; if (singleResult->_isError) { _listener->imageCreationError(_tileId, singleResult->_error); } else if (singleResult->_isCanceled) { _listener->imageCreationCanceled(_tileId); } else { _listener->imageCreated(singleResult->_imageId, singleResult->_image->shallowCopy(), singleResult->_imageId, singleResult->_contribution); } cleanUp(); } else { if (_anyError) { std::string composedError = ""; for (int i = 0; i < _contributionsSize; i++) { const ChildResult* childResult = _results[i]; if (childResult->_isError) { composedError += childResult->_error + " "; } } _listener->imageCreationError(_tileId, composedError); cleanUp(); } else if (_anyCancelation) { _listener->imageCreationCanceled(_tileId); cleanUp(); } else { // ICanvas* canvas = IFactory::instance()->createCanvas(); // // canvas->initialize(_width, _height); // // std::string imageId = ""; // // for (int i = 0; i < _contributionsSize; i++) { // const ChildResult* result = _results[i]; // // imageId += result->_imageId + "|"; //#warning JM: consider sector and transparency // canvas->drawImage(result->_image, 0, 0); // } // _imageId = imageId; // // canvas->createImage(new ComposerImageListener(this), true); // // delete canvas; _frameTasksExecutor->addPreRenderTask(new ComposerFrameTask(this)); } } } RectangleF* CompositeTileImageProvider::Composer::getInnerRectangle(int wholeSectorWidth, int wholeSectorHeight, const Sector& wholeSector, const Sector& innerSector) const { if (wholeSector.isEquals(innerSector)){ return new RectangleF(0, 0, wholeSectorWidth, wholeSectorHeight); } const double widthFactor = innerSector._deltaLongitude.div(wholeSector._deltaLongitude); const double heightFactor = innerSector._deltaLatitude.div(wholeSector._deltaLatitude); const Vector2D lowerUV = wholeSector.getUVCoordinates(innerSector.getNW()); return new RectangleF((float) (lowerUV._x * wholeSectorWidth), (float) (lowerUV._y * wholeSectorHeight), (float) (widthFactor * wholeSectorWidth), (float) (heightFactor * wholeSectorHeight)); } void CompositeTileImageProvider::Composer::mixResult() { if (_canceled) { cleanUp(); return; } ICanvas* canvas = IFactory::instance()->createCanvas(); canvas->initialize(_width, _height); std::string imageId = ""; for (int i = 0; i < _contributionsSize; i++) { const ChildResult* result = _results[i]; imageId += result->_imageId + "|"; #warning //For now, we consider the whole image will appear on the tile (no source rect needed) const IImage* image = result->_image; const float alpha = result->_contribution->_alpha; if (result->_contribution->isFullCoverageAndOpaque()) { canvas->drawImage(image, 0, 0); } else { if (result->_contribution->isFullCoverage()) { canvas->drawImage(image, //SRC RECT 0,0, image->getWidth(), image->getHeight(), //DEST RECT 0, 0, _width, _height, alpha); } else { const Sector* imageSector = result->_contribution->getSector(); const RectangleF* destRect = getInnerRectangle(_width, _height, _tileSector, *imageSector); //TEST MADRID // if (_tileSector.contains(Angle::fromDegrees(40.41677540051771), Angle::fromDegrees(-3.7037901976145804))){ // printf("TS: %s\nIS: %s\nR: %s\n",_tileSector.description().c_str(), // imageSector->description().c_str(), // rect->description().c_str()); // } canvas->drawImage(image, //SRC RECT 0,0, image->getWidth(), image->getHeight(), //DEST RECT destRect->_x, destRect->_y, destRect->_width, destRect->_height, alpha); delete destRect; } } } _imageId = imageId; canvas->createImage(new ComposerImageListener(this), true); delete canvas; } bool CompositeTileImageProvider::ComposerFrameTask::isCanceled(const G3MRenderContext* rc) { return false; } void CompositeTileImageProvider::ComposerFrameTask::execute(const G3MRenderContext* rc) { _composer->mixResult(); } void CompositeTileImageProvider::Composer::imageCreated(const IImage* image) { const CompositeTileImageContribution* compositeContribution = _compositeContribution; _compositeContribution = NULL; // the _compositeContribution ownership moved to the listener _listener->imageCreated(_tileId, image, _imageId, compositeContribution); cleanUp(); } void CompositeTileImageProvider::Composer::stepDone() { _stepsDone++; if (_stepsDone == _contributionsSize) { done(); } } void CompositeTileImageProvider::Composer::imageCreated(const std::string& tileId, const IImage* image, const std::string& imageId, const TileImageContribution* contribution, const int index) { #warning DEBUG MEMORY // TileImageContribution::retainContribution(contribution); _results[index] = ChildResult::image(image, imageId, contribution); stepDone(); } void CompositeTileImageProvider::Composer::imageCreationError(const std::string& error, const int index) { _results[index] = ChildResult::error(error); _anyError = true; stepDone(); } void CompositeTileImageProvider::Composer::imageCreationCanceled(const int index) { _results[index] = ChildResult::cancelation(); _anyCancelation = true; stepDone(); } void CompositeTileImageProvider::Composer::cancel(const std::string& tileId) { _canceled = true; _compositeTileImageProvider->cancelChildren(tileId, _compositeContribution); } void CompositeTileImageProvider::ChildTileImageListener::imageCreated(const std::string& tileId, const IImage* image, const std::string& imageId, const TileImageContribution* contribution) { _composer->imageCreated(tileId, image, imageId, contribution, _index); } void CompositeTileImageProvider::ChildTileImageListener::imageCreationError(const std::string& tileId, const std::string& error) { _composer->imageCreationError(error, _index); } void CompositeTileImageProvider::ChildTileImageListener::imageCreationCanceled(const std::string& tileId) { _composer->imageCreationCanceled(_index); } void CompositeTileImageProvider::create(const Tile* tile, const TileImageContribution* contribution, const Vector2I& resolution, long long tileDownloadPriority, bool logDownloadActivity, TileImageListener* listener, bool deleteListener, FrameTasksExecutor* frameTasksExecutor) { const CompositeTileImageContribution* compositeContribution = (const CompositeTileImageContribution*) contribution; const std::string tileId = tile->_id; Composer* composer = new Composer(resolution._x, resolution._y, this, tileId, tile->_sector, listener, deleteListener, compositeContribution, frameTasksExecutor); _composers[ tileId ] = composer; const int contributionsSize = compositeContribution->size(); for (int i = 0; i < contributionsSize; i++) { const CompositeTileImageContribution::ChildContribution* childContribution = compositeContribution->get(i); TileImageProvider* child = _children[ childContribution->_childIndex ]; child->create(tile, childContribution->_contribution, resolution, tileDownloadPriority, logDownloadActivity, new ChildTileImageListener(composer, i), true, frameTasksExecutor); } } void CompositeTileImageProvider::cancel(const std::string& tileId) { #ifdef C_CODE if (_composers.find(tileId) != _composers.end()) { Composer* composer = _composers[tileId]; composer->cancel(tileId); _composers.erase(tileId); } #endif #ifdef JAVA_CODE final Composer composer = _composers.remove(tileId); if (composer != null) { composer.cancel(tileId); } #endif } void CompositeTileImageProvider::composerDone(Composer* composer) { _composers.erase( composer->_tileId ); composer->_release(); } void CompositeTileImageProvider::cancelChildren(const std::string& tileId, const CompositeTileImageContribution* compositeContribution) { const int contributionsSize = compositeContribution->size(); // store all the indexes before calling child->cancel(). // child->cancel() can force the deletion of the builder (and in order the deletion of compositeContribution) int* indexes = new int[contributionsSize]; for (int i = 0; i < contributionsSize; i++) { indexes[i] = compositeContribution->get(i)->_childIndex; } for (int i = 0; i < contributionsSize; i++) { TileImageProvider* child = _children[ indexes[i] ]; child->cancel(tileId); } delete [] indexes; } <commit_msg>Tile's image creation refactoring - NOT YET USABLE<commit_after>// // CompositeTileImageProvider.cpp // G3MiOSSDK // // Created by Diego Gomez Deck on 4/23/14. // // #include "CompositeTileImageProvider.hpp" #include "TileImageListener.hpp" #include "Tile.hpp" #include "CompositeTileImageContribution.hpp" #include "IFactory.hpp" #include "ICanvas.hpp" #include "IImage.hpp" #include "FrameTasksExecutor.hpp" CompositeTileImageProvider::~CompositeTileImageProvider() { for (int i = 0; i < _childrenSize; i++) { TileImageProvider* child = _children[i]; child->_release(); } #ifdef JAVA_CODE super.dispose(); #endif } const TileImageContribution* CompositeTileImageProvider::contribution(const Tile* tile) { std::vector<const CompositeTileImageContribution::ChildContribution*> childrenContributions; for (int i = 0; i < _childrenSize; i++) { TileImageProvider* child = _children[i]; const TileImageContribution* childContribution = child->contribution(tile); if (childContribution != NULL) { // ignore previous contributions, they are covered by the current fullCoverage & Opaque contribution. const int childrenContributionsSize = childrenContributions.size(); if ((childrenContributionsSize > 0) && childContribution->isFullCoverageAndOpaque()) { for (int j = 0; j < childrenContributionsSize; j++) { const CompositeTileImageContribution::ChildContribution* previousContribution = childrenContributions[j]; #ifdef C_CODE delete previousContribution; #endif #ifdef JAVA_CODE previousContribution.dispose(); #endif } childrenContributions.clear(); } childrenContributions.push_back( new CompositeTileImageContribution::ChildContribution(i, childContribution) ); } } return CompositeTileImageContribution::create(childrenContributions); } CompositeTileImageProvider::ChildResult::ChildResult(const bool isError, const bool isCanceled, const IImage* image, const std::string& imageId, const TileImageContribution* contribution, const std::string& error) : _isError(isError), _isCanceled(isCanceled), _image(image), _imageId(imageId), _contribution(contribution), _error(error) { // TileImageContribution::retainContribution(_contribution); } CompositeTileImageProvider::ChildResult::~ChildResult() { delete _image; // TileImageContribution::releaseContribution(_contribution); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::image(const IImage* image, const std::string& imageId, const TileImageContribution* contribution) { return new CompositeTileImageProvider::ChildResult(false , // isError false, // isCanceled image, imageId, contribution, "" // error ); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::error(const std::string& error) { return new CompositeTileImageProvider::ChildResult(true, // isError false, // isCanceled NULL, // image "", // imageId NULL, // contribution error); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::cancelation() { return new CompositeTileImageProvider::ChildResult(false, // isError true, // isCanceled NULL, // image "", // imageId NULL, // contribution "" // error ); } CompositeTileImageProvider::Composer::Composer(int width, int height, CompositeTileImageProvider* compositeTileImageProvider, const std::string& tileId, const Sector& tileSector, TileImageListener* listener, bool deleteListener, const CompositeTileImageContribution* compositeContribution, FrameTasksExecutor* frameTasksExecutor) : _width(width), _height(height), _compositeTileImageProvider(compositeTileImageProvider), _tileId(tileId), _listener(listener), _deleteListener(deleteListener), _compositeContribution(compositeContribution), _contributionsSize( compositeContribution->size() ), _frameTasksExecutor(frameTasksExecutor), _stepsDone(0), _anyError(false), _anyCancelation(false), _canceled(false), _tileSector(tileSector) { #warning DEBUG MEMORY // TileImageContribution::retainContribution(_compositeContribution); for (int i = 0; i < _contributionsSize; i++) { _results.push_back( NULL ); } } CompositeTileImageProvider::Composer::~Composer() { for (int i = 0; i < _contributionsSize; i++) { const ChildResult* result = _results[i]; delete result; } TileImageContribution::releaseContribution(_compositeContribution); #ifdef JAVA_CODE super.dispose(); #endif } void CompositeTileImageProvider::Composer::cleanUp() { if (_deleteListener) { delete _listener; _listener = NULL; } _compositeTileImageProvider->composerDone(this); } void CompositeTileImageProvider::Composer::done() { if (_canceled) { cleanUp(); return; } if (_contributionsSize == 1) { const ChildResult* singleResult = _results[0]; if (singleResult->_isError) { _listener->imageCreationError(_tileId, singleResult->_error); } else if (singleResult->_isCanceled) { _listener->imageCreationCanceled(_tileId); } else { _listener->imageCreated(singleResult->_imageId, singleResult->_image->shallowCopy(), singleResult->_imageId, singleResult->_contribution); } cleanUp(); } else { if (_anyError) { std::string composedError = ""; for (int i = 0; i < _contributionsSize; i++) { const ChildResult* childResult = _results[i]; if (childResult->_isError) { composedError += childResult->_error + " "; } } _listener->imageCreationError(_tileId, composedError); cleanUp(); } else if (_anyCancelation) { _listener->imageCreationCanceled(_tileId); cleanUp(); } else { // ICanvas* canvas = IFactory::instance()->createCanvas(); // // canvas->initialize(_width, _height); // // std::string imageId = ""; // // for (int i = 0; i < _contributionsSize; i++) { // const ChildResult* result = _results[i]; // // imageId += result->_imageId + "|"; //#warning JM: consider sector and transparency // canvas->drawImage(result->_image, 0, 0); // } // _imageId = imageId; // // canvas->createImage(new ComposerImageListener(this), true); // // delete canvas; _frameTasksExecutor->addPreRenderTask(new ComposerFrameTask(this)); } } } RectangleF* CompositeTileImageProvider::Composer::getInnerRectangle(int wholeSectorWidth, int wholeSectorHeight, const Sector& wholeSector, const Sector& innerSector) const { if (wholeSector.isEquals(innerSector)){ return new RectangleF(0, 0, wholeSectorWidth, wholeSectorHeight); } const double widthFactor = innerSector._deltaLongitude.div(wholeSector._deltaLongitude); const double heightFactor = innerSector._deltaLatitude.div(wholeSector._deltaLatitude); const Vector2D lowerUV = wholeSector.getUVCoordinates(innerSector.getNW()); return new RectangleF((float) (lowerUV._x * wholeSectorWidth), (float) (lowerUV._y * wholeSectorHeight), (float) (widthFactor * wholeSectorWidth), (float) (heightFactor * wholeSectorHeight)); } void CompositeTileImageProvider::Composer::mixResult() { if (_canceled) { cleanUp(); return; } ICanvas* canvas = IFactory::instance()->createCanvas(); canvas->initialize(_width, _height); std::string imageId = ""; for (int i = 0; i < _contributionsSize; i++) { const ChildResult* result = _results[i]; imageId += result->_imageId + "|"; #warning //For now, we consider the whole image will appear on the tile (no source rect needed) const IImage* image = result->_image; const float alpha = result->_contribution->_alpha; if (result->_contribution->isFullCoverageAndOpaque()) { canvas->drawImage(image, 0, 0); } else { if (result->_contribution->isFullCoverage()) { canvas->drawImage(image, //SRC RECT 0,0, image->getWidth(), image->getHeight(), //DEST RECT 0, 0, _width, _height, alpha); } else { const Sector* imageSector = result->_contribution->getSector(); const RectangleF* destRect = getInnerRectangle(_width, _height, _tileSector, *imageSector); //TEST MADRID // if (_tileSector.contains(Angle::fromDegrees(40.41677540051771), Angle::fromDegrees(-3.7037901976145804))){ // printf("TS: %s\nIS: %s\nR: %s\n",_tileSector.description().c_str(), // imageSector->description().c_str(), // rect->description().c_str()); // } canvas->drawImage(image, //SRC RECT 0,0, image->getWidth(), image->getHeight(), //DEST RECT destRect->_x, destRect->_y, destRect->_width, destRect->_height, alpha); delete destRect; } } } _imageId = imageId; canvas->createImage(new ComposerImageListener(this), true); delete canvas; } bool CompositeTileImageProvider::ComposerFrameTask::isCanceled(const G3MRenderContext* rc) { return false; } void CompositeTileImageProvider::ComposerFrameTask::execute(const G3MRenderContext* rc) { _composer->mixResult(); } void CompositeTileImageProvider::Composer::imageCreated(const IImage* image) { const CompositeTileImageContribution* compositeContribution = _compositeContribution; _compositeContribution = NULL; // the _compositeContribution ownership moved to the listener _listener->imageCreated(_tileId, image, _imageId, compositeContribution); cleanUp(); } void CompositeTileImageProvider::Composer::stepDone() { _stepsDone++; if (_stepsDone == _contributionsSize) { done(); } } void CompositeTileImageProvider::Composer::imageCreated(const std::string& tileId, const IImage* image, const std::string& imageId, const TileImageContribution* contribution, const int index) { #warning DEBUG MEMORY // TileImageContribution::retainContribution(contribution); _results[index] = ChildResult::image(image, imageId, contribution); stepDone(); } void CompositeTileImageProvider::Composer::imageCreationError(const std::string& error, const int index) { _results[index] = ChildResult::error(error); _anyError = true; stepDone(); } void CompositeTileImageProvider::Composer::imageCreationCanceled(const int index) { _results[index] = ChildResult::cancelation(); _anyCancelation = true; stepDone(); } void CompositeTileImageProvider::Composer::cancel(const std::string& tileId) { _canceled = true; _compositeTileImageProvider->cancelChildren(tileId, _compositeContribution); } void CompositeTileImageProvider::ChildTileImageListener::imageCreated(const std::string& tileId, const IImage* image, const std::string& imageId, const TileImageContribution* contribution) { _composer->imageCreated(tileId, image, imageId, contribution, _index); } void CompositeTileImageProvider::ChildTileImageListener::imageCreationError(const std::string& tileId, const std::string& error) { _composer->imageCreationError(error, _index); } void CompositeTileImageProvider::ChildTileImageListener::imageCreationCanceled(const std::string& tileId) { _composer->imageCreationCanceled(_index); } void CompositeTileImageProvider::create(const Tile* tile, const TileImageContribution* contribution, const Vector2I& resolution, long long tileDownloadPriority, bool logDownloadActivity, TileImageListener* listener, bool deleteListener, FrameTasksExecutor* frameTasksExecutor) { const CompositeTileImageContribution* compositeContribution = (const CompositeTileImageContribution*) contribution; const std::string tileId = tile->_id; Composer* composer = new Composer(resolution._x, resolution._y, this, tileId, tile->_sector, listener, deleteListener, compositeContribution, frameTasksExecutor); _composers[ tileId ] = composer; const int contributionsSize = compositeContribution->size(); for (int i = 0; i < contributionsSize; i++) { const CompositeTileImageContribution::ChildContribution* childContribution = compositeContribution->get(i); TileImageProvider* child = _children[ childContribution->_childIndex ]; #warning DEBUG MEMORY childContribution->_contribution->_retain(); child->create(tile, childContribution->_contribution, resolution, tileDownloadPriority, logDownloadActivity, new ChildTileImageListener(composer, i), true, frameTasksExecutor); } } void CompositeTileImageProvider::cancel(const std::string& tileId) { #ifdef C_CODE if (_composers.find(tileId) != _composers.end()) { Composer* composer = _composers[tileId]; composer->cancel(tileId); _composers.erase(tileId); } #endif #ifdef JAVA_CODE final Composer composer = _composers.remove(tileId); if (composer != null) { composer.cancel(tileId); } #endif } void CompositeTileImageProvider::composerDone(Composer* composer) { _composers.erase( composer->_tileId ); composer->_release(); } void CompositeTileImageProvider::cancelChildren(const std::string& tileId, const CompositeTileImageContribution* compositeContribution) { const int contributionsSize = compositeContribution->size(); // store all the indexes before calling child->cancel(). // child->cancel() can force the deletion of the builder (and in order the deletion of compositeContribution) int* indexes = new int[contributionsSize]; for (int i = 0; i < contributionsSize; i++) { indexes[i] = compositeContribution->get(i)->_childIndex; } for (int i = 0; i < contributionsSize; i++) { TileImageProvider* child = _children[ indexes[i] ]; child->cancel(tileId); } delete [] indexes; } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <manasij7479@gmail.com> // author: Vassil Vassilev <vvasilev@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "AutoloadingTransform.h" #include "cling/Interpreter/Transaction.h" #include "clang/AST/DeclVisitor.h" using namespace clang; namespace cling { class DeclFixer : public DeclVisitor<DeclFixer> { public: void VisitDecl(Decl* D) { if (DeclContext* DC = dyn_cast<DeclContext>(D)) for (auto Child : DC->decls()) Visit(Child); } void VisitEnumDecl(EnumDecl* ED) { if (ED->isFixed()) { StringRef str = ED->getAttr<AnnotateAttr>()->getAnnotation(); char ch = str.back(); str.drop_back(2); ED->getAttr<AnnotateAttr>()->setAnnotation(ED->getASTContext(), str); struct EnumDeclDerived: public EnumDecl { static void setFixed(EnumDecl* ED, bool value = true) { ((EnumDeclDerived*)ED)->IsFixed = value; } }; if (ch != '1') EnumDeclDerived::setFixed(ED, false); } } }; void AutoloadingTransform::Transform() { const Transaction* T = getTransaction(); DeclFixer visitor; for (Transaction::const_iterator I = T->decls_begin(), E = T->decls_end(); I != E; ++I) { Transaction::DelayCallInfo DCI = *I; for (DeclGroupRef::iterator J = DCI.m_DGR.begin(), JE = DCI.m_DGR.end(); J != JE; ++J) { if (!(*J)->hasAttr<AnnotateAttr>()) continue; visitor.Visit(*J); //FIXME: Enable when safe ! // if ( (*J)->hasAttr<AnnotateAttr>() /*FIXME: && CorrectCallbackLoaded() how ? */ ) // clang::Decl::castToDeclContext(*J)->setHasExternalLexicalStorage(); } } } } // end namespace cling <commit_msg>Turn on the AutoloadingTransform only on transactions containing fwd decl entries.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <manasij7479@gmail.com> // author: Vassil Vassilev <vvasilev@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "AutoloadingTransform.h" #include "cling/Interpreter/Transaction.h" #include "clang/AST/DeclVisitor.h" using namespace clang; namespace cling { class DeclFixer : public DeclVisitor<DeclFixer> { public: void VisitDecl(Decl* D) { if (DeclContext* DC = dyn_cast<DeclContext>(D)) for (auto Child : DC->decls()) Visit(Child); } void VisitEnumDecl(EnumDecl* ED) { if (ED->isFixed()) { StringRef str = ED->getAttr<AnnotateAttr>()->getAnnotation(); char ch = str.back(); str.drop_back(2); ED->getAttr<AnnotateAttr>()->setAnnotation(ED->getASTContext(), str); struct EnumDeclDerived: public EnumDecl { static void setFixed(EnumDecl* ED, bool value = true) { ((EnumDeclDerived*)ED)->IsFixed = value; } }; if (ch != '1') EnumDeclDerived::setFixed(ED, false); } } }; void AutoloadingTransform::Transform() { const Transaction* T = getTransaction(); if (T->decls_begin() == T->decls_end()) return; DeclGroupRef DGR = T->decls_begin()->m_DGR; if (DGR.isNull()) return; if (const NamedDecl* ND = dyn_cast<NamedDecl>(*DGR.begin())) if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) { DeclFixer visitor; for (Transaction::const_iterator I = T->decls_begin(), E = T->decls_end(); I != E; ++I) { Transaction::DelayCallInfo DCI = *I; for (DeclGroupRef::iterator J = DCI.m_DGR.begin(), JE = DCI.m_DGR.end(); J != JE; ++J) { visitor.Visit(*J); //FIXME: Enable when safe ! // if ( (*J)->hasAttr<AnnotateAttr>() /*FIXME: && CorrectCallbackLoaded() how ? */ ) // clang::Decl::castToDeclContext(*J)->setHasExternalLexicalStorage(); } } } } } // end namespace cling <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2009, John Wiegley. 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 New Artisans LLC 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 "predicate.h" namespace ledger { string args_to_predicate_expr(value_t::sequence_t::const_iterator begin, value_t::sequence_t::const_iterator end) { std::ostringstream expr; bool append_or = false; bool only_parenthesis; while (begin != end) { string arg = (*begin).as_string(); string prefix; bool parse_argument = true; bool only_closed_parenthesis = false;; if (arg == "not" || arg == "NOT") { if (append_or) prefix = " | ! "; else prefix = " ! "; parse_argument = false; append_or = false; } else if (arg == "and" || arg == "AND") { prefix = " & "; parse_argument = false; append_or = false; } else if (arg == "or" || arg == "OR") { prefix = " | "; parse_argument = false; append_or = false; } else if (append_or) { if (! only_parenthesis) prefix = " | "; } else { append_or = true; } value_t::sequence_t::const_iterator next = begin; if (++next != end) { if (arg == "desc" || arg == "DESC" || arg == "payee" || arg == "PAYEE") { arg = string("@") + (*++begin).as_string(); } else if (arg == "note" || arg == "NOTE") { arg = string("&") + (*++begin).as_string(); } else if (arg == "tag" || arg == "TAG" || arg == "meta" || arg == "META" || arg == "data" || arg == "DATA") { arg = string("%") + (*++begin).as_string(); } else if (arg == "expr" || arg == "EXPR") { arg = string("=") + (*++begin).as_string(); } } if (parse_argument) { bool in_prefix = true; bool found_specifier = false; bool no_final_slash = false; only_parenthesis = true; std::ostringstream buf; for (const char * c = arg.c_str(); *c != '\0'; c++) { bool consumed = false; if (*c != '(' && *c != ')') only_parenthesis = false; if (in_prefix) { switch (*c) { case '@': buf << "(payee =~ /"; found_specifier = true; consumed = true; break; case '=': buf << "("; found_specifier = true; no_final_slash = true; consumed = true; break; case '&': buf << "(note =~ /"; found_specifier = true; consumed = true; break; case '%': { bool found_metadata = false; for (const char *q = c; *q != '\0'; q++) if (*q == '=') { buf << "has_tag(/" << string(c + 1, q - c - 1) << "/, /"; found_metadata = true; c = q; break; } if (! found_metadata) { buf << "has_tag(/"; } found_specifier = true; consumed = true; break; } case ')': if (only_parenthesis) only_closed_parenthesis = true; // fall_through... default: if (! found_specifier) { buf << "(account =~ /"; found_specifier = true; } in_prefix = false; break; } } if (! consumed) buf << *c; } if (! prefix.empty() && ! (only_parenthesis && only_closed_parenthesis)) expr << prefix; expr << buf.str(); if (found_specifier) { if (! no_final_slash) expr << "/"; expr << ")"; } } else { expr << prefix; } begin++; } return expr.str(); } } // namespace ledger <commit_msg>Corrected a problem with parsing parens in argument query expressions.<commit_after>/* * Copyright (c) 2003-2009, John Wiegley. 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 New Artisans LLC 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 "predicate.h" namespace ledger { string args_to_predicate_expr(value_t::sequence_t::const_iterator begin, value_t::sequence_t::const_iterator end) { std::ostringstream expr; bool append_or = false; bool only_parenthesis; while (begin != end) { string arg = (*begin).as_string(); string prefix; bool parse_argument = true; bool only_closed_parenthesis = false;; if (arg == "not" || arg == "NOT") { if (append_or) prefix = " | ! "; else prefix = " ! "; parse_argument = false; append_or = false; } else if (arg == "and" || arg == "AND") { prefix = " & "; parse_argument = false; append_or = false; } else if (arg == "or" || arg == "OR") { prefix = " | "; parse_argument = false; append_or = false; } else if (append_or) { if (! only_parenthesis) prefix = " | "; } else { append_or = true; } value_t::sequence_t::const_iterator next = begin; if (++next != end) { if (arg == "desc" || arg == "DESC" || arg == "payee" || arg == "PAYEE") { arg = string("@") + (*++begin).as_string(); } else if (arg == "note" || arg == "NOTE") { arg = string("&") + (*++begin).as_string(); } else if (arg == "tag" || arg == "TAG" || arg == "meta" || arg == "META" || arg == "data" || arg == "DATA") { arg = string("%") + (*++begin).as_string(); } else if (arg == "expr" || arg == "EXPR") { arg = string("=") + (*++begin).as_string(); } } if (parse_argument) { bool in_prefix = true; bool found_specifier = false; bool no_final_slash = false; only_parenthesis = true; std::ostringstream buf; string parens; for (const char * c = arg.c_str(); *c != '\0'; c++) { bool consumed = false; if (*c != '(' && *c != ')') only_parenthesis = false; if (in_prefix) { switch (*c) { case ')': if (only_parenthesis) only_closed_parenthesis = true; // fall through... case '(': parens += c; consumed = true; break; case '@': buf << "(payee =~ /"; found_specifier = true; consumed = true; break; case '=': buf << "("; found_specifier = true; no_final_slash = true; consumed = true; break; case '&': buf << "(note =~ /"; found_specifier = true; consumed = true; break; case '%': { bool found_metadata = false; for (const char *q = c; *q != '\0'; q++) if (*q == '=') { buf << "has_tag(/" << string(c + 1, q - c - 1) << "/, /"; found_metadata = true; c = q; break; } if (! found_metadata) { buf << "has_tag(/"; } found_specifier = true; consumed = true; break; } default: if (! found_specifier) { buf << parens << "(account =~ /"; parens.clear(); found_specifier = true; } in_prefix = false; break; } } if (! consumed) buf << *c; } if (! prefix.empty() && ! (only_parenthesis && only_closed_parenthesis)) expr << prefix; expr << parens << buf.str(); if (found_specifier) { if (! no_final_slash) expr << "/"; expr << ")"; } } else { expr << prefix; } begin++; } return expr.str(); } } // namespace ledger <|endoftext|>
<commit_before>/// /// @file primesum.cpp /// @brief primesum C++ API /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesum-internal.hpp> #include <primesum.hpp> #include <primesieve.hpp> #include <calculator.hpp> #include <int128.hpp> #include <pmath.hpp> #include <algorithm> #include <ctime> #include <cmath> #include <limits> #include <sstream> #include <string> #include <stdint.h> #ifdef _OPENMP #include <omp.h> #endif #ifdef HAVE_MPI #include <mpi.h> namespace primesum { int mpi_num_procs() { int procs; MPI_Comm_size(MPI_COMM_WORLD, &procs); return procs; } int mpi_proc_id() { int proc_id; MPI_Comm_rank(MPI_COMM_WORLD, &proc_id); return proc_id; } int mpi_master_proc_id() { return 0; } bool is_mpi_master_proc() { return mpi_proc_id() == mpi_master_proc_id(); } } // namespace #endif using namespace std; namespace { int threads_ = primesum::MAX_THREADS; int status_precision_ = -1; double alpha_ = -1; } namespace primesum { maxint_t pi(maxint_t x, int threads) { return pi_deleglise_rivat(x, threads); } maxint_t pi(maxint_t x) { return pi(x, threads_); } /// Alias for the fastest prime summing function in primesum. /// @param x integer arithmetic expression e.g. "10^12". /// @pre x <= get_max_x(). /// string pi(const string& x) { return pi(x, threads_); } /// Alias for the fastest prime summing function in primesum. /// @param x integer arithmetic expression e.g. "10^12". /// @pre x <= get_max_x(). /// string pi(const string& x, int threads) { maxint_t pi_x = pi(to_maxint(x), threads); ostringstream oss; oss << pi_x; return oss.str(); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// maxint_t pi_deleglise_rivat(maxint_t x, int threads) { return pi_deleglise_rivat_parallel1(x, threads); } /// Calculate the number of primes below x using Legendre's formula. /// Run time: O(x) operations, O(x^(1/2)) space. /// int64_t pi_legendre(int64_t x) { return pi_legendre(x, threads_); } /// Parallel implementation of the Lagarias-Miller-Odlyzko /// prime summing algorithm using OpenMP. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// maxint_t pi_lmo(maxint_t x, int threads) { return pi_lmo_parallel1(x, threads); } /// Calculate the number of primes below x using an optimized /// segmented sieve of Eratosthenes implementation. /// Run time: O(x log log x) operations, O(x^(1/2)) space. /// int64_t pi_primesieve(int64_t x) { return pi_primesieve(x, threads_); } /// Calculate the nth prime using a combination of the prime /// counting function and the sieve of Eratosthenes. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space. /// int64_t nth_prime(int64_t n) { return nth_prime(n, threads_); } /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// int64_t phi(int64_t x, int64_t a) { return phi(x, a, threads_); } int64_t prime_sum_tiny(int64_t x) { int64_t prime = 0; int64_t prime_sum = 0; primesieve::iterator iter(0, x); while ((prime = iter.next_prime()) <= x) prime_sum += prime; return prime_sum; } /// Returns the largest integer that can be used with /// pi(string x). The return type is a string as max can be a 128-bit /// integer which is not supported by all compilers. /// string get_max_x(double alpha) { ostringstream oss; #ifdef HAVE_INT128_T // primesum is limited by: // z < 2^62, with z = x^(2/3) / alpha // x^(2/3) / alpha < 2^62 // x < (2^62 * alpha)^(3/2) // safety buffer: use 61 instead of 62 double max_x = pow(pow(2.0, 61.0) * alpha, 3.0 / 2.0); oss << (int128_t) max_x; #else unused_param(alpha); oss << numeric_limits<int64_t>::max(); #endif return oss.str(); } /// Get the wall time in seconds. double get_wtime() { #ifdef _OPENMP return omp_get_wtime(); #else return static_cast<double>(std::clock()) / CLOCKS_PER_SEC; #endif } int validate_threads(int threads) { #ifdef _OPENMP if (threads == MAX_THREADS) threads = omp_get_max_threads(); return in_between(1, threads, omp_get_max_threads()); #else threads = 1; return threads; #endif } int validate_threads(int threads, int64_t sieve_limit, int64_t thread_threshold) { threads = validate_threads(threads); thread_threshold = max((int64_t) 1, thread_threshold); threads = (int) min((int64_t) threads, sieve_limit / thread_threshold); threads = max(1, threads); return threads; } void set_alpha(double alpha) { alpha_ = alpha; } double get_alpha() { return alpha_; } double get_alpha(maxint_t x, int64_t y) { // y = x13 * alpha, thus alpha = y / x13 double x13 = (double) iroot<3>(x); return (double) y / x13; } /// Calculate the Lagarias-Miller-Odlyzko alpha tuning factor. /// alpha = a log(x)^2 + b log(x) + c /// a, b and c are constants that should be determined empirically. /// @see ../doc/alpha-factor-tuning.pdf /// double get_alpha_lmo(maxint_t x) { double alpha = get_alpha(); // use default alpha if no command-line alpha provided if (alpha < 1) { double a = 0.00156512; double b = -0.0261411; double c = 0.990948; double logx = log((double) x); alpha = a * pow(logx, 2) + b * logx + c; } return in_between(1, alpha, iroot<6>(x)); } /// Calculate the Deleglise-Rivat alpha tuning factor. /// alpha = a log(x)^3 + b log(x)^2 + c log(x) + d /// a, b, c and d are constants that should be determined empirically. /// @see ../doc/alpha-tuning-factor.pdf /// double get_alpha_deleglise_rivat(maxint_t x) { double alpha = get_alpha(); double x2 = (double) x; // use default alpha if no command-line alpha provided if (alpha < 1) { double a = 0.00334278; double b = -0.126468; double c = 1.26094; double d = -1.10826; double logx = log(x2); alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d; } return in_between(1, alpha, iroot<6>(x)); } void set_num_threads(int threads) { threads_ = validate_threads(threads); } int get_num_threads() { return validate_threads(threads_); } void set_status_precision(int precision) { status_precision_ = in_between(0, precision, 5); } int get_status_precision(maxint_t x) { // use default precision when no command-line precision provided if (status_precision_ < 0) { if ((double) x >= 1e23) return 2; if ((double) x >= 1e21) return 1; } return (status_precision_ > 0) ? status_precision_ : 0; } maxint_t to_maxint(const string& expr) { maxint_t n = calculator::eval<maxint_t>(expr); return n; } /// Get the primesum version number, in the form “i.j”. string primesum_version() { return PRIMESUM_VERSION; } } // namespace primesum <commit_msg>Alpha factor tuning<commit_after>/// /// @file primesum.cpp /// @brief primesum C++ API /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesum-internal.hpp> #include <primesum.hpp> #include <primesieve.hpp> #include <calculator.hpp> #include <int128.hpp> #include <pmath.hpp> #include <algorithm> #include <ctime> #include <cmath> #include <limits> #include <sstream> #include <string> #include <stdint.h> #ifdef _OPENMP #include <omp.h> #endif #ifdef HAVE_MPI #include <mpi.h> namespace primesum { int mpi_num_procs() { int procs; MPI_Comm_size(MPI_COMM_WORLD, &procs); return procs; } int mpi_proc_id() { int proc_id; MPI_Comm_rank(MPI_COMM_WORLD, &proc_id); return proc_id; } int mpi_master_proc_id() { return 0; } bool is_mpi_master_proc() { return mpi_proc_id() == mpi_master_proc_id(); } } // namespace #endif using namespace std; namespace { int threads_ = primesum::MAX_THREADS; int status_precision_ = -1; double alpha_ = -1; } namespace primesum { maxint_t pi(maxint_t x, int threads) { return pi_deleglise_rivat(x, threads); } maxint_t pi(maxint_t x) { return pi(x, threads_); } /// Alias for the fastest prime summing function in primesum. /// @param x integer arithmetic expression e.g. "10^12". /// @pre x <= get_max_x(). /// string pi(const string& x) { return pi(x, threads_); } /// Alias for the fastest prime summing function in primesum. /// @param x integer arithmetic expression e.g. "10^12". /// @pre x <= get_max_x(). /// string pi(const string& x, int threads) { maxint_t pi_x = pi(to_maxint(x), threads); ostringstream oss; oss << pi_x; return oss.str(); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// maxint_t pi_deleglise_rivat(maxint_t x, int threads) { return pi_deleglise_rivat_parallel1(x, threads); } /// Calculate the number of primes below x using Legendre's formula. /// Run time: O(x) operations, O(x^(1/2)) space. /// int64_t pi_legendre(int64_t x) { return pi_legendre(x, threads_); } /// Parallel implementation of the Lagarias-Miller-Odlyzko /// prime summing algorithm using OpenMP. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// maxint_t pi_lmo(maxint_t x, int threads) { return pi_lmo_parallel1(x, threads); } /// Calculate the number of primes below x using an optimized /// segmented sieve of Eratosthenes implementation. /// Run time: O(x log log x) operations, O(x^(1/2)) space. /// int64_t pi_primesieve(int64_t x) { return pi_primesieve(x, threads_); } /// Calculate the nth prime using a combination of the prime /// counting function and the sieve of Eratosthenes. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space. /// int64_t nth_prime(int64_t n) { return nth_prime(n, threads_); } /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// int64_t phi(int64_t x, int64_t a) { return phi(x, a, threads_); } int64_t prime_sum_tiny(int64_t x) { int64_t prime = 0; int64_t prime_sum = 0; primesieve::iterator iter(0, x); while ((prime = iter.next_prime()) <= x) prime_sum += prime; return prime_sum; } /// Returns the largest integer that can be used with /// pi(string x). The return type is a string as max can be a 128-bit /// integer which is not supported by all compilers. /// string get_max_x(double alpha) { ostringstream oss; #ifdef HAVE_INT128_T // primesum is limited by: // z < 2^62, with z = x^(2/3) / alpha // x^(2/3) / alpha < 2^62 // x < (2^62 * alpha)^(3/2) // safety buffer: use 61 instead of 62 double max_x = pow(pow(2.0, 61.0) * alpha, 3.0 / 2.0); oss << (int128_t) max_x; #else unused_param(alpha); oss << numeric_limits<int64_t>::max(); #endif return oss.str(); } /// Get the wall time in seconds. double get_wtime() { #ifdef _OPENMP return omp_get_wtime(); #else return static_cast<double>(std::clock()) / CLOCKS_PER_SEC; #endif } int validate_threads(int threads) { #ifdef _OPENMP if (threads == MAX_THREADS) threads = omp_get_max_threads(); return in_between(1, threads, omp_get_max_threads()); #else threads = 1; return threads; #endif } int validate_threads(int threads, int64_t sieve_limit, int64_t thread_threshold) { threads = validate_threads(threads); thread_threshold = max((int64_t) 1, thread_threshold); threads = (int) min((int64_t) threads, sieve_limit / thread_threshold); threads = max(1, threads); return threads; } void set_alpha(double alpha) { alpha_ = alpha; } double get_alpha() { return alpha_; } double get_alpha(maxint_t x, int64_t y) { // y = x13 * alpha, thus alpha = y / x13 double x13 = (double) iroot<3>(x); return (double) y / x13; } /// Calculate the Lagarias-Miller-Odlyzko alpha tuning factor. /// alpha = a log(x)^2 + b log(x) + c /// a, b and c are constants that should be determined empirically. /// @see ../doc/alpha-factor-tuning.pdf /// double get_alpha_lmo(maxint_t x) { double alpha = get_alpha(); // use default alpha if no command-line alpha provided if (alpha < 1) { double a = 0.00156512; double b = -0.0261411; double c = 0.990948; double logx = log((double) x); alpha = a * pow(logx, 2) + b * logx + c; } return in_between(1, alpha, iroot<6>(x)); } /// Calculate the Deleglise-Rivat alpha tuning factor. /// alpha = a log(x)^3 + b log(x)^2 + c log(x) + d /// a, b, c and d are constants that should be determined empirically. /// @see ../doc/alpha-tuning-factor.pdf /// double get_alpha_deleglise_rivat(maxint_t x) { double alpha = get_alpha(); double x2 = (double) x; // use default alpha if no command-line alpha provided if (alpha < 1) { double a = 0.00261288; double b = -0.0975921; double c = 0.964706; double d = -0.5712; double logx = log(x2); alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d; } return in_between(1, alpha, iroot<6>(x)); } void set_num_threads(int threads) { threads_ = validate_threads(threads); } int get_num_threads() { return validate_threads(threads_); } void set_status_precision(int precision) { status_precision_ = in_between(0, precision, 5); } int get_status_precision(maxint_t x) { // use default precision when no command-line precision provided if (status_precision_ < 0) { if ((double) x >= 1e23) return 2; if ((double) x >= 1e21) return 1; } return (status_precision_ > 0) ? status_precision_ : 0; } maxint_t to_maxint(const string& expr) { maxint_t n = calculator::eval<maxint_t>(expr); return n; } /// Get the primesum version number, in the form “i.j”. string primesum_version() { return PRIMESUM_VERSION; } } // namespace primesum <|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Fons Rademakers 11/10/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TStopwatch // // // // Stopwatch class. This class returns the real and cpu time between // // the start and stop events. // // // ////////////////////////////////////////////////////////////////////////// #include "TStopwatch.h" #include "TTimeStamp.h" #include "TString.h" #if defined(R__UNIX) # include <sys/times.h> # include <unistd.h> static Double_t gTicks = 0; #elif defined(WIN32) # include "TError.h" const Double_t gTicks = 1.0e-7; # include "Windows4Root.h" #endif ClassImp(TStopwatch) //______________________________________________________________________________ TStopwatch::TStopwatch() { // Create a stopwatch and start it. #ifdef R__UNIX if (gTicks <= 0.0) gTicks = (Double_t)sysconf(_SC_CLK_TCK); #endif Start(); } //______________________________________________________________________________ void TStopwatch::Start(Bool_t reset) { // Start the stopwatch. If reset is kTRUE reset the stopwatch before // starting it (including the stopwatch counter). // Use kFALSE to continue timing after a Stop() without // resetting the stopwatch. if (reset) { fState = kUndefined; fTotalCpuTime = 0; fTotalRealTime = 0; fCounter = 0; } if (fState != kRunning) { fStartRealTime = GetRealTime(); fStartCpuTime = GetCPUTime(); } fState = kRunning; fCounter++; } //______________________________________________________________________________ void TStopwatch::Stop() { // Stop the stopwatch. fStopRealTime = GetRealTime(); fStopCpuTime = GetCPUTime(); if (fState == kRunning) { fTotalCpuTime += fStopCpuTime - fStartCpuTime; fTotalRealTime += fStopRealTime - fStartRealTime; } fState = kStopped; } //______________________________________________________________________________ void TStopwatch::Continue() { // Resume a stopped stopwatch. The stopwatch continues counting from the last // Start() onwards (this is like the laptimer function). if (fState == kUndefined) Error("Continue", "stopwatch not started"); if (fState == kStopped) { fTotalCpuTime -= fStopCpuTime - fStartCpuTime; fTotalRealTime -= fStopRealTime - fStartRealTime; } fState = kRunning; } //______________________________________________________________________________ Double_t TStopwatch::RealTime() { // Return the realtime passed between the start and stop events. If the // stopwatch was still running stop it first. if (fState == kUndefined) Error("RealTime", "stopwatch not started"); if (fState == kRunning) Stop(); return fTotalRealTime; } //______________________________________________________________________________ Double_t TStopwatch::CpuTime() { // Return the cputime passed between the start and stop events. If the // stopwatch was still running stop it first. if (fState == kUndefined) Error("CpuTime", "stopwatch not started"); if (fState == kRunning) Stop(); return fTotalCpuTime; } //______________________________________________________________________________ Double_t TStopwatch::GetRealTime() { // Private static method returning system realtime. #if defined(R__UNIX) return TTimeStamp(); #elif defined(WIN32) union { FILETIME ftFileTime; __int64 ftInt64; } ftRealTime; // time the process has spent in kernel mode SYSTEMTIME st; GetSystemTime(&st); SystemTimeToFileTime(&st,&ftRealTime.ftFileTime); return (Double_t)ftRealTime.ftInt64 * gTicks; #endif } //______________________________________________________________________________ Double_t TStopwatch::GetCPUTime() { // Private static method returning system CPU time. #if defined(R__UNIX) struct tms cpt; times(&cpt); return (Double_t)(cpt.tms_utime+cpt.tms_stime) / gTicks; #elif defined(WIN32) OSVERSIONINFO OsVersionInfo; // Value Platform //---------------------------------------------------- // VER_PLATFORM_WIN32s Win32s on Windows 3.1 // VER_PLATFORM_WIN32_WINDOWS Win32 on Windows 95 // VER_PLATFORM_WIN32_NT Windows NT // OsVersionInfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO); GetVersionEx(&OsVersionInfo); if (OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) { DWORD ret; FILETIME ftCreate, // when the process was created ftExit; // when the process exited union { FILETIME ftFileTime; __int64 ftInt64; } ftKernel; // time the process has spent in kernel mode union { FILETIME ftFileTime; __int64 ftInt64; } ftUser; // time the process has spent in user mode HANDLE hThread = GetCurrentThread(); ret = GetThreadTimes (hThread, &ftCreate, &ftExit, &ftKernel.ftFileTime, &ftUser.ftFileTime); if (ret != TRUE) { ret = GetLastError (); ::Error ("GetCPUTime", " Error on GetProcessTimes 0x%lx", (int)ret); } // Process times are returned in a 64-bit structure, as the number of // 100 nanosecond ticks since 1 January 1601. User mode and kernel mode // times for this process are in separate 64-bit structures. // To convert to floating point seconds, we will: // // Convert sum of high 32-bit quantities to 64-bit int return (Double_t) (ftKernel.ftInt64 + ftUser.ftInt64) * gTicks; } else return GetRealTime(); #endif } //______________________________________________________________________________ void TStopwatch::Print(Option_t *opt) const { // Print the real and cpu time passed between the start and stop events. // and the number of times (slices) this TStopwatch was called // (if this number > 1). If opt="m" print out realtime in milli second // precision. If opt="u" print out realtime in micro second precision. Double_t realt = const_cast<TStopwatch*>(this)->RealTime(); Double_t cput = const_cast<TStopwatch*>(this)->CpuTime(); Int_t hours = Int_t(realt / 3600); realt -= hours * 3600; Int_t min = Int_t(realt / 60); realt -= min * 60; Int_t sec = Int_t(realt); if (realt < 0) realt = 0; if (cput < 0) cput = 0; if (opt && *opt == 'm') { if (Counter() > 1) { Printf("Real time %d:%02d:%06.3f, CP time %.3f, %d slices", hours, min, realt, cput, Counter()); } else { Printf("Real time %d:%02d:%06.3f, CP time %.3f", hours, min, realt, cput); } } else if (opt && *opt == 'u') { if (Counter() > 1) { Printf("Real time %d:%02d:%09.6f, CP time %.3f, %d slices", hours, min, realt, cput, Counter()); } else { Printf("Real time %d:%02d:%09.6f, CP time %.3f", hours, min, realt, cput); } } else { if (Counter() > 1) { Printf("Real time %d:%02d:%02d, CP time %.3f, %d slices", hours, min, sec, cput, Counter()); } else { Printf("Real time %d:%02d:%02d, CP time %.3f", hours, min, sec, cput); } } } <commit_msg>coverity 11108.<commit_after>// @(#)root/base:$Id$ // Author: Fons Rademakers 11/10/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TStopwatch // // // // Stopwatch class. This class returns the real and cpu time between // // the start and stop events. // // // ////////////////////////////////////////////////////////////////////////// #include "TStopwatch.h" #include "TTimeStamp.h" #include "TString.h" #if defined(R__UNIX) # include <sys/times.h> # include <unistd.h> static Double_t gTicks = 0; #elif defined(WIN32) # include "TError.h" const Double_t gTicks = 1.0e-7; # include "Windows4Root.h" #endif ClassImp(TStopwatch) //______________________________________________________________________________ TStopwatch::TStopwatch() { // Create a stopwatch and start it. #ifdef R__UNIX if (gTicks <= 0.0) gTicks = (Double_t)sysconf(_SC_CLK_TCK); #endif fStopRealTime = 0; fStopCpuTime = 0; Start(); } //______________________________________________________________________________ void TStopwatch::Start(Bool_t reset) { // Start the stopwatch. If reset is kTRUE reset the stopwatch before // starting it (including the stopwatch counter). // Use kFALSE to continue timing after a Stop() without // resetting the stopwatch. if (reset) { fState = kUndefined; fTotalCpuTime = 0; fTotalRealTime = 0; fCounter = 0; } if (fState != kRunning) { fStartRealTime = GetRealTime(); fStartCpuTime = GetCPUTime(); } fState = kRunning; fCounter++; } //______________________________________________________________________________ void TStopwatch::Stop() { // Stop the stopwatch. fStopRealTime = GetRealTime(); fStopCpuTime = GetCPUTime(); if (fState == kRunning) { fTotalCpuTime += fStopCpuTime - fStartCpuTime; fTotalRealTime += fStopRealTime - fStartRealTime; } fState = kStopped; } //______________________________________________________________________________ void TStopwatch::Continue() { // Resume a stopped stopwatch. The stopwatch continues counting from the last // Start() onwards (this is like the laptimer function). if (fState == kUndefined) Error("Continue", "stopwatch not started"); if (fState == kStopped) { fTotalCpuTime -= fStopCpuTime - fStartCpuTime; fTotalRealTime -= fStopRealTime - fStartRealTime; } fState = kRunning; } //______________________________________________________________________________ Double_t TStopwatch::RealTime() { // Return the realtime passed between the start and stop events. If the // stopwatch was still running stop it first. if (fState == kUndefined) Error("RealTime", "stopwatch not started"); if (fState == kRunning) Stop(); return fTotalRealTime; } //______________________________________________________________________________ Double_t TStopwatch::CpuTime() { // Return the cputime passed between the start and stop events. If the // stopwatch was still running stop it first. if (fState == kUndefined) Error("CpuTime", "stopwatch not started"); if (fState == kRunning) Stop(); return fTotalCpuTime; } //______________________________________________________________________________ Double_t TStopwatch::GetRealTime() { // Private static method returning system realtime. #if defined(R__UNIX) return TTimeStamp(); #elif defined(WIN32) union { FILETIME ftFileTime; __int64 ftInt64; } ftRealTime; // time the process has spent in kernel mode SYSTEMTIME st; GetSystemTime(&st); SystemTimeToFileTime(&st,&ftRealTime.ftFileTime); return (Double_t)ftRealTime.ftInt64 * gTicks; #endif } //______________________________________________________________________________ Double_t TStopwatch::GetCPUTime() { // Private static method returning system CPU time. #if defined(R__UNIX) struct tms cpt; times(&cpt); return (Double_t)(cpt.tms_utime+cpt.tms_stime) / gTicks; #elif defined(WIN32) OSVERSIONINFO OsVersionInfo; // Value Platform //---------------------------------------------------- // VER_PLATFORM_WIN32s Win32s on Windows 3.1 // VER_PLATFORM_WIN32_WINDOWS Win32 on Windows 95 // VER_PLATFORM_WIN32_NT Windows NT // OsVersionInfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO); GetVersionEx(&OsVersionInfo); if (OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) { DWORD ret; FILETIME ftCreate, // when the process was created ftExit; // when the process exited union { FILETIME ftFileTime; __int64 ftInt64; } ftKernel; // time the process has spent in kernel mode union { FILETIME ftFileTime; __int64 ftInt64; } ftUser; // time the process has spent in user mode HANDLE hThread = GetCurrentThread(); ret = GetThreadTimes (hThread, &ftCreate, &ftExit, &ftKernel.ftFileTime, &ftUser.ftFileTime); if (ret != TRUE) { ret = GetLastError (); ::Error ("GetCPUTime", " Error on GetProcessTimes 0x%lx", (int)ret); } // Process times are returned in a 64-bit structure, as the number of // 100 nanosecond ticks since 1 January 1601. User mode and kernel mode // times for this process are in separate 64-bit structures. // To convert to floating point seconds, we will: // // Convert sum of high 32-bit quantities to 64-bit int return (Double_t) (ftKernel.ftInt64 + ftUser.ftInt64) * gTicks; } else return GetRealTime(); #endif } //______________________________________________________________________________ void TStopwatch::Print(Option_t *opt) const { // Print the real and cpu time passed between the start and stop events. // and the number of times (slices) this TStopwatch was called // (if this number > 1). If opt="m" print out realtime in milli second // precision. If opt="u" print out realtime in micro second precision. Double_t realt = const_cast<TStopwatch*>(this)->RealTime(); Double_t cput = const_cast<TStopwatch*>(this)->CpuTime(); Int_t hours = Int_t(realt / 3600); realt -= hours * 3600; Int_t min = Int_t(realt / 60); realt -= min * 60; Int_t sec = Int_t(realt); if (realt < 0) realt = 0; if (cput < 0) cput = 0; if (opt && *opt == 'm') { if (Counter() > 1) { Printf("Real time %d:%02d:%06.3f, CP time %.3f, %d slices", hours, min, realt, cput, Counter()); } else { Printf("Real time %d:%02d:%06.3f, CP time %.3f", hours, min, realt, cput); } } else if (opt && *opt == 'u') { if (Counter() > 1) { Printf("Real time %d:%02d:%09.6f, CP time %.3f, %d slices", hours, min, realt, cput, Counter()); } else { Printf("Real time %d:%02d:%09.6f, CP time %.3f", hours, min, realt, cput); } } else { if (Counter() > 1) { Printf("Real time %d:%02d:%02d, CP time %.3f, %d slices", hours, min, sec, cput, Counter()); } else { Printf("Real time %d:%02d:%02d, CP time %.3f", hours, min, sec, cput); } } } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file src/relay/transforms/quantize_fake_quantization.cc * \brief A pass for taking fake quantized graphs and converting them * to actual integer operations. */ #include <tvm/relay/expr.h> #include <tvm/relay/expr_functor.h> #include <tvm/relay/transform.h> /* Description of FakeQuantizationToInteger * * The purpose of this pass is to find regions of the graph that follow * the general pattern: * * x w * | | * dq dq * \ / * op1 * | * op2 * | * q * * and convert them into subgraphs with actual integer operations on x and w * * The pass does this via a multi-pass approach: * * The main pass is a MixedModeMutator that traverses the full graph searching for * quantize operations * * The second pass is an ExprVisitor that recursively searches for subgraphs leading to the * quantize for subtraphs bounded by dequantize operations. This pass extracts the affine * types of the inputs for later processing, where affine denotes the transformation * x_real = (x_affine - zero_point) * scale * * The third pass is an ExprMutator that recursively rewrites the subgraphs using packed funcs * registered with the FTVMFakeQuantizationToInteger attribute. These packed funcs rewrite * the ops based on the affine types of their inputs and then return the affine types of the * new rewriten ops to pass that information down the stack during rewrite. * * After the second and third passes run, the first pass replaces the quantize with the * rewritten subgraph and the processing continues */ namespace tvm { namespace relay { /*! * \brief AffineType representation * \sa AffineType */ class AffineTypeNode : public Object { public: /*! \brief The scale of this type */ Expr scale; /*! \brief The zero point of this type */ Expr zero_point; /*! \brief The data type of this type */ DataType dtype; void VisitAttrs(tvm::AttrVisitor* v) { v->Visit("scale", &scale); v->Visit("zero_point", &zero_point); v->Visit("dtype", &dtype); } bool SEqualReduce(const AffineTypeNode* other, SEqualReducer equal) const { equal->MarkGraphNode(); return equal(scale, other->scale) && equal(zero_point, other->zero_point) && equal(dtype, other->dtype); } void SHashReduce(SHashReducer hash_reduce) const { hash_reduce->MarkGraphNode(); hash_reduce(scale); hash_reduce(zero_point); hash_reduce(dtype); } static constexpr const bool _type_has_method_sequal_reduce = true; static constexpr const bool _type_has_method_shash_reduce = true; static constexpr const char* _type_key = "AffineTypeNode"; TVM_DECLARE_BASE_OBJECT_INFO(AffineTypeNode, Object); }; /*! * \brief Managed reference to AffineTypes. * \sa AffineTypeNode */ class AffineType : public ObjectRef { public: TVM_DLL AffineType(Expr scale, Expr zero_point, DataType dtype) { ObjectPtr<AffineTypeNode> n = make_object<AffineTypeNode>(); n->scale = std::move(scale); n->zero_point = std::move(zero_point); n->dtype = std::move(dtype); data_ = std::move(n); } TVM_DEFINE_OBJECT_REF_METHODS(AffineType, ObjectRef, AffineTypeNode); }; TVM_REGISTER_NODE_TYPE(AffineTypeNode); using ExprSet = std::unordered_set<Expr, ObjectPtrHash, ObjectPtrEqual>; using ExprMap = std::unordered_map<Expr, Expr, ObjectPtrHash, ObjectPtrEqual>; using AffineTypeMap = Map<Expr, AffineType>; using FTVMFakeQuantizationToInteger = runtime::TypedPackedFunc<Array<ObjectRef>(const Expr& expr, const AffineTypeMap& map)>; class SubgraphExtractor : public ExprVisitor { public: const ExprSet GetSubgraph(const Expr& expr) { VisitExpr(expr); ExprSet subgraph; if (is_fake_quantized_) { for (auto kv : this->visit_counter_) { if (auto call_node = GetRef<ObjectRef>(kv.first).as<CallNode>()) { if (call_node->op != quantize_op_) { subgraph.insert(Downcast<Expr>(GetRef<ObjectRef>(kv.first))); } } } } return subgraph; } const AffineTypeMap GetAffineTypes() { return affine_types_; } void VisitExpr(const Expr& expr) { if (expr.as<CallNode>() == nullptr && expr.as<OpNode>() == nullptr && expr.as<TupleNode>() == nullptr) { is_fake_quantized_ = false; } else { ExprVisitor::VisitExpr(expr); } } protected: void VisitExpr_(const CallNode* call_node) override { if (call_node->op == quantize_op_) { // Only look at arg0 for quantize VisitExpr(call_node->args[0]); // Collect type of quantize ops affine_types_.Set(GetRef<Expr>(call_node), AffineType(call_node->args[1], call_node->args[2], call_node->checked_type().as<TensorTypeNode>()->dtype)); } else if (call_node->op == dequantize_op_) { // Collect type of dequantize ops affine_types_.Set(GetRef<Expr>(call_node), AffineType(call_node->args[1], call_node->args[2], call_node->args[0]->checked_type().as<TensorTypeNode>()->dtype)); } else { // run normally on everything else. ExprVisitor::VisitExpr_(call_node); } } const Op quantize_op_ = Op::Get("qnn.quantize"); const Op dequantize_op_ = Op::Get("qnn.dequantize"); bool is_fake_quantized_ = true; AffineTypeMap affine_types_; }; class SubgraphMutator : public ExprMutator { public: SubgraphMutator(ExprSet subgraph, AffineTypeMap affine_types) : subgraph_(subgraph), affine_types_(affine_types) {} Expr MutateSubgraph(const Expr& expr) { if (subgraph_.size() == 0) { return expr; } const CallNode* quantize_node = expr.as<CallNode>(); ICHECK(quantize_node); ICHECK(quantize_node->op == quantize_op_); out_type_ = affine_types_[expr]; static auto fqfq = Op::GetAttrMap<FTVMFakeQuantizationToInteger>("FTVMFakeQuantizationToInteger"); for (auto node : subgraph_) { if (!fqfq.count(Downcast<Op>(node.as<CallNode>()->op))) { // Only modify the subgraph if we have translation // rules for every op return expr; } } return Mutate(expr); } protected: Expr VisitExpr_(const CallNode* call_node) { Expr out; static auto fqfq = Op::GetAttrMap<FTVMFakeQuantizationToInteger>("FTVMFakeQuantizationToInteger"); Op op = Downcast<Op>(call_node->op); if (fqfq.count(op)) { Expr expr; if (op == dequantize_op_) { expr = GetRef<Expr>(call_node); } else { expr = ExprMutator::VisitExpr_(call_node); // Set the current op to the output type, useful if we can't deduce output parameters // from input parameters affine_types_.Set(expr, out_type_); } // Call the rewrite Array<ObjectRef> vals = fqfq[op](expr, affine_types_); // Save teh outputs of the rewrite ICHECK(vals.size() == 4) << "got the wrong number of returned arguments from FTVMFakeQuantizationToInteger for " << AsText(op, false); out = Downcast<Expr>(vals[0]); affine_types_.Set(out, AffineType(Downcast<Expr>(vals[1]), Downcast<Expr>(vals[2]), DataType(String2DLDataType(Downcast<String>(vals[3]))))); } else { ICHECK(false) << "When rewriting a fake quantized graph, found an invalid node " << AsText(GetRef<Expr>(call_node), false); } return out; } ExprSet subgraph_; AffineTypeMap affine_types_; AffineType out_type_; const Op quantize_op_ = Op::Get("qnn.quantize"); const Op dequantize_op_ = Op::Get("qnn.dequantize"); }; class FakeQuantizationRewriter : public MixedModeMutator { protected: Expr Rewrite_(const CallNode* pre, const Expr& post) override { if (const CallNode* call_node = post.as<CallNode>()) { if (call_node->op == quantize_op_) { SubgraphExtractor extractor; ExprSet subgraph = extractor.GetSubgraph(GetRef<Expr>(pre)); AffineTypeMap affine_types = extractor.GetAffineTypes(); ExprSet post_subgraph; AffineTypeMap post_affine_types; for (auto kv : affine_types) { if (pre == kv.first.as<CallNode>()) { // we havent memoized the current op yet post_affine_types.Set(post, kv.second); } else { post_affine_types.Set(memo_.at(kv.first), kv.second); } } for (auto expr : subgraph) { post_subgraph.insert(memo_[expr]); } Expr out = SubgraphMutator(post_subgraph, post_affine_types).MutateSubgraph(post); return out; } } return post; } const Op quantize_op_ = Op::Get("qnn.quantize"); }; Expr FakeQuantizationToInteger(const Expr& expr, const IRModule& mod) { return FakeQuantizationRewriter().Mutate(expr); } namespace transform { Pass FakeQuantizationToInteger() { runtime::TypedPackedFunc<Function(Function, IRModule, PassContext)> pass_func = [=](Function f, IRModule m, PassContext pc) { return Downcast<Function>(FakeQuantizationToInteger(f, m)); }; return CreateFunctionPass(pass_func, 0, "FakeQuantizationToInteger", {"InferType"}); } TVM_REGISTER_GLOBAL("relay._transform.FakeQuantizationToInteger") .set_body_typed(FakeQuantizationToInteger); } // namespace transform } // namespace relay } // namespace tvm <commit_msg>fake quantization to integer (#8228)<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file src/relay/transforms/quantize_fake_quantization.cc * \brief A pass for taking fake quantized graphs and converting them * to actual integer operations. */ #include <tvm/relay/expr.h> #include <tvm/relay/expr_functor.h> #include <tvm/relay/transform.h> /* Description of FakeQuantizationToInteger * * The purpose of this pass is to find regions of the graph that follow * the general pattern: * * x w * | | * dq dq * \ / * op1 * | * op2 * | * q * * and convert them into subgraphs with actual integer operations on x and w * * The pass does this via a multi-pass approach: * * The main pass is a MixedModeMutator that traverses the full graph searching for * quantize operations * * The second pass is an ExprVisitor that recursively searches for subgraphs leading to the * quantize for subtraphs bounded by dequantize operations. This pass extracts the affine * types of the inputs for later processing, where affine denotes the transformation * x_real = (x_affine - zero_point) * scale * * The third pass is an ExprMutator that recursively rewrites the subgraphs using packed funcs * registered with the FTVMFakeQuantizationToInteger attribute. These packed funcs rewrite * the ops based on the affine types of their inputs and then return the affine types of the * new rewriten ops to pass that information down the stack during rewrite. * * After the second and third passes run, the first pass replaces the quantize with the * rewritten subgraph and the processing continues */ namespace tvm { namespace relay { /*! * \brief AffineType representation * \sa AffineType */ class AffineTypeNode : public Object { public: /*! \brief The scale of this type */ Expr scale; /*! \brief The zero point of this type */ Expr zero_point; /*! \brief The data type of this type */ DataType dtype; void VisitAttrs(tvm::AttrVisitor* v) { v->Visit("scale", &scale); v->Visit("zero_point", &zero_point); v->Visit("dtype", &dtype); } bool SEqualReduce(const AffineTypeNode* other, SEqualReducer equal) const { equal->MarkGraphNode(); return equal(scale, other->scale) && equal(zero_point, other->zero_point) && equal(dtype, other->dtype); } void SHashReduce(SHashReducer hash_reduce) const { hash_reduce->MarkGraphNode(); hash_reduce(scale); hash_reduce(zero_point); hash_reduce(dtype); } static constexpr const bool _type_has_method_sequal_reduce = true; static constexpr const bool _type_has_method_shash_reduce = true; static constexpr const char* _type_key = "AffineTypeNode"; TVM_DECLARE_BASE_OBJECT_INFO(AffineTypeNode, Object); }; /*! * \brief Managed reference to AffineTypes. * \sa AffineTypeNode */ class AffineType : public ObjectRef { public: TVM_DLL AffineType(Expr scale, Expr zero_point, DataType dtype) { ObjectPtr<AffineTypeNode> n = make_object<AffineTypeNode>(); n->scale = std::move(scale); n->zero_point = std::move(zero_point); n->dtype = std::move(dtype); data_ = std::move(n); } TVM_DEFINE_OBJECT_REF_METHODS(AffineType, ObjectRef, AffineTypeNode); }; TVM_REGISTER_NODE_TYPE(AffineTypeNode); using ExprSet = std::unordered_set<Expr, ObjectPtrHash, ObjectPtrEqual>; using ExprMap = std::unordered_map<Expr, Expr, ObjectPtrHash, ObjectPtrEqual>; using AffineTypeMap = Map<Expr, AffineType>; using FTVMFakeQuantizationToInteger = runtime::TypedPackedFunc<Array<ObjectRef>(const Expr& expr, const AffineTypeMap& map)>; class SubgraphExtractor : public ExprVisitor { public: const ExprSet GetSubgraph(const Expr& expr) { VisitExpr(expr); ExprSet subgraph; if (is_fake_quantized_) { for (auto kv : this->visit_counter_) { if (auto call_node = GetRef<ObjectRef>(kv.first).as<CallNode>()) { if (call_node->op != quantize_op_) { subgraph.insert(Downcast<Expr>(GetRef<ObjectRef>(kv.first))); } } } } return subgraph; } const AffineTypeMap GetAffineTypes() { return affine_types_; } void VisitExpr(const Expr& expr) override { if (expr.as<CallNode>() == nullptr && expr.as<OpNode>() == nullptr && expr.as<TupleNode>() == nullptr) { is_fake_quantized_ = false; } else { ExprVisitor::VisitExpr(expr); } } protected: void VisitExpr_(const CallNode* call_node) override { if (call_node->op == quantize_op_) { // Only look at arg0 for quantize VisitExpr(call_node->args[0]); // Collect type of quantize ops affine_types_.Set(GetRef<Expr>(call_node), AffineType(call_node->args[1], call_node->args[2], call_node->checked_type().as<TensorTypeNode>()->dtype)); } else if (call_node->op == dequantize_op_) { // Collect type of dequantize ops affine_types_.Set(GetRef<Expr>(call_node), AffineType(call_node->args[1], call_node->args[2], call_node->args[0]->checked_type().as<TensorTypeNode>()->dtype)); } else { // run normally on everything else. ExprVisitor::VisitExpr_(call_node); } } const Op quantize_op_ = Op::Get("qnn.quantize"); const Op dequantize_op_ = Op::Get("qnn.dequantize"); bool is_fake_quantized_ = true; AffineTypeMap affine_types_; }; class SubgraphMutator : public ExprMutator { public: SubgraphMutator(ExprSet subgraph, AffineTypeMap affine_types) : subgraph_(subgraph), affine_types_(affine_types) {} Expr MutateSubgraph(const Expr& expr) { if (subgraph_.size() == 0) { return expr; } const CallNode* quantize_node = expr.as<CallNode>(); ICHECK(quantize_node); ICHECK(quantize_node->op == quantize_op_); out_type_ = affine_types_[expr]; static auto fqfq = Op::GetAttrMap<FTVMFakeQuantizationToInteger>("FTVMFakeQuantizationToInteger"); for (auto node : subgraph_) { if (!fqfq.count(Downcast<Op>(node.as<CallNode>()->op))) { // Only modify the subgraph if we have translation // rules for every op return expr; } } return Mutate(expr); } protected: Expr VisitExpr_(const CallNode* call_node) { Expr out; static auto fqfq = Op::GetAttrMap<FTVMFakeQuantizationToInteger>("FTVMFakeQuantizationToInteger"); Op op = Downcast<Op>(call_node->op); if (fqfq.count(op)) { Expr expr; if (op == dequantize_op_) { expr = GetRef<Expr>(call_node); } else { expr = ExprMutator::VisitExpr_(call_node); // Set the current op to the output type, useful if we can't deduce output parameters // from input parameters affine_types_.Set(expr, out_type_); } // Call the rewrite Array<ObjectRef> vals = fqfq[op](expr, affine_types_); // Save teh outputs of the rewrite ICHECK(vals.size() == 4) << "got the wrong number of returned arguments from FTVMFakeQuantizationToInteger for " << AsText(op, false); out = Downcast<Expr>(vals[0]); affine_types_.Set(out, AffineType(Downcast<Expr>(vals[1]), Downcast<Expr>(vals[2]), DataType(String2DLDataType(Downcast<String>(vals[3]))))); } else { ICHECK(false) << "When rewriting a fake quantized graph, found an invalid node " << AsText(GetRef<Expr>(call_node), false); } return out; } ExprSet subgraph_; AffineTypeMap affine_types_; AffineType out_type_; const Op quantize_op_ = Op::Get("qnn.quantize"); const Op dequantize_op_ = Op::Get("qnn.dequantize"); }; class FakeQuantizationRewriter : public MixedModeMutator { protected: Expr Rewrite_(const CallNode* pre, const Expr& post) override { if (const CallNode* call_node = post.as<CallNode>()) { if (call_node->op == quantize_op_) { SubgraphExtractor extractor; ExprSet subgraph = extractor.GetSubgraph(GetRef<Expr>(pre)); AffineTypeMap affine_types = extractor.GetAffineTypes(); ExprSet post_subgraph; AffineTypeMap post_affine_types; for (auto kv : affine_types) { if (pre == kv.first.as<CallNode>()) { // we havent memoized the current op yet post_affine_types.Set(post, kv.second); } else { post_affine_types.Set(memo_.at(kv.first), kv.second); } } for (auto expr : subgraph) { post_subgraph.insert(memo_[expr]); } Expr out = SubgraphMutator(post_subgraph, post_affine_types).MutateSubgraph(post); return out; } } return post; } const Op quantize_op_ = Op::Get("qnn.quantize"); }; Expr FakeQuantizationToInteger(const Expr& expr, const IRModule& mod) { return FakeQuantizationRewriter().Mutate(expr); } namespace transform { Pass FakeQuantizationToInteger() { runtime::TypedPackedFunc<Function(Function, IRModule, PassContext)> pass_func = [=](Function f, IRModule m, PassContext pc) { return Downcast<Function>(FakeQuantizationToInteger(f, m)); }; return CreateFunctionPass(pass_func, 0, "FakeQuantizationToInteger", {"InferType"}); } TVM_REGISTER_GLOBAL("relay._transform.FakeQuantizationToInteger") .set_body_typed(FakeQuantizationToInteger); } // namespace transform } // namespace relay } // namespace tvm <|endoftext|>
<commit_before>#ifndef PLATE2D_HPP #define PLATE2D_HPP #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/datetime.h> #include <vector> #include <functional> #include "Plater.hpp" #include "ColorScheme.hpp" #include "Settings.hpp" #include "Plater/Plater2DObject.hpp" #include "misc_ui.hpp" #include "Log.hpp" namespace Slic3r { namespace GUI { // Setup for an Easter Egg with the canvas text. const wxDateTime today_date {wxDateTime().GetDateOnly()}; const wxDateTime special_date {13, wxDateTime::Month::Sep, 2006, 0, 0, 0, 0}; const bool today_is_special = {today_date.GetDay() == special_date.GetDay() && today_date.GetMonth() == special_date.GetMonth()}; enum class MoveDirection { Up, Down, Left, Right }; class Plate2D : public wxPanel { public: Plate2D(wxWindow* parent, const wxSize& size, std::vector<Plater2DObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings); // std::function<> on_select_object {}; private: std::vector<Plater2DObject>& objects; std::shared_ptr<Slic3r::Model> model; std::shared_ptr<Slic3r::Config> config; std::shared_ptr<Settings> settings; // Different brushes to draw with wxBrush objects_brush {}; wxBrush instance_brush {}; wxBrush selected_brush {}; wxBrush bed_brush {}; wxBrush dragged_brush {}; wxBrush transparent_brush {}; wxPen grid_pen {}; wxPen print_center_pen {}; wxPen clearance_pen {}; wxPen skirt_pen {}; wxPen dark_pen {}; bool user_drawn_background {(the_os == OS::Mac ? false : true)}; size_t selected_instance; /// Handle mouse-move events void mouse_drag(wxMouseEvent& e); /// Handle repaint events void repaint(wxPaintEvent& e); void nudge_key(wxKeyEvent& e); void nudge(MoveDirection dir); /// Set/Update all of the colors used by the various brushes in the panel. void set_colors(); /// Convert a scale point array to a pixel polygon suitable for DrawPolygon std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale); std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polyline& poly, bool unscale); // For a specific point, unscaled it wxPoint unscaled_point_to_pixel(const wxPoint& in) { const auto& canvas_height {this->GetSize().GetHeight()}; const auto& zero = this->bed_origin; return wxPoint(in.x * this->scaling_factor + zero.x, in.y * this->scaling_factor + (zero.y - canvas_height)); } /// Read print bed size from config and calculate the scaled rendition of the bed given the draw canvas. void update_bed_size(); /// private class variables to stash bits for drawing the print bed area. wxPoint bed_origin {}; wxPoint print_center {}; Slic3r::Polygon bed_polygon {}; std::vector<wxPoint> grid {}; /// Set up the 2D canvas blank canvas text. /// Easter egg: Sept. 13, 2006. The first part ever printed by a RepRap to make another RepRap. const wxString CANVAS_TEXT { today_is_special ? _(L"What do you want to print today?™") : _("Drag your objects here") }; /// How much to scale the points to fit in the draw bounding box area. /// Expressed as pixel / mm double scaling_factor {1.0}; const std::string LogChannel {"GUI_2D"}; }; } } // Namespace Slic3r::GUI #endif // PLATE2D_HPP <commit_msg>Added point_to_model_units() and clarified a couple comments.<commit_after>#ifndef PLATE2D_HPP #define PLATE2D_HPP #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/datetime.h> #include <vector> #include <functional> #include "Plater.hpp" #include "ColorScheme.hpp" #include "Settings.hpp" #include "Plater/Plater2DObject.hpp" #include "misc_ui.hpp" #include "Log.hpp" namespace Slic3r { namespace GUI { // Setup for an Easter Egg with the canvas text. const wxDateTime today_date {wxDateTime().GetDateOnly()}; const wxDateTime special_date {13, wxDateTime::Month::Sep, 2006, 0, 0, 0, 0}; const bool today_is_special = {today_date.GetDay() == special_date.GetDay() && today_date.GetMonth() == special_date.GetMonth()}; enum class MoveDirection { Up, Down, Left, Right }; class Plate2D : public wxPanel { public: Plate2D(wxWindow* parent, const wxSize& size, std::vector<Plater2DObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings); // std::function<> on_select_object {}; private: std::vector<Plater2DObject>& objects; std::shared_ptr<Slic3r::Model> model; std::shared_ptr<Slic3r::Config> config; std::shared_ptr<Settings> settings; // Different brushes to draw with, initialized from settings->Color during the constructor wxBrush objects_brush {}; wxBrush instance_brush {}; wxBrush selected_brush {}; wxBrush bed_brush {}; wxBrush dragged_brush {}; wxBrush transparent_brush {}; wxPen grid_pen {}; wxPen print_center_pen {}; wxPen clearance_pen {}; wxPen skirt_pen {}; wxPen dark_pen {}; bool user_drawn_background {(the_os == OS::Mac ? false : true)}; size_t selected_instance; /// Handle mouse-move events void mouse_drag(wxMouseEvent& e); /// Handle repaint events void repaint(wxPaintEvent& e); void nudge_key(wxKeyEvent& e); void nudge(MoveDirection dir); /// Set/Update all of the colors used by the various brushes in the panel. void set_colors(); /// Convert a scale point array to a pixel polygon suitable for DrawPolygon std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale); std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polyline& poly, bool unscale); /// For a specific point, unscale it relative to the origin wxPoint unscaled_point_to_pixel(const wxPoint& in) { const auto& canvas_height {this->GetSize().GetHeight()}; const auto& zero = this->bed_origin; return wxPoint(in.x * this->scaling_factor + zero.x, in.y * this->scaling_factor + (zero.y - canvas_height)); } /// Read print bed size from config and calculate the scaled rendition of the bed given the draw canvas. void update_bed_size(); /// private class variables to stash bits for drawing the print bed area. wxPoint bed_origin {}; wxPoint print_center {}; Slic3r::Polygon bed_polygon {}; std::vector<wxPoint> grid {}; /// Set up the 2D canvas blank canvas text. /// Easter egg: Sept. 13, 2006. The first part ever printed by a RepRap to make another RepRap. const wxString CANVAS_TEXT { today_is_special ? _(L"What do you want to print today?™") : _("Drag your objects here") }; /// How much to scale the points to fit in the draw bounding box area. /// Expressed as pixel / mm double scaling_factor {1.0}; const std::string LogChannel {"GUI_2D"}; Slic3r::Point point_to_model_units(coordf_t x, coordf_t y) { const auto& zero {this->bed_origin}; return Slic3r::Point( scale_(x - zero.x) / this->scaling_factor, scale_(y - zero.y) / this->scaling_factor ); } Slic3r::Point point_to_model_units(const wxPoint& pt) { return this->point_to_model_units(pt.x, pt.y); } Slic3r::Point point_to_model_units(const Pointf& pt) { return this->point_to_model_units(pt.x, pt.y); } }; } } // Namespace Slic3r::GUI #endif // PLATE2D_HPP <|endoftext|>
<commit_before>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 */ /* Hardware tests for general POST (power-on self tests) and for detailed hardware diagnostics. Some are generic such as testing clock behaviour, others will be very specific to some board revisions (eg looking for shorts or testing expected attached hardware). Most should return true on success and false on failure. Some may require being passed a Print reference (which will often be an active hardware serial connection) to dump diagnostics to. */ #ifndef OTV0P2BASE_HARDWARETESTS_H #define OTV0P2BASE_HARDWARETESTS_H #ifdef ARDUINO_ARCH_AVR #include "util/atomic.h" #endif #include "OTV0P2BASE_Entropy.h" #include "OTV0P2BASE_Sleep.h" #include "OTV0P2BASE_HardwareTests.h" #include "OTV0P2BASE_Serial_IO.h" namespace OTV0P2BASE { namespace HWTEST { #ifdef ARDUINO_ARCH_AVR // Returns true if the 32768Hz low-frequency async crystal oscillator appears to be running. // This means the the Timer 2 clock needs to be running // and have an acceptable frequency compared to the CPU clock (1MHz). // Uses nap, and needs the Timer 2 to have been set up in async clock mode. // In passing gathers some entropy for the system. bool check32768HzOsc() { // Check that the 32768Hz async clock is actually running at least somewhat. const uint8_t initialSCT = OTV0P2BASE::getSubCycleTime(); // Allow time for 32768Hz crystal to start reliably, see: http://www.atmel.com/Images/doc1259.pdf #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("Sleeping to let 32768Hz clock start..."); #endif // Time spent here should not be a whole multiple of basic cycle time // to avoid a spuriously-stationary async clock reading! // Allow several seconds (~3s+) to start. // Attempt to capture some entropy while waiting, // implicitly from oscillator start-up time if nothing else. for(uint8_t i = 255; --i > 0; ) { const uint8_t sct = OTV0P2BASE::getSubCycleTime(); OTV0P2BASE::addEntropyToPool(sct, 0); // If counter has incremented/changed (twice) then assume probably OK. if((sct != initialSCT) && (sct != (uint8_t)(initialSCT+1))) { return(true); } // Ensure lower bound of ~3s until loop finishes. OTV0P2BASE::nap(WDTO_15MS); } #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("32768Hz clock may not be running!"); #endif return(false); // FAIL // panic(F("Xtal")); // Async clock not running. } #endif #endif #ifdef ARDUINO_ARCH_AVR // Returns true if the 32768Hz low-frequency async crystal oscillator appears to be running and sane. // Performs an extended test that the CPU (RC) and crystal frequencies are in a sensible ratio. // This means the the Timer 2 clock needs to be running // and have an acceptable frequency compared to the CPU clock (1MHz). // Uses nap, and needs the Timer 2 to have been set up in async clock mode. // In passing gathers some entropy for the system. bool check32768HzOscExtended() { // Check that the slow clock appears to be running. if(!check32768HzOsc()) { return(false); } // Test low frequency oscillator vs main CPU clock oscillator (at 1MHz). // Tests clock frequency between 15 ms naps between for up to 30 cycles and fails if not within bounds. // As of 2016-02-16, all working REV7s give count >= 120 and that fail to program via bootloader give count <= 119 // REV10 gives 119-120 (only one tested though). static const uint8_t optimalLFClock = 122; // May be optimal... static const uint8_t errorLFClock = 4; // Max drift from allowed value. uint8_t count = 0; for(uint8_t i = 0; ; i++) { ::OTV0P2BASE::nap(WDTO_15MS); ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { // Wait for edge on xtal counter edge. // Start counting cycles. // On next edge, stop. const uint8_t t0 = TCNT2; while(t0 == TCNT2) {} const uint8_t t01 = TCNT0; const uint8_t t1 = TCNT2; while(t1 == TCNT2) {} const uint8_t t02 = TCNT0; count = t02-t01; } // Check end conditions. if((count < optimalLFClock+errorLFClock) & (count > optimalLFClock-errorLFClock)) { break; } if(i > 30) { return(false); } // FAIL { panic(F("xtal")); } // Capture some entropy from the (chaotic?) clock wobble, but don't claim any. (TODO-800) OTV0P2BASE::addEntropyToPool(count, 0); #if 0 && defined(DEBUG) // Optionally print value to debug. DEBUG_SERIAL_PRINT_FLASHSTRING("Xtal freq check: "); DEBUG_SERIAL_PRINT(count); DEBUG_SERIAL_PRINTLN(); #endif } return(true); // Success! } #endif // ARDUINO_ARCH_AVR #ifdef ARDUINO_ARCH_AVR /** * @brief Calibrate the internal RC oscillator against and external 32786 Hz crystal oscillator or resonator. The target frequency is 1 MHz. * @param todo do we want settable stuff, e.g. ext osc rate, internal osc rate, etc? * @retval True on calibration success. False if Xtal not running or calibration fails. * @note OSCCAL register is cleared on reset so changes are not persistent. * @note cf4: f8 94 cli CLEAR INTERRUPTS!!!!!!!! cf6: 30 91 b2 00 lds r19, 0x00B2 ; 0x8000b2 <__data_load_end+0x7ff25e> cfa: 80 91 b2 00 lds r24, 0x00B2 ; 0x8000b2 <__data_load_end+0x7ff25e> cfe: 8f 5f subi r24, 0xFF ; 255 d00: 90 91 b2 00 lds r25, 0x00B2 ; 0x8000b2 <__data_load_end+0x7ff25e> d04: 39 17 cp r19, r25 d06: e1 f3 breq .-8 ; 0xd00 <main+0x15c> WAIT FOR TCNT2? d08: e1 2c mov r14, r1 MEASUREMENT LOOP HERE d0a: e3 94 inc r14 1 d0c: 91 2f mov r25, r17 1 d0e: 9a 95 dec r25 * d10: 01 f0 breq .+0 ; 0xd12 <main+0x16e> * d12: e9 f7 brne .-6 ; 0xd0e <main+0x16a> 4 4 instructions * 8 = 32 d14: 90 91 b2 00 lds r25, 0x00B2 ; 0x8000b2 <__data_load_end+0x7ff25e>2? d18: 98 17 cp r25, r24 1 d1a: b9 f3 breq .-18 ; 0xd0a <main+0x166> 2 I make this 7 + 4 * <no delay cycles> */ bool calibrateInternalOscWithExtOsc() { // todo these should probably go somewhere else but not sure where. const constexpr uint8_t maxTries = 128; // Maximum number of values to attempt. const constexpr uint8_t initOscCal = 0; // Initial oscillator calibration value to start from. // TCNT2 overflows every 2 seconds. One tick is 2000/256 = 7.815 ms, or 7815 clock cycles at 1 MHz. // Minimum number of cycles we want per count is (7815*1.1)/255 = 34, to give some play in case the clock is too fast. const constexpr uint16_t cyclesPerTick = 7815; const constexpr uint8_t innerLoopTime = 39; // the number of cycles the inner loop takes to execute. const constexpr uint8_t targetCount = cyclesPerTick/innerLoopTime; // The number of counts we are aiming for. // Check that the slow clock appears to be running. if(!check32768HzOsc()) { return(false); } // Set initial calibration value and wait to settle. // OSCCAL = initOscCal; _delay_x4cycles(2); // > 8 us. max oscillator settling time is 5 us. // Calibration routine for(uint8_t i = 0; i < maxTries; i++) { uint8_t count = 0; #if 0 OTV0P2BASE::serialPrintAndFlush("OSCCAL: "); // 10000001 on my test version OTV0P2BASE::serialPrintAndFlush(OSCCAL, BIN); #endif // 1 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { // Wait for edge on xtal counter edge. const uint8_t t0 = TCNT2; const uint8_t t1 = TCNT2 + 1; while(t0 == TCNT2) {} // Start counting cycles. do { count++; // 2 cycles? // 8*4 = 32 cycles per count. _delay_x4cycles(8); // Repeat loop until TCNT2 increments. } while (TCNT2 == t1); // 2 cycles? } #if 0 OTV0P2BASE::serialPrintAndFlush("\t count: "); OTV0P2BASE::serialPrintAndFlush(count); OTV0P2BASE::serialPrintAndFlush("\t mismatch: "); OTV0P2BASE::serialPrintAndFlush(count - targetCount); OTV0P2BASE::serialPrintAndFlush(F("\tUUUUU")); OTV0P2BASE::serialPrintlnAndFlush(); // delay(1000); #endif // 1 // Set new calibration value. if(count > targetCount) OSCCAL--; else if(count < targetCount) OSCCAL++; else { return true; #if 0 while (true) { OTV0P2BASE::serialPrintAndFlush("\t count: "); OTV0P2BASE::serialPrintAndFlush(count); OTV0P2BASE::serialPrintAndFlush("\t OSCCAL: "); OTV0P2BASE::serialPrintAndFlush(OSCCAL, BIN); OTV0P2BASE::serialPrintAndFlush(F("\tUUUUU")); OTV0P2BASE::serialPrintlnAndFlush(); delay(1000); } #endif // 0 } // Wait for oscillator to settle. _delay_x4cycles(2); } return false; } #endif // ARDUINO_ARCH_AVR } } <commit_msg>added range checks to oscillator calibration<commit_after>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 */ /* Hardware tests for general POST (power-on self tests) and for detailed hardware diagnostics. Some are generic such as testing clock behaviour, others will be very specific to some board revisions (eg looking for shorts or testing expected attached hardware). Most should return true on success and false on failure. Some may require being passed a Print reference (which will often be an active hardware serial connection) to dump diagnostics to. */ #ifndef OTV0P2BASE_HARDWARETESTS_H #define OTV0P2BASE_HARDWARETESTS_H #ifdef ARDUINO_ARCH_AVR #include "util/atomic.h" #endif #include "OTV0P2BASE_Entropy.h" #include "OTV0P2BASE_Sleep.h" #include "OTV0P2BASE_HardwareTests.h" #include "OTV0P2BASE_Serial_IO.h" namespace OTV0P2BASE { namespace HWTEST { #ifdef ARDUINO_ARCH_AVR // Returns true if the 32768Hz low-frequency async crystal oscillator appears to be running. // This means the the Timer 2 clock needs to be running // and have an acceptable frequency compared to the CPU clock (1MHz). // Uses nap, and needs the Timer 2 to have been set up in async clock mode. // In passing gathers some entropy for the system. bool check32768HzOsc() { // Check that the 32768Hz async clock is actually running at least somewhat. const uint8_t initialSCT = OTV0P2BASE::getSubCycleTime(); // Allow time for 32768Hz crystal to start reliably, see: http://www.atmel.com/Images/doc1259.pdf #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("Sleeping to let 32768Hz clock start..."); #endif // Time spent here should not be a whole multiple of basic cycle time // to avoid a spuriously-stationary async clock reading! // Allow several seconds (~3s+) to start. // Attempt to capture some entropy while waiting, // implicitly from oscillator start-up time if nothing else. for(uint8_t i = 255; --i > 0; ) { const uint8_t sct = OTV0P2BASE::getSubCycleTime(); OTV0P2BASE::addEntropyToPool(sct, 0); // If counter has incremented/changed (twice) then assume probably OK. if((sct != initialSCT) && (sct != (uint8_t)(initialSCT+1))) { return(true); } // Ensure lower bound of ~3s until loop finishes. OTV0P2BASE::nap(WDTO_15MS); } #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("32768Hz clock may not be running!"); #endif return(false); // FAIL // panic(F("Xtal")); // Async clock not running. } #endif #endif #ifdef ARDUINO_ARCH_AVR // Returns true if the 32768Hz low-frequency async crystal oscillator appears to be running and sane. // Performs an extended test that the CPU (RC) and crystal frequencies are in a sensible ratio. // This means the the Timer 2 clock needs to be running // and have an acceptable frequency compared to the CPU clock (1MHz). // Uses nap, and needs the Timer 2 to have been set up in async clock mode. // In passing gathers some entropy for the system. bool check32768HzOscExtended() { // Check that the slow clock appears to be running. if(!check32768HzOsc()) { return(false); } // Test low frequency oscillator vs main CPU clock oscillator (at 1MHz). // Tests clock frequency between 15 ms naps between for up to 30 cycles and fails if not within bounds. // As of 2016-02-16, all working REV7s give count >= 120 and that fail to program via bootloader give count <= 119 // REV10 gives 119-120 (only one tested though). static const uint8_t optimalLFClock = 122; // May be optimal... static const uint8_t errorLFClock = 4; // Max drift from allowed value. uint8_t count = 0; for(uint8_t i = 0; ; i++) { ::OTV0P2BASE::nap(WDTO_15MS); ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { // Wait for edge on xtal counter edge. // Start counting cycles. // On next edge, stop. const uint8_t t0 = TCNT2; while(t0 == TCNT2) {} const uint8_t t01 = TCNT0; const uint8_t t1 = TCNT2; while(t1 == TCNT2) {} const uint8_t t02 = TCNT0; count = t02-t01; } // Check end conditions. if((count < optimalLFClock+errorLFClock) & (count > optimalLFClock-errorLFClock)) { break; } if(i > 30) { return(false); } // FAIL { panic(F("xtal")); } // Capture some entropy from the (chaotic?) clock wobble, but don't claim any. (TODO-800) OTV0P2BASE::addEntropyToPool(count, 0); #if 0 && defined(DEBUG) // Optionally print value to debug. DEBUG_SERIAL_PRINT_FLASHSTRING("Xtal freq check: "); DEBUG_SERIAL_PRINT(count); DEBUG_SERIAL_PRINTLN(); #endif } return(true); // Success! } #endif // ARDUINO_ARCH_AVR #ifdef ARDUINO_ARCH_AVR /** * @brief Calibrate the internal RC oscillator against and external 32786 Hz crystal oscillator or resonator. The target frequency is 1 MHz. * @param todo do we want settable stuff, e.g. ext osc rate, internal osc rate, etc? * @retval True on calibration success. False if Xtal not running or calibration fails. * @note OSCCAL register is cleared on reset so changes are not persistent. * @note cf4: f8 94 cli CLEAR INTERRUPTS!!!!!!!! cf6: 30 91 b2 00 lds r19, 0x00B2 ; 0x8000b2 <__data_load_end+0x7ff25e> cfa: 80 91 b2 00 lds r24, 0x00B2 ; 0x8000b2 <__data_load_end+0x7ff25e> cfe: 8f 5f subi r24, 0xFF ; 255 d00: 90 91 b2 00 lds r25, 0x00B2 ; 0x8000b2 <__data_load_end+0x7ff25e> d04: 39 17 cp r19, r25 d06: e1 f3 breq .-8 ; 0xd00 <main+0x15c> WAIT FOR TCNT2? d08: e1 2c mov r14, r1 MEASUREMENT LOOP HERE d0a: e3 94 inc r14 1 d0c: 91 2f mov r25, r17 1 d0e: 9a 95 dec r25 * d10: 01 f0 breq .+0 ; 0xd12 <main+0x16e> * d12: e9 f7 brne .-6 ; 0xd0e <main+0x16a> 4 4 instructions * 8 = 32 d14: 90 91 b2 00 lds r25, 0x00B2 ; 0x8000b2 <__data_load_end+0x7ff25e>2? d18: 98 17 cp r25, r24 1 d1a: b9 f3 breq .-18 ; 0xd0a <main+0x166> 2 I make this 7 + 4 * <no delay cycles> * @note Final OSCCAL register values for all the REV7s I have that I could get working. (DE20161209) * hh 81 91 9E A1 9E 8D 96 92 */ bool calibrateInternalOscWithExtOsc() { // todo these should probably go somewhere else but not sure where. const constexpr uint8_t maxTries = 128; // Maximum number of values to attempt. const constexpr uint8_t initOscCal = 0; // Initial oscillator calibration value to start from. // TCNT2 overflows every 2 seconds. One tick is 2000/256 = 7.815 ms, or 7815 clock cycles at 1 MHz. // Minimum number of cycles we want per count is (7815*1.1)/255 = 34, to give some play in case the clock is too fast. const constexpr uint16_t cyclesPerTick = 7815; const constexpr uint8_t innerLoopTime = 39; // the number of cycles the inner loop takes to execute. const constexpr uint8_t targetCount = cyclesPerTick/innerLoopTime; // The number of counts we are aiming for. // Check that the slow clock appears to be running. if(!check32768HzOsc()) { return(false); } // Set initial calibration value and wait to settle. // OSCCAL = initOscCal; _delay_x4cycles(2); // > 8 us. max oscillator settling time is 5 us. // Calibration routine for(uint8_t i = 0; i < maxTries; i++) { uint8_t count = 0; #if 0 OTV0P2BASE::serialPrintAndFlush("OSCCAL: "); // 10000001 on my test version OTV0P2BASE::serialPrintAndFlush(OSCCAL, HEX); #endif // 1 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { // Wait for edge on xtal counter edge. const uint8_t t0 = TCNT2; const uint8_t t1 = TCNT2 + 1; while(t0 == TCNT2) {} // Start counting cycles. do { count++; // 2 cycles? // 8*4 = 32 cycles per count. _delay_x4cycles(8); // Repeat loop until TCNT2 increments. } while (TCNT2 == t1); // 2 cycles? } #if 0 OTV0P2BASE::serialPrintAndFlush("\t count: "); OTV0P2BASE::serialPrintAndFlush(count); OTV0P2BASE::serialPrintAndFlush("\t mismatch: "); OTV0P2BASE::serialPrintAndFlush(count - targetCount); OTV0P2BASE::serialPrintAndFlush(F("\tUUUUU")); OTV0P2BASE::serialPrintlnAndFlush(); // delay(1000); #endif // 1 // Set new calibration value. if ((OSCCAL == 0x80) || (OSCCAL == 0xFF)) return false; // Return false if OSCCAL is at limits. if(count > targetCount) OSCCAL--; else if(count < targetCount) OSCCAL++; else { return true; #if 0 while (true) { OTV0P2BASE::serialPrintAndFlush("\t count: "); OTV0P2BASE::serialPrintAndFlush(count); OTV0P2BASE::serialPrintAndFlush("\t OSCCAL: "); OTV0P2BASE::serialPrintAndFlush(OSCCAL, HEX); OTV0P2BASE::serialPrintAndFlush(F("\tUUUUU")); OTV0P2BASE::serialPrintlnAndFlush(); delay(1000); } #endif // 0 } // Wait for oscillator to settle. _delay_x4cycles(2); } return false; } #endif // ARDUINO_ARCH_AVR } } <|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Rene Brun 05/09/99 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //______________________________________________________________________________ // // TVirtualPS is an abstract interface to a Postscript, PDF and SVG drivers // #include "Riostream.h" #include "TVirtualPS.h" TVirtualPS *gVirtualPS = 0; const Int_t kMaxBuffer = 250; ClassImp(TVirtualPS) //______________________________________________________________________________ TVirtualPS::TVirtualPS() { // VirtualPS default constructor. fStream = 0; fNByte = 0; fSizBuffer = kMaxBuffer; fBuffer = new char[fSizBuffer+1]; fLenBuffer = 0; fPrinted = kFALSE; fImplicitCREsc = 0; } //______________________________________________________________________________ TVirtualPS::TVirtualPS(const char *name, Int_t) : TNamed(name,"Postscript interface") { // VirtualPS constructor. fStream = 0; fNByte = 0; fSizBuffer = kMaxBuffer; fBuffer = new char[fSizBuffer+1]; fLenBuffer = 0; fPrinted = kFALSE; fImplicitCREsc = 0; } //______________________________________________________________________________ TVirtualPS::~TVirtualPS() { // VirtualPS destructor if (fBuffer) delete [] fBuffer; } //______________________________________________________________________________ void TVirtualPS::PrintStr(const char *str) { // Output the string str in the output buffer Int_t len = strlen(str); if (!len || !str) return; while (len) { if (str[0] == '@') { if (fLenBuffer) { fStream->write(fBuffer, fLenBuffer); fNByte += fLenBuffer; fLenBuffer = 0; fStream->write("\n", 1); fNByte++; fPrinted = kTRUE; } len--; str++; } else { Int_t lenText = len; if (str[len-1] == '@') lenText--; PrintFast(lenText, str); len -= lenText; str += lenText; } } } //______________________________________________________________________________ void TVirtualPS::PrintFast(Int_t len, const char *str) { // Fast version of Print if (!len || !str) return; while ((len + fLenBuffer) > kMaxBuffer) { Int_t nWrite = kMaxBuffer; if (fImplicitCREsc) { if (fLenBuffer > 0) nWrite = fLenBuffer; } else { if ((len + fLenBuffer) > nWrite) { // Search for the nearest preceeding space to break a line, if there is no instruction to escape the <end-of-line>. while ((nWrite >= fLenBuffer) && (str[nWrite - fLenBuffer] != ' ')) nWrite--; if (nWrite < fLenBuffer) { while ((nWrite >= 0) && (fBuffer[nWrite] != ' ')) nWrite--; } if (nWrite <= 0) { // Cannot find a convenient place to break a line, so we just break at this location. nWrite = kMaxBuffer; } } } if (nWrite >= fLenBuffer) { if (fLenBuffer > 0) { fStream->write(fBuffer, fLenBuffer); fNByte += fLenBuffer; nWrite -= fLenBuffer; fLenBuffer = 0; } if (nWrite > 0) { fStream->write(str, nWrite); len -= nWrite; str += nWrite; fNByte += nWrite; } } else { if (nWrite > 0) { fStream->write(fBuffer, nWrite); fNByte += nWrite; memmove(fBuffer, fBuffer + nWrite, fLenBuffer - nWrite); // not strcpy because source and destination overlap fBuffer[fLenBuffer - nWrite] = 0; // not sure if this is needed, but just in case fLenBuffer -= nWrite; } } if (fImplicitCREsc) { // Write escape characters (if any) before an end-of-line is enforced. // For example, in PostScript the <new line> character must be escaped inside strings. Int_t crlen = strlen(fImplicitCREsc); fStream->write(fImplicitCREsc, crlen); fNByte += crlen; } fStream->write("\n",1); fNByte++; } if (len > 0) { strlcpy(fBuffer + fLenBuffer, str, len+1); fLenBuffer += len; fBuffer[fLenBuffer] = 0; } fPrinted = kTRUE; } //______________________________________________________________________________ void TVirtualPS::WriteInteger(Int_t n, Bool_t space ) { // Write one Integer to the file // // n: Integer to be written in the file. // space: If TRUE, a space in written before the integer. char str[15]; if (space) { sprintf(str," %d", n); } else { sprintf(str,"%d", n); } PrintStr(str); } //______________________________________________________________________________ void TVirtualPS::WriteReal(Float_t z) { // Write a Real number to the file char str[15]; sprintf(str," %g", z); PrintStr(str); } <commit_msg>fix coverity 10686.<commit_after>// @(#)root/base:$Id$ // Author: Rene Brun 05/09/99 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //______________________________________________________________________________ // // TVirtualPS is an abstract interface to a Postscript, PDF and SVG drivers // #include "Riostream.h" #include "TVirtualPS.h" TVirtualPS *gVirtualPS = 0; const Int_t kMaxBuffer = 250; ClassImp(TVirtualPS) //______________________________________________________________________________ TVirtualPS::TVirtualPS() { // VirtualPS default constructor. fStream = 0; fNByte = 0; fSizBuffer = kMaxBuffer; fBuffer = new char[fSizBuffer+1]; fLenBuffer = 0; fPrinted = kFALSE; fImplicitCREsc = 0; } //______________________________________________________________________________ TVirtualPS::TVirtualPS(const char *name, Int_t) : TNamed(name,"Postscript interface") { // VirtualPS constructor. fStream = 0; fNByte = 0; fSizBuffer = kMaxBuffer; fBuffer = new char[fSizBuffer+1]; fLenBuffer = 0; fPrinted = kFALSE; fImplicitCREsc = 0; } //______________________________________________________________________________ TVirtualPS::~TVirtualPS() { // VirtualPS destructor if (fBuffer) delete [] fBuffer; } //______________________________________________________________________________ void TVirtualPS::PrintStr(const char *str) { // Output the string str in the output buffer if (!str || !str[0]) return; Int_t len = strlen(str); while (len) { if (str[0] == '@') { if (fLenBuffer) { fStream->write(fBuffer, fLenBuffer); fNByte += fLenBuffer; fLenBuffer = 0; fStream->write("\n", 1); fNByte++; fPrinted = kTRUE; } len--; str++; } else { Int_t lenText = len; if (str[len-1] == '@') lenText--; PrintFast(lenText, str); len -= lenText; str += lenText; } } } //______________________________________________________________________________ void TVirtualPS::PrintFast(Int_t len, const char *str) { // Fast version of Print if (!len || !str) return; while ((len + fLenBuffer) > kMaxBuffer) { Int_t nWrite = kMaxBuffer; if (fImplicitCREsc) { if (fLenBuffer > 0) nWrite = fLenBuffer; } else { if ((len + fLenBuffer) > nWrite) { // Search for the nearest preceeding space to break a line, if there is no instruction to escape the <end-of-line>. while ((nWrite >= fLenBuffer) && (str[nWrite - fLenBuffer] != ' ')) nWrite--; if (nWrite < fLenBuffer) { while ((nWrite >= 0) && (fBuffer[nWrite] != ' ')) nWrite--; } if (nWrite <= 0) { // Cannot find a convenient place to break a line, so we just break at this location. nWrite = kMaxBuffer; } } } if (nWrite >= fLenBuffer) { if (fLenBuffer > 0) { fStream->write(fBuffer, fLenBuffer); fNByte += fLenBuffer; nWrite -= fLenBuffer; fLenBuffer = 0; } if (nWrite > 0) { fStream->write(str, nWrite); len -= nWrite; str += nWrite; fNByte += nWrite; } } else { if (nWrite > 0) { fStream->write(fBuffer, nWrite); fNByte += nWrite; memmove(fBuffer, fBuffer + nWrite, fLenBuffer - nWrite); // not strcpy because source and destination overlap fBuffer[fLenBuffer - nWrite] = 0; // not sure if this is needed, but just in case fLenBuffer -= nWrite; } } if (fImplicitCREsc) { // Write escape characters (if any) before an end-of-line is enforced. // For example, in PostScript the <new line> character must be escaped inside strings. Int_t crlen = strlen(fImplicitCREsc); fStream->write(fImplicitCREsc, crlen); fNByte += crlen; } fStream->write("\n",1); fNByte++; } if (len > 0) { strlcpy(fBuffer + fLenBuffer, str, len+1); fLenBuffer += len; fBuffer[fLenBuffer] = 0; } fPrinted = kTRUE; } //______________________________________________________________________________ void TVirtualPS::WriteInteger(Int_t n, Bool_t space ) { // Write one Integer to the file // // n: Integer to be written in the file. // space: If TRUE, a space in written before the integer. char str[15]; if (space) { sprintf(str," %d", n); } else { sprintf(str,"%d", n); } PrintStr(str); } //______________________________________________________________________________ void TVirtualPS::WriteReal(Float_t z) { // Write a Real number to the file char str[15]; sprintf(str," %g", z); PrintStr(str); } <|endoftext|>
<commit_before>// AMX profiler for SA-MP server: http://sa-mp.com // // Copyright (C) 2011 Sergey Zolotarev // // 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> #include <cassert> #include <map> #include <set> #include <numeric> #include <sstream> #include <string> #include <boost/scoped_ptr.hpp> #include "abstract_printer.h" #include "function.h" #include "function_profile.h" #include "native_function.h" #include "normal_function.h" #include "profiler.h" #include "public_function.h" #include "amx/amx.h" #include "amx/amxdbg.h" namespace { int AMXAPI Debug(AMX *amx) { return samp_profiler::Profiler::Get(amx)->Debug(); } // Reads from a code section at a given location. inline cell ReadAmxCode(AMX *amx, cell where) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); return *reinterpret_cast<cell*>(amx->base + hdr->cod + where); } } // anonymous namespace namespace samp_profiler { // statics std::map<AMX*, Profiler*> Profiler::instances_; Profiler::Profiler() { } Profiler::~Profiler() { for (Functions::const_iterator iterator = functions_.begin(); iterator != functions_.end(); ++iterator) { delete iterator->first; } } bool Profiler::IsScriptProfilable(AMX *amx) { uint16_t flags; amx_Flags(amx, &flags); if ((flags & AMX_FLAG_DEBUG) != 0) { return true; } if ((flags & AMX_FLAG_NOCHECKS) == 0) { return true; } return false; } // static void Profiler::Attach(AMX *amx) { Profiler *prof = new Profiler(amx); instances_[amx] = prof; prof->Activate(); } // static void Profiler::Attach(AMX *amx, const DebugInfo &debug_info) { Attach(amx); Get(amx)->SetDebugInfo(debug_info); } // static void Profiler::Detach(AMX *amx) { Profiler *prof = Profiler::Get(amx); if (prof != 0) { prof->Deactivate(); delete prof; } instances_.erase(amx); } // static Profiler *Profiler::Get(AMX *amx) { std::map<AMX*, Profiler*>::iterator it = instances_.find(amx); if (it != instances_.end()) { return it->second; } return 0; } Profiler::Profiler(AMX *amx) : active_(false) , amx_(amx) , debug_(amx->debug) { } void Profiler::SetDebugInfo(const DebugInfo &info) { debug_info_ = info; } void Profiler::Activate() { if (!active_) { active_ = true; amx_SetDebugHook(amx_, ::Debug); } } bool Profiler::IsActive() const { return active_; } void Profiler::Deactivate() { if (active_) { active_ = false; amx_SetDebugHook(amx_, debug_); } } void Profiler::ResetStats() { functions_.clear(); } void Profiler::PrintStats(const std::string &script_name, std::ostream &stream, AbstractPrinter *printer) const { std::vector<const FunctionProfile*> stats; for (Functions::const_iterator iterator = functions_.begin(); iterator != functions_.end(); ++iterator) { stats.push_back(&iterator->second); } printer->Print(script_name, stream, stats); } int Profiler::Debug() { cell prevFrame = amx_->stp; if (!call_stack_.IsEmpty()) { prevFrame = call_stack_.GetTop().frame(); } if (amx_->frm < prevFrame) { cell address = amx_->cip - 2*sizeof(cell); if (call_stack_.GetTop().frame() != amx_->frm) { boost::scoped_ptr<NormalFunction> fn(new NormalFunction(amx_, address, &debug_info_)); EnterFunction(fn.get(), amx_->frm); } } else if (amx_->frm > prevFrame) { const Function *top_fn = call_stack_.GetTop().function(); if (top_fn->type() == "normal") { LeaveFunction(top_fn); } } if (debug_ != 0) { return debug_(amx_); } return AMX_ERR_NONE; } int Profiler::Callback(cell index, cell *result, cell *params) { boost::scoped_ptr<NativeFunction> fn(new NativeFunction(amx_, index)); EnterFunction(fn.get(), amx_->frm); int error = amx_Callback(amx_, index, result, params); LeaveFunction(fn.get()); return error; } int Profiler::Exec(cell *retval, int index) { if (index >= 0 || index == AMX_EXEC_MAIN) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base); cell address = 0; if (index == AMX_EXEC_MAIN) { address = hdr->cip; } else { AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx_->base + hdr->publics); address = publics[index].address; } boost::scoped_ptr<PublicFunction> fn(new PublicFunction(amx_, index)); EnterFunction(fn.get(), amx_->stk - 3*sizeof(cell)); int error = amx_Exec(amx_, retval, index); LeaveFunction(fn.get()); return error; } else { return amx_Exec(amx_, retval, index); } } void Profiler::EnterFunction(const Function *fn, ucell frame) { Functions::iterator iterator = functions_.find(const_cast<Function*>(fn)); if (iterator == functions_.end()) { Function *new_fn = fn->Clone(); functions_.insert(std::make_pair(new_fn, FunctionProfile(new_fn))); call_stack_.Push(new_fn, frame); } else { iterator->second.num_calls()++; call_stack_.Push(iterator->second.function(), frame); } } void Profiler::LeaveFunction(const Function *fn) { assert(!call_stack_.IsEmpty()); while (true) { FunctionCall current = call_stack_.Pop(); Functions::iterator current_it = functions_.find(current.function()); if (current.IsRecursive()) { //current_it->second.total_time() += current.timer().child_time(); current_it->second.child_time() -= current.timer().child_time(); } else { current_it->second.total_time() += current.timer().total_time(); } if (!call_stack_.IsEmpty()) { FunctionCall &top = call_stack_.GetTop(); functions_.find(top.function())->second.child_time() += current.timer().total_time(); } if (fn == 0 || (current.function()->type() == fn->type() && current.function()->Compare(fn) == 0)) { break; } } } } // namespace samp_profiler <commit_msg>Remove unused function ReadAmxCode()<commit_after>// AMX profiler for SA-MP server: http://sa-mp.com // // Copyright (C) 2011 Sergey Zolotarev // // 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> #include <cassert> #include <map> #include <set> #include <numeric> #include <sstream> #include <string> #include <boost/scoped_ptr.hpp> #include "abstract_printer.h" #include "function.h" #include "function_profile.h" #include "native_function.h" #include "normal_function.h" #include "profiler.h" #include "public_function.h" #include "amx/amx.h" #include "amx/amxdbg.h" namespace { int AMXAPI Debug(AMX *amx) { return samp_profiler::Profiler::Get(amx)->Debug(); } } // anonymous namespace namespace samp_profiler { // statics std::map<AMX*, Profiler*> Profiler::instances_; Profiler::Profiler() { } Profiler::~Profiler() { for (Functions::const_iterator iterator = functions_.begin(); iterator != functions_.end(); ++iterator) { delete iterator->first; } } bool Profiler::IsScriptProfilable(AMX *amx) { uint16_t flags; amx_Flags(amx, &flags); if ((flags & AMX_FLAG_DEBUG) != 0) { return true; } if ((flags & AMX_FLAG_NOCHECKS) == 0) { return true; } return false; } // static void Profiler::Attach(AMX *amx) { Profiler *prof = new Profiler(amx); instances_[amx] = prof; prof->Activate(); } // static void Profiler::Attach(AMX *amx, const DebugInfo &debug_info) { Attach(amx); Get(amx)->SetDebugInfo(debug_info); } // static void Profiler::Detach(AMX *amx) { Profiler *prof = Profiler::Get(amx); if (prof != 0) { prof->Deactivate(); delete prof; } instances_.erase(amx); } // static Profiler *Profiler::Get(AMX *amx) { std::map<AMX*, Profiler*>::iterator it = instances_.find(amx); if (it != instances_.end()) { return it->second; } return 0; } Profiler::Profiler(AMX *amx) : active_(false) , amx_(amx) , debug_(amx->debug) { } void Profiler::SetDebugInfo(const DebugInfo &info) { debug_info_ = info; } void Profiler::Activate() { if (!active_) { active_ = true; amx_SetDebugHook(amx_, ::Debug); } } bool Profiler::IsActive() const { return active_; } void Profiler::Deactivate() { if (active_) { active_ = false; amx_SetDebugHook(amx_, debug_); } } void Profiler::ResetStats() { functions_.clear(); } void Profiler::PrintStats(const std::string &script_name, std::ostream &stream, AbstractPrinter *printer) const { std::vector<const FunctionProfile*> stats; for (Functions::const_iterator iterator = functions_.begin(); iterator != functions_.end(); ++iterator) { stats.push_back(&iterator->second); } printer->Print(script_name, stream, stats); } int Profiler::Debug() { cell prevFrame = amx_->stp; if (!call_stack_.IsEmpty()) { prevFrame = call_stack_.GetTop().frame(); } if (amx_->frm < prevFrame) { cell address = amx_->cip - 2*sizeof(cell); if (call_stack_.GetTop().frame() != amx_->frm) { boost::scoped_ptr<NormalFunction> fn(new NormalFunction(amx_, address, &debug_info_)); EnterFunction(fn.get(), amx_->frm); } } else if (amx_->frm > prevFrame) { const Function *top_fn = call_stack_.GetTop().function(); if (top_fn->type() == "normal") { LeaveFunction(top_fn); } } if (debug_ != 0) { return debug_(amx_); } return AMX_ERR_NONE; } int Profiler::Callback(cell index, cell *result, cell *params) { boost::scoped_ptr<NativeFunction> fn(new NativeFunction(amx_, index)); EnterFunction(fn.get(), amx_->frm); int error = amx_Callback(amx_, index, result, params); LeaveFunction(fn.get()); return error; } int Profiler::Exec(cell *retval, int index) { if (index >= 0 || index == AMX_EXEC_MAIN) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base); cell address = 0; if (index == AMX_EXEC_MAIN) { address = hdr->cip; } else { AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx_->base + hdr->publics); address = publics[index].address; } boost::scoped_ptr<PublicFunction> fn(new PublicFunction(amx_, index)); EnterFunction(fn.get(), amx_->stk - 3*sizeof(cell)); int error = amx_Exec(amx_, retval, index); LeaveFunction(fn.get()); return error; } else { return amx_Exec(amx_, retval, index); } } void Profiler::EnterFunction(const Function *fn, ucell frame) { Functions::iterator iterator = functions_.find(const_cast<Function*>(fn)); if (iterator == functions_.end()) { Function *new_fn = fn->Clone(); functions_.insert(std::make_pair(new_fn, FunctionProfile(new_fn))); call_stack_.Push(new_fn, frame); } else { iterator->second.num_calls()++; call_stack_.Push(iterator->second.function(), frame); } } void Profiler::LeaveFunction(const Function *fn) { assert(!call_stack_.IsEmpty()); while (true) { FunctionCall current = call_stack_.Pop(); Functions::iterator current_it = functions_.find(current.function()); if (current.IsRecursive()) { //current_it->second.total_time() += current.timer().child_time(); current_it->second.child_time() -= current.timer().child_time(); } else { current_it->second.total_time() += current.timer().total_time(); } if (!call_stack_.IsEmpty()) { FunctionCall &top = call_stack_.GetTop(); functions_.find(top.function())->second.child_time() += current.timer().total_time(); } if (fn == 0 || (current.function()->type() == fn->type() && current.function()->Compare(fn) == 0)) { break; } } } } // namespace samp_profiler <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2016, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software 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 "boost/bind.hpp" #include "IECoreGL/Texture.h" #include "IECoreGL/Selector.h" #include "Gaffer/UndoContext.h" #include "Gaffer/Metadata.h" #include "Gaffer/ArrayPlug.h" #include "GafferUI/Nodule.h" #include "GafferUI/ImageGadget.h" #include "GafferUI/PlugAdder.h" #include "GafferUI/Style.h" #include "GafferUI/ConnectionGadget.h" using namespace Imath; using namespace IECore; using namespace Gaffer; using namespace GafferUI; ////////////////////////////////////////////////////////////////////////// // Internal utilities ////////////////////////////////////////////////////////////////////////// namespace { static IECoreGL::Texture *texture( Style::State state ) { static IECoreGL::TexturePtr normalTexture = NULL; static IECoreGL::TexturePtr highlightedTexture = NULL; IECoreGL::TexturePtr &texture = state == Style::HighlightedState ? highlightedTexture : normalTexture; if( !texture ) { texture = ImageGadget::textureLoader()->load( state == Style::HighlightedState ? "plugAdderHighlighted.png" : "plugAdder.png" ); IECoreGL::Texture::ScopedBinding binding( *texture ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); } return texture.get(); } V3f edgeTangent( StandardNodeGadget::Edge edge ) { switch( edge ) { case StandardNodeGadget::TopEdge : return V3f( 0, 1, 0 ); case StandardNodeGadget::BottomEdge : return V3f( 0, -1, 0 ); case StandardNodeGadget::LeftEdge : return V3f( -1, 0, 0 ); default : return V3f( 1, 0, 0 ); } } StandardNodeGadget::Edge oppositeEdge( StandardNodeGadget::Edge edge ) { switch( edge ) { case StandardNodeGadget::TopEdge : return StandardNodeGadget::BottomEdge; case StandardNodeGadget::BottomEdge : return StandardNodeGadget::TopEdge; case StandardNodeGadget::LeftEdge : return StandardNodeGadget::RightEdge; default : return StandardNodeGadget::LeftEdge; } } const char *edgeName( StandardNodeGadget::Edge edge ) { switch( edge ) { case StandardNodeGadget::TopEdge : return "top"; case StandardNodeGadget::BottomEdge : return "bottom"; case StandardNodeGadget::LeftEdge : return "left"; default : return "right"; } } const char *edgeOrientation( StandardNodeGadget::Edge edge ) { switch( edge ) { case StandardNodeGadget::TopEdge : case StandardNodeGadget::BottomEdge : return "x"; default : return "y"; } } void updateMetadata( Plug *plug, InternedString key, const char *value ) { ConstStringDataPtr s = Metadata::value<StringData>( plug, key ); if( s && s->readable() == value ) { // Metadata already has the value we want. No point adding on // an instance override with the exact same value. return; } Metadata::registerValue( plug, key, new StringData( value ) ); } } // namespace ////////////////////////////////////////////////////////////////////////// // PlugAdder ////////////////////////////////////////////////////////////////////////// IE_CORE_DEFINERUNTIMETYPED( PlugAdder ); PlugAdder::PlugAdder( StandardNodeGadget::Edge edge ) : m_edge( edge ), m_dragging( false ) { enterSignal().connect( boost::bind( &PlugAdder::enter, this, ::_1, ::_2 ) ); leaveSignal().connect( boost::bind( &PlugAdder::leave, this, ::_1, ::_2 ) ); buttonPressSignal().connect( boost::bind( &PlugAdder::buttonPress, this, ::_1, ::_2 ) ); dragBeginSignal().connect( boost::bind( &PlugAdder::dragBegin, this, ::_1, ::_2 ) ); dragEnterSignal().connect( boost::bind( &PlugAdder::dragEnter, this, ::_2 ) ); dragMoveSignal().connect( boost::bind( &PlugAdder::dragMove, this, ::_1, ::_2 ) ); dragLeaveSignal().connect( boost::bind( &PlugAdder::dragLeave, this, ::_2 ) ); dropSignal().connect( boost::bind( &PlugAdder::drop, this, ::_2 ) ); dragEndSignal().connect( boost::bind( &PlugAdder::dragEnd, this, ::_2 ) ); } PlugAdder::~PlugAdder() { } Imath::Box3f PlugAdder::bound() const { return Box3f( V3f( -0.5f, -0.5f, 0.0f ), V3f( 0.5f, 0.5f, 0.0f ) ); } void PlugAdder::updateDragEndPoint( const Imath::V3f position, const Imath::V3f &tangent ) { m_dragPosition = position; m_dragTangent = tangent; m_dragging = true; requestRender(); } PlugAdder::PlugMenuSignal &PlugAdder::plugMenuSignal() { static PlugMenuSignal s; return s; } void PlugAdder::doRender( const Style *style ) const { if( m_dragging ) { if( !IECoreGL::Selector::currentSelector() ) { V3f srcTangent( 0.0f, 0.0f, 0.0f ); style->renderConnection( V3f( 0 ), srcTangent, m_dragPosition, m_dragTangent, Style::HighlightedState ); } } float radius = 0.75f; Style::State state = Style::NormalState; if( getHighlighted() ) { radius = 1.25f; state = Style::HighlightedState; } style->renderImage( Box2f( V2f( -radius ), V2f( radius ) ), texture( state ) ); } void PlugAdder::applyEdgeMetadata( Gaffer::Plug *plug, bool opposite ) const { StandardNodeGadget::Edge edge = opposite ? oppositeEdge( m_edge ) : m_edge; updateMetadata( plug, "nodeGraphLayout:section", edgeName( edge ) ); } void PlugAdder::enter( GadgetPtr gadget, const ButtonEvent &event ) { setHighlighted( true ); } void PlugAdder::leave( GadgetPtr gadget, const ButtonEvent &event ) { setHighlighted( false ); } bool PlugAdder::buttonPress( GadgetPtr gadget, const ButtonEvent &event ) { return event.buttons == ButtonEvent::Left; } IECore::RunTimeTypedPtr PlugAdder::dragBegin( GadgetPtr gadget, const ButtonEvent &event ) { return this; } bool PlugAdder::dragEnter( const DragDropEvent &event ) { if( event.buttons != DragDropEvent::Left ) { return false; } if( event.sourceGadget == this ) { updateDragEndPoint( event.line.p0, V3f( 0 ) ); return true; } const Plug *plug = runTimeCast<Plug>( event.data.get() ); if( !plug || !acceptsPlug( plug ) ) { return false; } setHighlighted( true ); V3f center = V3f( 0.0f ) * fullTransform(); center = center * event.sourceGadget->fullTransform().inverse(); const V3f tangent = edgeTangent( m_edge ); if( Nodule *sourceNodule = runTimeCast<Nodule>( event.sourceGadget.get() ) ) { sourceNodule->updateDragEndPoint( center, tangent ); } else if( ConnectionGadget *connectionGadget = runTimeCast<ConnectionGadget>( event.sourceGadget.get() ) ) { connectionGadget->updateDragEndPoint( center, tangent ); } return true; } bool PlugAdder::dragMove( GadgetPtr gadget, const DragDropEvent &event ) { m_dragPosition = event.line.p0; requestRender(); return true; } bool PlugAdder::dragLeave( const DragDropEvent &event ) { setHighlighted( false ); return true; } bool PlugAdder::drop( const DragDropEvent &event ) { setHighlighted( false ); if( Plug *plug = runTimeCast<Plug>( event.data.get() ) ) { addPlug( plug ); return true; } return false; } bool PlugAdder::dragEnd( const DragDropEvent &event ) { m_dragging = false; requestRender(); return false; } <commit_msg>PlugAdder : Remove unused function.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2016, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software 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 "boost/bind.hpp" #include "IECoreGL/Texture.h" #include "IECoreGL/Selector.h" #include "Gaffer/UndoContext.h" #include "Gaffer/Metadata.h" #include "Gaffer/ArrayPlug.h" #include "GafferUI/Nodule.h" #include "GafferUI/ImageGadget.h" #include "GafferUI/PlugAdder.h" #include "GafferUI/Style.h" #include "GafferUI/ConnectionGadget.h" using namespace Imath; using namespace IECore; using namespace Gaffer; using namespace GafferUI; ////////////////////////////////////////////////////////////////////////// // Internal utilities ////////////////////////////////////////////////////////////////////////// namespace { static IECoreGL::Texture *texture( Style::State state ) { static IECoreGL::TexturePtr normalTexture = NULL; static IECoreGL::TexturePtr highlightedTexture = NULL; IECoreGL::TexturePtr &texture = state == Style::HighlightedState ? highlightedTexture : normalTexture; if( !texture ) { texture = ImageGadget::textureLoader()->load( state == Style::HighlightedState ? "plugAdderHighlighted.png" : "plugAdder.png" ); IECoreGL::Texture::ScopedBinding binding( *texture ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); } return texture.get(); } V3f edgeTangent( StandardNodeGadget::Edge edge ) { switch( edge ) { case StandardNodeGadget::TopEdge : return V3f( 0, 1, 0 ); case StandardNodeGadget::BottomEdge : return V3f( 0, -1, 0 ); case StandardNodeGadget::LeftEdge : return V3f( -1, 0, 0 ); default : return V3f( 1, 0, 0 ); } } StandardNodeGadget::Edge oppositeEdge( StandardNodeGadget::Edge edge ) { switch( edge ) { case StandardNodeGadget::TopEdge : return StandardNodeGadget::BottomEdge; case StandardNodeGadget::BottomEdge : return StandardNodeGadget::TopEdge; case StandardNodeGadget::LeftEdge : return StandardNodeGadget::RightEdge; default : return StandardNodeGadget::LeftEdge; } } const char *edgeName( StandardNodeGadget::Edge edge ) { switch( edge ) { case StandardNodeGadget::TopEdge : return "top"; case StandardNodeGadget::BottomEdge : return "bottom"; case StandardNodeGadget::LeftEdge : return "left"; default : return "right"; } } void updateMetadata( Plug *plug, InternedString key, const char *value ) { ConstStringDataPtr s = Metadata::value<StringData>( plug, key ); if( s && s->readable() == value ) { // Metadata already has the value we want. No point adding on // an instance override with the exact same value. return; } Metadata::registerValue( plug, key, new StringData( value ) ); } } // namespace ////////////////////////////////////////////////////////////////////////// // PlugAdder ////////////////////////////////////////////////////////////////////////// IE_CORE_DEFINERUNTIMETYPED( PlugAdder ); PlugAdder::PlugAdder( StandardNodeGadget::Edge edge ) : m_edge( edge ), m_dragging( false ) { enterSignal().connect( boost::bind( &PlugAdder::enter, this, ::_1, ::_2 ) ); leaveSignal().connect( boost::bind( &PlugAdder::leave, this, ::_1, ::_2 ) ); buttonPressSignal().connect( boost::bind( &PlugAdder::buttonPress, this, ::_1, ::_2 ) ); dragBeginSignal().connect( boost::bind( &PlugAdder::dragBegin, this, ::_1, ::_2 ) ); dragEnterSignal().connect( boost::bind( &PlugAdder::dragEnter, this, ::_2 ) ); dragMoveSignal().connect( boost::bind( &PlugAdder::dragMove, this, ::_1, ::_2 ) ); dragLeaveSignal().connect( boost::bind( &PlugAdder::dragLeave, this, ::_2 ) ); dropSignal().connect( boost::bind( &PlugAdder::drop, this, ::_2 ) ); dragEndSignal().connect( boost::bind( &PlugAdder::dragEnd, this, ::_2 ) ); } PlugAdder::~PlugAdder() { } Imath::Box3f PlugAdder::bound() const { return Box3f( V3f( -0.5f, -0.5f, 0.0f ), V3f( 0.5f, 0.5f, 0.0f ) ); } void PlugAdder::updateDragEndPoint( const Imath::V3f position, const Imath::V3f &tangent ) { m_dragPosition = position; m_dragTangent = tangent; m_dragging = true; requestRender(); } PlugAdder::PlugMenuSignal &PlugAdder::plugMenuSignal() { static PlugMenuSignal s; return s; } void PlugAdder::doRender( const Style *style ) const { if( m_dragging ) { if( !IECoreGL::Selector::currentSelector() ) { V3f srcTangent( 0.0f, 0.0f, 0.0f ); style->renderConnection( V3f( 0 ), srcTangent, m_dragPosition, m_dragTangent, Style::HighlightedState ); } } float radius = 0.75f; Style::State state = Style::NormalState; if( getHighlighted() ) { radius = 1.25f; state = Style::HighlightedState; } style->renderImage( Box2f( V2f( -radius ), V2f( radius ) ), texture( state ) ); } void PlugAdder::applyEdgeMetadata( Gaffer::Plug *plug, bool opposite ) const { StandardNodeGadget::Edge edge = opposite ? oppositeEdge( m_edge ) : m_edge; updateMetadata( plug, "nodeGraphLayout:section", edgeName( edge ) ); } void PlugAdder::enter( GadgetPtr gadget, const ButtonEvent &event ) { setHighlighted( true ); } void PlugAdder::leave( GadgetPtr gadget, const ButtonEvent &event ) { setHighlighted( false ); } bool PlugAdder::buttonPress( GadgetPtr gadget, const ButtonEvent &event ) { return event.buttons == ButtonEvent::Left; } IECore::RunTimeTypedPtr PlugAdder::dragBegin( GadgetPtr gadget, const ButtonEvent &event ) { return this; } bool PlugAdder::dragEnter( const DragDropEvent &event ) { if( event.buttons != DragDropEvent::Left ) { return false; } if( event.sourceGadget == this ) { updateDragEndPoint( event.line.p0, V3f( 0 ) ); return true; } const Plug *plug = runTimeCast<Plug>( event.data.get() ); if( !plug || !acceptsPlug( plug ) ) { return false; } setHighlighted( true ); V3f center = V3f( 0.0f ) * fullTransform(); center = center * event.sourceGadget->fullTransform().inverse(); const V3f tangent = edgeTangent( m_edge ); if( Nodule *sourceNodule = runTimeCast<Nodule>( event.sourceGadget.get() ) ) { sourceNodule->updateDragEndPoint( center, tangent ); } else if( ConnectionGadget *connectionGadget = runTimeCast<ConnectionGadget>( event.sourceGadget.get() ) ) { connectionGadget->updateDragEndPoint( center, tangent ); } return true; } bool PlugAdder::dragMove( GadgetPtr gadget, const DragDropEvent &event ) { m_dragPosition = event.line.p0; requestRender(); return true; } bool PlugAdder::dragLeave( const DragDropEvent &event ) { setHighlighted( false ); return true; } bool PlugAdder::drop( const DragDropEvent &event ) { setHighlighted( false ); if( Plug *plug = runTimeCast<Plug>( event.data.get() ) ) { addPlug( plug ); return true; } return false; } bool PlugAdder::dragEnd( const DragDropEvent &event ) { m_dragging = false; requestRender(); return false; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2005-2008 by the FIFE team * * http://www.fifengine.de * * This file is part of FIFE. * * * * FIFE 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 * ***************************************************************************/ // Standard C++ library includes #include <string> // 3rd party library includes #include <boost/lexical_cast.hpp> // FIFE includes // These includes are split up in two parts, separated by one empty line // First block: files included from the FIFE root src directory // Second block: files included from the same folder #include "util/base/exception.h" #include "util/structures/purge.h" #include "util/structures/rect.h" #include "view/camera.h" #include "view/rendererbase.h" #include "video/renderbackend.h" #include "video/imagepool.h" #include "video/animationpool.h" #include "map.h" #include "layer.h" namespace FIFE { Map::Map(const std::string& identifier, RenderBackend* renderBackend, const std::vector<RendererBase*>& renderers, ImagePool* imagePool, AnimationPool* animPool, TimeProvider* tp_master): m_id(identifier), m_timeprovider(tp_master), m_changelisteners(), m_changedlayers(), m_changed(false), m_renderbackend(renderBackend), m_imagepool(imagePool), m_animpool(animPool), m_renderers(renderers) { } Map::~Map() { deleteLayers(); } Layer* Map::getLayer(const std::string& id) { std::list<Layer*>::const_iterator it = m_layers.begin(); for(; it != m_layers.end(); ++it) { if((*it)->getId() == id) return *it; } throw NotFound(id); } size_t Map::getNumLayers() const { return m_layers.size(); } Layer* Map::createLayer(const std::string& identifier, CellGrid* grid) { std::list<Layer*>::const_iterator it = m_layers.begin(); for(; it != m_layers.end(); ++it) { if(identifier == (*it)->getId()) throw NameClash(identifier); } Layer* layer = new Layer(identifier, this, grid); m_layers.push_back(layer); m_changed = true; std::vector<MapChangeListener*>::iterator i = m_changelisteners.begin(); while (i != m_changelisteners.end()) { (*i)->onLayerCreate(this, layer); ++i; } return layer; } void Map::deleteLayer(Layer* layer) { std::list<Layer*>::iterator it = m_layers.begin(); for(; it != m_layers.end(); ++it) { if((*it) == layer) { std::vector<MapChangeListener*>::iterator i = m_changelisteners.begin(); while (i != m_changelisteners.end()) { (*i)->onLayerDelete(this, layer); ++i; } delete layer; m_layers.erase(it); return ; } } m_changed = true; } void Map::deleteLayers() { std::list<Layer*>::iterator it = m_layers.begin(); for(; it != m_layers.end(); ++it) { std::vector<MapChangeListener*>::iterator i = m_changelisteners.begin(); while (i != m_changelisteners.end()) { (*i)->onLayerDelete(this, *it); ++i; } } purge(m_layers); m_layers.clear(); } bool Map::update() { m_changedlayers.clear(); std::list<Layer*>::iterator it = m_layers.begin(); for(; it != m_layers.end(); ++it) { if ((*it)->update()) { m_changedlayers.push_back(*it); } } if (!m_changedlayers.empty()) { std::vector<MapChangeListener*>::iterator i = m_changelisteners.begin(); while (i != m_changelisteners.end()) { (*i)->onMapChanged(this, m_changedlayers); ++i; } } // loop over cameras and update if enabled std::vector<Camera*>::iterator camIter = m_cameras.begin(); for ( ; camIter != m_cameras.end(); ++camIter) { if ((*camIter)->isEnabled()) { (*camIter)->update(); (*camIter)->render(); } } bool retval = m_changed; m_changed = false; return retval; } void Map::addChangeListener(MapChangeListener* listener) { m_changelisteners.push_back(listener); } void Map::removeChangeListener(MapChangeListener* listener) { std::vector<MapChangeListener*>::iterator i = m_changelisteners.begin(); while (i != m_changelisteners.end()) { if ((*i) == listener) { m_changelisteners.erase(i); return; } ++i; } } Camera* Map::addCamera(const std::string &id, Layer *layer, const Rect& viewport) { if (layer == NULL) { throw NotSupported("Must have valid layer for camera"); } if (getCamera(id)) { std::string errorStr = "Camera: " + id + " already exists"; throw NameClash(errorStr); } // create new camera and add to list of cameras Camera* camera = new Camera(id, layer, viewport, m_renderbackend, m_imagepool, m_animpool); m_cameras.push_back(camera); std::vector<RendererBase*>::iterator iter = m_renderers.begin(); for ( ; iter != m_renderers.end(); ++iter) { camera->addRenderer((*iter)->clone()); } return camera; } void Map::removeCamera(const std::string &id) { std::vector<Camera*>::iterator iter = m_cameras.begin(); for ( ; iter != m_cameras.end(); ++iter) { if ((*iter)->getId() == id) { // camera has been found delete it delete *iter; // now remove it from the vector // note this invalidates iterators, but we do not need // to worry about it in this case since we are done m_cameras.erase(iter); break; } } } Camera* Map::getCamera(const std::string &id) { std::vector<Camera*>::iterator iter = m_cameras.begin(); for ( ; iter != m_cameras.end(); ++iter) { if ((*iter)->getId() == id) { return *iter; } } return NULL; } std::vector<Camera*>& Map::getCameras() { return m_cameras; } } //FIFE <commit_msg>fixed small memory leak in map destructor; cameras were not being deleted when the map was deleted.<commit_after>/*************************************************************************** * Copyright (C) 2005-2008 by the FIFE team * * http://www.fifengine.de * * This file is part of FIFE. * * * * FIFE 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 * ***************************************************************************/ // Standard C++ library includes #include <string> // 3rd party library includes #include <boost/lexical_cast.hpp> // FIFE includes // These includes are split up in two parts, separated by one empty line // First block: files included from the FIFE root src directory // Second block: files included from the same folder #include "util/base/exception.h" #include "util/structures/purge.h" #include "util/structures/rect.h" #include "view/camera.h" #include "view/rendererbase.h" #include "video/renderbackend.h" #include "video/imagepool.h" #include "video/animationpool.h" #include "map.h" #include "layer.h" namespace FIFE { Map::Map(const std::string& identifier, RenderBackend* renderBackend, const std::vector<RendererBase*>& renderers, ImagePool* imagePool, AnimationPool* animPool, TimeProvider* tp_master): m_id(identifier), m_timeprovider(tp_master), m_changelisteners(), m_changedlayers(), m_changed(false), m_renderbackend(renderBackend), m_imagepool(imagePool), m_animpool(animPool), m_renderers(renderers) { } Map::~Map() { // remove all cameras std::vector<Camera*>::iterator iter = m_cameras.begin(); for ( ; iter != m_cameras.end(); ++iter) { delete *iter; } m_cameras.clear(); deleteLayers(); } Layer* Map::getLayer(const std::string& id) { std::list<Layer*>::const_iterator it = m_layers.begin(); for(; it != m_layers.end(); ++it) { if((*it)->getId() == id) return *it; } throw NotFound(id); } size_t Map::getNumLayers() const { return m_layers.size(); } Layer* Map::createLayer(const std::string& identifier, CellGrid* grid) { std::list<Layer*>::const_iterator it = m_layers.begin(); for(; it != m_layers.end(); ++it) { if(identifier == (*it)->getId()) throw NameClash(identifier); } Layer* layer = new Layer(identifier, this, grid); m_layers.push_back(layer); m_changed = true; std::vector<MapChangeListener*>::iterator i = m_changelisteners.begin(); while (i != m_changelisteners.end()) { (*i)->onLayerCreate(this, layer); ++i; } return layer; } void Map::deleteLayer(Layer* layer) { std::list<Layer*>::iterator it = m_layers.begin(); for(; it != m_layers.end(); ++it) { if((*it) == layer) { std::vector<MapChangeListener*>::iterator i = m_changelisteners.begin(); while (i != m_changelisteners.end()) { (*i)->onLayerDelete(this, layer); ++i; } delete layer; m_layers.erase(it); return ; } } m_changed = true; } void Map::deleteLayers() { std::list<Layer*>::iterator it = m_layers.begin(); for(; it != m_layers.end(); ++it) { std::vector<MapChangeListener*>::iterator i = m_changelisteners.begin(); while (i != m_changelisteners.end()) { (*i)->onLayerDelete(this, *it); ++i; } } purge(m_layers); m_layers.clear(); } bool Map::update() { m_changedlayers.clear(); std::list<Layer*>::iterator it = m_layers.begin(); for(; it != m_layers.end(); ++it) { if ((*it)->update()) { m_changedlayers.push_back(*it); } } if (!m_changedlayers.empty()) { std::vector<MapChangeListener*>::iterator i = m_changelisteners.begin(); while (i != m_changelisteners.end()) { (*i)->onMapChanged(this, m_changedlayers); ++i; } } // loop over cameras and update if enabled std::vector<Camera*>::iterator camIter = m_cameras.begin(); for ( ; camIter != m_cameras.end(); ++camIter) { if ((*camIter)->isEnabled()) { (*camIter)->update(); (*camIter)->render(); } } bool retval = m_changed; m_changed = false; return retval; } void Map::addChangeListener(MapChangeListener* listener) { m_changelisteners.push_back(listener); } void Map::removeChangeListener(MapChangeListener* listener) { std::vector<MapChangeListener*>::iterator i = m_changelisteners.begin(); while (i != m_changelisteners.end()) { if ((*i) == listener) { m_changelisteners.erase(i); return; } ++i; } } Camera* Map::addCamera(const std::string &id, Layer *layer, const Rect& viewport) { if (layer == NULL) { throw NotSupported("Must have valid layer for camera"); } if (getCamera(id)) { std::string errorStr = "Camera: " + id + " already exists"; throw NameClash(errorStr); } // create new camera and add to list of cameras Camera* camera = new Camera(id, layer, viewport, m_renderbackend, m_imagepool, m_animpool); m_cameras.push_back(camera); std::vector<RendererBase*>::iterator iter = m_renderers.begin(); for ( ; iter != m_renderers.end(); ++iter) { camera->addRenderer((*iter)->clone()); } return camera; } void Map::removeCamera(const std::string &id) { std::vector<Camera*>::iterator iter = m_cameras.begin(); for ( ; iter != m_cameras.end(); ++iter) { if ((*iter)->getId() == id) { // camera has been found delete it delete *iter; // now remove it from the vector // note this invalidates iterators, but we do not need // to worry about it in this case since we are done m_cameras.erase(iter); break; } } } Camera* Map::getCamera(const std::string &id) { std::vector<Camera*>::iterator iter = m_cameras.begin(); for ( ; iter != m_cameras.end(); ++iter) { if ((*iter)->getId() == id) { return *iter; } } return NULL; } std::vector<Camera*>& Map::getCameras() { return m_cameras; } } //FIFE <|endoftext|>
<commit_before>/* This file is part of KContactManager. Copyright (c) 2007 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <kaboutdata.h> #include <kcmdlineargs.h> #include <klocale.h> #include <kuniqueapplication.h> #include <akonadi/control.h> #include "mainwindow.h" int main( int argc, char **argv ) { KAboutData *about = new KAboutData( "kcontactmanager", 0, ki18n( "KContactManager" ), "0.1", ki18n( "The KDE Contact Management Application" ), KAboutData::License_GPL_V2, ki18n( "(c) 2007-2009 The KDE PIM Team" ) ); about->addAuthor( ki18n( "Tobias Koenig" ), ki18n( "Current maintainer" ), "tokoe@kde.org" ); KCmdLineArgs::init( argc, argv, about ); KCmdLineOptions options; KCmdLineArgs::addCmdLineOptions( options ); KUniqueApplication::addCmdLineOptions(); if ( !KUniqueApplication::start() ) exit( 0 ); KUniqueApplication app; MainWindow *window = new MainWindow; window->show(); Akonadi::Control::start( window ); app.exec(); } <commit_msg>Return somethink<commit_after>/* This file is part of KContactManager. Copyright (c) 2007 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <kaboutdata.h> #include <kcmdlineargs.h> #include <klocale.h> #include <kuniqueapplication.h> #include <akonadi/control.h> #include "mainwindow.h" int main( int argc, char **argv ) { KAboutData *about = new KAboutData( "kcontactmanager", 0, ki18n( "KContactManager" ), "0.1", ki18n( "The KDE Contact Management Application" ), KAboutData::License_GPL_V2, ki18n( "(c) 2007-2009 The KDE PIM Team" ) ); about->addAuthor( ki18n( "Tobias Koenig" ), ki18n( "Current maintainer" ), "tokoe@kde.org" ); KCmdLineArgs::init( argc, argv, about ); KCmdLineOptions options; KCmdLineArgs::addCmdLineOptions( options ); KUniqueApplication::addCmdLineOptions(); if ( !KUniqueApplication::start() ) exit( 0 ); KUniqueApplication app; MainWindow *window = new MainWindow; window->show(); Akonadi::Control::start( window ); return app.exec(); } <|endoftext|>
<commit_before>/* $Id: $ * * Copyright (C) 2013 by the deal.II authors * * This file is subject to QPL and may not be distributed * without copyright and license information. Please refer * to the file deal.II/doc/license.html for the text and * further information on this license. */ // @sect3{Include files} #include <deal.II/grid/tria.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/grid/tria_iterator.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/grid_tools.h> #include <deal.II/grid/tria_boundary_lib.h> #include <deal.II/grid/grid_out.h> #include <deal.II/grid/grid_in.h> #include <fstream> #include <map> using namespace dealii; // @sect3{Generate some output for a given mesh} template<int dim> void mesh_info(Triangulation<dim> &tria, const char *filename) { // some general info: std::cout << "Mesh info:" << std::endl << " dimension: " << dim << std::endl << " no. of cells: " << tria.n_active_cells() << std::endl; // loop over all the cells and find how often each boundary indicator is used: { std::map<unsigned int, unsigned int> boundary_count; typename Triangulation<dim>::active_cell_iterator cell = tria.begin_active(), endc = tria.end(); for (; cell!=endc; ++cell) { for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face) { if (cell->face(face)->at_boundary()) boundary_count[cell->face(face)->boundary_indicator()]++; } } std::cout << " boundary indicators: "; for (std::map<unsigned int, unsigned int>::iterator it=boundary_count.begin(); it!=boundary_count.end(); ++it) { std::cout << it->first << "(" << it->second << ") "; } std::cout << std::endl; } // Now we want to write a graphical representation of the mesh to an output // file. std::ofstream out (filename); GridOut grid_out; grid_out.write_eps (tria, out); std::cout << " written to " << filename << std::endl; } // @sect3{Main routines} // load from a msh generated by gmsh void grid_1 () { Triangulation<2> triangulation; GridIn<2> gridin; gridin.attach_triangulation(triangulation); std::ifstream f("untitled.msh"); gridin.read_msh(f); mesh_info(triangulation, "grid-1.eps"); } // merge triangulations // note: the vertices have to be exactly on top of each other! void grid_2 () { Triangulation<2> triangulation; Triangulation<2> tria1, tria2; GridGenerator::hyper_cube_with_cylindrical_hole (tria1, 0.25, 1.0); std::vector< unsigned int > repetitions(2); repetitions[0]=3; repetitions[1]=2; GridGenerator::subdivided_hyper_rectangle (tria2, repetitions, Point<2>(1.0,-1.0), Point<2>(4.0,1.0)); GridGenerator::merge_triangulations (tria1, tria2, triangulation); mesh_info(triangulation, "grid-2.eps"); } // move vertices void grid_3 () { Triangulation<2> triangulation; GridGenerator::hyper_cube_with_cylindrical_hole (triangulation, 0.25, 1.0); Triangulation<2>::active_cell_iterator cell = triangulation.begin_active(), endc = triangulation.end(); for (; cell!=endc; ++cell) { for (unsigned int i=0; i<GeometryInfo<2>::vertices_per_cell; ++i) { Point<2> &v = cell->vertex(i); if (std::abs(v(1)-1.0)<1e-5) v(1)+=0.5; } } const HyperBallBoundary<2> boundary_description(Point<2>(0,0),0.25); triangulation.set_boundary (1, boundary_description); triangulation.refine_global(2); mesh_info(triangulation, "grid-3.eps"); // remove boundary object from Triangulation again: triangulation.set_boundary (1); } // demonstrate extrude_triangulation void grid_4() { Triangulation<2> triangulation; Triangulation<3> out; GridGenerator::hyper_cube_with_cylindrical_hole (triangulation, 0.25, 1.0); GridGenerator::extrude_triangulation(triangulation, 3, 2.0, out); mesh_info(out, "grid-4.eps"); } // demonstrate GridTools::transform void grid_5() { Triangulation<2> tria; std::vector< unsigned int > repetitions(2); repetitions[0]=14; repetitions[1]=2; GridGenerator::subdivided_hyper_rectangle (tria, repetitions, Point<2>(0.0,0.0), Point<2>(10.0,1.0)); struct Func { Point<2> operator() (const Point<2> & in) const { return Point<2>(in(0), in(1)+sin(in(0)/5.0*3.14159)); } }; GridTools::transform(Func(), tria); mesh_info(tria, "grid-5.eps"); } // demonstrate GridTools::transform void grid_6() { Triangulation<2> tria; std::vector< unsigned int > repetitions(2); repetitions[0]=40; repetitions[1]=40; GridGenerator::subdivided_hyper_rectangle (tria, repetitions, Point<2>(0.0,0.0), Point<2>(1.0,1.0)); struct Func { double trans(double x) const { //return atan((x-0.5)*3.14159); return tanh(2*x)/tanh(2);//(x-0.5)*3.14159); } Point<2> operator() (const Point<2> & in) const { return Point<2>((in(0)), trans(in(1))); } }; GridTools::transform(Func(), tria); mesh_info(tria, "grid-6.eps"); } //demonstrate distort_random void grid_7() { Triangulation<2> tria; std::vector< unsigned int > repetitions(2); repetitions[0]=16; repetitions[1]=16; GridGenerator::subdivided_hyper_rectangle (tria, repetitions, Point<2>(0.0,0.0), Point<2>(1.0,1.0)); tria.distort_random(0.3, true); mesh_info(tria, "grid-7.eps"); } // @sect3{The main function} // Finally, the main function. There isn't much to do here, only to call the // subfunctions. int main () { grid_1 (); grid_2 (); grid_3 (); grid_4 (); grid_5 (); grid_6 (); grid_7 (); } <commit_msg>step-49: small fixes<commit_after>/* $Id: $ * * Copyright (C) 2013 by the deal.II authors * * This file is subject to QPL and may not be distributed * without copyright and license information. Please refer * to the file deal.II/doc/license.html for the text and * further information on this license. */ // @sect3{Include files} #include <deal.II/grid/tria.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/grid/tria_iterator.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/grid_tools.h> #include <deal.II/grid/tria_boundary_lib.h> #include <deal.II/grid/grid_out.h> #include <deal.II/grid/grid_in.h> #include <fstream> #include <map> using namespace dealii; // @sect3{Generate some output for a given mesh} template<int dim> void mesh_info(Triangulation<dim> &tria, const char *filename) { // some general info: std::cout << "Mesh info:" << std::endl << " dimension: " << dim << std::endl << " no. of cells: " << tria.n_active_cells() << std::endl; // loop over all the cells and find how often each boundary indicator is used: { std::map<unsigned int, unsigned int> boundary_count; typename Triangulation<dim>::active_cell_iterator cell = tria.begin_active(), endc = tria.end(); for (; cell!=endc; ++cell) { for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face) { if (cell->face(face)->at_boundary()) boundary_count[cell->face(face)->boundary_indicator()]++; } } std::cout << " boundary indicators: "; for (std::map<unsigned int, unsigned int>::iterator it=boundary_count.begin(); it!=boundary_count.end(); ++it) { std::cout << it->first << "(" << it->second << ") "; } std::cout << std::endl; } // Now we want to write a graphical representation of the mesh to an output // file. std::ofstream out (filename); GridOut grid_out; grid_out.write_eps (tria, out); std::cout << " written to " << filename << std::endl; } // @sect3{Main routines} // load from a msh generated by gmsh void grid_1 () { Triangulation<2> triangulation; GridIn<2> gridin; gridin.attach_triangulation(triangulation); std::ifstream f("untitled.msh"); gridin.read_msh(f); mesh_info(triangulation, "grid-1.eps"); } // merge triangulations // note: the vertices have to be exactly on top of each other! void grid_2 () { Triangulation<2> triangulation; Triangulation<2> tria1, tria2; GridGenerator::hyper_cube_with_cylindrical_hole (tria1, 0.25, 1.0); std::vector< unsigned int > repetitions(2); repetitions[0]=3; repetitions[1]=2; GridGenerator::subdivided_hyper_rectangle (tria2, repetitions, Point<2>(1.0,-1.0), Point<2>(4.0,1.0)); GridGenerator::merge_triangulations (tria1, tria2, triangulation); mesh_info(triangulation, "grid-2.eps"); } // move vertices void grid_3 () { Triangulation<2> triangulation; GridGenerator::hyper_cube_with_cylindrical_hole (triangulation, 0.25, 1.0); Triangulation<2>::active_cell_iterator cell = triangulation.begin_active(), endc = triangulation.end(); for (; cell!=endc; ++cell) { for (unsigned int i=0; i<GeometryInfo<2>::vertices_per_cell; ++i) { Point<2> &v = cell->vertex(i); if (std::abs(v(1)-1.0)<1e-5) v(1)+=0.5; } } // here we are going to set a boundary descriptor for the round hole // and refine the mesh twice. const HyperBallBoundary<2> boundary_description(Point<2>(0,0),0.25); triangulation.set_boundary (1, boundary_description); triangulation.refine_global(2); mesh_info(triangulation, "grid-3.eps"); // remove boundary object from Triangulation again: triangulation.set_boundary (1); } // demonstrate extrude_triangulation void grid_4() { Triangulation<2> triangulation; Triangulation<3> out; GridGenerator::hyper_cube_with_cylindrical_hole (triangulation, 0.25, 1.0); GridGenerator::extrude_triangulation(triangulation, 3, 2.0, out); mesh_info(out, "grid-4.eps"); } struct Grid5Func { Point<2> operator() (const Point<2> & in) const { return Point<2>(in(0), in(1)+sin(in(0)/5.0*3.14159)); } }; // demonstrate GridTools::transform void grid_5() { Triangulation<2> tria; std::vector< unsigned int > repetitions(2); repetitions[0]=14; repetitions[1]=2; GridGenerator::subdivided_hyper_rectangle (tria, repetitions, Point<2>(0.0,0.0), Point<2>(10.0,1.0)); GridTools::transform(Grid5Func(), tria); mesh_info(tria, "grid-5.eps"); } struct Grid6Func { double trans(double x) const { return tanh(2*x)/tanh(2); } Point<2> operator() (const Point<2> & in) const { return Point<2>((in(0)), trans(in(1))); } }; // demonstrate GridTools::transform void grid_6() { Triangulation<2> tria; std::vector< unsigned int > repetitions(2); repetitions[0]=40; repetitions[1]=40; GridGenerator::subdivided_hyper_rectangle (tria, repetitions, Point<2>(0.0,0.0), Point<2>(1.0,1.0)); GridTools::transform(Grid6Func(), tria); mesh_info(tria, "grid-6.eps"); } //demonstrate distort_random void grid_7() { Triangulation<2> tria; std::vector< unsigned int > repetitions(2); repetitions[0]=16; repetitions[1]=16; GridGenerator::subdivided_hyper_rectangle (tria, repetitions, Point<2>(0.0,0.0), Point<2>(1.0,1.0)); tria.distort_random(0.3, true); mesh_info(tria, "grid-7.eps"); } // @sect3{The main function} // Finally, the main function. There isn't much to do here, only to call the // subfunctions. int main () { grid_1 (); grid_2 (); grid_3 (); grid_4 (); grid_5 (); grid_6 (); grid_7 (); } <|endoftext|>
<commit_before>/********************************************************/ /* Routines generales de gestion des commandes usuelles */ /********************************************************/ /* controle.cpp */ #include "fctsys.h" #include "common.h" #include "class_drawpanel.h" #include "pcbnew.h" #include "wxPcbStruct.h" #include "protos.h" #include "pcbnew_id.h" #include "collectors.h" //external funtions used here: extern bool Magnetize( BOARD* m_Pcb, PCB_EDIT_FRAME* frame, int aCurrentTool, wxSize grid, wxPoint on_grid, wxPoint* curpos ); /** * Function AllAreModulesAndReturnSmallestIfSo * tests that all items in the collection are MODULEs and if so, returns the * smallest MODULE. * @return BOARD_ITEM* - The smallest or NULL. */ static BOARD_ITEM* AllAreModulesAndReturnSmallestIfSo( GENERAL_COLLECTOR* aCollector ) { int count = aCollector->GetCount(); for( int i = 0; i<count; ++i ) { if( (*aCollector)[i]->Type() != TYPE_MODULE ) return NULL; } // all are modules, now find smallest MODULE int minDim = 0x7FFFFFFF; int minNdx = 0; for( int i = 0; i<count; ++i ) { MODULE* module = (MODULE*) (*aCollector)[i]; int lx = module->m_BoundaryBox.GetWidth(); int ly = module->m_BoundaryBox.GetHeight(); int lmin = MIN( lx, ly ); if( lmin <= minDim ) { minDim = lmin; minNdx = i; } } return (*aCollector)[minNdx]; } BOARD_ITEM* PCB_BASE_FRAME::PcbGeneralLocateAndDisplay( int aHotKeyCode ) { BOARD_ITEM* item; GENERAL_COLLECTORS_GUIDE guide = GetCollectorsGuide(); // Assign to scanList the proper item types desired based on tool type // or hotkey that is in play. const KICAD_T* scanList = NULL; if( aHotKeyCode ) { // @todo: add switch here and add calls to PcbGeneralLocateAndDisplay( int aHotKeyCode ) // when searching is needed from a hotkey handler } else if( GetToolId() == ID_NO_TOOL_SELECTED ) { switch( m_HTOOL_current_state ) { case ID_TOOLBARH_PCB_MODE_MODULE: scanList = GENERAL_COLLECTOR::ModuleItems; break; default: scanList = DisplayOpt.DisplayZonesMode == 0 ? GENERAL_COLLECTOR::AllBoardItems : GENERAL_COLLECTOR::AllButZones; break; } } else { switch( GetToolId() ) { case ID_PCB_SHOW_1_RATSNEST_BUTT: scanList = GENERAL_COLLECTOR::PadsOrModules; break; case ID_TRACK_BUTT: scanList = GENERAL_COLLECTOR::Tracks; break; case ID_PCB_MODULE_BUTT: scanList = GENERAL_COLLECTOR::ModuleItems; break; default: scanList = DisplayOpt.DisplayZonesMode == 0 ? GENERAL_COLLECTOR::AllBoardItems : GENERAL_COLLECTOR::AllButZones; } } m_Collector->Collect( m_Pcb, scanList, GetScreen()->RefPos( true ), guide ); #if 0 // debugging: print out the collected items, showing their priority order too. for( int i = 0; i<m_Collector->GetCount(); ++i ) (*m_Collector)[i]->Show( 0, std::cout ); #endif /* Remove redundancies: sometime, zones are found twice, * because zones can be filled by overlapping segments (this is a fill option) */ unsigned long timestampzone = 0; for( int ii = 0; ii < m_Collector->GetCount(); ii++ ) { item = (*m_Collector)[ii]; if( item->Type() != TYPE_ZONE ) continue; /* Found a TYPE ZONE */ if( item->m_TimeStamp == timestampzone ) // Remove it, redundant, zone already found { m_Collector->Remove( ii ); ii--; } else timestampzone = item->m_TimeStamp; } if( m_Collector->GetCount() <= 1 ) { item = (*m_Collector)[0]; SetCurItem( item ); } // If the count is 2, and first item is a pad or moduletext, and the 2nd item is its // parent module: else if( m_Collector->GetCount() == 2 && ( (*m_Collector)[0]->Type() == TYPE_PAD || (*m_Collector)[0]->Type() == TYPE_TEXTE_MODULE ) && (*m_Collector)[1]->Type() == TYPE_MODULE && (*m_Collector)[0]->GetParent()== (*m_Collector)[1] ) { item = (*m_Collector)[0]; SetCurItem( item ); } // if all are modules, find the smallest one amoung the primary choices else if( ( item = AllAreModulesAndReturnSmallestIfSo( m_Collector ) ) != NULL ) { SetCurItem( item ); } else // we can't figure out which item user wants, do popup menu so user can choose { wxMenu itemMenu; /* Give a title to the selection menu. This is also a cancel menu item */ wxMenuItem * item_title = new wxMenuItem(&itemMenu, -1, _( "Selection Clarification" ) ); #ifdef __WINDOWS__ wxFont bold_font(*wxNORMAL_FONT); bold_font.SetWeight(wxFONTWEIGHT_BOLD); bold_font.SetStyle( wxFONTSTYLE_ITALIC); item_title->SetFont(bold_font); #endif itemMenu.Append(item_title); itemMenu.AppendSeparator(); int limit = MIN( MAX_ITEMS_IN_PICKER, m_Collector->GetCount() ); for( int i = 0; i<limit; ++i ) { wxString text; const char** xpm; item = (*m_Collector)[i]; text = item->MenuText( m_Pcb ); xpm = item->MenuIcon(); ADD_MENUITEM( &itemMenu, ID_POPUP_PCB_ITEM_SELECTION_START + i, text, xpm ); } /* @todo: rather than assignment to true, these should be increment and decrement * operators throughout _everywhere_. * That way we can handle nesting. * But I tried that and found there cases where the assignment to true (converted to * a m_IgnoreMouseEvents++ ) * was not balanced with the -- (now m_IgnoreMouseEvents=false), so I had to revert. * Somebody should track down these and make them balanced. * DrawPanel->m_IgnoreMouseEvents = true; */ // this menu's handler is void PCB_BASE_FRAME::ProcessItemSelection() // and it calls SetCurItem() which in turn calls DisplayInfo() on the item. DrawPanel->m_AbortRequest = true; // changed in false if an item PopupMenu( &itemMenu ); // m_AbortRequest = false if an item is selected DrawPanel->MoveCursorToCrossHair(); // DrawPanel->m_IgnoreMouseEvents = false; // The function ProcessItemSelection() has set the current item, return it. item = GetCurItem(); } return item; } void PCB_EDIT_FRAME::GeneralControl( wxDC* aDC, const wxPoint& aPosition, int aHotKey ) { wxRealPoint gridSize; wxPoint oldpos; wxPoint pos = GetScreen()->GetNearestGridPosition( aPosition ); // Save the board after the time out : int CurrentTime = time( NULL ); if( !GetScreen()->IsModify() || GetScreen()->IsSave() ) { /* If no change, reset the time out */ g_SaveTime = CurrentTime; } if( (CurrentTime - g_SaveTime) > g_TimeOut ) { wxString tmpFileName = GetScreen()->GetFileName(); wxFileName fn = wxFileName( wxEmptyString, g_SaveFileName, PcbFileExtension ); bool flgmodify = GetScreen()->IsModify(); SavePcbFile( fn.GetFullPath() ); if( flgmodify ) // Set the flags m_Modify cleared by SavePcbFile() { OnModify(); GetScreen()->SetSave(); // Set the flags m_FlagSave cleared by SetModify() } GetScreen()->SetFileName( tmpFileName ); SetTitle( GetScreen()->GetFileName() ); } oldpos = GetScreen()->GetCrossHairPosition(); gridSize = GetScreen()->GetGridSize(); switch( aHotKey ) { case WXK_NUMPAD8: /* Deplacement curseur vers le haut */ case WXK_UP: pos.y -= wxRound( gridSize.y ); DrawPanel->MoveCursor( pos ); break; case WXK_NUMPAD2: /* Deplacement curseur vers le bas */ case WXK_DOWN: pos.y += wxRound( gridSize.y ); DrawPanel->MoveCursor( pos ); break; case WXK_NUMPAD4: /* Deplacement curseur vers la gauche */ case WXK_LEFT: pos.x -= wxRound( gridSize.x ); DrawPanel->MoveCursor( pos ); break; case WXK_NUMPAD6: /* Deplacement curseur vers la droite */ case WXK_RIGHT: pos.x += wxRound( gridSize.x ); DrawPanel->MoveCursor( pos ); break; default: break; } // Put cursor in new position, according to the zoom keys (if any). GetScreen()->SetCrossHairPosition( pos ); /* Put cursor on grid or a pad centre if requested. If the tool DELETE is active the * cursor is left off grid this is better to reach items to delete off grid, */ bool keep_on_grid = true; if( GetToolId() == ID_PCB_DELETE_ITEM_BUTT ) keep_on_grid = false; /* Cursor is left off grid if no block in progress and no moving object */ if( GetScreen()->m_BlockLocate.m_State != STATE_NO_BLOCK ) keep_on_grid = true; EDA_ITEM* DrawStruct = GetScreen()->GetCurItem(); if( DrawStruct && DrawStruct->m_Flags ) keep_on_grid = true; if( keep_on_grid ) { wxPoint on_grid = GetScreen()->GetNearestGridPosition( pos ); wxSize grid; grid.x = (int) GetScreen()->GetGridSize().x; grid.y = (int) GetScreen()->GetGridSize().y; if( Magnetize( m_Pcb, this, GetToolId(), grid, on_grid, &pos ) ) { GetScreen()->SetCrossHairPosition( pos, false ); } else { // If there's no intrusion and DRC is active, we pass the cursor // "as is", and let ShowNewTrackWhenMovingCursor figure out what to do. if( !Drc_On || !g_CurrentTrackSegment || g_CurrentTrackSegment != this->GetCurItem() || !LocateIntrusion( m_Pcb->m_Track, g_CurrentTrackSegment, GetScreen()->m_Active_Layer, GetScreen()->RefPos( true ) ) ) { GetScreen()->SetCrossHairPosition( on_grid ); } } } if( oldpos != GetScreen()->GetCrossHairPosition() ) { pos = GetScreen()->GetCrossHairPosition(); GetScreen()->SetCrossHairPosition( oldpos, false ); DrawPanel->CrossHairOff( aDC ); GetScreen()->SetCrossHairPosition( pos, false ); DrawPanel->CrossHairOn( aDC ); if( DrawPanel->IsMouseCaptured() ) { #ifdef USE_WX_OVERLAY wxDCOverlay oDC( DrawPanel->m_overlay, (wxWindowDC*)aDC ); oDC.Clear(); DrawPanel->m_mouseCaptureCallback( DrawPanel, aDC, aPosition, false ); #else DrawPanel->m_mouseCaptureCallback( DrawPanel, aDC, aPosition, true ); #endif } #ifdef USE_WX_OVERLAY else DrawPanel->m_overlay.Reset(); #endif } if( aHotKey ) { OnHotKey( aDC, aHotKey, aPosition ); } UpdateStatusBar(); /* Display new cursor coordinates */ } <commit_msg>Fix a minor issue in Pcbnew<commit_after>/********************************************************/ /* Routines generales de gestion des commandes usuelles */ /********************************************************/ /* controle.cpp */ #include "fctsys.h" #include "common.h" #include "class_drawpanel.h" #include "pcbnew.h" #include "wxPcbStruct.h" #include "protos.h" #include "pcbnew_id.h" #include "collectors.h" //external funtions used here: extern bool Magnetize( BOARD* m_Pcb, PCB_EDIT_FRAME* frame, int aCurrentTool, wxSize grid, wxPoint on_grid, wxPoint* curpos ); /** * Function AllAreModulesAndReturnSmallestIfSo * tests that all items in the collection are MODULEs and if so, returns the * smallest MODULE. * @return BOARD_ITEM* - The smallest or NULL. */ static BOARD_ITEM* AllAreModulesAndReturnSmallestIfSo( GENERAL_COLLECTOR* aCollector ) { int count = aCollector->GetCount(); for( int i = 0; i<count; ++i ) { if( (*aCollector)[i]->Type() != TYPE_MODULE ) return NULL; } // all are modules, now find smallest MODULE int minDim = 0x7FFFFFFF; int minNdx = 0; for( int i = 0; i<count; ++i ) { MODULE* module = (MODULE*) (*aCollector)[i]; int lx = module->m_BoundaryBox.GetWidth(); int ly = module->m_BoundaryBox.GetHeight(); int lmin = MIN( lx, ly ); if( lmin <= minDim ) { minDim = lmin; minNdx = i; } } return (*aCollector)[minNdx]; } BOARD_ITEM* PCB_BASE_FRAME::PcbGeneralLocateAndDisplay( int aHotKeyCode ) { BOARD_ITEM* item; GENERAL_COLLECTORS_GUIDE guide = GetCollectorsGuide(); // Assign to scanList the proper item types desired based on tool type // or hotkey that is in play. const KICAD_T* scanList = NULL; if( aHotKeyCode ) { // @todo: add switch here and add calls to PcbGeneralLocateAndDisplay( int aHotKeyCode ) // when searching is needed from a hotkey handler } else if( GetToolId() == ID_NO_TOOL_SELECTED ) { switch( m_HTOOL_current_state ) { case ID_TOOLBARH_PCB_MODE_MODULE: scanList = GENERAL_COLLECTOR::ModuleItems; break; default: scanList = DisplayOpt.DisplayZonesMode == 0 ? GENERAL_COLLECTOR::AllBoardItems : GENERAL_COLLECTOR::AllButZones; break; } } else { switch( GetToolId() ) { case ID_PCB_SHOW_1_RATSNEST_BUTT: scanList = GENERAL_COLLECTOR::PadsOrModules; break; case ID_TRACK_BUTT: scanList = GENERAL_COLLECTOR::Tracks; break; case ID_PCB_MODULE_BUTT: scanList = GENERAL_COLLECTOR::ModuleItems; break; default: scanList = DisplayOpt.DisplayZonesMode == 0 ? GENERAL_COLLECTOR::AllBoardItems : GENERAL_COLLECTOR::AllButZones; } } m_Collector->Collect( m_Pcb, scanList, GetScreen()->RefPos( true ), guide ); #if 0 // debugging: print out the collected items, showing their priority order too. for( int i = 0; i<m_Collector->GetCount(); ++i ) (*m_Collector)[i]->Show( 0, std::cout ); #endif /* Remove redundancies: sometime, zones are found twice, * because zones can be filled by overlapping segments (this is a fill option) */ unsigned long timestampzone = 0; for( int ii = 0; ii < m_Collector->GetCount(); ii++ ) { item = (*m_Collector)[ii]; if( item->Type() != TYPE_ZONE ) continue; /* Found a TYPE ZONE */ if( item->m_TimeStamp == timestampzone ) // Remove it, redundant, zone already found { m_Collector->Remove( ii ); ii--; } else timestampzone = item->m_TimeStamp; } if( m_Collector->GetCount() <= 1 ) { item = (*m_Collector)[0]; SetCurItem( item ); } // If the count is 2, and first item is a pad or moduletext, and the 2nd item is its // parent module: else if( m_Collector->GetCount() == 2 && ( (*m_Collector)[0]->Type() == TYPE_PAD || (*m_Collector)[0]->Type() == TYPE_TEXTE_MODULE ) && (*m_Collector)[1]->Type() == TYPE_MODULE && (*m_Collector)[0]->GetParent()== (*m_Collector)[1] ) { item = (*m_Collector)[0]; SetCurItem( item ); } // if all are modules, find the smallest one amoung the primary choices else if( ( item = AllAreModulesAndReturnSmallestIfSo( m_Collector ) ) != NULL ) { SetCurItem( item ); } else // we can't figure out which item user wants, do popup menu so user can choose { wxMenu itemMenu; /* Give a title to the selection menu. This is also a cancel menu item */ wxMenuItem * item_title = new wxMenuItem(&itemMenu, -1, _( "Selection Clarification" ) ); #ifdef __WINDOWS__ wxFont bold_font(*wxNORMAL_FONT); bold_font.SetWeight(wxFONTWEIGHT_BOLD); bold_font.SetStyle( wxFONTSTYLE_ITALIC); item_title->SetFont(bold_font); #endif itemMenu.Append(item_title); itemMenu.AppendSeparator(); int limit = MIN( MAX_ITEMS_IN_PICKER, m_Collector->GetCount() ); for( int i = 0; i<limit; ++i ) { wxString text; const char** xpm; item = (*m_Collector)[i]; text = item->MenuText( m_Pcb ); xpm = item->MenuIcon(); ADD_MENUITEM( &itemMenu, ID_POPUP_PCB_ITEM_SELECTION_START + i, text, xpm ); } /* @todo: rather than assignment to true, these should be increment and decrement * operators throughout _everywhere_. * That way we can handle nesting. * But I tried that and found there cases where the assignment to true (converted to * a m_IgnoreMouseEvents++ ) * was not balanced with the -- (now m_IgnoreMouseEvents=false), so I had to revert. * Somebody should track down these and make them balanced. * DrawPanel->m_IgnoreMouseEvents = true; */ // this menu's handler is void PCB_BASE_FRAME::ProcessItemSelection() // and it calls SetCurItem() which in turn calls DisplayInfo() on the item. DrawPanel->m_AbortRequest = true; // changed in false if an item is selected PopupMenu( &itemMenu ); DrawPanel->MoveCursorToCrossHair(); // The function ProcessItemSelection() has set the current item, return it. if( DrawPanel->m_AbortRequest ) // Nothing selected item = NULL; else item = GetCurItem(); } return item; } void PCB_EDIT_FRAME::GeneralControl( wxDC* aDC, const wxPoint& aPosition, int aHotKey ) { wxRealPoint gridSize; wxPoint oldpos; wxPoint pos = GetScreen()->GetNearestGridPosition( aPosition ); // Save the board after the time out : int CurrentTime = time( NULL ); if( !GetScreen()->IsModify() || GetScreen()->IsSave() ) { /* If no change, reset the time out */ g_SaveTime = CurrentTime; } if( (CurrentTime - g_SaveTime) > g_TimeOut ) { wxString tmpFileName = GetScreen()->GetFileName(); wxFileName fn = wxFileName( wxEmptyString, g_SaveFileName, PcbFileExtension ); bool flgmodify = GetScreen()->IsModify(); SavePcbFile( fn.GetFullPath() ); if( flgmodify ) // Set the flags m_Modify cleared by SavePcbFile() { OnModify(); GetScreen()->SetSave(); // Set the flags m_FlagSave cleared by SetModify() } GetScreen()->SetFileName( tmpFileName ); SetTitle( GetScreen()->GetFileName() ); } oldpos = GetScreen()->GetCrossHairPosition(); gridSize = GetScreen()->GetGridSize(); switch( aHotKey ) { case WXK_NUMPAD8: /* Deplacement curseur vers le haut */ case WXK_UP: pos.y -= wxRound( gridSize.y ); DrawPanel->MoveCursor( pos ); break; case WXK_NUMPAD2: /* Deplacement curseur vers le bas */ case WXK_DOWN: pos.y += wxRound( gridSize.y ); DrawPanel->MoveCursor( pos ); break; case WXK_NUMPAD4: /* Deplacement curseur vers la gauche */ case WXK_LEFT: pos.x -= wxRound( gridSize.x ); DrawPanel->MoveCursor( pos ); break; case WXK_NUMPAD6: /* Deplacement curseur vers la droite */ case WXK_RIGHT: pos.x += wxRound( gridSize.x ); DrawPanel->MoveCursor( pos ); break; default: break; } // Put cursor in new position, according to the zoom keys (if any). GetScreen()->SetCrossHairPosition( pos ); /* Put cursor on grid or a pad centre if requested. If the tool DELETE is active the * cursor is left off grid this is better to reach items to delete off grid, */ bool keep_on_grid = true; if( GetToolId() == ID_PCB_DELETE_ITEM_BUTT ) keep_on_grid = false; /* Cursor is left off grid if no block in progress and no moving object */ if( GetScreen()->m_BlockLocate.m_State != STATE_NO_BLOCK ) keep_on_grid = true; EDA_ITEM* DrawStruct = GetScreen()->GetCurItem(); if( DrawStruct && DrawStruct->m_Flags ) keep_on_grid = true; if( keep_on_grid ) { wxPoint on_grid = GetScreen()->GetNearestGridPosition( pos ); wxSize grid; grid.x = (int) GetScreen()->GetGridSize().x; grid.y = (int) GetScreen()->GetGridSize().y; if( Magnetize( m_Pcb, this, GetToolId(), grid, on_grid, &pos ) ) { GetScreen()->SetCrossHairPosition( pos, false ); } else { // If there's no intrusion and DRC is active, we pass the cursor // "as is", and let ShowNewTrackWhenMovingCursor figure out what to do. if( !Drc_On || !g_CurrentTrackSegment || g_CurrentTrackSegment != this->GetCurItem() || !LocateIntrusion( m_Pcb->m_Track, g_CurrentTrackSegment, GetScreen()->m_Active_Layer, GetScreen()->RefPos( true ) ) ) { GetScreen()->SetCrossHairPosition( on_grid ); } } } if( oldpos != GetScreen()->GetCrossHairPosition() ) { pos = GetScreen()->GetCrossHairPosition(); GetScreen()->SetCrossHairPosition( oldpos, false ); DrawPanel->CrossHairOff( aDC ); GetScreen()->SetCrossHairPosition( pos, false ); DrawPanel->CrossHairOn( aDC ); if( DrawPanel->IsMouseCaptured() ) { #ifdef USE_WX_OVERLAY wxDCOverlay oDC( DrawPanel->m_overlay, (wxWindowDC*)aDC ); oDC.Clear(); DrawPanel->m_mouseCaptureCallback( DrawPanel, aDC, aPosition, false ); #else DrawPanel->m_mouseCaptureCallback( DrawPanel, aDC, aPosition, true ); #endif } #ifdef USE_WX_OVERLAY else DrawPanel->m_overlay.Reset(); #endif } if( aHotKey ) { OnHotKey( aDC, aHotKey, aPosition ); } UpdateStatusBar(); /* Display new cursor coordinates */ } <|endoftext|>
<commit_before> /** * PyOtherSide: Asynchronous Python 3 Bindings for Qt 5 * Copyright (c) 2014, Dennis Tomas <den.t@gmx.de> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. **/ #include "qpython_priv.h" #include "pyglarea.h" #include <QVariant> #include <QPointF> #include <QtQuick/qquickwindow.h> #include <QtGui/QOpenGLShaderProgram> #include <QtGui/QOpenGLContext> PyGLArea::PyGLArea() : m_t(0) , m_before(false) , m_renderer(0) { connect(this, SIGNAL(windowChanged(QQuickWindow*)), this, SLOT(handleWindowChanged(QQuickWindow*))); } PyGLArea::~PyGLArea() { if (m_renderer) { delete m_renderer; m_renderer = 0; } } void PyGLArea::setRenderer(QVariant renderer) { if (renderer == m_pyRenderer) return; m_pyRenderer = renderer; if (m_renderer) { delete m_renderer; m_renderer = 0; } } void PyGLArea::setBefore(bool before) { if (before == m_before) return; m_before = before; if (m_renderer) { delete m_renderer; m_renderer = 0; } } void PyGLArea::setT(qreal t) { if (t == m_t) return; m_t = t; emit tChanged(); } void PyGLArea::handleWindowChanged(QQuickWindow *win) { if (win) { connect(win, SIGNAL(beforeSynchronizing()), this, SLOT(sync()), Qt::DirectConnection); connect(win, SIGNAL(sceneGraphInvalidated()), this, SLOT(cleanup()), Qt::DirectConnection); // If we allow QML to do the clearing, they would clear what we paint // and nothing would show. win->setClearBeforeRendering(false); } } void PyGLArea::update() { if (window()) window()->update(); } void PyGLArea::sync() { if (!m_renderer && !m_pyRenderer.isNull()) { disconnect(window(), SIGNAL(beforeRendering()), this, SLOT(render())); disconnect(window(), SIGNAL(afterRendering()), this, SLOT(render())); m_renderer = new PyGLRenderer(m_pyRenderer); /*m_renderer->setInitGL(m_initGL); m_renderer->setPaintGL(m_paintGL); m_renderer->setCleanupGL(m_cleanupGL);*/ if (m_before) connect(window(), SIGNAL(beforeRendering()), this, SLOT(render()), Qt::DirectConnection); else connect(window(), SIGNAL(afterRendering()), this, SLOT(render()), Qt::DirectConnection); } } void PyGLArea::render() { QPointF pos = mapToScene(QPointF(.0, .0)); m_renderer->setRect( QRect( (long)pos.x(), (long)(window()->height() - this->height() - pos.y()), (long)this->width(), (long)this->height() ) ); m_renderer->init(); m_renderer->render(); window()->resetOpenGLState(); } void PyGLArea::cleanup() { m_renderer->cleanup(); } <commit_msg>Update PyGLArea when properties have changed.<commit_after> /** * PyOtherSide: Asynchronous Python 3 Bindings for Qt 5 * Copyright (c) 2014, Dennis Tomas <den.t@gmx.de> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. **/ #include "qpython_priv.h" #include "pyglarea.h" #include <QVariant> #include <QPointF> #include <QtQuick/qquickwindow.h> #include <QtGui/QOpenGLShaderProgram> #include <QtGui/QOpenGLContext> PyGLArea::PyGLArea() : m_t(0) , m_before(false) , m_renderer(0) { connect(this, SIGNAL(windowChanged(QQuickWindow*)), this, SLOT(handleWindowChanged(QQuickWindow*))); } PyGLArea::~PyGLArea() { if (m_renderer) { delete m_renderer; m_renderer = 0; } } void PyGLArea::setRenderer(QVariant renderer) { if (renderer == m_pyRenderer) return; m_pyRenderer = renderer; if (m_renderer) { delete m_renderer; m_renderer = 0; } update(); } void PyGLArea::setBefore(bool before) { if (before == m_before) return; m_before = before; if (m_renderer) { delete m_renderer; m_renderer = 0; } update(); } void PyGLArea::setT(qreal t) { if (t == m_t) return; m_t = t; emit tChanged(); } void PyGLArea::handleWindowChanged(QQuickWindow *win) { if (win) { connect(win, SIGNAL(beforeSynchronizing()), this, SLOT(sync()), Qt::DirectConnection); connect(win, SIGNAL(sceneGraphInvalidated()), this, SLOT(cleanup()), Qt::DirectConnection); // If we allow QML to do the clearing, they would clear what we paint // and nothing would show. win->setClearBeforeRendering(false); } } void PyGLArea::update() { if (window()) window()->update(); } void PyGLArea::sync() { if (!m_renderer && !m_pyRenderer.isNull()) { disconnect(window(), SIGNAL(beforeRendering()), this, SLOT(render())); disconnect(window(), SIGNAL(afterRendering()), this, SLOT(render())); m_renderer = new PyGLRenderer(m_pyRenderer); if (m_before) connect(window(), SIGNAL(beforeRendering()), this, SLOT(render()), Qt::DirectConnection); else connect(window(), SIGNAL(afterRendering()), this, SLOT(render()), Qt::DirectConnection); } } void PyGLArea::render() { QPointF pos = mapToScene(QPointF(.0, .0)); m_renderer->setRect( QRect( (long)pos.x(), (long)(window()->height() - this->height() - pos.y()), (long)this->width(), (long)this->height() ) ); m_renderer->init(); m_renderer->render(); window()->resetOpenGLState(); } void PyGLArea::cleanup() { m_renderer->cleanup(); } <|endoftext|>
<commit_before>/* * test1.cpp * * Created on: Jun 15, 2013 * Author: alo */ #include "gtest/gtest.h" int main (int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Adds a example test<commit_after>/* * test1.cpp * * Created on: Jun 15, 2013 * Author: alo */ #include "gtest/gtest.h" #include <boost/locale.hpp> namespace loc = boost::locale; TEST(BoostUTF8, Basics) { std::string UTF8String = u8"lvaro Lpez Ortega"; EXPECT_EQ (UTF8String.size(), 19); EXPECT_EQ (UTF8String.length(), 19); } TEST(BoostUTF8, LetterPosition) { std::string UTF8String = u8"can"; EXPECT_EQ(UTF8String[3], ''); EXPECT_EQ(UTF8String[4], 'n'); } int main (int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/* * test1.cxx * * $Id$ * */ #ifdef _MSC_VER // Disable long symbol name warning on MSVC++ #pragma warning(disable:4786) #endif #include <tptlib/buffer.h> #include <tptlib/parse.h> #include <iostream> #include <stdexcept> #include <sstream> #include <cstring> #include <cstdio> #include <cstdlib> bool test1(unsigned testcount); int main(int argc, char* argv[]) { bool result=false, r; if (argc != 2) { std::cout << "Usage: test1 <testcount>" << std::endl; return 0; } try { r = test1(std::atoi(argv[1])); // if (r) std::cout << "failed" << std::endl; // else std::cout << "passed" << std::endl; result|= r; } catch(const std::exception& e) { result = true; std::cout << "Exception " << e.what() << std::endl; } catch(...) { result = true; std::cout << "Unknown exception" << std::endl; } if (result) std::cout << "FAILED" << std::endl; else std::cout << "PASSED" << std::endl; return result; } bool test1(unsigned testcount) { TPTLib::SymbolTable sym; TPTLib::ErrorList errlist; bool result = false; sym["var"] = "this is the value of var"; sym["var1"] = "Supercalifragilisticexpialidocious"; sym["var2"] = "The red fox runs through the plain and jumps over the fence."; sym["title"] = "TEST TITLE"; char tptfile[256], outfile[256]; unsigned i; for (i = 0; i < testcount; ++i) { std::cout << "test" << (i+1) << ".tpt: "; // generate test file names by rule sprintf(tptfile, "test%u.tpt", i+1); sprintf(outfile, "test%u.out", i+1); // Process the tpt file and store the result in a string TPTLib::Buffer tptbuf(tptfile); TPTLib::Parser p(tptbuf, &sym); std::string tptstr; std::stringstream strs(tptstr); p.run(strs); if (errlist.size()) { std::cout << "Errors!" << std::endl; } // Load the out file TPTLib::Buffer outbuf(outfile); std::string outstr; while (outbuf) outstr+= outbuf.getnextchar(); // Compare tptstr to outstr if (strs.str() == outstr) { std::cout << "passed" << std::endl; } else { result|= true; std::cout << "failed" << std::endl; } std::cout << "\ntptstr = (" << strs.str().size() << ")\n<quote>" << strs.str() << "</quote>" <<std::endl; std::cout << "\noutstr = (" << outstr.size() << ")\n<quote>" << outstr << "</quote>" <<std::endl; } return result; } <commit_msg>update<commit_after>/* * test1.cxx * * $Id$ * */ #ifdef _MSC_VER // Disable long symbol name warning on MSVC++ #pragma warning(disable:4786) #endif #include <tptlib/buffer.h> #include <tptlib/parse.h> #include <iostream> #include <stdexcept> #include <sstream> #include <cstring> #include <cstdio> #include <cstdlib> bool test1(unsigned testcount); int main(int argc, char* argv[]) { bool result=false, r; if (argc != 2) { std::cout << "Usage: test1 <testcount>" << std::endl; return 0; } try { r = test1(std::atoi(argv[1])); // if (r) std::cout << "failed" << std::endl; // else std::cout << "passed" << std::endl; result|= r; } catch(const std::exception& e) { result = true; std::cout << "Exception " << e.what() << std::endl; } catch(...) { result = true; std::cout << "Unknown exception" << std::endl; } if (result) std::cout << "FAILED" << std::endl; else std::cout << "PASSED" << std::endl; return result; } bool test1(unsigned testcount) { TPTLib::SymbolTable sym; TPTLib::ErrorList errlist; bool result = false; sym["var"] = "this is the value of var"; sym["var1"] = "Supercalifragilisticexpialidocious"; sym["var2"] = "The red fox runs through the plain and jumps over the fence."; sym["title"] = "TEST TITLE"; char tptfile[256], outfile[256]; unsigned i; for (i = 0; i < testcount; ++i) { std::cout << "test" << (i+1) << ".tpt: "; // generate test file names by rule sprintf(tptfile, "test%u.tpt", i+1); sprintf(outfile, "test%u.out", i+1); // Process the tpt file and store the result in a string TPTLib::Buffer tptbuf(tptfile); TPTLib::Parser p(tptbuf, &sym); std::string tptstr; std::stringstream strs(tptstr); p.run(strs); if (errlist.size()) { std::cout << "Errors!" << std::endl; } // Load the out file TPTLib::Buffer outbuf(outfile); std::string outstr; while (outbuf) outstr+= outbuf.getnextchar(); // Compare tptstr to outstr if (strs.str() == outstr) { std::cout << "passed" << std::endl; } else { result|= true; std::cout << "failed" << std::endl; } // std::cout << "\ntptstr = (" << strs.str().size() << ")\n<quote>" << strs.str() << "</quote>" <<std::endl; // std::cout << "\noutstr = (" << outstr.size() << ")\n<quote>" << outstr << "</quote>" <<std::endl; } return result; } <|endoftext|>
<commit_before>#include "gui.hh" namespace GUI { void HUD::Tick() { // TODO: update with score } void HUD::Draw() { Cell::Cell cell(' ', this->health_bar_color_, this->health_bar_color_); auto width = this->graphics_->width(); auto height = this->graphics_->height(); this->graphics_->DrawHline(cell, height, 0, this->health_ * 100 / width); } } // namespace GUI <commit_msg>fix heath bar length<commit_after>#include "gui.hh" namespace GUI { void HUD::Tick() { // TODO: update with score } void HUD::Draw() { Cell::Cell cell(' ', this->health_bar_color_, this->health_bar_color_); auto width = this->graphics_->width(); auto height = this->graphics_->height(); auto bar_width = static_cast<int>(static_cast<double>(this->health_) / 100.0 * static_cast<double>(width)); this->graphics_->DrawHline(cell, height, 0, bar_width); } } // namespace GUI <|endoftext|>
<commit_before><commit_msg>beautified expr. in a comment<commit_after><|endoftext|>
<commit_before>#pragma once #include "apple_hid_usage_tables.hpp" #include "constants.hpp" #include "hid_report.hpp" #include "human_interface_device.hpp" #include "iokit_user_client.hpp" #include "local_datagram_client.hpp" #include "logger.hpp" #include "userspace_defs.h" #include "virtual_hid_manager_user_client_method.hpp" class event_grabber final { public: event_grabber(void) : iokit_user_client_(logger::get_logger(), "org_pqrs_driver_VirtualHIDManager", kIOHIDServerConnectType), console_user_client_(constants::get_console_user_socket_file_path()) { iokit_user_client_.start(); manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (!manager_) { return; } auto device_matching_dictionaries = create_device_matching_dictionaries(); if (device_matching_dictionaries) { IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries); CFRelease(device_matching_dictionaries); IOHIDManagerRegisterDeviceMatchingCallback(manager_, device_matching_callback, this); IOHIDManagerRegisterDeviceRemovalCallback(manager_, device_removal_callback, this); IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); } } ~event_grabber(void) { if (manager_) { IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); CFRelease(manager_); manager_ = nullptr; } } private: CFDictionaryRef _Nonnull create_device_matching_dictionary(uint32_t usage_page, uint32_t usage) { auto device_matching_dictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (!device_matching_dictionary) { goto finish; } // usage_page if (!usage_page) { goto finish; } else { auto number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage_page); if (!number) { goto finish; } CFDictionarySetValue(device_matching_dictionary, CFSTR(kIOHIDDeviceUsagePageKey), number); CFRelease(number); } // usage (The usage is only valid if the usage page is also defined) if (!usage) { goto finish; } else { auto number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage); if (!number) { goto finish; } CFDictionarySetValue(device_matching_dictionary, CFSTR(kIOHIDDeviceUsageKey), number); CFRelease(number); } finish: return device_matching_dictionary; } CFArrayRef _Nullable create_device_matching_dictionaries(void) { auto device_matching_dictionaries = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); if (!device_matching_dictionaries) { return nullptr; } // kHIDUsage_GD_Keyboard { auto device_matching_dictionary = create_device_matching_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard); if (device_matching_dictionary) { CFArrayAppendValue(device_matching_dictionaries, device_matching_dictionary); CFRelease(device_matching_dictionary); } } #if 0 // kHIDUsage_Csmr_ConsumerControl { auto device_matching_dictionary = create_device_matching_dictionary(kHIDPage_Consumer, kHIDUsage_Csmr_ConsumerControl); if (device_matching_dictionary) { CFArrayAppendValue(device_matching_dictionaries, device_matching_dictionary); CFRelease(device_matching_dictionary); } } // kHIDUsage_GD_Mouse { auto device_matching_dictionary = create_device_matching_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse); if (device_matching_dictionary) { CFArrayAppendValue(device_matching_dictionaries, device_matching_dictionary); CFRelease(device_matching_dictionary); } } #endif return device_matching_dictionaries; } static void device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<event_grabber*>(context); if (!self) { return; } if (!device) { return; } (self->hids_)[device] = std::make_unique<human_interface_device>(device); auto& dev = (self->hids_)[device]; std::cout << "matching: " << std::endl << " vendor_id:0x" << std::hex << dev->get_vendor_id() << std::endl << " product_id:0x" << std::hex << dev->get_product_id() << std::endl << " location_id:0x" << std::hex << dev->get_location_id() << std::endl << " serial_number:" << dev->get_serial_number_string() << std::endl << " manufacturer:" << dev->get_manufacturer() << std::endl << " product:" << dev->get_product() << std::endl << " transport:" << dev->get_transport() << std::endl; if (dev->get_serial_number_string() == "org.pqrs.driver.VirtualHIDKeyboard") { return; } //if (dev->get_manufacturer() != "pqrs.org") { if (dev->get_manufacturer() == "Apple Inc.") { dev->grab(queue_value_available_callback, self); } } static void device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<event_grabber*>(context); if (!self) { return; } if (!device) { return; } auto it = (self->hids_).find(device); if (it != (self->hids_).end()) { auto& dev = it->second; if (dev) { std::cout << "removal vendor_id:0x" << std::hex << dev->get_vendor_id() << " product_id:0x" << std::hex << dev->get_product_id() << std::endl; (self->hids_).erase(it); } } } static void queue_value_available_callback(void* _Nullable context, IOReturn result, void* _Nullable sender) { auto self = static_cast<event_grabber*>(context); auto queue = static_cast<IOHIDQueueRef>(sender); while (true) { auto value = IOHIDQueueCopyNextValueWithTimeout(queue, 0.); if (!value) { break; } auto element = IOHIDValueGetElement(value); if (element) { auto usage_page = IOHIDElementGetUsagePage(element); auto usage = IOHIDElementGetUsage(element); std::cout << "element" << std::endl << " usage_page:0x" << std::hex << usage_page << std::endl << " usage:0x" << std::hex << usage << std::endl << " type:" << IOHIDElementGetType(element) << std::endl << " length:" << IOHIDValueGetLength(value) << std::endl << " integer_value:" << IOHIDValueGetIntegerValue(value) << std::endl; bool pressed = IOHIDValueGetIntegerValue(value); switch (usage_page) { case kHIDPage_KeyboardOrKeypad: { if (self) { self->handle_keyboard_event(usage, pressed); } break; } case kHIDPage_AppleVendorTopCase: if (usage == kHIDUsage_AV_TopCase_KeyboardFn) { IOOptionBits flags = 0; if (pressed) { flags |= NX_SECONDARYFNMASK; } std::vector<uint8_t> buffer; buffer.resize(1 + sizeof(flags)); buffer[0] = KRBN_OP_TYPE_POST_MODIFIER_FLAGS; memcpy(&(buffer[1]), &flags, sizeof(flags)); self->console_user_client_.send_to(buffer); } break; default: break; } } CFRelease(value); } } void handle_keyboard_event(uint32_t usage, bool pressed) { // ---------------------------------------- // modify usage if (usage == kHIDUsage_KeyboardCapsLock) { usage = kHIDUsage_KeyboardDeleteOrBackspace; } // ---------------------------------------- if (pressed) { pressing_key_usages_.push_back(usage); } else { pressing_key_usages_.remove(usage); } // ---------------------------------------- hid_report::keyboard_input report; while (pressing_key_usages_.size() > sizeof(report.keys)) { pressing_key_usages_.pop_front(); } int i = 0; for (const auto& u : pressing_key_usages_) { report.keys[i] = u; ++i; } auto kr = iokit_user_client_.call_struct_method(static_cast<uint32_t>(virtual_hid_manager_user_client_method::keyboard_input_report), static_cast<const void*>(&report), sizeof(report), nullptr, 0); if (kr != KERN_SUCCESS) { std::cerr << "failed to sent report: 0x" << std::hex << kr << std::dec << std::endl; } } iokit_user_client iokit_user_client_; IOHIDManagerRef _Nullable manager_; std::unordered_map<IOHIDDeviceRef, std::unique_ptr<human_interface_device>> hids_; std::list<uint32_t> pressing_key_usages_; local_datagram_client console_user_client_; }; <commit_msg>use iokit_utility::create_device_matching_dictionaries<commit_after>#pragma once #include "apple_hid_usage_tables.hpp" #include "constants.hpp" #include "hid_report.hpp" #include "human_interface_device.hpp" #include "iokit_user_client.hpp" #include "iokit_utility.hpp" #include "local_datagram_client.hpp" #include "logger.hpp" #include "userspace_defs.h" #include "virtual_hid_manager_user_client_method.hpp" class event_grabber final { public: event_grabber(void) : iokit_user_client_(logger::get_logger(), "org_pqrs_driver_VirtualHIDManager", kIOHIDServerConnectType), console_user_client_(constants::get_console_user_socket_file_path()) { iokit_user_client_.start(); manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (!manager_) { return; } auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries({ std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard), // std::make_pair(kHIDPage_Consumer, kHIDUsage_Csmr_ConsumerControl), // std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse), }); if (device_matching_dictionaries) { IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries); CFRelease(device_matching_dictionaries); IOHIDManagerRegisterDeviceMatchingCallback(manager_, device_matching_callback, this); IOHIDManagerRegisterDeviceRemovalCallback(manager_, device_removal_callback, this); IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); } } ~event_grabber(void) { if (manager_) { IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); CFRelease(manager_); manager_ = nullptr; } } private: static void device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<event_grabber*>(context); if (!self) { return; } if (!device) { return; } (self->hids_)[device] = std::make_unique<human_interface_device>(device); auto& dev = (self->hids_)[device]; std::cout << "matching: " << std::endl << " vendor_id:0x" << std::hex << dev->get_vendor_id() << std::endl << " product_id:0x" << std::hex << dev->get_product_id() << std::endl << " location_id:0x" << std::hex << dev->get_location_id() << std::endl << " serial_number:" << dev->get_serial_number_string() << std::endl << " manufacturer:" << dev->get_manufacturer() << std::endl << " product:" << dev->get_product() << std::endl << " transport:" << dev->get_transport() << std::endl; if (dev->get_serial_number_string() == "org.pqrs.driver.VirtualHIDKeyboard") { return; } //if (dev->get_manufacturer() != "pqrs.org") { if (dev->get_manufacturer() == "Apple Inc.") { dev->grab(queue_value_available_callback, self); } } static void device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<event_grabber*>(context); if (!self) { return; } if (!device) { return; } auto it = (self->hids_).find(device); if (it != (self->hids_).end()) { auto& dev = it->second; if (dev) { std::cout << "removal vendor_id:0x" << std::hex << dev->get_vendor_id() << " product_id:0x" << std::hex << dev->get_product_id() << std::endl; (self->hids_).erase(it); } } } static void queue_value_available_callback(void* _Nullable context, IOReturn result, void* _Nullable sender) { auto self = static_cast<event_grabber*>(context); auto queue = static_cast<IOHIDQueueRef>(sender); while (true) { auto value = IOHIDQueueCopyNextValueWithTimeout(queue, 0.); if (!value) { break; } auto element = IOHIDValueGetElement(value); if (element) { auto usage_page = IOHIDElementGetUsagePage(element); auto usage = IOHIDElementGetUsage(element); std::cout << "element" << std::endl << " usage_page:0x" << std::hex << usage_page << std::endl << " usage:0x" << std::hex << usage << std::endl << " type:" << IOHIDElementGetType(element) << std::endl << " length:" << IOHIDValueGetLength(value) << std::endl << " integer_value:" << IOHIDValueGetIntegerValue(value) << std::endl; bool pressed = IOHIDValueGetIntegerValue(value); switch (usage_page) { case kHIDPage_KeyboardOrKeypad: { if (self) { self->handle_keyboard_event(usage, pressed); } break; } case kHIDPage_AppleVendorTopCase: if (usage == kHIDUsage_AV_TopCase_KeyboardFn) { IOOptionBits flags = 0; if (pressed) { flags |= NX_SECONDARYFNMASK; } std::vector<uint8_t> buffer; buffer.resize(1 + sizeof(flags)); buffer[0] = KRBN_OP_TYPE_POST_MODIFIER_FLAGS; memcpy(&(buffer[1]), &flags, sizeof(flags)); self->console_user_client_.send_to(buffer); } break; default: break; } } CFRelease(value); } } void handle_keyboard_event(uint32_t usage, bool pressed) { // ---------------------------------------- // modify usage if (usage == kHIDUsage_KeyboardCapsLock) { usage = kHIDUsage_KeyboardDeleteOrBackspace; } // ---------------------------------------- if (pressed) { pressing_key_usages_.push_back(usage); } else { pressing_key_usages_.remove(usage); } // ---------------------------------------- hid_report::keyboard_input report; while (pressing_key_usages_.size() > sizeof(report.keys)) { pressing_key_usages_.pop_front(); } int i = 0; for (const auto& u : pressing_key_usages_) { report.keys[i] = u; ++i; } auto kr = iokit_user_client_.call_struct_method(static_cast<uint32_t>(virtual_hid_manager_user_client_method::keyboard_input_report), static_cast<const void*>(&report), sizeof(report), nullptr, 0); if (kr != KERN_SUCCESS) { std::cerr << "failed to sent report: 0x" << std::hex << kr << std::dec << std::endl; } } iokit_user_client iokit_user_client_; IOHIDManagerRef _Nullable manager_; std::unordered_map<IOHIDDeviceRef, std::unique_ptr<human_interface_device>> hids_; std::list<uint32_t> pressing_key_usages_; local_datagram_client console_user_client_; }; <|endoftext|>
<commit_before>#include <shogun/mathematics/linalgrefactor/GPUBackend.h> #include <shogun/mathematics/linalgrefactor/GPUArray.h> #ifdef HAVE_VIENNACL #include <viennacl/vector.hpp> #include <viennacl/linalg/inner_prod.hpp> #endif namespace shogun { template <typename T> T GPUBackend::dot(const GPUVector<T> &a, const GPUVector<T> &b) const { #ifdef HAVE_VIENNACL /** * Method that computes the dot product using ViennaCL */ return viennacl::linalg::inner_prod(a.gpuarray->GPUvec(), b.gpuarray->GPUvec()); #else SG_SERROR("User did not register GPU backend. \n"); return T(0); #endif } template int32_t GPUBackend::dot<int32_t>(const GPUVector<int32_t> &a, const GPUVector<int32_t> &b) const; template float32_t GPUBackend::dot<float32_t>(const GPUVector<float32_t> &a, const GPUVector<float32_t> &b) const; } <commit_msg>update<commit_after>#include <shogun/mathematics/linalgrefactor/GPUBackend.h> #include <shogun/mathematics/linalgrefactor/GPUArray.h> #ifdef HAVE_VIENNACL #include <viennacl/vector.hpp> #include <viennacl/linalg/inner_prod.hpp> #endif namespace shogun { template <typename T> T GPUBackend::dot(const GPUVector<T> &a, const GPUVector<T> &b) const { #ifdef HAVE_VIENNACL /** * Method that computes the dot product using ViennaCL */ return viennacl::linalg::inner_prod(a.gpuarray->GPUvec(), b.gpuarray->GPUvec()); #else SG_SERROR("User did not register GPU backend. \n"); return T(0); #endif } template int32_t GPUBackend::dot<int32_t>(const GPUVector<int32_t> &a, const GPUVector<int32_t> &b) const; template float32_t GPUBackend::dot<float32_t>(const GPUVector<float32_t> &a, const GPUVector<float32_t> &b) const; } <|endoftext|>
<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "intro.h" #include "ui_intro.h" #include "guiutil.h" #include "util.h" #include <boost/filesystem.hpp> #include <QFileDialog> #include <QMessageBox> #include <QSettings> /* Minimum free space (in bytes) needed for data directory */ static const uint64_t GB_BYTES = 1000000000LL; static const uint64_t BLOCK_CHAIN_SIZE = 1LL * GB_BYTES; /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: FreespaceChecker(Intro* intro); enum Status { ST_OK, ST_ERROR }; public slots: void check(); signals: void reply(int status, const QString& message, quint64 available); private: Intro* intro; }; #include "intro.moc" FreespaceChecker::FreespaceChecker(Intro* intro) { this->intro = intro; } void FreespaceChecker::check() { namespace fs = boost::filesystem; QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while (parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if (fs::exists(dataDir)) { if (fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (fs::filesystem_error& e) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } emit reply(replyStatus, replyMessage, freeBytesAvailable); } Intro::Intro(QWidget* parent) : QDialog(parent), ui(new Ui::Intro), thread(0), signalled(false) { ui->setupUi(this); ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE / GB_BYTES)); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ emit stopThread(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString& dataDir) { ui->dataDirectory->setText(dataDir); if (dataDir == getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } QString Intro::getDefaultDataDirectory() { return GUIUtil::boostPathToQString(GetDefaultDataDir()); } bool Intro::pickDataDirectory() { namespace fs = boost::filesystem; QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if (!GetArg("-datadir", "").empty()) return true; /* 1) Default data directory for operating system */ QString dataDir = getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir */ dataDir = settings.value("strDataDir", dataDir).toString(); if (!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", false)) { /* If current default data directory does not exist, let the user choose one */ Intro intro; intro.setDataDirectory(dataDir); intro.setWindowIcon(QIcon(":icons/bitcoin")); while (true) { if (!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir)); break; } catch (fs::filesystem_error& e) { QMessageBox::critical(0, tr("PIVX Core"), tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } settings.setValue("strDataDir", dataDir); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the pivx.conf file in the default data directory * (to be consistent with pivxd behavior) */ if (dataDir != getDefaultDataDirectory()) SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting return true; } void Intro::setStatus(int status, const QString& message, quint64 bytesAvailable) { switch (status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); break; } /* Indicate number of bytes available */ if (status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { QString freeString = tr("%1 GB of free space available").arg(bytesAvailable / GB_BYTES); if (bytesAvailable < BLOCK_CHAIN_SIZE) { freeString += " " + tr("(of %1 GB needed)").arg(BLOCK_CHAIN_SIZE / GB_BYTES); ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::on_dataDirectory_textChanged(const QString& dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text())); if (!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker* executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, SIGNAL(reply(int, QString, quint64)), this, SLOT(setStatus(int, QString, quint64))); connect(this, SIGNAL(requestCheck()), executor, SLOT(check())); /* make sure executor object is deleted in its own thread */ connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopThread()), thread, SLOT(quit())); thread->start(); } void Intro::checkPath(const QString& dataDir) { mutex.lock(); pathToCheck = dataDir; if (!signalled) { signalled = true; emit requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; } <commit_msg>Update intro.cpp<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017 The Phore developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "intro.h" #include "ui_intro.h" #include "guiutil.h" #include "util.h" #include <boost/filesystem.hpp> #include <QFileDialog> #include <QMessageBox> #include <QSettings> /* Minimum free space (in bytes) needed for data directory */ static const uint64_t GB_BYTES = 1000000000LL; static const uint64_t BLOCK_CHAIN_SIZE = 1LL * GB_BYTES; /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: FreespaceChecker(Intro* intro); enum Status { ST_OK, ST_ERROR }; public slots: void check(); signals: void reply(int status, const QString& message, quint64 available); private: Intro* intro; }; #include "intro.moc" FreespaceChecker::FreespaceChecker(Intro* intro) { this->intro = intro; } void FreespaceChecker::check() { namespace fs = boost::filesystem; QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while (parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if (fs::exists(dataDir)) { if (fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (fs::filesystem_error& e) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } emit reply(replyStatus, replyMessage, freeBytesAvailable); } Intro::Intro(QWidget* parent) : QDialog(parent), ui(new Ui::Intro), thread(0), signalled(false) { ui->setupUi(this); ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE / GB_BYTES)); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ emit stopThread(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString& dataDir) { ui->dataDirectory->setText(dataDir); if (dataDir == getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } QString Intro::getDefaultDataDirectory() { return GUIUtil::boostPathToQString(GetDefaultDataDir()); } bool Intro::pickDataDirectory() { namespace fs = boost::filesystem; QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if (!GetArg("-datadir", "").empty()) return true; /* 1) Default data directory for operating system */ QString dataDir = getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir */ dataDir = settings.value("strDataDir", dataDir).toString(); if (!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", false)) { /* If current default data directory does not exist, let the user choose one */ Intro intro; intro.setDataDirectory(dataDir); intro.setWindowIcon(QIcon(":icons/bitcoin")); while (true) { if (!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir)); break; } catch (fs::filesystem_error& e) { QMessageBox::critical(0, tr("Phore Core"), tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } settings.setValue("strDataDir", dataDir); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the phore.conf file in the default data directory * (to be consistent with phored behavior) */ if (dataDir != getDefaultDataDirectory()) SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting return true; } void Intro::setStatus(int status, const QString& message, quint64 bytesAvailable) { switch (status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); break; } /* Indicate number of bytes available */ if (status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { QString freeString = tr("%1 GB of free space available").arg(bytesAvailable / GB_BYTES); if (bytesAvailable < BLOCK_CHAIN_SIZE) { freeString += " " + tr("(of %1 GB needed)").arg(BLOCK_CHAIN_SIZE / GB_BYTES); ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::on_dataDirectory_textChanged(const QString& dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text())); if (!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker* executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, SIGNAL(reply(int, QString, quint64)), this, SLOT(setStatus(int, QString, quint64))); connect(this, SIGNAL(requestCheck()), executor, SLOT(check())); /* make sure executor object is deleted in its own thread */ connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopThread()), thread, SLOT(quit())); thread->start(); } void Intro::checkPath(const QString& dataDir) { mutex.lock(); pathToCheck = dataDir; if (!signalled) { signalled = true; emit requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; } <|endoftext|>
<commit_before>// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2021 The Dash 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/dash-config.h> #endif #include <fs.h> #include <qt/intro.h> #include <qt/forms/ui_intro.h> #include <qt/guiutil.h> #include <interfaces/node.h> #include <util.h> #include <QFileDialog> #include <QSettings> #include <QMessageBox> #include <cmath> static const uint64_t GB_BYTES = 1000000000LL; /* Minimum free space (in GB) needed for data directory */ static const uint64_t BLOCK_CHAIN_SIZE = 30; /* Minimum free space (in GB) needed for data directory when pruned; Does not include prune target */ static const uint64_t CHAIN_STATE_SIZE = 1; /* Total required space (in GB) depending on user choice (prune, not prune) */ static uint64_t requiredSpace; /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: explicit FreespaceChecker(Intro *intro); enum Status { ST_OK, ST_ERROR }; public Q_SLOTS: void check(); Q_SIGNALS: void reply(int status, const QString &message, quint64 available); private: Intro *intro; }; #include <qt/intro.moc> FreespaceChecker::FreespaceChecker(Intro *_intro) { this->intro = _intro; } void FreespaceChecker::check() { QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while(parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if(fs::exists(dataDir)) { if(fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (const fs::filesystem_error&) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable); } Intro::Intro(QWidget *parent) : QDialog(parent), ui(new Ui::Intro), thread(0), signalled(false) { ui->setupUi(this); ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME))); ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME))); ui->lblExplanation1->setText(ui->lblExplanation1->text() .arg(tr(PACKAGE_NAME)) .arg(BLOCK_CHAIN_SIZE) .arg(2014) .arg("Dash") ); ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(tr(PACKAGE_NAME))); uint64_t pruneTarget = std::max<int64_t>(0, gArgs.GetArg("-prune", 0)); requiredSpace = BLOCK_CHAIN_SIZE; QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time."); if (pruneTarget) { uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES); if (prunedGBs <= requiredSpace) { requiredSpace = prunedGBs; storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory."); } ui->lblExplanation3->setVisible(true); } else { ui->lblExplanation3->setVisible(false); } requiredSpace += CHAIN_STATE_SIZE; ui->sizeWarningLabel->setText( tr("%1 will download and store a copy of the Dash block chain.").arg(tr(PACKAGE_NAME)) + " " + storageRequiresMsg.arg(requiredSpace) + " " + tr("The wallet will also be stored in this directory.") ); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ Q_EMIT stopThread(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString &dataDir) { ui->dataDirectory->setText(dataDir); if(dataDir == getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } QString Intro::getDefaultDataDirectory() { return GUIUtil::boostPathToQString(GetDefaultDataDir()); } bool Intro::pickDataDirectory(interfaces::Node& node) { QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if(!gArgs.GetArg("-datadir", "").empty()) return true; /* 1) Default data directory for operating system */ QString dataDirDefaultCurrent = getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir */ QString dataDir = settings.value("strDataDir", dataDirDefaultCurrent).toString(); /* 3) Check to see if default datadir is the one we expect */ QString dataDirDefaultSettings = settings.value("strDataDirDefault").toString(); if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || dataDirDefaultCurrent != dataDirDefaultSettings) { /* Let the user choose one */ Intro intro; GUIUtil::disableMacFocusRect(&intro); GUIUtil::loadStyleSheet(true); intro.setDataDirectory(dataDirDefaultCurrent); intro.setWindowIcon(QIcon(":icons/dash")); while(true) { if(!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) { // If a new data directory has been created, make wallets subdirectory too TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets"); } break; } catch (const fs::filesystem_error&) { QMessageBox::critical(0, tr(PACKAGE_NAME), tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } settings.setValue("strDataDir", dataDir); settings.setValue("strDataDirDefault", dataDirDefaultCurrent); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the dash.conf file in the default data directory * (to be consistent with dashd behavior) */ if(dataDir != dataDirDefaultCurrent) { node.softSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting } return true; } void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable) { switch(status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR)); break; } /* Indicate number of bytes available */ if(status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { QString freeString = tr("%1 GB of free space available").arg(bytesAvailable/GB_BYTES); if(bytesAvailable < requiredSpace * GB_BYTES) { freeString += " " + tr("(of %1 GB needed)").arg(requiredSpace); ui->freeSpace->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR)); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::on_dataDirectory_textChanged(const QString &dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text())); if(!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker *executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64))); connect(this, SIGNAL(requestCheck()), executor, SLOT(check())); /* make sure executor object is deleted in its own thread */ connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopThread()), thread, SLOT(quit())); thread->start(); } void Intro::checkPath(const QString &dataDir) { mutex.lock(); pathToCheck = dataDir; if(!signalled) { signalled = true; Q_EMIT requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; } <commit_msg>increase BLOCK_CHAIN_SIZE marginally (#4150)<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2021 The Dash 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/dash-config.h> #endif #include <fs.h> #include <qt/intro.h> #include <qt/forms/ui_intro.h> #include <qt/guiutil.h> #include <interfaces/node.h> #include <util.h> #include <QFileDialog> #include <QSettings> #include <QMessageBox> #include <cmath> static const uint64_t GB_BYTES = 1000000000LL; /* Minimum free space (in GB) needed for data directory */ static const uint64_t BLOCK_CHAIN_SIZE = 35; /* Minimum free space (in GB) needed for data directory when pruned; Does not include prune target */ static const uint64_t CHAIN_STATE_SIZE = 1; /* Total required space (in GB) depending on user choice (prune, not prune) */ static uint64_t requiredSpace; /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: explicit FreespaceChecker(Intro *intro); enum Status { ST_OK, ST_ERROR }; public Q_SLOTS: void check(); Q_SIGNALS: void reply(int status, const QString &message, quint64 available); private: Intro *intro; }; #include <qt/intro.moc> FreespaceChecker::FreespaceChecker(Intro *_intro) { this->intro = _intro; } void FreespaceChecker::check() { QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while(parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if(fs::exists(dataDir)) { if(fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (const fs::filesystem_error&) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable); } Intro::Intro(QWidget *parent) : QDialog(parent), ui(new Ui::Intro), thread(0), signalled(false) { ui->setupUi(this); ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME))); ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME))); ui->lblExplanation1->setText(ui->lblExplanation1->text() .arg(tr(PACKAGE_NAME)) .arg(BLOCK_CHAIN_SIZE) .arg(2014) .arg("Dash") ); ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(tr(PACKAGE_NAME))); uint64_t pruneTarget = std::max<int64_t>(0, gArgs.GetArg("-prune", 0)); requiredSpace = BLOCK_CHAIN_SIZE; QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time."); if (pruneTarget) { uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES); if (prunedGBs <= requiredSpace) { requiredSpace = prunedGBs; storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory."); } ui->lblExplanation3->setVisible(true); } else { ui->lblExplanation3->setVisible(false); } requiredSpace += CHAIN_STATE_SIZE; ui->sizeWarningLabel->setText( tr("%1 will download and store a copy of the Dash block chain.").arg(tr(PACKAGE_NAME)) + " " + storageRequiresMsg.arg(requiredSpace) + " " + tr("The wallet will also be stored in this directory.") ); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ Q_EMIT stopThread(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString &dataDir) { ui->dataDirectory->setText(dataDir); if(dataDir == getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } QString Intro::getDefaultDataDirectory() { return GUIUtil::boostPathToQString(GetDefaultDataDir()); } bool Intro::pickDataDirectory(interfaces::Node& node) { QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if(!gArgs.GetArg("-datadir", "").empty()) return true; /* 1) Default data directory for operating system */ QString dataDirDefaultCurrent = getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir */ QString dataDir = settings.value("strDataDir", dataDirDefaultCurrent).toString(); /* 3) Check to see if default datadir is the one we expect */ QString dataDirDefaultSettings = settings.value("strDataDirDefault").toString(); if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || dataDirDefaultCurrent != dataDirDefaultSettings) { /* Let the user choose one */ Intro intro; GUIUtil::disableMacFocusRect(&intro); GUIUtil::loadStyleSheet(true); intro.setDataDirectory(dataDirDefaultCurrent); intro.setWindowIcon(QIcon(":icons/dash")); while(true) { if(!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) { // If a new data directory has been created, make wallets subdirectory too TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets"); } break; } catch (const fs::filesystem_error&) { QMessageBox::critical(0, tr(PACKAGE_NAME), tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } settings.setValue("strDataDir", dataDir); settings.setValue("strDataDirDefault", dataDirDefaultCurrent); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the dash.conf file in the default data directory * (to be consistent with dashd behavior) */ if(dataDir != dataDirDefaultCurrent) { node.softSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting } return true; } void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable) { switch(status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR)); break; } /* Indicate number of bytes available */ if(status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { QString freeString = tr("%1 GB of free space available").arg(bytesAvailable/GB_BYTES); if(bytesAvailable < requiredSpace * GB_BYTES) { freeString += " " + tr("(of %1 GB needed)").arg(requiredSpace); ui->freeSpace->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR)); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::on_dataDirectory_textChanged(const QString &dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text())); if(!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker *executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64))); connect(this, SIGNAL(requestCheck()), executor, SLOT(check())); /* make sure executor object is deleted in its own thread */ connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopThread()), thread, SLOT(quit())); thread->start(); } void Intro::checkPath(const QString &dataDir) { mutex.lock(); pathToCheck = dataDir; if(!signalled) { signalled = true; Q_EMIT requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; } <|endoftext|>
<commit_before>#include <LD30/Entity/Player.hpp> #include <SFML/Window.hpp> #include <iostream> #include <cmath> ld::Player::Player(sf::RenderWindow &window) :Entity(window) { m_direction = sf::Vector2f(0,0); } ld::Player::~Player() { } void ld::Player::update(const float delta) { keyInput(delta); const float mag = std::sqrt(m_direction.x*m_direction.x + m_direction.y*m_direction.y); const float maxspeed = 100; if (mag > maxspeed) { sf::Vector2f normalize = m_direction / mag; m_direction = normalize*maxspeed; } this->move(m_direction*delta); m_direction *= 0.9999f-delta/10; } void ld::Player::keyInput(const float delta) { sf::Vector2f temp; const float speed = 50.f*delta; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { temp += sf::Vector2f(-speed, 0); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { temp += sf::Vector2f(speed, 0); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { temp += sf::Vector2f(0, -speed); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { temp += sf::Vector2f(0, speed); } m_direction += temp; } <commit_msg>Esko happened<commit_after>#include <LD30/Entity/Player.hpp> #include <SFML/Window.hpp> #include <iostream> #include <cmath> ld::Player::Player(sf::RenderWindow &window) :Entity(window) { m_direction = sf::Vector2f(0,0); } ld::Player::~Player() { } void ld::Player::update(const float delta) { keyInput(delta); const float mag = std::sqrt(m_direction.x*m_direction.x + m_direction.y*m_direction.y); const float maxspeed = 100; if (mag > maxspeed) { sf::Vector2f normalize = m_direction / mag; m_direction = normalize*maxspeed; } this->move(m_direction*delta); m_direction *= 0.9999f-delta/10; } void ld::Player::keyInput(const float delta) { sf::Vector2f temp; const float speed = 50.f*delta; temp += sf::Vector2f( (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) - sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) * speed, (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) - sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) * speed); m_direction += temp; } <|endoftext|>
<commit_before>/* * 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. */ // ForcedDebugDlg.cpp : t@C // #include "stdafx.h" #include "MZ3.h" #include "ForcedDebugDlg.h" // CForcedDebugDlg _CAO IMPLEMENT_DYNAMIC(CForcedDebugDlg, CDialog) CForcedDebugDlg::CForcedDebugDlg(CWnd* pParent /*=NULL*/) : CDialog(CForcedDebugDlg::IDD, pParent) , m_bStop(false) , drawing(false) { } CForcedDebugDlg::~CForcedDebugDlg() { } void CForcedDebugDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CForcedDebugDlg, CDialog) ON_WM_SIZE() ON_WM_DESTROY() ON_WM_PAINT() END_MESSAGE_MAP() // CForcedDebugDlg bZ[W nh /// return generated random value between [from,to]. int rand_range( int from, int to ) { int range = to - from +1; return rand() % range + from; } #define N_BUG 10 BOOL CForcedDebugDlg::OnInitDialog() { CDialog::OnInitDialog(); // TODO: ɏljĂ CRect rect; GetClientRect( &rect ); int w = rect.Width(); int h = rect.Height(); // init force force.w = 100; force.h = 20; force.dx = 10; // speed force.init( w, h ); // init ball Ball ball; ball.alive = true; ball.w = 10; ball.h = 10; CPoint ball_zone( w/2 - ball.w/2, 120 ); for( int i=0; i<N_BUG; i++ ) { ball.x = ball_zone.x + rand_range(-100,100); ball.y = ball_zone.y + rand_range(-100,100); ball.dx = rand_range( -2, 2 ); ball.dy = rand_range( 2, 3 ); balls.push_back(ball); } // start working thread AfxBeginThread( Ticker, this ); return TRUE; // return TRUE unless you set the focus to a control // O : OCX vpeB y[W͕K FALSE Ԃ܂B } unsigned int CForcedDebugDlg::Ticker( LPVOID This ) { CForcedDebugDlg* pDlg = (CForcedDebugDlg*) This; ::Sleep( 1000L ); pDlg->Invalidate( FALSE ); while( !pDlg->m_bStop ) { static const DWORD dwWait = 30L; ::Sleep( dwWait ); if( !pDlg->drawing ) { pDlg->drawing = true; pDlg->NextFrame(); pDlg->Invalidate( FALSE ); } } return 0; } BOOL CForcedDebugDlg::PreTranslateMessage(MSG* pMsg) { switch( pMsg->message ) { case WM_KEYDOWN: switch( pMsg->wParam ) { case VK_RETURN: break; case VK_UP: force.dx ++; break; case VK_DOWN: force.dx --; break; } return TRUE; case WM_KEYUP: switch( pMsg->wParam ) { case VK_F1: OnOK(); break; case VK_F2: break; } } return CDialog::PreTranslateMessage(pMsg); } void CForcedDebugDlg::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); } void CForcedDebugDlg::OnDestroy() { CDialog::OnDestroy(); // TODO: ɃbZ[W nh R[hlj܂B m_bStop = true; } bool CForcedDebugDlg::NextFrame(void) { CRect rect; GetClientRect( &rect ); int w = rect.Width(); int h = rect.Height(); bool bKeyRight = (GetAsyncKeyState( VK_RIGHT ) & 0x8000) != 0; bool bKeyLeft = (GetAsyncKeyState( VK_LEFT ) & 0x8000) != 0; // force move // right if( bKeyRight ) { force.moveRight(); } // left if( bKeyLeft ) { force.moveLeft(); } // correct pos. if( force.x + force.w/2 > w ) { force.x = w - force.w/2; } if( force.x - force.w/2 < 0 ) { force.x = force.w/2; } // move balls for( unsigned int i=0; i<balls.size(); i++ ) { Ball& ball = balls[i]; if( ball.alive ) { ball.move(); } } // collect/refleft balls for( unsigned int i=0; i<balls.size(); i++ ) { Ball& ball = balls[i]; if( ball.alive ) { // collect balls drop out if( ball.y > h ) { ball.alive = false; continue; } // reflection by side walls if( ball.x+ball.w/2 > w || ball.x-ball.w/2 < 0 ) { ball.dx = -ball.dx; continue; } // reflection by top wall if( ball.y -ball.h/2 < 0 ) { ball.dy = -ball.dy; } // reflection by force // modify dx by left/right key if( force.left() <= ball.x && ball.x <= force.right() && force.top() <= ball.y && ball.y <= force.bottom() && ball.dy > 0 ) { // modify dx by left key if( bKeyLeft ) { ball.dx -= 1; } // modify dx by right key if( bKeyRight ) { ball.dx += 1; } // reflect ball.dy = -ball.dy; // speed up/down if( bKeyLeft || bKeyRight ) { // speed up ball.dy --; }else{ // speed down when not lowest. ball.dy ++; if( ball.dy > -2 ) { ball.dy = -1; } } } } } // remove died balls from ball list int removedBallCount = 0; for( unsigned int i=0; i<balls.size(); ) { Ball& ball = balls[i]; if( !ball.alive ) { balls.erase( balls.begin()+i ); removedBallCount ++; }else{ i++; } } // append balls /* if( removedBallCount > 0 ) { // init ball Ball ball; ball.alive = true; ball.w = 10; ball.h = 10; ball.dx = 1; ball.dy = 1; CPoint bug_zone( w/2 - ball.w/2, 120 ); for( int i=0; i<removedBallCount; i++ ) { ball.x = bug_zone.x + rand_range(-100,100); ball.y = bug_zone.y + rand_range(-100,100); ball.dx = rand_range( -2, 2 ); ball.dy = rand_range( 1, 2 ); balls.push_back(ball); } } */ return true; } void CForcedDebugDlg::OnPaint() { CPaintDC dc(this); // device context for painting // TODO: ɃbZ[W nh R[hlj܂B // `惁bZ[W CDialog::OnPaint() ĂяoȂłB // clear screen CRect rect; GetClientRect( &rect ); dc.FillSolidRect( rect, RGB(128,255,128) ); // status CString s; CRect r( 10, 20, 200, 20+100 ); dc.SetBkMode( TRANSPARENT ); // ball count s.Format( L"balls : %d", balls.size() ); r.top = 20; r.bottom = r.top + 100; dc.DrawText( s, r, DT_LEFT ); // pos,speed s.Format( L"%d,%d", force.x, force.dx ); r.top = 50; r.bottom = r.top + 100; dc.DrawText( s, r, DT_LEFT ); // draw ball for( unsigned int i=0; i<balls.size(); i++ ) { Ball& ball = balls[i]; if( ball.alive ) { dc.Ellipse( ball.x-ball.w/2, ball.y-ball.h/2, ball.x+ball.w/2, ball.y+ball.h/2 ); } } // draw force dc.Rectangle( force.x-force.w/2, force.y-force.h/2, force.x+force.w/2, force.y+force.h/2 ); drawing = false; } void CForcedDebugDlg::OnOK() { m_bStop = true; CDialog::OnOK(); } <commit_msg>サイズ調整<commit_after>/* * 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. */ // ForcedDebugDlg.cpp : t@C // #include "stdafx.h" #include "MZ3.h" #include "ForcedDebugDlg.h" // CForcedDebugDlg _CAO IMPLEMENT_DYNAMIC(CForcedDebugDlg, CDialog) CForcedDebugDlg::CForcedDebugDlg(CWnd* pParent /*=NULL*/) : CDialog(CForcedDebugDlg::IDD, pParent) , m_bStop(false) , drawing(false) { } CForcedDebugDlg::~CForcedDebugDlg() { } void CForcedDebugDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CForcedDebugDlg, CDialog) ON_WM_SIZE() ON_WM_DESTROY() ON_WM_PAINT() END_MESSAGE_MAP() // CForcedDebugDlg bZ[W nh /// return generated random value between [from,to]. int rand_range( int from, int to ) { int range = to - from +1; return rand() % range + from; } #define N_BUG 10 BOOL CForcedDebugDlg::OnInitDialog() { CDialog::OnInitDialog(); #ifndef WINCE // TCY WINDOWPLACEMENT wp; if (GetWindowPlacement(&wp)) { SetWindowPos(NULL, wp.rcNormalPosition.left, wp.rcNormalPosition.top, 480, 640, SWP_SHOWWINDOW); } #endif CRect rect; GetClientRect( &rect ); int w = rect.Width(); int h = rect.Height(); // init force force.w = 100; force.h = 20; force.dx = 10; // speed force.init( w, h ); // init ball Ball ball; ball.alive = true; ball.w = 10; ball.h = 10; CPoint ball_zone( w/2 - ball.w/2, 120 ); for( int i=0; i<N_BUG; i++ ) { ball.x = ball_zone.x + rand_range(-100,100); ball.y = ball_zone.y + rand_range(-100,100); ball.dx = rand_range( -2, 2 ); ball.dy = rand_range( 2, 3 ); balls.push_back(ball); } // start working thread AfxBeginThread( Ticker, this ); return TRUE; // return TRUE unless you set the focus to a control // O : OCX vpeB y[W͕K FALSE Ԃ܂B } unsigned int CForcedDebugDlg::Ticker( LPVOID This ) { CForcedDebugDlg* pDlg = (CForcedDebugDlg*) This; ::Sleep( 1000L ); pDlg->Invalidate( FALSE ); while( !pDlg->m_bStop ) { static const DWORD dwWait = 30L; ::Sleep( dwWait ); if( !pDlg->drawing ) { pDlg->drawing = true; pDlg->NextFrame(); pDlg->Invalidate( FALSE ); } } return 0; } BOOL CForcedDebugDlg::PreTranslateMessage(MSG* pMsg) { switch( pMsg->message ) { case WM_KEYDOWN: switch( pMsg->wParam ) { case VK_RETURN: break; case VK_UP: force.dx ++; break; case VK_DOWN: force.dx --; break; } return TRUE; case WM_KEYUP: switch( pMsg->wParam ) { case VK_F1: OnOK(); break; case VK_F2: break; } } return CDialog::PreTranslateMessage(pMsg); } void CForcedDebugDlg::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); } void CForcedDebugDlg::OnDestroy() { CDialog::OnDestroy(); // TODO: ɃbZ[W nh R[hlj܂B m_bStop = true; } bool CForcedDebugDlg::NextFrame(void) { CRect rect; GetClientRect( &rect ); int w = rect.Width(); int h = rect.Height(); bool bKeyRight = (GetAsyncKeyState( VK_RIGHT ) & 0x8000) != 0; bool bKeyLeft = (GetAsyncKeyState( VK_LEFT ) & 0x8000) != 0; // force move // right if( bKeyRight ) { force.moveRight(); } // left if( bKeyLeft ) { force.moveLeft(); } // correct pos. if( force.x + force.w/2 > w ) { force.x = w - force.w/2; } if( force.x - force.w/2 < 0 ) { force.x = force.w/2; } // move balls for( unsigned int i=0; i<balls.size(); i++ ) { Ball& ball = balls[i]; if( ball.alive ) { ball.move(); } } // collect/refleft balls for( unsigned int i=0; i<balls.size(); i++ ) { Ball& ball = balls[i]; if( ball.alive ) { // collect balls drop out if( ball.y > h ) { ball.alive = false; continue; } // reflection by side walls if( ball.x+ball.w/2 > w || ball.x-ball.w/2 < 0 ) { ball.dx = -ball.dx; continue; } // reflection by top wall if( ball.y -ball.h/2 < 0 ) { ball.dy = -ball.dy; } // reflection by force // modify dx by left/right key if( force.left() <= ball.x && ball.x <= force.right() && force.top() <= ball.y && ball.y <= force.bottom() && ball.dy > 0 ) { // modify dx by left key if( bKeyLeft ) { ball.dx -= 1; } // modify dx by right key if( bKeyRight ) { ball.dx += 1; } // reflect ball.dy = -ball.dy; // speed up/down if( bKeyLeft || bKeyRight ) { // speed up ball.dy --; }else{ // speed down when not lowest. ball.dy ++; if( ball.dy > -2 ) { ball.dy = -1; } } } } } // remove died balls from ball list int removedBallCount = 0; for( unsigned int i=0; i<balls.size(); ) { Ball& ball = balls[i]; if( !ball.alive ) { balls.erase( balls.begin()+i ); removedBallCount ++; }else{ i++; } } // append balls /* if( removedBallCount > 0 ) { // init ball Ball ball; ball.alive = true; ball.w = 10; ball.h = 10; ball.dx = 1; ball.dy = 1; CPoint bug_zone( w/2 - ball.w/2, 120 ); for( int i=0; i<removedBallCount; i++ ) { ball.x = bug_zone.x + rand_range(-100,100); ball.y = bug_zone.y + rand_range(-100,100); ball.dx = rand_range( -2, 2 ); ball.dy = rand_range( 1, 2 ); balls.push_back(ball); } } */ return true; } void CForcedDebugDlg::OnPaint() { CPaintDC dc(this); // device context for painting // TODO: ɃbZ[W nh R[hlj܂B // `惁bZ[W CDialog::OnPaint() ĂяoȂłB // clear screen CRect rect; GetClientRect( &rect ); dc.FillSolidRect( rect, RGB(128,255,128) ); // status CString s; CRect r( 10, 20, 200, 20+100 ); dc.SetBkMode( TRANSPARENT ); // ball count s.Format( L"balls : %d", balls.size() ); r.top = 20; r.bottom = r.top + 100; dc.DrawText( s, r, DT_LEFT ); // pos,speed s.Format( L"%d,%d", force.x, force.dx ); r.top = 50; r.bottom = r.top + 100; dc.DrawText( s, r, DT_LEFT ); // draw ball for( unsigned int i=0; i<balls.size(); i++ ) { Ball& ball = balls[i]; if( ball.alive ) { dc.Ellipse( ball.x-ball.w/2, ball.y-ball.h/2, ball.x+ball.w/2, ball.y+ball.h/2 ); } } // draw force dc.Rectangle( force.x-force.w/2, force.y-force.h/2, force.x+force.w/2, force.y+force.h/2 ); drawing = false; } void CForcedDebugDlg::OnOK() { m_bStop = true; CDialog::OnOK(); } <|endoftext|>
<commit_before>#ifndef RECOMBINATION_DEF_HPP_ #define RECOMBINATION_DEF_HPP_ #include <cassert> #include "clotho/powerset/variable_subset.hpp" #include "clotho/utility/bit_walker.hpp" namespace clotho { namespace recombine { template < class Sequence, class Classifier > class recombination; template < class Element, class Block, class BlockMap, class ElementKeyer, class Classifier > class recombination< clotho::powersets::variable_subset< Element, Block, BlockMap, ElementKeyer >, Classifier > { public: typedef clotho::powersets::variable_subset< Element, Block, BlockMap, ElementKeyer > subset_type; typedef typename subset_type::pointer sequence_type; typedef Classifier classifier_type; typedef typename subset_type::bitset_type bit_sequence_type; typedef Block block_type; typedef clotho::utility::block_walker< block_type, unsigned short > block_walker_type; void operator()( sequence_type base, sequence_type alt, classifier_type & elem_classifier) { assert( base->isSameFamily( alt ) ); m_match_base = m_match_alt = m_empty = true; if( base == alt ) { return; } m_res_seq.reset(); m_res_seq.resize( base->max_size(), false ); typename subset_type::cblock_iterator base_it = base->begin(), base_end = base->end(); typename subset_type::cblock_iterator alt_it = base->begin(), alt_end = base->end(); typename subset_type::block_iterator res_it = m_res_seq.m_bits.begin(); while( true ) { if( alt_it == alt_end ) { while( base_it != base_end ) { block_type _base = (*base_it++); recombine( (*res_it), _base, 0, elem_classifier ); ++res_it; } break; } if( base_it == base_end ) { while( alt_it != alt_end ) { block_type _alt = (*alt_it++); recombine( (*res_it), 0, _alt, elem_classifier ); ++res_it; } break; } block_type _base = (*base_it++), _alt = (*alt_it++); recombine( (*res_it), _base, _alt, elem_classifier ); ++res_it; } } bit_sequence_type * getResultSequence() { return &m_res_seq; } bool isMatchBase() const { return m_match_base; } bool isMatchAlt() const { return m_match_alt; } bool isEmpty() const { return m_empty; } void recombine( block_type & res, const block_type base, const block_type alt, classifier_type & elem_classifier ) { block_type hom = base & alt; block_type hets = base ^ alt; elem_classifier.resetResult(); block_walker_type::apply( hets, elem_classifier ); block_type base_mask = elem_classifier.getResult(); block_type alt_mask = ((~base_mask & hets) & alt); res =(hom | (alt_mask | (base_mask & base))); m_match_base = (m_match_base && (base == res) ); m_match_alt = (m_match_alt && (alt == res) ); m_empty = (m_empty && (res == 0) ); } virtual ~recombination() {} protected: bit_sequence_type m_res_seq; bool m_match_base, m_match_alt, m_empty; }; } // namespace recombine } // namespace clotho #endif // RECOMBINATION_DEF_HPP_ <commit_msg>Moved partial specialization for variable_subsets into powerset directory<commit_after>#ifndef RECOMBINATION_DEF_HPP_ #define RECOMBINATION_DEF_HPP_ #include <cassert> namespace clotho { namespace recombine { template < class Sequence, class Classifier > class recombination; } // namespace recombine } // namespace clotho #endif // RECOMBINATION_DEF_HPP_ <|endoftext|>
<commit_before>//===--- DeclSerialization.cpp - Serialization of Decls ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Ted Kremenek and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This files defines methods that implement bitcode serialization for Decls. // //===----------------------------------------------------------------------===// #include "clang/AST/Decl.h" #include "clang/AST/Expr.h" #include "llvm/Bitcode/Serialize.h" #include "llvm/Bitcode/Deserialize.h" using llvm::Serializer; using llvm::Deserializer; using llvm::SerializedPtrID; using namespace clang; //===----------------------------------------------------------------------===// // Decl Serialization: Dispatch code to handle specialized decl types. //===----------------------------------------------------------------------===// void Decl::Emit(Serializer& S) const { S.EmitInt(getKind()); EmitImpl(S); } Decl* Decl::Create(Deserializer& D) { Kind k = static_cast<Kind>(D.ReadInt()); switch (k) { default: assert (false && "Not implemented."); break; case BlockVar: return BlockVarDecl::CreateImpl(D); case Enum: return EnumDecl::CreateImpl(D); case EnumConstant: return EnumConstantDecl::CreateImpl(D); case Field: return FieldDecl::CreateImpl(D); case FileVar: return FileVarDecl::CreateImpl(D); case ParmVar: return ParmVarDecl::CreateImpl(D); case Function: return FunctionDecl::CreateImpl(D); case Union: case Struct: return RecordDecl::CreateImpl(k,D); case Typedef: return TypedefDecl::CreateImpl(D); } } //===----------------------------------------------------------------------===// // Common serialization logic for subclasses of Decl. //===----------------------------------------------------------------------===// void Decl::EmitInRec(Serializer& S) const { S.Emit(getLocation()); // From Decl. } void Decl::ReadInRec(Deserializer& D) { Loc = SourceLocation::ReadVal(D); // From Decl. } //===----------------------------------------------------------------------===// // Common serialization logic for subclasses of NamedDecl. //===----------------------------------------------------------------------===// void NamedDecl::EmitInRec(Serializer& S) const { Decl::EmitInRec(S); S.EmitPtr(getIdentifier()); // From NamedDecl. } void NamedDecl::ReadInRec(Deserializer& D) { Decl::ReadInRec(D); D.ReadPtr(Identifier); // From NamedDecl. } //===----------------------------------------------------------------------===// // Common serialization logic for subclasses of ScopedDecl. //===----------------------------------------------------------------------===// void ScopedDecl::EmitInRec(Serializer& S) const { NamedDecl::EmitInRec(S); S.EmitPtr(getNext()); // From ScopedDecl. } void ScopedDecl::ReadInRec(Deserializer& D) { NamedDecl::ReadInRec(D); D.ReadPtr(Next); // From ScopedDecl. } //===------------------------------------------------------------===// // NOTE: Not all subclasses of ScopedDecl will use the "OutRec" // // methods. This is because owned pointers are usually "batched" // // together for efficiency. // //===------------------------------------------------------------===// void ScopedDecl::EmitOutRec(Serializer& S) const { S.EmitOwnedPtr(getNextDeclarator()); // From ScopedDecl. } void ScopedDecl::ReadOutRec(Deserializer& D) { NextDeclarator = cast_or_null<ScopedDecl>(D.ReadOwnedPtr<Decl>()); // From ScopedDecl. } //===----------------------------------------------------------------------===// // Common serialization logic for subclasses of ValueDecl. //===----------------------------------------------------------------------===// void ValueDecl::EmitInRec(Serializer& S) const { ScopedDecl::EmitInRec(S); S.Emit(getType()); // From ValueDecl. } void ValueDecl::ReadInRec(Deserializer& D) { ScopedDecl::ReadInRec(D); DeclType = QualType::ReadVal(D); // From ValueDecl. } //===----------------------------------------------------------------------===// // Common serialization logic for subclasses of VarDecl. //===----------------------------------------------------------------------===// void VarDecl::EmitInRec(Serializer& S) const { ValueDecl::EmitInRec(S); S.EmitInt(getStorageClass()); // From VarDecl. S.EmitInt(getObjcDeclQualifier()); // From VarDecl. } void VarDecl::ReadInRec(Deserializer& D) { ValueDecl::ReadInRec(D); SClass = static_cast<StorageClass>(D.ReadInt()); // From VarDecl. objcDeclQualifier = static_cast<ObjcDeclQualifier>(D.ReadInt()); // VarDecl. } //===------------------------------------------------------------===// // NOTE: VarDecl has its own "OutRec" methods that doesn't use // // the one define in ScopedDecl. This is to batch emit the // // owned pointers, which results in a smaller output. //===------------------------------------------------------------===// void VarDecl::EmitOutRec(Serializer& S) const { // Emit these last because they will create records of their own. S.BatchEmitOwnedPtrs(getInit(), // From VarDecl. getNextDeclarator()); // From ScopedDecl. } void VarDecl::ReadOutRec(Deserializer& D) { Decl* next_declarator; D.BatchReadOwnedPtrs(Init, // From VarDecl. next_declarator); // From ScopedDecl. setNextDeclarator(cast_or_null<ScopedDecl>(next_declarator)); } void VarDecl::EmitImpl(Serializer& S) const { VarDecl::EmitInRec(S); VarDecl::EmitOutRec(S); } void VarDecl::ReadImpl(Deserializer& D) { ReadInRec(D); ReadOutRec(D); } //===----------------------------------------------------------------------===// // BlockVarDecl Serialization. //===----------------------------------------------------------------------===// BlockVarDecl* BlockVarDecl::CreateImpl(Deserializer& D) { BlockVarDecl* decl = new BlockVarDecl(SourceLocation(),NULL,QualType(),None,NULL); decl->VarDecl::ReadImpl(D); return decl; } //===----------------------------------------------------------------------===// // FileVarDecl Serialization. //===----------------------------------------------------------------------===// FileVarDecl* FileVarDecl::CreateImpl(Deserializer& D) { FileVarDecl* decl = new FileVarDecl(SourceLocation(),NULL,QualType(),None,NULL); decl->VarDecl::ReadImpl(D); return decl; } //===----------------------------------------------------------------------===// // ParmDecl Serialization. //===----------------------------------------------------------------------===// ParmVarDecl* ParmVarDecl::CreateImpl(Deserializer& D) { ParmVarDecl* decl = new ParmVarDecl(SourceLocation(),NULL,QualType(),None,NULL); decl->VarDecl::ReadImpl(D); return decl; } //===----------------------------------------------------------------------===// // EnumDecl Serialization. //===----------------------------------------------------------------------===// void EnumDecl::EmitImpl(Serializer& S) const { ScopedDecl::EmitInRec(S); S.EmitBool(isDefinition()); S.Emit(IntegerType); S.BatchEmitOwnedPtrs(ElementList,getNextDeclarator()); } EnumDecl* EnumDecl::CreateImpl(Deserializer& D) { EnumDecl* decl = new EnumDecl(SourceLocation(),NULL,NULL); decl->ScopedDecl::ReadInRec(D); decl->setDefinition(D.ReadBool()); decl->IntegerType = QualType::ReadVal(D); Decl* next_declarator; Decl* Elist; D.BatchReadOwnedPtrs(Elist,next_declarator); decl->ElementList = cast_or_null<EnumConstantDecl>(Elist); decl->setNextDeclarator(cast_or_null<ScopedDecl>(next_declarator)); return decl; } //===----------------------------------------------------------------------===// // EnumConstantDecl Serialization. //===----------------------------------------------------------------------===// void EnumConstantDecl::EmitImpl(Serializer& S) const { S.Emit(Val); ValueDecl::EmitInRec(S); S.BatchEmitOwnedPtrs(getNextDeclarator(),Init); } EnumConstantDecl* EnumConstantDecl::CreateImpl(Deserializer& D) { llvm::APSInt val(0); D.Read(val); EnumConstantDecl* decl = new EnumConstantDecl(SourceLocation(),NULL,QualType(),NULL, val,NULL); decl->ValueDecl::ReadInRec(D); Decl* next_declarator; D.BatchReadOwnedPtrs(next_declarator,decl->Init); decl->setNextDeclarator(cast<ScopedDecl>(next_declarator)); return decl; } //===----------------------------------------------------------------------===// // FieldDecl Serialization. //===----------------------------------------------------------------------===// void FieldDecl::EmitImpl(Serializer& S) const { S.Emit(getType()); NamedDecl::EmitInRec(S); S.EmitOwnedPtr(BitWidth); } FieldDecl* FieldDecl::CreateImpl(Deserializer& D) { FieldDecl* decl = new FieldDecl(SourceLocation(),NULL,QualType()); decl->DeclType.ReadBackpatch(D); decl->ReadInRec(D); decl->BitWidth = D.ReadOwnedPtr<Expr>(); return decl; } //===----------------------------------------------------------------------===// // FunctionDecl Serialization. //===----------------------------------------------------------------------===// void FunctionDecl::EmitImpl(Serializer& S) const { S.EmitInt(SClass); // From FunctionDecl. S.EmitBool(IsInline); // From FunctionDecl. ValueDecl::EmitInRec(S); S.EmitPtr(DeclChain); // NOTE: We do not need to serialize out the number of parameters, because // that is encoded in the type (accessed via getNumParams()). if (ParamInfo != NULL) { S.EmitBool(true); S.BatchEmitOwnedPtrs(getNumParams(),&ParamInfo[0], Body, getNextDeclarator()); } else { S.EmitBool(false); S.BatchEmitOwnedPtrs(Body,getNextDeclarator()); } } FunctionDecl* FunctionDecl::CreateImpl(Deserializer& D) { StorageClass SClass = static_cast<StorageClass>(D.ReadInt()); bool IsInline = D.ReadBool(); FunctionDecl* decl = new FunctionDecl(SourceLocation(),NULL,QualType(),SClass,IsInline); decl->ValueDecl::ReadInRec(D); D.ReadPtr(decl->DeclChain); decl->ParamInfo = decl->getNumParams() ? new ParmVarDecl*[decl->getNumParams()] : NULL; Decl* next_declarator; bool hasParamDecls = D.ReadBool(); if (hasParamDecls) D.BatchReadOwnedPtrs(decl->getNumParams(), reinterpret_cast<Decl**>(&decl->ParamInfo[0]), decl->Body, next_declarator); else D.BatchReadOwnedPtrs(decl->Body, next_declarator); decl->setNextDeclarator(cast_or_null<ScopedDecl>(next_declarator)); return decl; } //===----------------------------------------------------------------------===// // RecordDecl Serialization. //===----------------------------------------------------------------------===// void RecordDecl::EmitImpl(Serializer& S) const { ScopedDecl::EmitInRec(S); S.EmitBool(isDefinition()); S.EmitBool(hasFlexibleArrayMember()); S.EmitSInt(getNumMembers()); if (getNumMembers() > 0) { assert (Members); S.BatchEmitOwnedPtrs((unsigned) getNumMembers(), (Decl**) &Members[0],getNextDeclarator()); } else ScopedDecl::EmitOutRec(S); } RecordDecl* RecordDecl::CreateImpl(Decl::Kind DK, Deserializer& D) { RecordDecl* decl = new RecordDecl(DK,SourceLocation(),NULL,NULL); decl->ScopedDecl::ReadInRec(D); decl->setDefinition(D.ReadBool()); decl->setHasFlexibleArrayMember(D.ReadBool()); decl->NumMembers = D.ReadSInt(); if (decl->getNumMembers() > 0) { Decl* next_declarator; decl->Members = new FieldDecl*[(unsigned) decl->getNumMembers()]; D.BatchReadOwnedPtrs((unsigned) decl->getNumMembers(), (Decl**) &decl->Members[0], next_declarator); decl->setNextDeclarator(cast_or_null<ScopedDecl>(next_declarator)); } else decl->ScopedDecl::ReadOutRec(D); return decl; } //===----------------------------------------------------------------------===// // TypedefDecl Serialization. //===----------------------------------------------------------------------===// void TypedefDecl::EmitImpl(Serializer& S) const { S.Emit(UnderlyingType); ScopedDecl::EmitInRec(S); ScopedDecl::EmitOutRec(S); } TypedefDecl* TypedefDecl::CreateImpl(Deserializer& D) { QualType T = QualType::ReadVal(D); TypedefDecl* decl = new TypedefDecl(SourceLocation(),NULL,T,NULL); decl->ScopedDecl::ReadInRec(D); decl->ScopedDecl::ReadOutRec(D); return decl; } <commit_msg>Fixed bug in serialization of EnumConstantDecl where we improperly "default constructed" an APSInt. Fixed another bug in the same method where we did not allow the NextDeclarator to be NULL.<commit_after>//===--- DeclSerialization.cpp - Serialization of Decls ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Ted Kremenek and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This files defines methods that implement bitcode serialization for Decls. // //===----------------------------------------------------------------------===// #include "clang/AST/Decl.h" #include "clang/AST/Expr.h" #include "llvm/Bitcode/Serialize.h" #include "llvm/Bitcode/Deserialize.h" using llvm::Serializer; using llvm::Deserializer; using llvm::SerializedPtrID; using namespace clang; //===----------------------------------------------------------------------===// // Decl Serialization: Dispatch code to handle specialized decl types. //===----------------------------------------------------------------------===// void Decl::Emit(Serializer& S) const { S.EmitInt(getKind()); EmitImpl(S); } Decl* Decl::Create(Deserializer& D) { Kind k = static_cast<Kind>(D.ReadInt()); switch (k) { default: assert (false && "Not implemented."); break; case BlockVar: return BlockVarDecl::CreateImpl(D); case Enum: return EnumDecl::CreateImpl(D); case EnumConstant: return EnumConstantDecl::CreateImpl(D); case Field: return FieldDecl::CreateImpl(D); case FileVar: return FileVarDecl::CreateImpl(D); case ParmVar: return ParmVarDecl::CreateImpl(D); case Function: return FunctionDecl::CreateImpl(D); case Union: case Struct: return RecordDecl::CreateImpl(k,D); case Typedef: return TypedefDecl::CreateImpl(D); } } //===----------------------------------------------------------------------===// // Common serialization logic for subclasses of Decl. //===----------------------------------------------------------------------===// void Decl::EmitInRec(Serializer& S) const { S.Emit(getLocation()); // From Decl. } void Decl::ReadInRec(Deserializer& D) { Loc = SourceLocation::ReadVal(D); // From Decl. } //===----------------------------------------------------------------------===// // Common serialization logic for subclasses of NamedDecl. //===----------------------------------------------------------------------===// void NamedDecl::EmitInRec(Serializer& S) const { Decl::EmitInRec(S); S.EmitPtr(getIdentifier()); // From NamedDecl. } void NamedDecl::ReadInRec(Deserializer& D) { Decl::ReadInRec(D); D.ReadPtr(Identifier); // From NamedDecl. } //===----------------------------------------------------------------------===// // Common serialization logic for subclasses of ScopedDecl. //===----------------------------------------------------------------------===// void ScopedDecl::EmitInRec(Serializer& S) const { NamedDecl::EmitInRec(S); S.EmitPtr(getNext()); // From ScopedDecl. } void ScopedDecl::ReadInRec(Deserializer& D) { NamedDecl::ReadInRec(D); D.ReadPtr(Next); // From ScopedDecl. } //===------------------------------------------------------------===// // NOTE: Not all subclasses of ScopedDecl will use the "OutRec" // // methods. This is because owned pointers are usually "batched" // // together for efficiency. // //===------------------------------------------------------------===// void ScopedDecl::EmitOutRec(Serializer& S) const { S.EmitOwnedPtr(getNextDeclarator()); // From ScopedDecl. } void ScopedDecl::ReadOutRec(Deserializer& D) { NextDeclarator = cast_or_null<ScopedDecl>(D.ReadOwnedPtr<Decl>()); // From ScopedDecl. } //===----------------------------------------------------------------------===// // Common serialization logic for subclasses of ValueDecl. //===----------------------------------------------------------------------===// void ValueDecl::EmitInRec(Serializer& S) const { ScopedDecl::EmitInRec(S); S.Emit(getType()); // From ValueDecl. } void ValueDecl::ReadInRec(Deserializer& D) { ScopedDecl::ReadInRec(D); DeclType = QualType::ReadVal(D); // From ValueDecl. } //===----------------------------------------------------------------------===// // Common serialization logic for subclasses of VarDecl. //===----------------------------------------------------------------------===// void VarDecl::EmitInRec(Serializer& S) const { ValueDecl::EmitInRec(S); S.EmitInt(getStorageClass()); // From VarDecl. S.EmitInt(getObjcDeclQualifier()); // From VarDecl. } void VarDecl::ReadInRec(Deserializer& D) { ValueDecl::ReadInRec(D); SClass = static_cast<StorageClass>(D.ReadInt()); // From VarDecl. objcDeclQualifier = static_cast<ObjcDeclQualifier>(D.ReadInt()); // VarDecl. } //===------------------------------------------------------------===// // NOTE: VarDecl has its own "OutRec" methods that doesn't use // // the one define in ScopedDecl. This is to batch emit the // // owned pointers, which results in a smaller output. //===------------------------------------------------------------===// void VarDecl::EmitOutRec(Serializer& S) const { // Emit these last because they will create records of their own. S.BatchEmitOwnedPtrs(getInit(), // From VarDecl. getNextDeclarator()); // From ScopedDecl. } void VarDecl::ReadOutRec(Deserializer& D) { Decl* next_declarator; D.BatchReadOwnedPtrs(Init, // From VarDecl. next_declarator); // From ScopedDecl. setNextDeclarator(cast_or_null<ScopedDecl>(next_declarator)); } void VarDecl::EmitImpl(Serializer& S) const { VarDecl::EmitInRec(S); VarDecl::EmitOutRec(S); } void VarDecl::ReadImpl(Deserializer& D) { ReadInRec(D); ReadOutRec(D); } //===----------------------------------------------------------------------===// // BlockVarDecl Serialization. //===----------------------------------------------------------------------===// BlockVarDecl* BlockVarDecl::CreateImpl(Deserializer& D) { BlockVarDecl* decl = new BlockVarDecl(SourceLocation(),NULL,QualType(),None,NULL); decl->VarDecl::ReadImpl(D); return decl; } //===----------------------------------------------------------------------===// // FileVarDecl Serialization. //===----------------------------------------------------------------------===// FileVarDecl* FileVarDecl::CreateImpl(Deserializer& D) { FileVarDecl* decl = new FileVarDecl(SourceLocation(),NULL,QualType(),None,NULL); decl->VarDecl::ReadImpl(D); return decl; } //===----------------------------------------------------------------------===// // ParmDecl Serialization. //===----------------------------------------------------------------------===// ParmVarDecl* ParmVarDecl::CreateImpl(Deserializer& D) { ParmVarDecl* decl = new ParmVarDecl(SourceLocation(),NULL,QualType(),None,NULL); decl->VarDecl::ReadImpl(D); return decl; } //===----------------------------------------------------------------------===// // EnumDecl Serialization. //===----------------------------------------------------------------------===// void EnumDecl::EmitImpl(Serializer& S) const { ScopedDecl::EmitInRec(S); S.EmitBool(isDefinition()); S.Emit(IntegerType); S.BatchEmitOwnedPtrs(ElementList,getNextDeclarator()); } EnumDecl* EnumDecl::CreateImpl(Deserializer& D) { EnumDecl* decl = new EnumDecl(SourceLocation(),NULL,NULL); decl->ScopedDecl::ReadInRec(D); decl->setDefinition(D.ReadBool()); decl->IntegerType = QualType::ReadVal(D); Decl* next_declarator; Decl* Elist; D.BatchReadOwnedPtrs(Elist,next_declarator); decl->ElementList = cast_or_null<EnumConstantDecl>(Elist); decl->setNextDeclarator(cast_or_null<ScopedDecl>(next_declarator)); return decl; } //===----------------------------------------------------------------------===// // EnumConstantDecl Serialization. //===----------------------------------------------------------------------===// void EnumConstantDecl::EmitImpl(Serializer& S) const { S.Emit(Val); ValueDecl::EmitInRec(S); S.BatchEmitOwnedPtrs(getNextDeclarator(),Init); } EnumConstantDecl* EnumConstantDecl::CreateImpl(Deserializer& D) { llvm::APSInt val(1); D.Read(val); EnumConstantDecl* decl = new EnumConstantDecl(SourceLocation(),NULL,QualType(),NULL, val,NULL); decl->ValueDecl::ReadInRec(D); Decl* next_declarator; D.BatchReadOwnedPtrs(next_declarator,decl->Init); decl->setNextDeclarator(cast_or_null<ScopedDecl>(next_declarator)); return decl; } //===----------------------------------------------------------------------===// // FieldDecl Serialization. //===----------------------------------------------------------------------===// void FieldDecl::EmitImpl(Serializer& S) const { S.Emit(getType()); NamedDecl::EmitInRec(S); S.EmitOwnedPtr(BitWidth); } FieldDecl* FieldDecl::CreateImpl(Deserializer& D) { FieldDecl* decl = new FieldDecl(SourceLocation(),NULL,QualType()); decl->DeclType.ReadBackpatch(D); decl->ReadInRec(D); decl->BitWidth = D.ReadOwnedPtr<Expr>(); return decl; } //===----------------------------------------------------------------------===// // FunctionDecl Serialization. //===----------------------------------------------------------------------===// void FunctionDecl::EmitImpl(Serializer& S) const { S.EmitInt(SClass); // From FunctionDecl. S.EmitBool(IsInline); // From FunctionDecl. ValueDecl::EmitInRec(S); S.EmitPtr(DeclChain); // NOTE: We do not need to serialize out the number of parameters, because // that is encoded in the type (accessed via getNumParams()). if (ParamInfo != NULL) { S.EmitBool(true); S.BatchEmitOwnedPtrs(getNumParams(),&ParamInfo[0], Body, getNextDeclarator()); } else { S.EmitBool(false); S.BatchEmitOwnedPtrs(Body,getNextDeclarator()); } } FunctionDecl* FunctionDecl::CreateImpl(Deserializer& D) { StorageClass SClass = static_cast<StorageClass>(D.ReadInt()); bool IsInline = D.ReadBool(); FunctionDecl* decl = new FunctionDecl(SourceLocation(),NULL,QualType(),SClass,IsInline); decl->ValueDecl::ReadInRec(D); D.ReadPtr(decl->DeclChain); decl->ParamInfo = decl->getNumParams() ? new ParmVarDecl*[decl->getNumParams()] : NULL; Decl* next_declarator; bool hasParamDecls = D.ReadBool(); if (hasParamDecls) D.BatchReadOwnedPtrs(decl->getNumParams(), reinterpret_cast<Decl**>(&decl->ParamInfo[0]), decl->Body, next_declarator); else D.BatchReadOwnedPtrs(decl->Body, next_declarator); decl->setNextDeclarator(cast_or_null<ScopedDecl>(next_declarator)); return decl; } //===----------------------------------------------------------------------===// // RecordDecl Serialization. //===----------------------------------------------------------------------===// void RecordDecl::EmitImpl(Serializer& S) const { ScopedDecl::EmitInRec(S); S.EmitBool(isDefinition()); S.EmitBool(hasFlexibleArrayMember()); S.EmitSInt(getNumMembers()); if (getNumMembers() > 0) { assert (Members); S.BatchEmitOwnedPtrs((unsigned) getNumMembers(), (Decl**) &Members[0],getNextDeclarator()); } else ScopedDecl::EmitOutRec(S); } RecordDecl* RecordDecl::CreateImpl(Decl::Kind DK, Deserializer& D) { RecordDecl* decl = new RecordDecl(DK,SourceLocation(),NULL,NULL); decl->ScopedDecl::ReadInRec(D); decl->setDefinition(D.ReadBool()); decl->setHasFlexibleArrayMember(D.ReadBool()); decl->NumMembers = D.ReadSInt(); if (decl->getNumMembers() > 0) { Decl* next_declarator; decl->Members = new FieldDecl*[(unsigned) decl->getNumMembers()]; D.BatchReadOwnedPtrs((unsigned) decl->getNumMembers(), (Decl**) &decl->Members[0], next_declarator); decl->setNextDeclarator(cast_or_null<ScopedDecl>(next_declarator)); } else decl->ScopedDecl::ReadOutRec(D); return decl; } //===----------------------------------------------------------------------===// // TypedefDecl Serialization. //===----------------------------------------------------------------------===// void TypedefDecl::EmitImpl(Serializer& S) const { S.Emit(UnderlyingType); ScopedDecl::EmitInRec(S); ScopedDecl::EmitOutRec(S); } TypedefDecl* TypedefDecl::CreateImpl(Deserializer& D) { QualType T = QualType::ReadVal(D); TypedefDecl* decl = new TypedefDecl(SourceLocation(),NULL,T,NULL); decl->ScopedDecl::ReadInRec(D); decl->ScopedDecl::ReadOutRec(D); return decl; } <|endoftext|>
<commit_before>// Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "config.h" #include "SkiaUtils.h" #include "SharedBuffer.h" #include "SkCanvas.h" #include "SkColorPriv.h" #include "SkMatrix.h" #include "SkRegion.h" #include "base/gfx/bitmap_header.h" void WebCorePointToSkiaPoint(const WebCore::FloatPoint& src, SkPoint* dst) { dst->set(WebCoreFloatToSkScalar(src.x()), WebCoreFloatToSkScalar(src.y())); } void WebCoreRectToSkiaRect(const WebCore::IntRect& src, SkRect* dst) { dst->set(SkIntToScalar(src.x()), SkIntToScalar(src.y()), SkIntToScalar(src.x() + src.width()), SkIntToScalar(src.y() + src.height())); } void WebCoreRectToSkiaRect(const WebCore::IntRect& src, SkIRect* dst) { dst->set(src.x(), src.y(), src.x() + src.width(), src.y() + src.height()); } void WebCoreRectToSkiaRect(const WebCore::FloatRect& src, SkRect* dst) { dst->set(WebCoreFloatToSkScalar(src.x()), WebCoreFloatToSkScalar(src.y()), WebCoreFloatToSkScalar(src.x() + src.width()), WebCoreFloatToSkScalar(src.y() + src.height())); } void WebCoreRectToSkiaRect(const WebCore::FloatRect& src, SkIRect* dst) { dst->set(SkScalarRound(WebCoreFloatToSkScalar(src.x())), SkScalarRound(WebCoreFloatToSkScalar(src.y())), SkScalarRound(WebCoreFloatToSkScalar(src.x() + src.width())), SkScalarRound(WebCoreFloatToSkScalar(src.y() + src.height()))); } static const struct CompositOpToPorterDuffMode { uint8_t mCompositOp; uint8_t mPorterDuffMode; } gMapCompositOpsToPorterDuffModes[] = { { WebCore::CompositeClear, SkPorterDuff::kClear_Mode }, { WebCore::CompositeCopy, SkPorterDuff::kSrcOver_Mode }, // TODO { WebCore::CompositeSourceOver, SkPorterDuff::kSrcOver_Mode }, { WebCore::CompositeSourceIn, SkPorterDuff::kSrcIn_Mode }, { WebCore::CompositeSourceOut, SkPorterDuff::kSrcOut_Mode }, { WebCore::CompositeSourceAtop, SkPorterDuff::kSrcATop_Mode }, { WebCore::CompositeDestinationOver, SkPorterDuff::kDstOver_Mode }, { WebCore::CompositeDestinationIn, SkPorterDuff::kDstIn_Mode }, { WebCore::CompositeDestinationOut, SkPorterDuff::kDstOut_Mode }, { WebCore::CompositeDestinationAtop, SkPorterDuff::kDstATop_Mode }, { WebCore::CompositeXOR, SkPorterDuff::kXor_Mode }, { WebCore::CompositePlusDarker, SkPorterDuff::kDarken_Mode }, { WebCore::CompositeHighlight, SkPorterDuff::kSrcOver_Mode }, // TODO { WebCore::CompositePlusLighter, SkPorterDuff::kLighten_Mode } }; SkPorterDuff::Mode WebCoreCompositeToSkiaComposite(WebCore::CompositeOperator op) { const CompositOpToPorterDuffMode* table = gMapCompositOpsToPorterDuffModes; for (unsigned i = 0; i < SK_ARRAY_COUNT(gMapCompositOpsToPorterDuffModes); i++) { if (table[i].mCompositOp == op) { return (SkPorterDuff::Mode)table[i].mPorterDuffMode; } } SkDEBUGF(("GraphicsContext::setCompositeOperation uknown CompositOperator %d\n", op)); return SkPorterDuff::kSrcOver_Mode; // fall-back } static U8CPU InvScaleByte(U8CPU component, uint32_t scale) { SkASSERT(component == (uint8_t)component); return (component * scale + 0x8000) >> 16; } // move this guy into SkColor.h static SkColor SkPMColorToColor(SkPMColor pm) { if (0 == pm) return 0; unsigned a = SkGetPackedA32(pm); uint32_t scale = (255 << 16) / a; return SkColorSetARGB(a, InvScaleByte(SkGetPackedR32(pm), scale), InvScaleByte(SkGetPackedG32(pm), scale), InvScaleByte(SkGetPackedB32(pm), scale)); } WebCore::Color SkPMColorToWebCoreColor(SkPMColor pm) { return SkPMColorToColor(pm); } void IntersectRectAndRegion(const SkRegion& region, const SkRect& src_rect, SkRect* dest_rect) { // The cliperator requires an int rect, so we round out. SkIRect src_rect_rounded; src_rect.roundOut(&src_rect_rounded); // The Cliperator will iterate over a bunch of rects where our transformed // rect and the clipping region (which may be non-square) overlap. SkRegion::Cliperator cliperator(region, src_rect_rounded); if (cliperator.done()) { dest_rect->setEmpty(); return; } // Get the union of all visible rects in the clip that overlap our bitmap. SkIRect cur_visible_rect = cliperator.rect(); cliperator.next(); while (!cliperator.done()) { cur_visible_rect.join(cliperator.rect()); cliperator.next(); } dest_rect->set(cur_visible_rect); } void ClipRectToCanvas(const SkCanvas& canvas, const SkRect& src_rect, SkRect* dest_rect) { // Translate into the canvas' coordinate space. This is where the clipping // region applies. SkRect transformed_src; canvas.getTotalMatrix().mapRect(&transformed_src, src_rect); // Do the intersection. SkRect transformed_dest; IntersectRectAndRegion(canvas.getTotalClip(), transformed_src, &transformed_dest); // Now transform it back into world space. SkMatrix inverse_transform; canvas.getTotalMatrix().invert(&inverse_transform); inverse_transform.mapRect(dest_rect, transformed_dest); } bool SkPathContainsPoint(SkPath* orig_path, WebCore::FloatPoint point, SkPath::FillType ft) { SkRegion rgn, clip; SkPath::FillType orig_ft = orig_path->getFillType(); // save const SkPath* path = orig_path; SkPath scaled_path; int scale = 1; SkRect bounds; orig_path->computeBounds(&bounds, SkPath::kFast_BoundsType); // We can immediately return false if the point is outside the bounding rect if (!bounds.contains(SkFloatToScalar(point.x()), SkFloatToScalar(point.y()))) return false; orig_path->setFillType(ft); // Skia has trouble with coordinates close to the max signed 16-bit values // If we have those, we need to scale. // // TODO: remove this code once Skia is patched to work properly with large // values const SkScalar kMaxCoordinate = SkIntToScalar(1<<15); SkScalar biggest_coord = std::max(std::max(std::max( bounds.fRight, bounds.fBottom), -bounds.fLeft), -bounds.fTop); if (biggest_coord > kMaxCoordinate) { scale = SkScalarCeil(SkScalarDiv(biggest_coord, kMaxCoordinate)); SkMatrix m; m.setScale(SkScalarInvert(SkIntToScalar(scale)), SkScalarInvert(SkIntToScalar(scale))); orig_path->transform(m, &scaled_path); path = &scaled_path; } int x = (int)floorf(point.x() / scale); int y = (int)floorf(point.y() / scale); clip.setRect(x, y, x + 1, y + 1); bool contains = rgn.setPath(*path, clip); orig_path->setFillType(orig_ft); // restore return contains; } PassRefPtr<WebCore::SharedBuffer> SerializeSkBitmap(const SkBitmap& bitmap) { int width = bitmap.width(); int height = bitmap.height(); // Create a BMP v4 header that we can serialize. BITMAPV4HEADER v4Header; gfx::CreateBitmapV4Header(width, height, &v4Header); v4Header.bV4SizeImage = width * sizeof(uint32_t) * height; // Serialize the bitmap. BITMAPFILEHEADER fileHeader; fileHeader.bfType = 0x4d42; // "BM" header fileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + v4Header.bV4Size; fileHeader.bfSize = fileHeader.bfOffBits + v4Header.bV4SizeImage; fileHeader.bfReserved1 = fileHeader.bfReserved2 = 0; // Write BITMAPFILEHEADER RefPtr<WebCore::SharedBuffer> buffer(WebCore::SharedBuffer::create( reinterpret_cast<const char*>(&fileHeader), sizeof(BITMAPFILEHEADER))); // Write BITMAPINFOHEADER buffer->append(reinterpret_cast<const char*>(&v4Header), sizeof(BITMAPV4HEADER)); // Write the image body. SkAutoLockPixels bitmap_lock(bitmap); buffer->append(reinterpret_cast<const char*>(bitmap.getAddr32(0, 0)), v4Header.bV4SizeImage); return buffer; } <commit_msg>Stub out Mac version of SerializeSkBitmap() function.<commit_after>// Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "config.h" #include "SkiaUtils.h" #include "SharedBuffer.h" #include "SkCanvas.h" #include "SkColorPriv.h" #include "SkMatrix.h" #include "SkRegion.h" #include "base/basictypes.h" #if defined(OS_WIN) #include "base/gfx/bitmap_header.h" #endif void WebCorePointToSkiaPoint(const WebCore::FloatPoint& src, SkPoint* dst) { dst->set(WebCoreFloatToSkScalar(src.x()), WebCoreFloatToSkScalar(src.y())); } void WebCoreRectToSkiaRect(const WebCore::IntRect& src, SkRect* dst) { dst->set(SkIntToScalar(src.x()), SkIntToScalar(src.y()), SkIntToScalar(src.x() + src.width()), SkIntToScalar(src.y() + src.height())); } void WebCoreRectToSkiaRect(const WebCore::IntRect& src, SkIRect* dst) { dst->set(src.x(), src.y(), src.x() + src.width(), src.y() + src.height()); } void WebCoreRectToSkiaRect(const WebCore::FloatRect& src, SkRect* dst) { dst->set(WebCoreFloatToSkScalar(src.x()), WebCoreFloatToSkScalar(src.y()), WebCoreFloatToSkScalar(src.x() + src.width()), WebCoreFloatToSkScalar(src.y() + src.height())); } void WebCoreRectToSkiaRect(const WebCore::FloatRect& src, SkIRect* dst) { dst->set(SkScalarRound(WebCoreFloatToSkScalar(src.x())), SkScalarRound(WebCoreFloatToSkScalar(src.y())), SkScalarRound(WebCoreFloatToSkScalar(src.x() + src.width())), SkScalarRound(WebCoreFloatToSkScalar(src.y() + src.height()))); } static const struct CompositOpToPorterDuffMode { uint8_t mCompositOp; uint8_t mPorterDuffMode; } gMapCompositOpsToPorterDuffModes[] = { { WebCore::CompositeClear, SkPorterDuff::kClear_Mode }, { WebCore::CompositeCopy, SkPorterDuff::kSrcOver_Mode }, // TODO { WebCore::CompositeSourceOver, SkPorterDuff::kSrcOver_Mode }, { WebCore::CompositeSourceIn, SkPorterDuff::kSrcIn_Mode }, { WebCore::CompositeSourceOut, SkPorterDuff::kSrcOut_Mode }, { WebCore::CompositeSourceAtop, SkPorterDuff::kSrcATop_Mode }, { WebCore::CompositeDestinationOver, SkPorterDuff::kDstOver_Mode }, { WebCore::CompositeDestinationIn, SkPorterDuff::kDstIn_Mode }, { WebCore::CompositeDestinationOut, SkPorterDuff::kDstOut_Mode }, { WebCore::CompositeDestinationAtop, SkPorterDuff::kDstATop_Mode }, { WebCore::CompositeXOR, SkPorterDuff::kXor_Mode }, { WebCore::CompositePlusDarker, SkPorterDuff::kDarken_Mode }, { WebCore::CompositeHighlight, SkPorterDuff::kSrcOver_Mode }, // TODO { WebCore::CompositePlusLighter, SkPorterDuff::kLighten_Mode } }; SkPorterDuff::Mode WebCoreCompositeToSkiaComposite(WebCore::CompositeOperator op) { const CompositOpToPorterDuffMode* table = gMapCompositOpsToPorterDuffModes; for (unsigned i = 0; i < SK_ARRAY_COUNT(gMapCompositOpsToPorterDuffModes); i++) { if (table[i].mCompositOp == op) { return (SkPorterDuff::Mode)table[i].mPorterDuffMode; } } SkDEBUGF(("GraphicsContext::setCompositeOperation uknown CompositOperator %d\n", op)); return SkPorterDuff::kSrcOver_Mode; // fall-back } static U8CPU InvScaleByte(U8CPU component, uint32_t scale) { SkASSERT(component == (uint8_t)component); return (component * scale + 0x8000) >> 16; } // move this guy into SkColor.h static SkColor SkPMColorToColor(SkPMColor pm) { if (0 == pm) return 0; unsigned a = SkGetPackedA32(pm); uint32_t scale = (255 << 16) / a; return SkColorSetARGB(a, InvScaleByte(SkGetPackedR32(pm), scale), InvScaleByte(SkGetPackedG32(pm), scale), InvScaleByte(SkGetPackedB32(pm), scale)); } WebCore::Color SkPMColorToWebCoreColor(SkPMColor pm) { return SkPMColorToColor(pm); } void IntersectRectAndRegion(const SkRegion& region, const SkRect& src_rect, SkRect* dest_rect) { // The cliperator requires an int rect, so we round out. SkIRect src_rect_rounded; src_rect.roundOut(&src_rect_rounded); // The Cliperator will iterate over a bunch of rects where our transformed // rect and the clipping region (which may be non-square) overlap. SkRegion::Cliperator cliperator(region, src_rect_rounded); if (cliperator.done()) { dest_rect->setEmpty(); return; } // Get the union of all visible rects in the clip that overlap our bitmap. SkIRect cur_visible_rect = cliperator.rect(); cliperator.next(); while (!cliperator.done()) { cur_visible_rect.join(cliperator.rect()); cliperator.next(); } dest_rect->set(cur_visible_rect); } void ClipRectToCanvas(const SkCanvas& canvas, const SkRect& src_rect, SkRect* dest_rect) { // Translate into the canvas' coordinate space. This is where the clipping // region applies. SkRect transformed_src; canvas.getTotalMatrix().mapRect(&transformed_src, src_rect); // Do the intersection. SkRect transformed_dest; IntersectRectAndRegion(canvas.getTotalClip(), transformed_src, &transformed_dest); // Now transform it back into world space. SkMatrix inverse_transform; canvas.getTotalMatrix().invert(&inverse_transform); inverse_transform.mapRect(dest_rect, transformed_dest); } bool SkPathContainsPoint(SkPath* orig_path, WebCore::FloatPoint point, SkPath::FillType ft) { SkRegion rgn, clip; SkPath::FillType orig_ft = orig_path->getFillType(); // save const SkPath* path = orig_path; SkPath scaled_path; int scale = 1; SkRect bounds; orig_path->computeBounds(&bounds, SkPath::kFast_BoundsType); // We can immediately return false if the point is outside the bounding rect if (!bounds.contains(SkFloatToScalar(point.x()), SkFloatToScalar(point.y()))) return false; orig_path->setFillType(ft); // Skia has trouble with coordinates close to the max signed 16-bit values // If we have those, we need to scale. // // TODO: remove this code once Skia is patched to work properly with large // values const SkScalar kMaxCoordinate = SkIntToScalar(1<<15); SkScalar biggest_coord = std::max(std::max(std::max( bounds.fRight, bounds.fBottom), -bounds.fLeft), -bounds.fTop); if (biggest_coord > kMaxCoordinate) { scale = SkScalarCeil(SkScalarDiv(biggest_coord, kMaxCoordinate)); SkMatrix m; m.setScale(SkScalarInvert(SkIntToScalar(scale)), SkScalarInvert(SkIntToScalar(scale))); orig_path->transform(m, &scaled_path); path = &scaled_path; } int x = (int)floorf(point.x() / scale); int y = (int)floorf(point.y() / scale); clip.setRect(x, y, x + 1, y + 1); bool contains = rgn.setPath(*path, clip); orig_path->setFillType(orig_ft); // restore return contains; } #if defined(OS_MACOSX) PassRefPtr<WebCore::SharedBuffer> SerializeSkBitmap(const SkBitmap& bitmap) { // TODO(playmobil): implement. ASSERT_NOT_REACHED(); RefPtr<WebCore::SharedBuffer> buffer(NULL); return buffer; } #elif defined(OS_WIN) PassRefPtr<WebCore::SharedBuffer> SerializeSkBitmap(const SkBitmap& bitmap) { int width = bitmap.width(); int height = bitmap.height(); // Create a BMP v4 header that we can serialize. BITMAPV4HEADER v4Header; gfx::CreateBitmapV4Header(width, height, &v4Header); v4Header.bV4SizeImage = width * sizeof(uint32_t) * height; // Serialize the bitmap. BITMAPFILEHEADER fileHeader; fileHeader.bfType = 0x4d42; // "BM" header fileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + v4Header.bV4Size; fileHeader.bfSize = fileHeader.bfOffBits + v4Header.bV4SizeImage; fileHeader.bfReserved1 = fileHeader.bfReserved2 = 0; // Write BITMAPFILEHEADER RefPtr<WebCore::SharedBuffer> buffer(WebCore::SharedBuffer::create( reinterpret_cast<const char*>(&fileHeader), sizeof(BITMAPFILEHEADER))); // Write BITMAPINFOHEADER buffer->append(reinterpret_cast<const char*>(&v4Header), sizeof(BITMAPV4HEADER)); // Write the image body. SkAutoLockPixels bitmap_lock(bitmap); buffer->append(reinterpret_cast<const char*>(bitmap.getAddr32(0, 0)), v4Header.bV4SizeImage); return buffer; } #endif <|endoftext|>
<commit_before>/** * \file * \brief ThreadControlBlock class header * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2015-02-03 */ #ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #include "distortos/scheduler/RoundRobinQuantum.hpp" #include "distortos/scheduler/ThreadControlBlockList-types.hpp" #include "distortos/scheduler/MutexControlBlockList.hpp" #include "distortos/architecture/Stack.hpp" #include "distortos/SchedulingPolicy.hpp" #include "distortos/estd/TypeErasedFunctor.hpp" #include <functional> namespace distortos { namespace scheduler { class ThreadControlBlockList; /// ThreadControlBlock class is a simple description of a Thread class ThreadControlBlock { public: /// state of the thread enum class State : uint8_t { /// state in which thread is created, before being added to Scheduler New, /// thread is runnable Runnable, /// thread is sleeping Sleeping, /// thread is blocked on Semaphore BlockedOnSemaphore, /// thread is suspended Suspended, /// thread is terminated Terminated, /// thread is blocked on Mutex BlockedOnMutex, /// thread is blocked on ConditionVariable BlockedOnConditionVariable, }; /// reason of thread unblocking enum class UnblockReason : uint8_t { /// explicit request to unblock the thread - normal unblock UnblockRequest, /// timeout - unblock via software timer Timeout, }; /// type of object used as storage for ThreadControlBlockList elements - 3 pointers using Link = std::array<std::aligned_storage<sizeof(void*), alignof(void*)>::type, 3>; /// UnblockFunctor is a functor executed when unblocking the thread, it receives one parameter - a reference to /// ThreadControlBlock that is being unblocked using UnblockFunctor = estd::TypeErasedFunctor<void(ThreadControlBlock&)>; /** * \brief ThreadControlBlock constructor. * * \param [in] buffer is a pointer to stack's buffer * \param [in] size is the size of stack's buffer, bytes * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread */ ThreadControlBlock(void* buffer, size_t size, uint8_t priority, SchedulingPolicy schedulingPolicy); /** * \brief Block hook function of thread * * Saves pointer to UnblockFunctor. * * \attention This function should be called only by Scheduler::blockInternal(). * * \param [in] unblockFunctor is a pointer to UnblockFunctor which will be executed in unblockHook() */ void blockHook(const UnblockFunctor* const unblockFunctor) { unblockFunctor_ = unblockFunctor; } /** * \return effective priority of ThreadControlBlock */ uint8_t getEffectivePriority() const { return std::max(priority_, boostedPriority_); } /** * \return iterator to the element on the list, valid only when list_ != nullptr */ ThreadControlBlockListIterator getIterator() const { return iterator_; } /** * \return reference to internal storage for list link */ Link& getLink() { return link_; } /** * \return const reference to internal storage for list link */ const Link& getLink() const { return link_; } /** * \return pointer to list that has this object */ ThreadControlBlockList* getList() const { return list_; } /** * \return reference to list of mutex control blocks with enabled priority protocol owned by this thread */ MutexControlBlockList& getOwnedProtocolMutexControlBlocksList() { return ownedProtocolMutexControlBlocksList_; } /** * \return const reference to list of mutex control blocks with enabled priority protocol owned by this thread */ const MutexControlBlockList& getOwnedProtocolMutexControlBlocksList() const { return ownedProtocolMutexControlBlocksList_; } /** * \return priority of ThreadControlBlock */ uint8_t getPriority() const { return priority_; } /** * \return reference to internal RoundRobinQuantum object */ RoundRobinQuantum& getRoundRobinQuantum() { return roundRobinQuantum_; } /** * \return const reference to internal RoundRobinQuantum object */ const RoundRobinQuantum& getRoundRobinQuantum() const { return roundRobinQuantum_; } /** * \return scheduling policy of the thread */ SchedulingPolicy getSchedulingPolicy() const { return schedulingPolicy_; } /** * \return reference to internal Stack object */ architecture::Stack& getStack() { return stack_; } /** * \return const reference to internal Stack object */ const architecture::Stack& getStack() const { return stack_; } /** * \return current state of object */ State getState() const { return state_; } /** * \return reason of previous unblocking of the thread */ UnblockReason getUnblockReason() const { return unblockReason_; } /** * \brief Sets the iterator to the element on the list. * * \param [in] iterator is an iterator to the element on the list */ void setIterator(const ThreadControlBlockListIterator iterator) { iterator_ = iterator; } /** * \brief Sets the list that has this object. * * \param [in] list is a pointer to list that has this object */ void setList(ThreadControlBlockList* const list) { list_ = list; } /** * \brief Changes priority of thread. * * If the priority really changes, the position in the thread list is adjusted and context switch may be requested. * * \param [in] priority is the new priority of thread * \param [in] alwaysBehind selects the method of ordering when lowering the priority * - false - the thread is moved to the head of the group of threads with the new priority (default), * - true - the thread is moved to the tail of the group of threads with the new priority. */ void setPriority(uint8_t priority, bool alwaysBehind = {}); /** * \param [in] priorityInheritanceMutexControlBlock is a pointer to MutexControlBlock (with PriorityInheritance * protocol) that blocks this thread */ void setPriorityInheritanceMutexControlBlock(const synchronization::MutexControlBlock* const priorityInheritanceMutexControlBlock) { priorityInheritanceMutexControlBlock_ = priorityInheritanceMutexControlBlock; } /** * param [in] schedulingPolicy is the new scheduling policy of the thread */ void setSchedulingPolicy(SchedulingPolicy schedulingPolicy); /** * \param [in] state is the new state of object */ void setState(const State state) { state_ = state; } /** * \brief Termination hook function of thread * * \attention This function should be called only by Scheduler::remove(). */ void terminationHook() { terminationHook_(); } /** * \brief Unblock hook function of thread * * Resets round-robin's quantum, sets unblock reason and executes unblock functor saved in blockHook(). * * \attention This function should be called only by Scheduler::unblockInternal(). * * \param [in] unblockReason is the new reason of unblocking of the thread */ void unblockHook(UnblockReason unblockReason); /** * \brief Updates boosted priority of the thread. * * This function should be called after all operations involving this thread and a mutex with enabled priority * protocol. * * \param [in] boostedPriority is the initial boosted priority, this should be effective priority of the thread that * is about to be blocked on a mutex owned by this thread, default - 0 */ void updateBoostedPriority(uint8_t boostedPriority = {}); protected: /** * \brief ThreadControlBlock constructor. * * This constructor is meant for MainThreadControlBlock. * * \param [in] stack is an rvalue reference to stack of main() * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread */ ThreadControlBlock(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy); /** * \brief ThreadControlBlock's destructor * * \note Polymorphic objects of ThreadControlBlock type must not be deleted via pointer/reference */ ~ThreadControlBlock(); private: /** * \brief Thread runner function - entry point of threads. * * After return from actual thread function, thread is terminated, so this function never returns. * * \param [in] threadControlBlock is a reference to ThreadControlBlock object that is being run */ static void threadRunner(ThreadControlBlock& threadControlBlock) __attribute__ ((noreturn)); /** * \brief Repositions the thread on the list it's currently on. * * This function should be called when thread's effective priority changes. * * \attention list_ must not be nullptr * * \param [in] loweringBefore selects the method of ordering when lowering the priority (it must be false when the * priority is raised!): * - true - the thread is moved to the head of the group of threads with the new priority, this is accomplished by * temporarily boosting effective priority by 1, * - false - the thread is moved to the tail of the group of threads with the new priority. */ void reposition(bool loweringBefore); /** * \brief "Run" function of thread * * This should be overridden by derived classes. */ virtual void run() = 0; /** * \brief Termination hook function of thread * * This function is called after run() completes. * * This should be overridden by derived classes. */ virtual void terminationHook_() = 0; /// internal stack object architecture::Stack stack_; /// storage for list link Link link_; /// list of mutex control blocks with enabled priority protocol owned by this thread MutexControlBlockList ownedProtocolMutexControlBlocksList_; /// pointer to MutexControlBlock (with PriorityInheritance protocol) that blocks this thread const synchronization::MutexControlBlock* priorityInheritanceMutexControlBlock_; /// pointer to list that has this object ThreadControlBlockList* list_; /// iterator to the element on the list, valid only when list_ != nullptr ThreadControlBlockListIterator iterator_; /// information related to unblocking union { /// functor executed in unblockHook() - valid only when thread is blocked const UnblockFunctor* unblockFunctor_; /// reason of previous unblocking of the thread - valid only when thread is not blocked UnblockReason unblockReason_; }; /// newlib's _reent structure with thread-specific data _reent reent_; /// thread's priority, 0 - lowest, UINT8_MAX - highest uint8_t priority_; /// thread's boosted priority, 0 - no boosting uint8_t boostedPriority_; /// round-robin quantum RoundRobinQuantum roundRobinQuantum_; /// scheduling policy of the thread SchedulingPolicy schedulingPolicy_; /// current state of object State state_; }; } // namespace scheduler } // namespace distortos #endif // INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ <commit_msg>ThreadControlBlock: add ThreadControlBlock::switchedToHook()<commit_after>/** * \file * \brief ThreadControlBlock class header * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2015-02-03 */ #ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #include "distortos/scheduler/RoundRobinQuantum.hpp" #include "distortos/scheduler/ThreadControlBlockList-types.hpp" #include "distortos/scheduler/MutexControlBlockList.hpp" #include "distortos/architecture/Stack.hpp" #include "distortos/SchedulingPolicy.hpp" #include "distortos/estd/TypeErasedFunctor.hpp" #include <functional> namespace distortos { namespace scheduler { class ThreadControlBlockList; /// ThreadControlBlock class is a simple description of a Thread class ThreadControlBlock { public: /// state of the thread enum class State : uint8_t { /// state in which thread is created, before being added to Scheduler New, /// thread is runnable Runnable, /// thread is sleeping Sleeping, /// thread is blocked on Semaphore BlockedOnSemaphore, /// thread is suspended Suspended, /// thread is terminated Terminated, /// thread is blocked on Mutex BlockedOnMutex, /// thread is blocked on ConditionVariable BlockedOnConditionVariable, }; /// reason of thread unblocking enum class UnblockReason : uint8_t { /// explicit request to unblock the thread - normal unblock UnblockRequest, /// timeout - unblock via software timer Timeout, }; /// type of object used as storage for ThreadControlBlockList elements - 3 pointers using Link = std::array<std::aligned_storage<sizeof(void*), alignof(void*)>::type, 3>; /// UnblockFunctor is a functor executed when unblocking the thread, it receives one parameter - a reference to /// ThreadControlBlock that is being unblocked using UnblockFunctor = estd::TypeErasedFunctor<void(ThreadControlBlock&)>; /** * \brief ThreadControlBlock constructor. * * \param [in] buffer is a pointer to stack's buffer * \param [in] size is the size of stack's buffer, bytes * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread */ ThreadControlBlock(void* buffer, size_t size, uint8_t priority, SchedulingPolicy schedulingPolicy); /** * \brief Block hook function of thread * * Saves pointer to UnblockFunctor. * * \attention This function should be called only by Scheduler::blockInternal(). * * \param [in] unblockFunctor is a pointer to UnblockFunctor which will be executed in unblockHook() */ void blockHook(const UnblockFunctor* const unblockFunctor) { unblockFunctor_ = unblockFunctor; } /** * \return effective priority of ThreadControlBlock */ uint8_t getEffectivePriority() const { return std::max(priority_, boostedPriority_); } /** * \return iterator to the element on the list, valid only when list_ != nullptr */ ThreadControlBlockListIterator getIterator() const { return iterator_; } /** * \return reference to internal storage for list link */ Link& getLink() { return link_; } /** * \return const reference to internal storage for list link */ const Link& getLink() const { return link_; } /** * \return pointer to list that has this object */ ThreadControlBlockList* getList() const { return list_; } /** * \return reference to list of mutex control blocks with enabled priority protocol owned by this thread */ MutexControlBlockList& getOwnedProtocolMutexControlBlocksList() { return ownedProtocolMutexControlBlocksList_; } /** * \return const reference to list of mutex control blocks with enabled priority protocol owned by this thread */ const MutexControlBlockList& getOwnedProtocolMutexControlBlocksList() const { return ownedProtocolMutexControlBlocksList_; } /** * \return priority of ThreadControlBlock */ uint8_t getPriority() const { return priority_; } /** * \return reference to internal RoundRobinQuantum object */ RoundRobinQuantum& getRoundRobinQuantum() { return roundRobinQuantum_; } /** * \return const reference to internal RoundRobinQuantum object */ const RoundRobinQuantum& getRoundRobinQuantum() const { return roundRobinQuantum_; } /** * \return scheduling policy of the thread */ SchedulingPolicy getSchedulingPolicy() const { return schedulingPolicy_; } /** * \return reference to internal Stack object */ architecture::Stack& getStack() { return stack_; } /** * \return const reference to internal Stack object */ const architecture::Stack& getStack() const { return stack_; } /** * \return current state of object */ State getState() const { return state_; } /** * \return reason of previous unblocking of the thread */ UnblockReason getUnblockReason() const { return unblockReason_; } /** * \brief Sets the iterator to the element on the list. * * \param [in] iterator is an iterator to the element on the list */ void setIterator(const ThreadControlBlockListIterator iterator) { iterator_ = iterator; } /** * \brief Sets the list that has this object. * * \param [in] list is a pointer to list that has this object */ void setList(ThreadControlBlockList* const list) { list_ = list; } /** * \brief Changes priority of thread. * * If the priority really changes, the position in the thread list is adjusted and context switch may be requested. * * \param [in] priority is the new priority of thread * \param [in] alwaysBehind selects the method of ordering when lowering the priority * - false - the thread is moved to the head of the group of threads with the new priority (default), * - true - the thread is moved to the tail of the group of threads with the new priority. */ void setPriority(uint8_t priority, bool alwaysBehind = {}); /** * \param [in] priorityInheritanceMutexControlBlock is a pointer to MutexControlBlock (with PriorityInheritance * protocol) that blocks this thread */ void setPriorityInheritanceMutexControlBlock(const synchronization::MutexControlBlock* const priorityInheritanceMutexControlBlock) { priorityInheritanceMutexControlBlock_ = priorityInheritanceMutexControlBlock; } /** * param [in] schedulingPolicy is the new scheduling policy of the thread */ void setSchedulingPolicy(SchedulingPolicy schedulingPolicy); /** * \param [in] state is the new state of object */ void setState(const State state) { state_ = state; } /** * \brief Hook function called when context is switched to this thread. * * Sets global _impure_ptr (from newlib) to thread's \a reent_ member variable. * * \attention This function should be called only by Scheduler::switchContext(). */ void switchedToHook() { _impure_ptr = &reent_; } /** * \brief Termination hook function of thread * * \attention This function should be called only by Scheduler::remove(). */ void terminationHook() { terminationHook_(); } /** * \brief Unblock hook function of thread * * Resets round-robin's quantum, sets unblock reason and executes unblock functor saved in blockHook(). * * \attention This function should be called only by Scheduler::unblockInternal(). * * \param [in] unblockReason is the new reason of unblocking of the thread */ void unblockHook(UnblockReason unblockReason); /** * \brief Updates boosted priority of the thread. * * This function should be called after all operations involving this thread and a mutex with enabled priority * protocol. * * \param [in] boostedPriority is the initial boosted priority, this should be effective priority of the thread that * is about to be blocked on a mutex owned by this thread, default - 0 */ void updateBoostedPriority(uint8_t boostedPriority = {}); protected: /** * \brief ThreadControlBlock constructor. * * This constructor is meant for MainThreadControlBlock. * * \param [in] stack is an rvalue reference to stack of main() * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread */ ThreadControlBlock(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy); /** * \brief ThreadControlBlock's destructor * * \note Polymorphic objects of ThreadControlBlock type must not be deleted via pointer/reference */ ~ThreadControlBlock(); private: /** * \brief Thread runner function - entry point of threads. * * After return from actual thread function, thread is terminated, so this function never returns. * * \param [in] threadControlBlock is a reference to ThreadControlBlock object that is being run */ static void threadRunner(ThreadControlBlock& threadControlBlock) __attribute__ ((noreturn)); /** * \brief Repositions the thread on the list it's currently on. * * This function should be called when thread's effective priority changes. * * \attention list_ must not be nullptr * * \param [in] loweringBefore selects the method of ordering when lowering the priority (it must be false when the * priority is raised!): * - true - the thread is moved to the head of the group of threads with the new priority, this is accomplished by * temporarily boosting effective priority by 1, * - false - the thread is moved to the tail of the group of threads with the new priority. */ void reposition(bool loweringBefore); /** * \brief "Run" function of thread * * This should be overridden by derived classes. */ virtual void run() = 0; /** * \brief Termination hook function of thread * * This function is called after run() completes. * * This should be overridden by derived classes. */ virtual void terminationHook_() = 0; /// internal stack object architecture::Stack stack_; /// storage for list link Link link_; /// list of mutex control blocks with enabled priority protocol owned by this thread MutexControlBlockList ownedProtocolMutexControlBlocksList_; /// pointer to MutexControlBlock (with PriorityInheritance protocol) that blocks this thread const synchronization::MutexControlBlock* priorityInheritanceMutexControlBlock_; /// pointer to list that has this object ThreadControlBlockList* list_; /// iterator to the element on the list, valid only when list_ != nullptr ThreadControlBlockListIterator iterator_; /// information related to unblocking union { /// functor executed in unblockHook() - valid only when thread is blocked const UnblockFunctor* unblockFunctor_; /// reason of previous unblocking of the thread - valid only when thread is not blocked UnblockReason unblockReason_; }; /// newlib's _reent structure with thread-specific data _reent reent_; /// thread's priority, 0 - lowest, UINT8_MAX - highest uint8_t priority_; /// thread's boosted priority, 0 - no boosting uint8_t boostedPriority_; /// round-robin quantum RoundRobinQuantum roundRobinQuantum_; /// scheduling policy of the thread SchedulingPolicy schedulingPolicy_; /// current state of object State state_; }; } // namespace scheduler } // namespace distortos #endif // INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ <|endoftext|>
<commit_before>/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/base/checks.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_receiver.h" #include "webrtc/system_wrappers/include/clock.h" namespace webrtc { void FuzzOneInput(const uint8_t* data, size_t size) { RTCPUtility::RTCPParserV2 rtcp_parser(data, size, true); if (!rtcp_parser.IsValid()) return; webrtc::SimulatedClock clock(1234); RTCPReceiver receiver(&clock, false, nullptr, nullptr, nullptr, nullptr, nullptr); RTCPHelp::RTCPPacketInformation rtcp_packet_information; receiver.IncomingRTCPPacket(rtcp_packet_information, &rtcp_parser); } } // namespace webrtc <commit_msg>Update rtcp receiver fuzzer to use generic function IncomingPacket(const uint8_t* packet, size_t size) instead of implementation specific IncomingRTCPPacket(PacketInfo* out, Parser* in) This would allow switch parse implementation<commit_after>/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/base/checks.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_receiver.h" #include "webrtc/system_wrappers/include/clock.h" namespace webrtc { namespace { class NullModuleRtpRtcp : public RTCPReceiver::ModuleRtpRtcp { public: void SetTmmbn(std::vector<rtcp::TmmbItem>) override {} void OnRequestSendReport() override {} void OnReceivedNack(const std::vector<uint16_t>&) override {}; void OnReceivedRtcpReportBlocks(const ReportBlockList&) override {}; }; } void FuzzOneInput(const uint8_t* data, size_t size) { NullModuleRtpRtcp rtp_rtcp_module; SimulatedClock clock(1234); RTCPReceiver receiver(&clock, false, nullptr, nullptr, nullptr, nullptr, &rtp_rtcp_module); receiver.IncomingPacket(data, size); } } // namespace webrtc <|endoftext|>
<commit_before>#include "EjectOSD.h" #include <Dbt.h> #include "..\HotkeyInfo.h" #include "..\Monitor.h" #include "..\Skin.h" #include "..\SkinManager.h" EjectOSD::EjectOSD() : OSD(L"3RVX-EjectDispatcher"), _mWnd(L"3RVX-EjectOSD", L"3RVX-EjectOSD") { Skin *skin = SkinManager::Instance()->CurrentSkin(); if (skin->HasOSD("eject") == false) { return; } /* TODO: NULL check*/ _mWnd.BackgroundImage(skin->ejectBackground); if (skin->ejectMask != NULL) { _mWnd.GlassMask(skin->ejectMask); } _mWnd.Update(); _mWnd.VisibleDuration(Settings::Instance()->HideDelay()); UpdateWindowPositions(ActiveMonitors()); } EjectOSD::~EjectOSD() { } void EjectOSD::EjectDrive(std::wstring driveLetter) { std::wstring name = L"\\\\.\\" + driveLetter + L":"; CLOG(L"Ejecting %s", name.c_str()); HANDLE dev = CreateFile(name.c_str(), GENERIC_READ, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL); if (dev == INVALID_HANDLE_VALUE) { CLOG(L"Failed to get device handle"); return; } DWORD bytesReturned = 0; bool success = DeviceIoControl(dev, FSCTL_LOCK_VOLUME, NULL, NULL, NULL, NULL, &bytesReturned, NULL) && DeviceIoControl(dev, FSCTL_DISMOUNT_VOLUME, NULL, NULL, NULL, NULL, &bytesReturned, NULL) && DeviceIoControl(dev, IOCTL_STORAGE_EJECT_MEDIA, NULL, NULL, NULL, NULL, &bytesReturned, NULL); if (success) { HideOthers(Eject); _mWnd.Show(); } CloseHandle(dev); } void EjectOSD::Hide() { _mWnd.Hide(false); } void EjectOSD::ProcessHotkeys(HotkeyInfo &hki) { switch (hki.action) { case HotkeyInfo::EjectDrive: if (hki.args.size() > 0) { EjectDrive(hki.args[0]); } break; } } void EjectOSD::UpdateWindowPositions(std::vector<Monitor> monitors) { PositionWindow(monitors[0], _mWnd); } LRESULT EjectOSD::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_DEVICECHANGE && wParam == DBT_DEVICEREMOVECOMPLETE) { CLOG(L"Device removal notification received"); PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR) lParam; if (lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME) { PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME) lpdb; if (lpdbv->dbcv_flags & DBTF_MEDIA) { CLOG(L"Media volume has been removed: eject notification"); HideOthers(Eject); _mWnd.Show(); } } } return DefWindowProc(hWnd, message, wParam, lParam); }<commit_msg>Fix eject detection bug<commit_after>#include "EjectOSD.h" #include <Dbt.h> #include "..\HotkeyInfo.h" #include "..\Monitor.h" #include "..\Skin.h" #include "..\SkinManager.h" EjectOSD::EjectOSD() : OSD(L"3RVX-EjectDispatcher"), _mWnd(L"3RVX-EjectOSD", L"3RVX-EjectOSD") { Skin *skin = SkinManager::Instance()->CurrentSkin(); if (skin->HasOSD("eject") == false) { return; } /* TODO: NULL check*/ _mWnd.BackgroundImage(skin->ejectBackground); if (skin->ejectMask != NULL) { _mWnd.GlassMask(skin->ejectMask); } _mWnd.Update(); _mWnd.VisibleDuration(Settings::Instance()->HideDelay()); UpdateWindowPositions(ActiveMonitors()); } EjectOSD::~EjectOSD() { } void EjectOSD::EjectDrive(std::wstring driveLetter) { std::wstring name = L"\\\\.\\" + driveLetter + L":"; CLOG(L"Ejecting %s", name.c_str()); HANDLE dev = CreateFile(name.c_str(), GENERIC_READ, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL); if (dev == INVALID_HANDLE_VALUE) { CLOG(L"Failed to get device handle"); return; } DWORD bytesReturned = 0; bool success = DeviceIoControl(dev, FSCTL_LOCK_VOLUME, NULL, NULL, NULL, NULL, &bytesReturned, NULL) && DeviceIoControl(dev, FSCTL_DISMOUNT_VOLUME, NULL, NULL, NULL, NULL, &bytesReturned, NULL) && DeviceIoControl(dev, IOCTL_STORAGE_EJECT_MEDIA, NULL, NULL, NULL, NULL, &bytesReturned, NULL); if (success) { HideOthers(Eject); _mWnd.Show(); } CloseHandle(dev); } void EjectOSD::Hide() { _mWnd.Hide(false); } void EjectOSD::ProcessHotkeys(HotkeyInfo &hki) { switch (hki.action) { case HotkeyInfo::EjectDrive: if (hki.args.size() > 0) { EjectDrive(hki.args[0]); } break; } } void EjectOSD::UpdateWindowPositions(std::vector<Monitor> monitors) { PositionWindow(monitors[0], _mWnd); } LRESULT EjectOSD::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_DEVICECHANGE && wParam == DBT_DEVICEREMOVECOMPLETE) { PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR) lParam; if (lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME) { PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME) lpdb; wchar_t driveLetter = (wchar_t) (log2(lpdbv->dbcv_unitmask) + 65); CLOG(L"Eject notification received for drive %c:", driveLetter); HideOthers(Eject); _mWnd.Show(); } } return DefWindowProc(hWnd, message, wParam, lParam); }<|endoftext|>
<commit_before>#include <stdexcept> #include "InputFeature.h" #include "moses/Util.h" #include "moses/ScoreComponentCollection.h" #include "moses/InputPath.h" #include "moses/StaticData.h" #include "moses/TranslationModel/PhraseDictionaryTreeAdaptor.h" using namespace std; namespace Moses { InputFeature *InputFeature::s_instance = NULL; InputFeature::InputFeature(const std::string &line) :StatelessFeatureFunction(line) { ReadParameters(); UTIL_THROW_IF2(s_instance, "Can only have 1 input feature"); s_instance = this; } void InputFeature::Load() { const PhraseDictionary *pt = PhraseDictionary::GetColl()[0]; const PhraseDictionaryTreeAdaptor *ptBin = dynamic_cast<const PhraseDictionaryTreeAdaptor*>(pt); m_legacy = (ptBin != NULL); } void InputFeature::SetParameter(const std::string& key, const std::string& value) { if (key == "num-input-features") { m_numInputScores = Scan<size_t>(value); } else if (key == "real-word-count") { m_numRealWordCount = Scan<size_t>(value); } else { StatelessFeatureFunction::SetParameter(key, value); } } void InputFeature::Evaluate(const InputType &input , const InputPath &inputPath , const TargetPhrase &targetPhrase , ScoreComponentCollection &scoreBreakdown , ScoreComponentCollection *estimatedFutureScore) const { if (m_legacy) { //binary phrase-table does input feature itself return; } /* const ScorePair *scores = inputPath.GetInputScore(); if (scores) { scoreBreakdown.PlusEquals(this, *scores); } */ } } // namespace <commit_msg>Proper initialization of class members of InputFeature.<commit_after>#include <stdexcept> #include "InputFeature.h" #include "moses/Util.h" #include "moses/ScoreComponentCollection.h" #include "moses/InputPath.h" #include "moses/StaticData.h" #include "moses/TranslationModel/PhraseDictionaryTreeAdaptor.h" using namespace std; namespace Moses { InputFeature *InputFeature::s_instance = NULL; InputFeature::InputFeature(const std::string &line) : StatelessFeatureFunction(line) , m_numInputScores(0) , m_numRealWordCount(0) { ReadParameters(); UTIL_THROW_IF2(s_instance, "Can only have 1 input feature"); s_instance = this; } void InputFeature::Load() { const PhraseDictionary *pt = PhraseDictionary::GetColl()[0]; const PhraseDictionaryTreeAdaptor *ptBin = dynamic_cast<const PhraseDictionaryTreeAdaptor*>(pt); m_legacy = (ptBin != NULL); } void InputFeature::SetParameter(const std::string& key, const std::string& value) { if (key == "num-input-features") { m_numInputScores = Scan<size_t>(value); } else if (key == "real-word-count") { m_numRealWordCount = Scan<size_t>(value); } else { StatelessFeatureFunction::SetParameter(key, value); } } void InputFeature::Evaluate(const InputType &input , const InputPath &inputPath , const TargetPhrase &targetPhrase , ScoreComponentCollection &scoreBreakdown , ScoreComponentCollection *estimatedFutureScore) const { if (m_legacy) { //binary phrase-table does input feature itself return; } /* const ScorePair *scores = inputPath.GetInputScore(); if (scores) { scoreBreakdown.PlusEquals(this, *scores); } */ } } // namespace <|endoftext|>
<commit_before>// Copyright since 2016 : Evgenii Shatunov (github.com/FrankStain/jnipp-test) // Apache 2.0 License #include <main.h> #include <gtest/gtest.h> #define DECLARE_TEST_ENV( TYPE, NAME ) \ Jni::ClassHandle class_handle{ "com/pfs/jnipptest/TestStaticFieldStorage" }; \ \ Jni::StaticFieldHandle<TYPE> field{ class_handle, NAME "_field" }; \ \ EXPECT_TRUE( field ); TEST( TestStaticFieldHandle, GetBool ) { DECLARE_TEST_ENV( bool, "bool" ); bool field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_TRUE( field_value ); }; TEST( TestStaticFieldHandle, GetString ) { DECLARE_TEST_ENV( std::string, "string" ); std::string field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_STREQ( "Jni++", field_value.c_str() ); }; TEST( TestStaticFieldHandle, GetFloat ) { DECLARE_TEST_ENV( float, "float" ); float field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 13.0f, field_value ); }; TEST( TestStaticFieldHandle, GetDouble ) { DECLARE_TEST_ENV( double, "double" ); double field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 42.0, field_value ); }; TEST( TestStaticFieldHandle, GetByte ) { DECLARE_TEST_ENV( int8_t, "byte" ); int8_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 28, field_value ); }; TEST( TestStaticFieldHandle, GetUnsignedByte ) { DECLARE_TEST_ENV( uint8_t, "short" ); uint8_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 24, field_value ); }; TEST( TestStaticFieldHandle, GetChar16 ) { DECLARE_TEST_ENV( char16_t, "char" ); char16_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( u'S', field_value ); }; TEST( TestStaticFieldHandle, GetShort ) { DECLARE_TEST_ENV( int16_t, "short" ); int16_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 24, field_value ); }; TEST( TestStaticFieldHandle, GetUnsignedShort ) { DECLARE_TEST_ENV( uint16_t, "int" ); uint16_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 0, field_value ); }; TEST( TestStaticFieldHandle, GetInt ) { DECLARE_TEST_ENV( int32_t, "int" ); int32_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 65536, field_value ); }; TEST( TestStaticFieldHandle, GetUnsignedInt ) { DECLARE_TEST_ENV( uint32_t, "long" ); uint32_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 0, field_value ); }; TEST( TestStaticFieldHandle, GetLong ) { DECLARE_TEST_ENV( int64_t, "long" ); int64_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( ( 1LL << 48 ), field_value ); }; TEST( TestStaticFieldHandle, GetUnsignedLong ) { DECLARE_TEST_ENV( uint64_t, "long" ); uint64_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( ( 1LL << 48 ), field_value ); }; <commit_msg>Small fix.<commit_after>// Copyright since 2016 : Evgenii Shatunov (github.com/FrankStain/jnipp-test) // Apache 2.0 License #include <main.h> #include <gtest/gtest.h> #define DECLARE_TEST_ENV( TYPE, NAME ) \ Jni::ClassHandle class_handle{ "com/pfs/jnipptest/TestStaticFieldStorage" }; \ \ Jni::StaticFieldHandle<TYPE> field{ class_handle, NAME "_field" }; \ \ EXPECT_TRUE( field ) TEST( TestStaticFieldHandle, GetBool ) { DECLARE_TEST_ENV( bool, "bool" ); bool field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_TRUE( field_value ); }; TEST( TestStaticFieldHandle, GetString ) { DECLARE_TEST_ENV( std::string, "string" ); std::string field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_STREQ( "Jni++", field_value.c_str() ); }; TEST( TestStaticFieldHandle, GetFloat ) { DECLARE_TEST_ENV( float, "float" ); float field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 13.0f, field_value ); }; TEST( TestStaticFieldHandle, GetDouble ) { DECLARE_TEST_ENV( double, "double" ); double field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 42.0, field_value ); }; TEST( TestStaticFieldHandle, GetByte ) { DECLARE_TEST_ENV( int8_t, "byte" ); int8_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 28, field_value ); }; TEST( TestStaticFieldHandle, GetUnsignedByte ) { DECLARE_TEST_ENV( uint8_t, "short" ); uint8_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 24, field_value ); }; TEST( TestStaticFieldHandle, GetChar16 ) { DECLARE_TEST_ENV( char16_t, "char" ); char16_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( u'S', field_value ); }; TEST( TestStaticFieldHandle, GetShort ) { DECLARE_TEST_ENV( int16_t, "short" ); int16_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 24, field_value ); }; TEST( TestStaticFieldHandle, GetUnsignedShort ) { DECLARE_TEST_ENV( uint16_t, "int" ); uint16_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 0, field_value ); }; TEST( TestStaticFieldHandle, GetInt ) { DECLARE_TEST_ENV( int32_t, "int" ); int32_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 65536, field_value ); }; TEST( TestStaticFieldHandle, GetUnsignedInt ) { DECLARE_TEST_ENV( uint32_t, "long" ); uint32_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( 0, field_value ); }; TEST( TestStaticFieldHandle, GetLong ) { DECLARE_TEST_ENV( int64_t, "long" ); int64_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( ( 1LL << 48 ), field_value ); }; TEST( TestStaticFieldHandle, GetUnsignedLong ) { DECLARE_TEST_ENV( uint64_t, "long" ); uint64_t field_value; EXPECT_TRUE( field.GetValue( field_value ) ); EXPECT_EQ( ( 1LL << 48 ), field_value ); }; <|endoftext|>
<commit_before>#include "ballDetector.h" using namespace std; using namespace cv; BallDetector::BallDetector(Camera* cam) { _state=BD_RUNNING; initKalmanFilter(); //Calibrage caméra Mat distCoeffs=(Mat_<double>(5,1) << -4.4806416419013684e-01,4.1928815312056306e-01,0,0,-4.8777148182526148e-01); Mat cameraMatrix=(Mat_<double>(3,3) << 6.4106316770762089e+02,0,3.195e+02,0,6.4106316770762089e+02,2.395e+02,0,0,1); Size imageSize=Size(640,480); initUndistortRectifyMap(cameraMatrix,distCoeffs,Mat(),getOptimalNewCameraMatrix(cameraMatrix,distCoeffs,imageSize,1,imageSize,0),imageSize,CV_16SC2,_calibMap1,_calibMap2); //--- _cam=cam; _timer=new Timer(); _hsvThresholder=new HSV_Thresholder(*_timer, true); _gaussianFilter=new GaussianFilter(*_timer, true); _dilateEroder=new DilateEroder(*_timer, true); _ellipseFitter=new EllipseFitter(*_timer); _momentsDetector=new MomentsCalculator(*_timer); _timables["Hsv"]=_hsvThresholder; _timables["Blur"]=_gaussianFilter; _timables["DilEr"]=_dilateEroder; _timables["Ellipse"]=_ellipseFitter; _timables["Moments"]=_momentsDetector; Mat vachier=Mat::zeros(Camera::width,Camera::height,CV_8UC3); _hsvThresholder->autoSet(vachier); } BallDetector::~BallDetector() { delete _momentsDetector; delete _ellipseFitter; delete _dilateEroder; delete _gaussianFilter; delete _hsvThresholder; delete _timer; } bool BallDetector::loop(Position& detection) { _timer->reset(); Mat input(Camera::width,Camera::height,CV_8UC3); Mat output(Camera::width,Camera::height,CV_8UC3); bool newFrame=_cam->read(input); Mat resized(WORK_W,WORK_H,CV_8UC3); resize(input,resized,Size(WORK_W,WORK_H)); remap(resized,resized,_calibMap1,_calibMap2,INTER_LINEAR); if(_state==BD_PLACE_BALL) { circle(resized,Point(WORK_W/2,WORK_H/2),HSV_AUTOSET_RADIUS,Scalar(0,0,255),4); Mat flipped(WORK_W,WORK_H,CV_8UC3); flip(resized,flipped,1); imshow("Input",flipped); imshow("Output",flipped); } else { Mat out; resized.copyTo(out); _gaussianFilter->apply(resized); _hsvThresholder->apply(resized, output); _dilateEroder->apply(output); DetectionList detections; _ellipseFitter->apply(output,out,detections); //switch ellipse/moments : switcher le true/false line 186 (true pour ellipses) //_momentsDetector->apply(output,resized,detections); /*double detX=0,detY=0,detR=-1,detValid=false; if(!detections.empty()) { for(DetectionList::const_iterator it=detections.begin();it!=detections.end();++it) { if(it->valid) { detX+=it->x; detY+=it->y; if(it->radius>detR) detR=it->radius; } } if(detX<0 || detX>WORK_W || detY<0 || detY>WORK_H || detR<=0) detValid=false; else detValid=true; } if(detValid) { double z=_cam->focal*ballRadius/(2*((double) sqrt(detR)/2*1.5)*4*_cam->pixelSize); //*1.5 : empirique (on considère qu'on a en général les deux tiers de la balle) detection.z=z*100; Mat filtered_position=kalmanFilter(detX,detY); detection.x=100*((((double) filtered_position.at<float>(0))*2-WORK_W)*_cam->pixelSize*z/_cam->focal); detection.y=100*((WORK_H-((double) filtered_position.at<float>(1))*2)*_cam->pixelSize*z/_cam->focal); detection.valid=true; ostringstream oss; oss << " (" << detection.x << "," << detection.y << "," << sqrt(detR)/2 << "," << string((detection.valid)?"VALID":"NOPE") << ")"; putText(resized,oss.str(),Point(10,10),1,1,Scalar(255,0,0),1); DetectionList outDetections; Detection outD; outD.x=detX; outD.y=detY; outD.radius=sqrt(detR)/2*1.5; //*1.5 : empirique (on considère qu'on a en général les deux tiers de la balle) outD.valid=true; outDetections.push_back(outD); drawDetections(resized,outDetections,true); } else detection.valid=false;*/ //OLD ELLIPSES CODE BEGIN drawDetections(out,detections,true); double detX=0,detY=0,detR=-1; /*for(DetectionList::const_iterator it=detections.begin();it!=detections.end();++it) { detX+=it->x; detY+=it->y; if(it->radius>detR) detR=it->radius; } detX/=detections.size(); detY/=detections.size();*/ double maxR=0; DetectionList::const_iterator maxRIt=detections.begin(); for(DetectionList::const_iterator it=detections.begin();it!=detections.end();++it) { if(it->radius>maxR) { maxR=it->radius; maxRIt=it; } } detX=maxRIt->x; detY=maxRIt->y; detR=maxR; if(!detections.empty()) { double z=_cam->focal*ballRadius/(2*((double) detR)*4*_cam->pixelSize); //detection.z=z*100; //cout << "u : " << detections[0].x << " / v : " << detections[0].y << " / r : " << detections[0].radius << " ### "; //detections[0] Mat filtered_position=kalmanFilter(detX,detY,z); //? detection.x=100*((((double) filtered_position.at<float>(0))*2-WORK_W)*_cam->pixelSize*z/_cam->focal); //detX detection.y=100*((WORK_H-((double) filtered_position.at<float>(1))*4)*_cam->pixelSize*z/_cam->focal); //detY detection.z=100*(double) filtered_position.at<float>(2); if(detection.x<0 || detection.x>WORK_W || detection.y<0 || detection.y>WORK_H) detection.valid=false; else detection.valid=true; } else detection.valid=false; //OLD ELLIPSES CODE END imshow("Input", out); imshow("Output", output); imshow("Trajectory",_kalman); logs["Benchmark"].reset() << "BENCHMARK ## " << "Total : " << _timer->total() << " ms | "; /*for(map<string,Timable*>::const_iterator it=_timables.begin();it!=_timables.end();++it) { logs["Benchmark"].append() << it->first << " : " << it->second->time() << " ms , "; }*/ logs.refresh(); } return true; } void BallDetector::initKalmanFilter() { pourcent=0; centre=Point(WORK_W/2,WORK_H/2); /*2D*/ //KF.transitionMatrix=(Mat_<float>(4,4) << 1,0,1,0, 0,1,0,1, 0,0,0.6,0, 0,0,0,0.6); //Sans * au début de la parenthèse /*3D*/ KF.transitionMatrix=(Mat_<float>(6,6) << 1,0,0,1,0,0, 0,1,0,0,1,0, 0,0,1,0,0,1, 0,0,0,0.6,0,0, 0,0,0,0,0.6,0, 0,0,0,0,0,0.6); /* x y dx dy | 1 0 0 0 | | 0 1 0 0 | | 0 0 1 0 | | 0 0 0 1 | Cas 3D: x y z dx dy dz | 1 0 0 1 0 0 | | 0 1 0 0 1 0 | | 0 0 1 0 0 1 | | 0 0 0 1 0 0 | | 0 0 0 0 1 0 | | 0 0 0 0 0 1 |*/ measurement.setTo(Scalar(0)); KF.statePost.at<float>(0)=0;//initial x position KF.statePost.at<float>(1)=0;//initial y position KF.statePost.at<float>(2)=0;//initial x speed KF.statePost.at<float>(3)=0;//initial y speed KF.statePost.at<float>(4)=0; KF.statePost.at<float>(5)=0; setIdentity(KF.measurementMatrix); setIdentity(KF.processNoiseCov,Scalar::all(0.05)); //1e-2 Rapidité du "rattrapage" de l'estimation setIdentity(KF.measurementNoiseCov,Scalar::all(10)); setIdentity(KF.errorCovPost,Scalar::all(1)); } cv::Mat BallDetector::kalmanFilter(double posx,double posy, double posz) { //First predict, to update the internal statePre variable Mat prediction=KF.predict(); Point3_<float> predictPt(prediction.at<float>(0),prediction.at<float>(1),prediction.at<float>(2)); //Get ball position measurement(0)=posx; measurement(1)=posy; measurement(2)=posz; //The update phase Mat estimated=KF.correct(measurement); Point3_<float> statePt(estimated.at<float>(0),estimated.at<float>(1),estimated.at<float>(2)); Point3_<float> measPt(measurement(0),measurement(1),measurement(2)); //plot points //activer si dessin sur fond noir positionv.push_back(measPt); kalmanv.push_back(statePt); if(positionv.size()>50) { positionv.erase(positionv.begin()); kalmanv.erase(kalmanv.begin()); _kalman=Scalar::all(0); } for(int i=0;i<positionv.size()-1;i++) { line(_kalman,Point(positionv[i].x,positionv[i].y),Point(positionv[i+1].x,positionv[i+1].y),Scalar(255,255,0),1); } for(int i=0;i<kalmanv.size()-1;i++) { if(positionv.size()>=50) line(_kalman,Point(kalmanv[i].x,kalmanv[i].y),Point(kalmanv[i+1].x,kalmanv[i+1].y),Scalar(0,0,255),1); } if(posx>WORK_W/2+40 || posx<WORK_H/2-40) { //circle(_kalman,centre,2*abs(320-posx),Scalar(0,0,255),1,1,1); pourcent=abs(WORK_W/2-posx)*100/(_kalman.cols); //2*Eloignement / largeur_image % //cout << "Puissance moteur = " << pourcent << "%" << endl; //putText(im,"TEST",centre,5,10,0,Scalar(0,0,255)); } /*cout << "x brut = " << posx; cout << " | y brut = " << posy << endl; cout << "x _kalman = " << estimated.at<float>(0); cout << " | y _kalman = " << estimated.at<float>(1) << endl; cout << " z brut = " << posz; cout << " | Kalman z = " << estimated.at<float>(2) << endl;*/ return estimated; } <commit_msg>Signed-off-by: jboehm1 <boehm.jean@gmail.com><commit_after>#include "ballDetector.h" using namespace std; using namespace cv; BallDetector::BallDetector(Camera* cam) { _state=BD_RUNNING; initKalmanFilter(); //Calibrage caméra Mat distCoeffs=(Mat_<double>(5,1) << -4.4806416419013684e-01,4.1928815312056306e-01,0,0,-4.8777148182526148e-01); Mat cameraMatrix=(Mat_<double>(3,3) << 6.4106316770762089e+02,0,3.195e+02,0,6.4106316770762089e+02,2.395e+02,0,0,1); Size imageSize=Size(640,480); initUndistortRectifyMap(cameraMatrix,distCoeffs,Mat(),getOptimalNewCameraMatrix(cameraMatrix,distCoeffs,imageSize,1,imageSize,0),imageSize,CV_16SC2,_calibMap1,_calibMap2); //--- _cam=cam; _timer=new Timer(); _hsvThresholder=new HSV_Thresholder(*_timer, true); _gaussianFilter=new GaussianFilter(*_timer, true); _dilateEroder=new DilateEroder(*_timer, true); _ellipseFitter=new EllipseFitter(*_timer); _momentsDetector=new MomentsCalculator(*_timer); _timables["Hsv"]=_hsvThresholder; _timables["Blur"]=_gaussianFilter; _timables["DilEr"]=_dilateEroder; _timables["Ellipse"]=_ellipseFitter; _timables["Moments"]=_momentsDetector; Mat vachier=Mat::zeros(Camera::width,Camera::height,CV_8UC3); _hsvThresholder->autoSet(vachier); } BallDetector::~BallDetector() { delete _momentsDetector; delete _ellipseFitter; delete _dilateEroder; delete _gaussianFilter; delete _hsvThresholder; delete _timer; } bool BallDetector::loop(Position& detection) { _timer->reset(); Mat input(Camera::width,Camera::height,CV_8UC3); Mat output(Camera::width,Camera::height,CV_8UC3); bool newFrame=_cam->read(input); Mat resized(WORK_W,WORK_H,CV_8UC3); resize(input,resized,Size(WORK_W,WORK_H)); remap(resized,resized,_calibMap1,_calibMap2,INTER_LINEAR); if(_state==BD_PLACE_BALL) { circle(resized,Point(WORK_W/2,WORK_H/2),HSV_AUTOSET_RADIUS,Scalar(0,0,255),4); Mat flipped(WORK_W,WORK_H,CV_8UC3); flip(resized,flipped,1); imshow("Input",flipped); imshow("Output",flipped); } else { Mat out; resized.copyTo(out); _gaussianFilter->apply(resized); _hsvThresholder->apply(resized, output); _dilateEroder->apply(output); DetectionList detections; _ellipseFitter->apply(output,out,detections); //switch ellipse/moments : switcher le true/false line 186 (true pour ellipses) //_momentsDetector->apply(output,resized,detections); /*double detX=0,detY=0,detR=-1,detValid=false; if(!detections.empty()) { for(DetectionList::const_iterator it=detections.begin();it!=detections.end();++it) { if(it->valid) { detX+=it->x; detY+=it->y; if(it->radius>detR) detR=it->radius; } } if(detX<0 || detX>WORK_W || detY<0 || detY>WORK_H || detR<=0) detValid=false; else detValid=true; } if(detValid) { double z=_cam->focal*ballRadius/(2*((double) sqrt(detR)/2*1.5)*4*_cam->pixelSize); //*1.5 : empirique (on considère qu'on a en général les deux tiers de la balle) detection.z=z*100; Mat filtered_position=kalmanFilter(detX,detY); detection.x=100*((((double) filtered_position.at<float>(0))*2-WORK_W)*_cam->pixelSize*z/_cam->focal); detection.y=100*((WORK_H-((double) filtered_position.at<float>(1))*2)*_cam->pixelSize*z/_cam->focal); detection.valid=true; ostringstream oss; oss << " (" << detection.x << "," << detection.y << "," << sqrt(detR)/2 << "," << string((detection.valid)?"VALID":"NOPE") << ")"; putText(resized,oss.str(),Point(10,10),1,1,Scalar(255,0,0),1); DetectionList outDetections; Detection outD; outD.x=detX; outD.y=detY; outD.radius=sqrt(detR)/2*1.5; //*1.5 : empirique (on considère qu'on a en général les deux tiers de la balle) outD.valid=true; outDetections.push_back(outD); drawDetections(resized,outDetections,true); } else detection.valid=false;*/ //OLD ELLIPSES CODE BEGIN drawDetections(out,detections,true); double detX=0,detY=0,detR=-1; /*for(DetectionList::const_iterator it=detections.begin();it!=detections.end();++it) { detX+=it->x; detY+=it->y; if(it->radius>detR) detR=it->radius; } detX/=detections.size(); detY/=detections.size();*/ double maxR=0; DetectionList::const_iterator maxRIt=detections.begin(); for(DetectionList::const_iterator it=detections.begin();it!=detections.end();++it) { if(it->radius>maxR) { maxR=it->radius; maxRIt=it; } } detX=maxRIt->x; detY=maxRIt->y; detR=maxR; if(!detections.empty()) { double z=_cam->focal*ballRadius/(2*((double) detR)*4*_cam->pixelSize); //detection.z=z*100; //cout << "u : " << detections[0].x << " / v : " << detections[0].y << " / r : " << detections[0].radius << " ### "; //detections[0] Mat filtered_position=kalmanFilter(detX,detY,z); //? detection.x=100*((((double) filtered_position.at<float>(0))*2-WORK_W)*_cam->pixelSize*z/_cam->focal); //detX detection.y=100*((WORK_H-((double) filtered_position.at<float>(1))*4)*_cam->pixelSize*z/_cam->focal); //detY detection.z=100*(double) filtered_position.at<float>(2); if(detection.x<0 || detection.x>WORK_W || detection.y<0 || detection.y>WORK_H) detection.valid=false; else detection.valid=true; } else detection.valid=false; //OLD ELLIPSES CODE END imshow("Input", out); imshow("Output", output); imshow("Trajectory",_kalman); logs["Benchmark"].reset() << "BENCHMARK ## " << "Total : " << _timer->total() << " ms | "; /*for(map<string,Timable*>::const_iterator it=_timables.begin();it!=_timables.end();++it) { logs["Benchmark"].append() << it->first << " : " << it->second->time() << " ms , "; }*/ logs.refresh(); } return true; } void BallDetector::initKalmanFilter() { pourcent=0; centre=Point(WORK_W/2,WORK_H/2); /*2D*/ //KF.transitionMatrix=(Mat_<float>(4,4) << 1,0,1,0, 0,1,0,1, 0,0,0.6,0, 0,0,0,0.6); //Sans * au début de la parenthèse /*3D*/ KF.transitionMatrix=(Mat_<float>(6,6) << 1,0,0,1,0,0, 0,1,0,0,1,0, 0,0,1,0,0,1, 0,0,0,0.6,0,0, 0,0,0,0,0.6,0, 0,0,0,0,0,0.6); /* x y dx dy | 1 0 0 0 | | 0 1 0 0 | | 0 0 1 0 | | 0 0 0 1 | Cas 3D: x y z dx dy dz | 1 0 0 1 0 0 | | 0 1 0 0 1 0 | | 0 0 1 0 0 1 | | 0 0 0 1 0 0 | | 0 0 0 0 1 0 | | 0 0 0 0 0 1 |*/ measurement.setTo(Scalar(0)); KF.statePost.at<float>(0)=0;//initial x position KF.statePost.at<float>(1)=0;//initial y position KF.statePost.at<float>(2)=0;//initial x speed KF.statePost.at<float>(3)=0;//initial y speed KF.statePost.at<float>(4)=0; KF.statePost.at<float>(5)=0; setIdentity(KF.measurementMatrix); setIdentity(KF.processNoiseCov,Scalar::all(0.001)); //1e-2 Rapidité du "rattrapage" de l'estimation setIdentity(KF.measurementNoiseCov,Scalar::all(10)); setIdentity(KF.errorCovPost,Scalar::all(1)); } cv::Mat BallDetector::kalmanFilter(double posx,double posy, double posz) { //First predict, to update the internal statePre variable Mat prediction=KF.predict(); Point3_<float> predictPt(prediction.at<float>(0),prediction.at<float>(1),prediction.at<float>(2)); //Get ball position measurement(0)=posx; measurement(1)=posy; measurement(2)=posz; //The update phase Mat estimated=KF.correct(measurement); Point3_<float> statePt(estimated.at<float>(0),estimated.at<float>(1),estimated.at<float>(2)); Point3_<float> measPt(measurement(0),measurement(1),measurement(2)); //plot points //activer si dessin sur fond noir positionv.push_back(measPt); kalmanv.push_back(statePt); if(positionv.size()>50) { positionv.erase(positionv.begin()); kalmanv.erase(kalmanv.begin()); _kalman=Scalar::all(0); } for(int i=0;i<positionv.size()-1;i++) { line(_kalman,Point(positionv[i].x,positionv[i].y),Point(positionv[i+1].x,positionv[i+1].y),Scalar(255,255,0),1); } for(int i=0;i<kalmanv.size()-1;i++) { if(positionv.size()>=50) line(_kalman,Point(kalmanv[i].x,kalmanv[i].y),Point(kalmanv[i+1].x,kalmanv[i+1].y),Scalar(0,0,255),1); } if(posx>WORK_W/2+40 || posx<WORK_H/2-40) { //circle(_kalman,centre,2*abs(320-posx),Scalar(0,0,255),1,1,1); pourcent=abs(WORK_W/2-posx)*100/(_kalman.cols); //2*Eloignement / largeur_image % //cout << "Puissance moteur = " << pourcent << "%" << endl; //putText(im,"TEST",centre,5,10,0,Scalar(0,0,255)); } /*cout << "x brut = " << posx; cout << " | y brut = " << posy << endl; cout << "x _kalman = " << estimated.at<float>(0); cout << " | y _kalman = " << estimated.at<float>(1) << endl; cout << " z brut = " << posz; cout << " | Kalman z = " << estimated.at<float>(2) << endl;*/ return estimated; } <|endoftext|>
<commit_before>/* * Copyright (c) 2003 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <math.h> #include "sim/host.hh" uint64_t procInfo(char *filename, char *target) { int done = 0; char line[80]; char format[80]; uint64_t usage; FILE *fp = fopen(filename, "r"); while (fp && !feof(fp) && !done) { if (fgets(line, 80, fp)) { if (strncmp(line, target, strlen(target)) == 0) { sprintf(format, "%s %%ld", target); sscanf(line, format, &usage); fclose(fp); return usage ; } } } if (fp) fclose(fp); return 0; } <commit_msg>small fixes<commit_after>/* * Copyright (c) 2003 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <math.h> #include "sim/host.hh" uint64_t procInfo(char *filename, char *target) { int done = 0; char line[80]; char format[80]; uint64_t usage; FILE *fp = fopen(filename, "r"); while (fp && !feof(fp) && !done) { if (fgets(line, 80, fp)) { if (strncmp(line, target, strlen(target)) == 0) { sprintf(format, "%s %%lld", target); sscanf(line, format, &usage); fclose(fp); return usage ; } } } if (fp) fclose(fp); return 0; } <|endoftext|>
<commit_before>/** \file * \brief routines for calculating the lensing properties of a non-singular isothermal ellipsoid * written by R.B. Metcalf, March 18, 2009 * based on the analytic solutions of Kormann et al. 1993 * convention here is gamma_1 = -(Axx-Ayy)/2 and gamma_2= -Axy */ #include "base_analens.h" /** \ingroup DeflectionL2 \ingroup function * \brief Deflection angle for non-singular isothermal ellipsoid in units of Einstein radii */ void alphaNSIE( double *alpha /// Deflection angle in units of the Einstein radius ,double *xt /// position on the image plane in Einstein radius units ,double f /// axis ratio of mass ,double bc /// core size in same units as alpha ,double theta /// position angle of ellipsoid ){ double r=sqrt(xt[0]*xt[0]+xt[1]*xt[1]); if( r < 1.0e-20 || r > 1.0e20){ alpha[0]=0.0; alpha[1]=0.0; return; } // deflection angle alpha has opposite sign with respect to ray position xt if( f==1.0 ){ if(bc == 0.0){ alpha[0]=-1.0*xt[0]/r; alpha[1]=-1.0*xt[1]/r; }else{ alpha[0]=-1.0*(sqrt(r*r+bc*bc) - bc)*xt[0]/r/r; alpha[1]=-1.0*(sqrt(r*r+bc*bc) - bc)*xt[1]/r/r; } return; } double x[2],angle[2],fp,b2,RCphase,SCphase; Utilities::rotation(x,xt,theta); fp=sqrt(1-f*f); b2=x[0]*x[0]+f*f*x[1]*x[1]; double Qp=( pow(fp*sqrt(b2+bc*bc)+x[0],2) + f*f*f*f*x[1]*x[1] ) /( pow(f*r*r+fp*bc*x[0],2)+fp*fp*bc*bc*x[1]*x[1] ); double Qm=( pow(fp*sqrt(b2+bc*bc)-x[0],2) + f*f*f*f*x[1]*x[1] ) /( pow(f*r*r-fp*bc*x[0],2)+fp*fp*bc*bc*x[1]*x[1] ); //printf("Q = %e %e\n",Qp,Qm); //double QpQm = ( pow(f*r*r-fp*bc*x[0],2)+fp*fp*bc*bc*x[1]*x[1] )/( pow(f*r*r+fp*bc*x[0],2)+fp*fp*bc*bc*x[1]*x[1] ); //printf(" fp=%e f=%e \n",fp,f); //printf("Qp=%e Qm=%e\n",Qp,Qm); //printf("Qp/Qm=%e log(Qp/Qm)=%e %e\n",Qp/Qm,log((float)(Qp/Qm)),log(6.853450e-02)); angle[0]=0.25*sqrt(f)*log(Qp/Qm)/fp; //printf("angle[0]=%e Qp=%e Qm=%e\n",angle[0],Qp,Qm); //exit(0); RCphase=atan2(-2*f*f*fp*sqrt(b2+bc*bc)*x[1],x[0]*x[0]+pow(f*f*x[1],2)-fp*fp*(b2+bc*bc)); SCphase=atan2(-2*f*fp*bc*x[1],f*f*r*r-fp*fp*bc*bc); angle[1]= -0.5*sqrt(f)*(RCphase-SCphase)/fp; Utilities::rotation(alpha,angle,-theta); alpha[0] = -1.0*alpha[0]; alpha[1] = -1.0*alpha[1]; if(alpha[0] != alpha[0] || alpha[1] != alpha[1] ){ printf("alpha is %e %e in nsie.c \n fp=%e b2=%e r=%e bc=%e f=%e theta=%e\n x = %e %e xt= %e %e\n" ,alpha[0],alpha[1],fp,b2,r,bc,f,theta,x[0],x[1],xt[0],xt[1]); printf("angle=%e %e Qp=%e Qm=%e RCphase=%e SCphase=%e\n",angle[0],angle[1],Qp,Qm,RCphase,SCphase); ERROR_MESSAGE(); exit(0); alpha[0]=alpha[1]=0; } //std::cout << xt[0] << " " << xt[1] << " " << alpha[0] << " " << alpha[1] << std::endl; return; } /**\ingroup DeflectionL2 \ingroup function * \brief Convergence for non-singular isothermal ellipsoid, units \f$ \frac{r_{einstein}}{units(x)} \f$ * or \f$ \frac{\sigma^2}{\Sigma_{crit}G\, units(xt) } \f$ */ KappaType kappaNSIE( double *xt /// position on the image plane in Einstein radius units ,double f /// axis ratio of mass ,double bc /// core size in units of Einstein radius ,double theta /// position angle of ellipsoid ){ double x[2],b2; Utilities::rotation(x,xt,theta); b2=x[0]*x[0]+f*f*x[1]*x[1]; if( (b2 < 1.0e-20)*(bc < 1.0e-20)){ return 1.0e10; } if(b2>1.0e20 ) return 0.0; return 0.5*sqrt(f/(b2+bc*bc)); } /**\ingroup DeflectionL2 \ingroup function * \brief Shear for non-singular isothermal ellipsoid, units \f$ \frac{r_{einstein}}{units(x)} \f$ * or \f$ \frac{\sigma^2}{\Sigma_{crit}G\, units(xt) } \f$ * */ void gammaNSIE( KappaType *gam /// output shear ,double *xt /// position on the image plane in Einstein radius units ,double f /// axis ratio of mass ,double bc /// core size in units of Einstein radius ,double theta /// position angle of ellipsoid ){ double r=sqrt(xt[0]*xt[0]+xt[1]*xt[1]); if(r < 1.0e-20 || r > 1.0e20){ gam[0]=gam[1]=0.0; return; } double x[2],fp,P,b2; double gam_tmp[2], gam_out[2]; Utilities::rotation(x,xt,theta); fp=sqrt(1-f*f); b2=x[0]*x[0]+f*f*x[1]*x[1]; //r=sqrt(x[0]*x[0]+x[1]*x[1]); P=sqrt(f)*( kappaNSIE(x,f,bc,0.0)*(x[0]*x[0] + f*f*f*f*x[1]*x[1])/sqrt(f) - 0.5*(1+f*f)*sqrt(b2+bc*bc)+f*bc ) /( pow(f*r,4) - 2*f*f*fp*fp*bc*bc*(x[0]*x[0]-x[1]*x[1]) + pow(fp*bc,4) ); gam_tmp[0]=(f*f*(x[0]*x[0]-x[1]*x[1])-fp*fp*bc*bc)*P; gam_tmp[1]=2*f*f*x[0]*x[1]*P; Utilities::rotation(gam,gam,-2*theta); return; } /** \ingroup function * \brief Elliptical radius \f$ R^2 = x^2 + f^2 y^2 \f$ of a NonSingular Isothermal Ellipsoid */ // TODO: BEN Check pi factor against notes. double rmaxNSIE( double sigma /// velocity dispersion in km/s ,double mass /// mass in Msun ,double f /// axis ratio ,double rc /// core radius Mpc ){ return sqrt( pow(mass*Grav*lightspeed*lightspeed*f/pi/sigma/sigma + rc,2) - rc*rc ); } /** \ingroup function * \brief Elliptical radius \f$ R^2 = x^2 + f^2 y^2 \f$ given f and position angle of model */ double ellipticRadiusNSIE( double *x ,double f ,double pa ){ double y[2]; Utilities::rotation(y,x,pa); return sqrt(y[0]*y[0] + f*f*y[1]*y[1]); } /* inverse magnification */ KappaType invmagNSIE( double *x ,double f ,double bc ,double theta ,KappaType *gam ,KappaType kap ){ gammaNSIE(gam,x,f,bc,theta); kap=kappaNSIE(x,f,bc,theta); return pow(1-kap,2) - gam[0]*gam[0] - gam[1]*gam[1]; } namespace Utilities{ /// Rotates 2 dimensional point without changing input point void rotation(float *xout,float *xin,double theta){ float tmp = xin[0]; // to make it work if xout == xin xout[0]=tmp*cos(theta)-xin[1]*sin(theta); xout[1]=xin[1]*cos(theta)+tmp*sin(theta); } /// Rotates 2 dimensional point without changing input point void rotation(double *xout,double *xin,double theta){ double tmp = xin[0]; // to make it work if xout == xin xout[0]=tmp*cos(theta)-xin[1]*sin(theta); xout[1]=xin[1]*cos(theta)+tmp*sin(theta); } } /* potential in Mpc^2 */ KappaType phiNSIE(double *xt,double f,double bc,double theta){ return 0.0; } /**\ingroup function * * Quadropole moment of an elliptically truncated NSIE * Units are unit[mass]*unit[Rmax]^2 */ void quadMomNSIE( float mass /// total mass ,float Rmax /// elliptical maximum radius ,float f /// axis ratio of mass ,float rc /// core size in same units as Rmax ,float theta /// position angle of ellipsoid ,double *quad /// output ){ double m3,b; b = rc/Rmax; m3 = f*Rmax*Rmax*mass*(1-f*f)*( (1-2*b*b)*sqrt(1+b*b) +2*b*b*b)/(sqrt(1+b*b)-b)/6/f/f; quad[0] = m3*cos(-2*theta); quad[1] = -m3*cos(-2*theta); quad[2] = m3*sin(-2*theta); return; } <commit_msg>Removal of an other small error happened during merge<commit_after>/** \file * \brief routines for calculating the lensing properties of a non-singular isothermal ellipsoid * written by R.B. Metcalf, March 18, 2009 * based on the analytic solutions of Kormann et al. 1993 * convention here is gamma_1 = -(Axx-Ayy)/2 and gamma_2= -Axy */ #include "base_analens.h" /** \ingroup DeflectionL2 \ingroup function * \brief Deflection angle for non-singular isothermal ellipsoid in units of Einstein radii */ void alphaNSIE( double *alpha /// Deflection angle in units of the Einstein radius ,double *xt /// position on the image plane in Einstein radius units ,double f /// axis ratio of mass ,double bc /// core size in same units as alpha ,double theta /// position angle of ellipsoid ){ double r=sqrt(xt[0]*xt[0]+xt[1]*xt[1]); if( r < 1.0e-20 || r > 1.0e20){ alpha[0]=0.0; alpha[1]=0.0; return; } // deflection angle alpha has opposite sign with respect to ray position xt if( f==1.0 ){ if(bc == 0.0){ alpha[0]=-1.0*xt[0]/r; alpha[1]=-1.0*xt[1]/r; }else{ alpha[0]=-1.0*(sqrt(r*r+bc*bc) - bc)*xt[0]/r/r; alpha[1]=-1.0*(sqrt(r*r+bc*bc) - bc)*xt[1]/r/r; } return; } double x[2],angle[2],fp,b2,RCphase,SCphase; Utilities::rotation(x,xt,theta); fp=sqrt(1-f*f); b2=x[0]*x[0]+f*f*x[1]*x[1]; double Qp=( pow(fp*sqrt(b2+bc*bc)+x[0],2) + f*f*f*f*x[1]*x[1] ) /( pow(f*r*r+fp*bc*x[0],2)+fp*fp*bc*bc*x[1]*x[1] ); double Qm=( pow(fp*sqrt(b2+bc*bc)-x[0],2) + f*f*f*f*x[1]*x[1] ) /( pow(f*r*r-fp*bc*x[0],2)+fp*fp*bc*bc*x[1]*x[1] ); //printf("Q = %e %e\n",Qp,Qm); //double QpQm = ( pow(f*r*r-fp*bc*x[0],2)+fp*fp*bc*bc*x[1]*x[1] )/( pow(f*r*r+fp*bc*x[0],2)+fp*fp*bc*bc*x[1]*x[1] ); //printf(" fp=%e f=%e \n",fp,f); //printf("Qp=%e Qm=%e\n",Qp,Qm); //printf("Qp/Qm=%e log(Qp/Qm)=%e %e\n",Qp/Qm,log((float)(Qp/Qm)),log(6.853450e-02)); angle[0]=0.25*sqrt(f)*log(Qp/Qm)/fp; //printf("angle[0]=%e Qp=%e Qm=%e\n",angle[0],Qp,Qm); //exit(0); RCphase=atan2(-2*f*f*fp*sqrt(b2+bc*bc)*x[1],x[0]*x[0]+pow(f*f*x[1],2)-fp*fp*(b2+bc*bc)); SCphase=atan2(-2*f*fp*bc*x[1],f*f*r*r-fp*fp*bc*bc); angle[1]= -0.5*sqrt(f)*(RCphase-SCphase)/fp; Utilities::rotation(alpha,angle,-theta); alpha[0] = -1.0*alpha[0]; alpha[1] = -1.0*alpha[1]; if(alpha[0] != alpha[0] || alpha[1] != alpha[1] ){ printf("alpha is %e %e in nsie.c \n fp=%e b2=%e r=%e bc=%e f=%e theta=%e\n x = %e %e xt= %e %e\n" ,alpha[0],alpha[1],fp,b2,r,bc,f,theta,x[0],x[1],xt[0],xt[1]); printf("angle=%e %e Qp=%e Qm=%e RCphase=%e SCphase=%e\n",angle[0],angle[1],Qp,Qm,RCphase,SCphase); ERROR_MESSAGE(); exit(0); alpha[0]=alpha[1]=0; } //std::cout << xt[0] << " " << xt[1] << " " << alpha[0] << " " << alpha[1] << std::endl; return; } /**\ingroup DeflectionL2 \ingroup function * \brief Convergence for non-singular isothermal ellipsoid, units \f$ \frac{r_{einstein}}{units(x)} \f$ * or \f$ \frac{\sigma^2}{\Sigma_{crit}G\, units(xt) } \f$ */ KappaType kappaNSIE( double *xt /// position on the image plane in Einstein radius units ,double f /// axis ratio of mass ,double bc /// core size in units of Einstein radius ,double theta /// position angle of ellipsoid ){ double x[2],b2; Utilities::rotation(x,xt,theta); b2=x[0]*x[0]+f*f*x[1]*x[1]; if( (b2 < 1.0e-20)*(bc < 1.0e-20)){ return 1.0e10; } if(b2>1.0e20 ) return 0.0; return 0.5*sqrt(f/(b2+bc*bc)); } /**\ingroup DeflectionL2 \ingroup function * \brief Shear for non-singular isothermal ellipsoid, units \f$ \frac{r_{einstein}}{units(x)} \f$ * or \f$ \frac{\sigma^2}{\Sigma_{crit}G\, units(xt) } \f$ * */ void gammaNSIE( KappaType *gam /// output shear ,double *xt /// position on the image plane in Einstein radius units ,double f /// axis ratio of mass ,double bc /// core size in units of Einstein radius ,double theta /// position angle of ellipsoid ){ double r=sqrt(xt[0]*xt[0]+xt[1]*xt[1]); if(r < 1.0e-20 || r > 1.0e20){ gam[0]=gam[1]=0.0; return; } double x[2],fp,P,b2; double gam_tmp[2], gam_out[2]; Utilities::rotation(x,xt,theta); fp=sqrt(1-f*f); b2=x[0]*x[0]+f*f*x[1]*x[1]; //r=sqrt(x[0]*x[0]+x[1]*x[1]); P=sqrt(f)*( kappaNSIE(x,f,bc,0.0)*(x[0]*x[0] + f*f*f*f*x[1]*x[1])/sqrt(f) - 0.5*(1+f*f)*sqrt(b2+bc*bc)+f*bc ) /( pow(f*r,4) - 2*f*f*fp*fp*bc*bc*(x[0]*x[0]-x[1]*x[1]) + pow(fp*bc,4) ); gam[0]=(f*f*(x[0]*x[0]-x[1]*x[1])-fp*fp*bc*bc)*P; gam[1]=2*f*f*x[0]*x[1]*P; Utilities::rotation(gam,gam,-2*theta); return; } /** \ingroup function * \brief Elliptical radius \f$ R^2 = x^2 + f^2 y^2 \f$ of a NonSingular Isothermal Ellipsoid */ // TODO: BEN Check pi factor against notes. double rmaxNSIE( double sigma /// velocity dispersion in km/s ,double mass /// mass in Msun ,double f /// axis ratio ,double rc /// core radius Mpc ){ return sqrt( pow(mass*Grav*lightspeed*lightspeed*f/pi/sigma/sigma + rc,2) - rc*rc ); } /** \ingroup function * \brief Elliptical radius \f$ R^2 = x^2 + f^2 y^2 \f$ given f and position angle of model */ double ellipticRadiusNSIE( double *x ,double f ,double pa ){ double y[2]; Utilities::rotation(y,x,pa); return sqrt(y[0]*y[0] + f*f*y[1]*y[1]); } /* inverse magnification */ KappaType invmagNSIE( double *x ,double f ,double bc ,double theta ,KappaType *gam ,KappaType kap ){ gammaNSIE(gam,x,f,bc,theta); kap=kappaNSIE(x,f,bc,theta); return pow(1-kap,2) - gam[0]*gam[0] - gam[1]*gam[1]; } namespace Utilities{ /// Rotates 2 dimensional point without changing input point void rotation(float *xout,float *xin,double theta){ float tmp = xin[0]; // to make it work if xout == xin xout[0]=tmp*cos(theta)-xin[1]*sin(theta); xout[1]=xin[1]*cos(theta)+tmp*sin(theta); } /// Rotates 2 dimensional point without changing input point void rotation(double *xout,double *xin,double theta){ double tmp = xin[0]; // to make it work if xout == xin xout[0]=tmp*cos(theta)-xin[1]*sin(theta); xout[1]=xin[1]*cos(theta)+tmp*sin(theta); } } /* potential in Mpc^2 */ KappaType phiNSIE(double *xt,double f,double bc,double theta){ return 0.0; } /**\ingroup function * * Quadropole moment of an elliptically truncated NSIE * Units are unit[mass]*unit[Rmax]^2 */ void quadMomNSIE( float mass /// total mass ,float Rmax /// elliptical maximum radius ,float f /// axis ratio of mass ,float rc /// core size in same units as Rmax ,float theta /// position angle of ellipsoid ,double *quad /// output ){ double m3,b; b = rc/Rmax; m3 = f*Rmax*Rmax*mass*(1-f*f)*( (1-2*b*b)*sqrt(1+b*b) +2*b*b*b)/(sqrt(1+b*b)-b)/6/f/f; quad[0] = m3*cos(-2*theta); quad[1] = -m3*cos(-2*theta); quad[2] = m3*sin(-2*theta); return; } <|endoftext|>
<commit_before>#ifndef ARBITER_IS_AMALGAMATION #include <arbiter/drivers/google.hpp> #endif #ifdef ARBITER_OPENSSL #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/rsa.h> #include <openssl/sha.h> #endif #ifndef ARBITER_IS_AMALGAMATION #include <arbiter/arbiter.hpp> #include <arbiter/drivers/fs.hpp> #include <arbiter/util/transforms.hpp> #endif #ifdef ARBITER_CUSTOM_NAMESPACE namespace ARBITER_CUSTOM_NAMESPACE { #endif namespace arbiter { namespace { std::mutex sslMutex; Json::Value parse(const std::string& s) { Json::Reader reader; Json::Value json; if (!reader.parse(s, json)) { throw std::runtime_error( "Parse failure: " + reader.getFormattedErrorMessages()); } return json; } std::string toFastString(const Json::Value& json) { std::string s = Json::FastWriter().write(json); s.pop_back(); // Strip trailing newline. return s; } const std::string baseUrl("www.googleapis.com/storage/v1/"); const std::string uploadUrl("www.googleapis.com/upload/storage/v1/"); const http::Query altMediaQuery{ { "alt", "media" } }; class GResource { public: GResource(std::string path) { const std::size_t split(path.find("/")); m_bucket = path.substr(0, split) + "/"; if (split != std::string::npos) m_object = path.substr(split + 1); } const std::string& bucket() const { return m_bucket; } const std::string& object() const { return m_object; } std::string endpoint() const { // https://cloud.google.com/storage/docs/json_api/#encoding static const std::string exclusions("!$&'()*+,;=:@"); // https://cloud.google.com/storage/docs/json_api/v1/ return baseUrl + "b/" + bucket() + "o/" + http::sanitize(object(), exclusions); } std::string uploadEndpoint() const { return uploadUrl + "b/" + bucket() + "o"; } std::string listEndpoint() const { return baseUrl + "b/" + bucket() + "o"; } private: std::string m_bucket; std::string m_object; }; } // unnamed namespace namespace drivers { Google::Google(http::Pool& pool, std::unique_ptr<Auth> auth) : Https(pool) , m_auth(std::move(auth)) { } std::unique_ptr<Google> Google::create( http::Pool& pool, const Json::Value& json) { if (auto auth = Auth::create(json)) { return util::makeUnique<Google>(pool, std::move(auth)); } return std::unique_ptr<Google>(); } std::unique_ptr<std::size_t> Google::tryGetSize(const std::string path) const { http::Headers headers(m_auth->headers()); const GResource resource(path); drivers::Https https(m_pool); const auto res( https.internalHead(resource.endpoint(), headers, altMediaQuery)); if (res.ok() && res.headers().count("Content-Length")) { const auto& s(res.headers().at("Content-Length")); return util::makeUnique<std::size_t>(std::stoul(s)); } return std::unique_ptr<std::size_t>(); } bool Google::get( const std::string path, std::vector<char>& data, const http::Headers userHeaders, const http::Query query) const { http::Headers headers(m_auth->headers()); headers.insert(userHeaders.begin(), userHeaders.end()); const GResource resource(path); drivers::Https https(m_pool); const auto res( https.internalGet(resource.endpoint(), headers, altMediaQuery)); if (res.ok()) { data = res.data(); return true; } else { std::cout << "Failed get - " << res.code() << ": " << res.str() << std::endl; return false; } } void Google::put( const std::string path, const std::vector<char>& data, const http::Headers userHeaders, const http::Query userQuery) const { const GResource resource(path); const std::string url(resource.uploadEndpoint()); http::Headers headers(m_auth->headers()); headers["Expect"] = ""; headers.insert(userHeaders.begin(), userHeaders.end()); http::Query query(userQuery); query["uploadType"] = "media"; query["name"] = resource.object(); drivers::Https https(m_pool); const auto res(https.internalPost(url, data, headers, query)); } std::vector<std::string> Google::glob(std::string path, bool verbose) const { std::vector<std::string> results; path.pop_back(); const bool recursive(path.back() == '*'); if (recursive) path.pop_back(); const GResource resource(path); const std::string url(resource.listEndpoint()); std::string pageToken; drivers::Https https(m_pool); http::Query query; // When the delimiter is set to "/", then the response will contain a // "prefixes" key in addition to the "items" key. The "prefixes" key will // contain the directories found, which we will ignore. if (!recursive) query["delimiter"] = "/"; if (resource.object().size()) query["prefix"] = resource.object(); do { if (pageToken.size()) query["pageToken"] = pageToken; const auto res(https.internalGet(url, m_auth->headers(), query)); if (!res.ok()) { throw ArbiterError(std::to_string(res.code()) + ": " + res.str()); } const Json::Value json(parse(res.str())); for (const auto& item : json["items"]) { results.push_back( "google://" + resource.bucket() + item["name"].asString()); } pageToken = json["nextPageToken"].asString(); } while (pageToken.size()); return results; } /////////////////////////////////////////////////////////////////////////////// std::unique_ptr<Google::Auth> Google::Auth::create(const Json::Value& json) { if (auto path = util::env("GOOGLE_APPLICATION_CREDENTIALS")) { if (const auto file = drivers::Fs().tryGet(*path)) { return util::makeUnique<Auth>(parse(*file)); } } else if (json.isString()) { const auto path = json.asString(); if (const auto file = drivers::Fs().tryGet(path)) { return util::makeUnique<Auth>(parse(*file)); } } return std::unique_ptr<Auth>(); } Google::Auth::Auth(const Json::Value& creds) : m_creds(creds) { maybeRefresh(); } http::Headers Google::Auth::headers() const { std::lock_guard<std::mutex> lock(m_mutex); maybeRefresh(); return m_headers; } void Google::Auth::maybeRefresh() const { using namespace crypto; const auto now(Time().unix()); if (m_expiration - now > 120) return; // Refresh when under 2 mins left. // https://developers.google.com/identity/protocols/OAuth2ServiceAccount Json::Value h; h["alg"] = "RS256"; h["typ"] = "JWT"; Json::Value c; c["iss"] = m_creds["client_email"].asString(); c["scope"] = "https://www.googleapis.com/auth/devstorage.read_write"; c["aud"] = "https://www.googleapis.com/oauth2/v4/token"; c["iat"] = now; c["exp"] = now + 3600; const std::string header(encodeBase64(toFastString(h))); const std::string claims(encodeBase64(toFastString(c))); const std::string key(m_creds["private_key"].asString()); const std::string signature( http::sanitize(encodeBase64(sign(header + '.' + claims, key)))); const std::string assertion(header + '.' + claims + '.' + signature); const std::string sbody = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&" "assertion=" + assertion; const std::vector<char> body(sbody.begin(), sbody.end()); const http::Headers headers { { "Expect", "" } }; const std::string tokenRequestUrl("www.googleapis.com/oauth2/v4/token"); http::Pool pool; drivers::Https https(pool); const auto res(https.internalPost(tokenRequestUrl, body, headers)); if (!res.ok()) throw ArbiterError("Failed to get token: " + res.str()); const Json::Value token(parse(res.str())); m_headers["Authorization"] = "Bearer " + token["access_token"].asString(); m_expiration = now + token["expires_in"].asInt64(); } std::string Google::Auth::sign( const std::string data, const std::string pkey) const { std::string signature; #ifdef ARBITER_OPENSSL std::lock_guard<std::mutex> lock(sslMutex); auto loadKey([](std::string s, bool isPublic)->EVP_PKEY* { EVP_PKEY* key(nullptr); if (BIO* bio = BIO_new_mem_buf(s.data(), -1)) { if (isPublic) { key = PEM_read_bio_PUBKEY(bio, &key, nullptr, nullptr); } else { key = PEM_read_bio_PrivateKey(bio, &key, nullptr, nullptr); } BIO_free(bio); if (!key) { std::vector<char> err(256, 0); ERR_error_string(ERR_get_error(), err.data()); throw ArbiterError( std::string("Could not load key: ") + err.data()); } } return key; }); EVP_PKEY* key(loadKey(pkey, false)); EVP_MD_CTX ctx; EVP_MD_CTX_init(&ctx); EVP_DigestSignInit(&ctx, nullptr, EVP_sha256(), nullptr, key); if (EVP_DigestSignUpdate(&ctx, data.data(), data.size()) == 1) { std::size_t size(0); if (EVP_DigestSignFinal(&ctx, nullptr, &size) == 1) { std::vector<unsigned char> v(size, 0); if (EVP_DigestSignFinal(&ctx, v.data(), &size) == 1) { signature.assign(reinterpret_cast<const char*>(v.data()), size); } } } EVP_MD_CTX_cleanup(&ctx); if (signature.empty()) throw ArbiterError("Could not sign JWT"); return signature; #else throw ArbiterError("Cannot use google driver without OpenSSL"); #endif } } // namespace drivers } // namespace arbiter #ifdef ARBITER_CUSTOM_NAMESPACE } #endif <commit_msg>Fix ambiguous conversion.<commit_after>#ifndef ARBITER_IS_AMALGAMATION #include <arbiter/drivers/google.hpp> #endif #ifdef ARBITER_OPENSSL #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/rsa.h> #include <openssl/sha.h> #endif #ifndef ARBITER_IS_AMALGAMATION #include <arbiter/arbiter.hpp> #include <arbiter/drivers/fs.hpp> #include <arbiter/util/transforms.hpp> #endif #ifdef ARBITER_CUSTOM_NAMESPACE namespace ARBITER_CUSTOM_NAMESPACE { #endif namespace arbiter { namespace { std::mutex sslMutex; Json::Value parse(const std::string& s) { Json::Reader reader; Json::Value json; if (!reader.parse(s, json)) { throw std::runtime_error( "Parse failure: " + reader.getFormattedErrorMessages()); } return json; } std::string toFastString(const Json::Value& json) { std::string s = Json::FastWriter().write(json); s.pop_back(); // Strip trailing newline. return s; } const std::string baseUrl("www.googleapis.com/storage/v1/"); const std::string uploadUrl("www.googleapis.com/upload/storage/v1/"); const http::Query altMediaQuery{ { "alt", "media" } }; class GResource { public: GResource(std::string path) { const std::size_t split(path.find("/")); m_bucket = path.substr(0, split) + "/"; if (split != std::string::npos) m_object = path.substr(split + 1); } const std::string& bucket() const { return m_bucket; } const std::string& object() const { return m_object; } std::string endpoint() const { // https://cloud.google.com/storage/docs/json_api/#encoding static const std::string exclusions("!$&'()*+,;=:@"); // https://cloud.google.com/storage/docs/json_api/v1/ return baseUrl + "b/" + bucket() + "o/" + http::sanitize(object(), exclusions); } std::string uploadEndpoint() const { return uploadUrl + "b/" + bucket() + "o"; } std::string listEndpoint() const { return baseUrl + "b/" + bucket() + "o"; } private: std::string m_bucket; std::string m_object; }; } // unnamed namespace namespace drivers { Google::Google(http::Pool& pool, std::unique_ptr<Auth> auth) : Https(pool) , m_auth(std::move(auth)) { } std::unique_ptr<Google> Google::create( http::Pool& pool, const Json::Value& json) { if (auto auth = Auth::create(json)) { return util::makeUnique<Google>(pool, std::move(auth)); } return std::unique_ptr<Google>(); } std::unique_ptr<std::size_t> Google::tryGetSize(const std::string path) const { http::Headers headers(m_auth->headers()); const GResource resource(path); drivers::Https https(m_pool); const auto res( https.internalHead(resource.endpoint(), headers, altMediaQuery)); if (res.ok() && res.headers().count("Content-Length")) { const auto& s(res.headers().at("Content-Length")); return util::makeUnique<std::size_t>(std::stoul(s)); } return std::unique_ptr<std::size_t>(); } bool Google::get( const std::string path, std::vector<char>& data, const http::Headers userHeaders, const http::Query query) const { http::Headers headers(m_auth->headers()); headers.insert(userHeaders.begin(), userHeaders.end()); const GResource resource(path); drivers::Https https(m_pool); const auto res( https.internalGet(resource.endpoint(), headers, altMediaQuery)); if (res.ok()) { data = res.data(); return true; } else { std::cout << "Failed get - " << res.code() << ": " << res.str() << std::endl; return false; } } void Google::put( const std::string path, const std::vector<char>& data, const http::Headers userHeaders, const http::Query userQuery) const { const GResource resource(path); const std::string url(resource.uploadEndpoint()); http::Headers headers(m_auth->headers()); headers["Expect"] = ""; headers.insert(userHeaders.begin(), userHeaders.end()); http::Query query(userQuery); query["uploadType"] = "media"; query["name"] = resource.object(); drivers::Https https(m_pool); const auto res(https.internalPost(url, data, headers, query)); } std::vector<std::string> Google::glob(std::string path, bool verbose) const { std::vector<std::string> results; path.pop_back(); const bool recursive(path.back() == '*'); if (recursive) path.pop_back(); const GResource resource(path); const std::string url(resource.listEndpoint()); std::string pageToken; drivers::Https https(m_pool); http::Query query; // When the delimiter is set to "/", then the response will contain a // "prefixes" key in addition to the "items" key. The "prefixes" key will // contain the directories found, which we will ignore. if (!recursive) query["delimiter"] = "/"; if (resource.object().size()) query["prefix"] = resource.object(); do { if (pageToken.size()) query["pageToken"] = pageToken; const auto res(https.internalGet(url, m_auth->headers(), query)); if (!res.ok()) { throw ArbiterError(std::to_string(res.code()) + ": " + res.str()); } const Json::Value json(parse(res.str())); for (const auto& item : json["items"]) { results.push_back( "google://" + resource.bucket() + item["name"].asString()); } pageToken = json["nextPageToken"].asString(); } while (pageToken.size()); return results; } /////////////////////////////////////////////////////////////////////////////// std::unique_ptr<Google::Auth> Google::Auth::create(const Json::Value& json) { if (auto path = util::env("GOOGLE_APPLICATION_CREDENTIALS")) { if (const auto file = drivers::Fs().tryGet(*path)) { return util::makeUnique<Auth>(parse(*file)); } } else if (json.isString()) { const auto path = json.asString(); if (const auto file = drivers::Fs().tryGet(path)) { return util::makeUnique<Auth>(parse(*file)); } } return std::unique_ptr<Auth>(); } Google::Auth::Auth(const Json::Value& creds) : m_creds(creds) { maybeRefresh(); } http::Headers Google::Auth::headers() const { std::lock_guard<std::mutex> lock(m_mutex); maybeRefresh(); return m_headers; } void Google::Auth::maybeRefresh() const { using namespace crypto; const auto now(Time().unix()); if (m_expiration - now > 120) return; // Refresh when under 2 mins left. // https://developers.google.com/identity/protocols/OAuth2ServiceAccount Json::Value h; h["alg"] = "RS256"; h["typ"] = "JWT"; Json::Value c; c["iss"] = m_creds["client_email"].asString(); c["scope"] = "https://www.googleapis.com/auth/devstorage.read_write"; c["aud"] = "https://www.googleapis.com/oauth2/v4/token"; c["iat"] = Json::Int64(now); c["exp"] = Json::Int64(now + 3600); const std::string header(encodeBase64(toFastString(h))); const std::string claims(encodeBase64(toFastString(c))); const std::string key(m_creds["private_key"].asString()); const std::string signature( http::sanitize(encodeBase64(sign(header + '.' + claims, key)))); const std::string assertion(header + '.' + claims + '.' + signature); const std::string sbody = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&" "assertion=" + assertion; const std::vector<char> body(sbody.begin(), sbody.end()); const http::Headers headers { { "Expect", "" } }; const std::string tokenRequestUrl("www.googleapis.com/oauth2/v4/token"); http::Pool pool; drivers::Https https(pool); const auto res(https.internalPost(tokenRequestUrl, body, headers)); if (!res.ok()) throw ArbiterError("Failed to get token: " + res.str()); const Json::Value token(parse(res.str())); m_headers["Authorization"] = "Bearer " + token["access_token"].asString(); m_expiration = now + token["expires_in"].asInt64(); } std::string Google::Auth::sign( const std::string data, const std::string pkey) const { std::string signature; #ifdef ARBITER_OPENSSL std::lock_guard<std::mutex> lock(sslMutex); auto loadKey([](std::string s, bool isPublic)->EVP_PKEY* { EVP_PKEY* key(nullptr); if (BIO* bio = BIO_new_mem_buf(s.data(), -1)) { if (isPublic) { key = PEM_read_bio_PUBKEY(bio, &key, nullptr, nullptr); } else { key = PEM_read_bio_PrivateKey(bio, &key, nullptr, nullptr); } BIO_free(bio); if (!key) { std::vector<char> err(256, 0); ERR_error_string(ERR_get_error(), err.data()); throw ArbiterError( std::string("Could not load key: ") + err.data()); } } return key; }); EVP_PKEY* key(loadKey(pkey, false)); EVP_MD_CTX ctx; EVP_MD_CTX_init(&ctx); EVP_DigestSignInit(&ctx, nullptr, EVP_sha256(), nullptr, key); if (EVP_DigestSignUpdate(&ctx, data.data(), data.size()) == 1) { std::size_t size(0); if (EVP_DigestSignFinal(&ctx, nullptr, &size) == 1) { std::vector<unsigned char> v(size, 0); if (EVP_DigestSignFinal(&ctx, v.data(), &size) == 1) { signature.assign(reinterpret_cast<const char*>(v.data()), size); } } } EVP_MD_CTX_cleanup(&ctx); if (signature.empty()) throw ArbiterError("Could not sign JWT"); return signature; #else throw ArbiterError("Cannot use google driver without OpenSSL"); #endif } } // namespace drivers } // namespace arbiter #ifdef ARBITER_CUSTOM_NAMESPACE } #endif <|endoftext|>
<commit_before>// kmfolderdia.cpp #include <assert.h> #include <qdir.h> #include <qfile.h> #include <qlabel.h> #include <qlayout.h> #include <qlineedit.h> #include <qlistbox.h> #include <qpushbutton.h> #include <qstring.h> #include <qtextstream.h> #include <klocale.h> #include <kmessagebox.h> #include "kmmainwin.h" #include "kmglobal.h" #include "kmaccount.h" #include "kmacctmgr.h" #include "kmacctfolder.h" #include "kmfoldermgr.h" #include "kmfolderdia.moc" //----------------------------------------------------------------------------- KMFolderDialog::KMFolderDialog(KMFolder* aFolder, KMFolderDir *aFolderDir, QWidget *aParent, const QString& aCap): KMFolderDialogInherited( aParent, "KMFolderDialog", TRUE, aCap, KDialogBase::Ok|KDialogBase::Cancel ), folder((KMAcctFolder*)aFolder),mFolderDir( aFolderDir ) { QWidget *page = new QWidget(this); setMainWidget( page ); QVBoxLayout *topLayout = new QVBoxLayout( page, 0, spacingHint() ); QHBoxLayout *hl = new QHBoxLayout(); topLayout->addSpacing( spacingHint()*2 ); topLayout->addLayout( hl ); topLayout->addSpacing( spacingHint()*2 ); QLabel *label = new QLabel( i18n("Name:"), page ); hl->addWidget( label ); nameEdit = new QLineEdit( page ); nameEdit->setFocus(); nameEdit->setText(folder ? folder->name() : i18n("unnamed")); nameEdit->setMinimumSize(nameEdit->sizeHint()); hl->addWidget( nameEdit ); hl->addSpacing( spacingHint() ); label = new QLabel( i18n("File under:" ), page ); hl->addWidget( label ); fileInFolder = new QComboBox(page); hl->addWidget( fileInFolder ); QStringList str; folderMgr->createFolderList( &str, &mFolders ); str.prepend( i18n( "Top Level" )); KMFolder *curFolder; int i = 1; fileInFolder->insertStringList( str ); for (curFolder = mFolders.first(); curFolder; curFolder = mFolders.next()) { if (curFolder->child() == aFolderDir) fileInFolder->setCurrentItem( i ); ++i; } } //----------------------------------------------------------------------------- void KMFolderDialog::slotOk() { QString acctName; QString fldName, oldFldName; KMFolderDir *selectedFolderDir = &(folderMgr->dir()); int curFolder = fileInFolder->currentItem(); if (folder) oldFldName = folder->name(); if (*nameEdit->text()) fldName = nameEdit->text(); else fldName = oldFldName; if (fldName.isEmpty()) fldName = i18n("unnamed"); if (curFolder != 0) selectedFolderDir = mFolders.at(curFolder - 1)->createChildFolder(); debug( QString("%1").arg( curFolder ) + mFolders.at(curFolder - 1)->path()); QString message = i18n( "Failed to create folder '" ) + (const char*)fldName + i18n( "', folder already exists." ); if ((selectedFolderDir->hasNamedFolder(fldName)) && (!((folder) && (selectedFolderDir == folder->parent()) && (folder->name() == fldName)))) { KMessageBox::error( this, message ); return; } message = i18n( "Cannot move a parent folder into a child folder." ); KMFolderDir* folderDir = selectedFolderDir; // Buggy? if (folder && folder->child()) while ((folderDir != &folderMgr->dir()) && (folderDir != folder->parent())){ if (folderDir->findRef( folder ) != -1) { KMessageBox::error( this, message ); return; } folderDir = folderDir->parent(); } // End buggy? if (folder && folder->child() && (selectedFolderDir) && (selectedFolderDir->path().find( folder->child()->path() + "/" ) == 0)) { KMessageBox::error( this, message ); return; } if (folder && folder->child() && (selectedFolderDir == folder->child())) { KMessageBox::error( this, message ); return; } if (!folder) { folder = (KMAcctFolder*)folderMgr->createFolder(fldName, FALSE, selectedFolderDir ); } else if ((oldFldName != fldName) || (folder->parent() != selectedFolderDir)) { if (folder->parent() != selectedFolderDir) folder->rename(fldName, selectedFolderDir ); else folder->rename(fldName); folderMgr->contentsChanged(); } KMFolderDialogInherited::slotOk(); } <commit_msg>Oops that debug statement really shouldn't have been there.<commit_after>// kmfolderdia.cpp #include <assert.h> #include <qdir.h> #include <qfile.h> #include <qlabel.h> #include <qlayout.h> #include <qlineedit.h> #include <qlistbox.h> #include <qpushbutton.h> #include <qstring.h> #include <qtextstream.h> #include <klocale.h> #include <kmessagebox.h> #include "kmmainwin.h" #include "kmglobal.h" #include "kmaccount.h" #include "kmacctmgr.h" #include "kmacctfolder.h" #include "kmfoldermgr.h" #include "kmfolderdia.moc" //----------------------------------------------------------------------------- KMFolderDialog::KMFolderDialog(KMFolder* aFolder, KMFolderDir *aFolderDir, QWidget *aParent, const QString& aCap): KMFolderDialogInherited( aParent, "KMFolderDialog", TRUE, aCap, KDialogBase::Ok|KDialogBase::Cancel ), folder((KMAcctFolder*)aFolder),mFolderDir( aFolderDir ) { QWidget *page = new QWidget(this); setMainWidget( page ); QVBoxLayout *topLayout = new QVBoxLayout( page, 0, spacingHint() ); QHBoxLayout *hl = new QHBoxLayout(); topLayout->addSpacing( spacingHint()*2 ); topLayout->addLayout( hl ); topLayout->addSpacing( spacingHint()*2 ); QLabel *label = new QLabel( i18n("Name:"), page ); hl->addWidget( label ); nameEdit = new QLineEdit( page ); nameEdit->setFocus(); nameEdit->setText(folder ? folder->name() : i18n("unnamed")); nameEdit->setMinimumSize(nameEdit->sizeHint()); hl->addWidget( nameEdit ); hl->addSpacing( spacingHint() ); label = new QLabel( i18n("File under:" ), page ); hl->addWidget( label ); fileInFolder = new QComboBox(page); hl->addWidget( fileInFolder ); QStringList str; folderMgr->createFolderList( &str, &mFolders ); str.prepend( i18n( "Top Level" )); KMFolder *curFolder; int i = 1; fileInFolder->insertStringList( str ); for (curFolder = mFolders.first(); curFolder; curFolder = mFolders.next()) { if (curFolder->child() == aFolderDir) fileInFolder->setCurrentItem( i ); ++i; } } //----------------------------------------------------------------------------- void KMFolderDialog::slotOk() { QString acctName; QString fldName, oldFldName; KMFolderDir *selectedFolderDir = &(folderMgr->dir()); int curFolder = fileInFolder->currentItem(); if (folder) oldFldName = folder->name(); if (*nameEdit->text()) fldName = nameEdit->text(); else fldName = oldFldName; if (fldName.isEmpty()) fldName = i18n("unnamed"); if (curFolder != 0) selectedFolderDir = mFolders.at(curFolder - 1)->createChildFolder(); QString message = i18n( "Failed to create folder '" ) + (const char*)fldName + i18n( "', folder already exists." ); if ((selectedFolderDir->hasNamedFolder(fldName)) && (!((folder) && (selectedFolderDir == folder->parent()) && (folder->name() == fldName)))) { KMessageBox::error( this, message ); return; } message = i18n( "Cannot move a parent folder into a child folder." ); KMFolderDir* folderDir = selectedFolderDir; // Buggy? if (folder && folder->child()) while ((folderDir != &folderMgr->dir()) && (folderDir != folder->parent())){ if (folderDir->findRef( folder ) != -1) { KMessageBox::error( this, message ); return; } folderDir = folderDir->parent(); } // End buggy? if (folder && folder->child() && (selectedFolderDir) && (selectedFolderDir->path().find( folder->child()->path() + "/" ) == 0)) { KMessageBox::error( this, message ); return; } if (folder && folder->child() && (selectedFolderDir == folder->child())) { KMessageBox::error( this, message ); return; } if (!folder) { folder = (KMAcctFolder*)folderMgr->createFolder(fldName, FALSE, selectedFolderDir ); } else if ((oldFldName != fldName) || (folder->parent() != selectedFolderDir)) { if (folder->parent() != selectedFolderDir) folder->rename(fldName, selectedFolderDir ); else folder->rename(fldName); folderMgr->contentsChanged(); } KMFolderDialogInherited::slotOk(); } <|endoftext|>
<commit_before>/* * KMTopLevelWidget class implementation * * Copyright (C) 1998 Stefan Taferner * * 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 * MERCHANTABLILITY 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, 675 Mass Ave, Cambridge, MA 02139, * USA. */ #include "kmtopwidget.h" #include <kapp.h> #include "kmsender.h" #include "kmglobal.h" //----------------------------------------------------------------------------- KMTopLevelWidget::KMTopLevelWidget(const char* aName): KMTopLevelWidgetInherited(0, aName) {} //----------------------------------------------------------------------------- KMTopLevelWidget::~KMTopLevelWidget() {} //----------------------------------------------------------------------------- void KMTopLevelWidget::closeEvent(QCloseEvent* e) { // Almost verbatim from KMainWindow writeConfig(); if (queryClose()) { e->accept(); int not_withdrawn = 0; QListIterator<KMainWindow> it(*KMainWindow::memberList); for (it.toFirst(); it.current(); ++it) { if ( !it.current()->testWState( WState_ForceHide ) ) not_withdrawn++; } if ( not_withdrawn <= 1 ) { // last window close accepted? kernel->quit(); // ...and quit aplication. } } else e->ignore(); } //----------------------------------------------------------------------------- void KMTopLevelWidget::readConfig(void) { } //----------------------------------------------------------------------------- void KMTopLevelWidget::writeConfig(void) { } #include "kmtopwidget.moc" <commit_msg>Patch from Matthias Ettrich.<commit_after>/* * KMTopLevelWidget class implementation * * Copyright (C) 1998 Stefan Taferner * * 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 * MERCHANTABLILITY 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, 675 Mass Ave, Cambridge, MA 02139, * USA. */ #include "kmtopwidget.h" #include <kapp.h> #include "kmsender.h" #include "kmglobal.h" //----------------------------------------------------------------------------- KMTopLevelWidget::KMTopLevelWidget(const char* aName): KMTopLevelWidgetInherited(0, aName) {} //----------------------------------------------------------------------------- KMTopLevelWidget::~KMTopLevelWidget() {} //----------------------------------------------------------------------------- void KMTopLevelWidget::closeEvent(QCloseEvent* e) { // Almost verbatim from KMainWindow writeConfig(); KMainWindow::closeEvent( e ); } //----------------------------------------------------------------------------- void KMTopLevelWidget::readConfig(void) { } //----------------------------------------------------------------------------- void KMTopLevelWidget::writeConfig(void) { } #include "kmtopwidget.moc" <|endoftext|>
<commit_before>/** * linklocator.cpp * * Copyright (c) 2002 Dave Corrie <kde@davecorrie.com> * * This file is part of KMail. * * KMail is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "linklocator.h" LinkLocator::LinkLocator(const QString& text, int pos) : mText(text), mPos(pos), mMaxUrlLen(4096), mMaxAddressLen(255) { // If you change either of the above values for maxUrlLen or // maxAddressLen, then please also update the documentation for // setMaxUrlLen()/setMaxAddressLen() in the header file AND the // default values used for the maxUrlLen/maxAddressLen parameters // of convertToHtml(). } void LinkLocator::setMaxUrlLen(int length) { mMaxUrlLen = length; } int LinkLocator::maxUrlLen() const { return mMaxUrlLen; } void LinkLocator::setMaxAddressLen(int length) { mMaxAddressLen = length; } int LinkLocator::maxAddressLen() const { return mMaxAddressLen; } QString LinkLocator::getUrl() { QString url; if(atUrl()) { // handle cases like this: <link>http://foobar.org/</link> int start = mPos; while(mPos < (int)mText.length() && mText[mPos] > ' ' && mText[mPos] != '"' && QString("<>()[]").find(mText[mPos]) == -1) { ++mPos; } /* some URLs really end with: # / & */ const QString allowedSpecialChars = QString("#/&"); while(mPos > start && mText[mPos-1].isPunct() && allowedSpecialChars.find(mText[mPos-1]) == -1 ) { --mPos; } url = mText.mid(start, mPos - start); if(isEmptyUrl(url) || mPos - start > maxUrlLen()) { mPos = start; url = ""; } else { --mPos; } } return url; } // keep this in sync with KMMainWin::slotUrlClicked() bool LinkLocator::atUrl() const { // the character directly before the URL must not be a letter, a number or // a dot if( ( mPos > 0 ) && ( mText[mPos-1].isLetterOrNumber() || ( mText[mPos-1] == '.' ) ) ) return false; QChar ch = mText[mPos]; return (ch=='h' && mText.mid(mPos, 7) == "http://") || (ch=='h' && mText.mid(mPos, 8) == "https://") || (ch=='v' && mText.mid(mPos, 6) == "vnc://") || (ch=='f' && ( mText.mid(mPos, 6) == "ftp://" || mText.mid(mPos, 7) == "ftps://") ) || (ch=='s' && mText.mid(mPos, 7) == "sftp://") || (ch=='s' && mText.mid(mPos, 6) == "smb://") || (ch=='m' && mText.mid(mPos, 7) == "mailto:") || (ch=='w' && mText.mid(mPos, 4) == "www.") || (ch=='f' && mText.mid(mPos, 4) == "ftp."); // note: no "file:" for security reasons } bool LinkLocator::isEmptyUrl(const QString& url) { return url.isEmpty() || url == "http://" || url == "https://" || url == "ftp://" || url == "ftps://" || url == "sftp://" || url == "smb://" || url == "vnc://" || url == "mailto" || url == "www" || url == "ftp"; } QString LinkLocator::getEmailAddress() { QString address; if(mText[mPos] == '@') { // the following characters are allowed in a dot-atom (RFC 2822): // a-z A-Z 0-9 . ! # $ % & ' * + - / = ? ^ _ ` { | } ~ const QString allowedSpecialChars = QString(".!#$%&'*+-/=?^_`{|}~"); // determine the local part of the email address int start = mPos - 1; while (start >= 0 && mText[start].unicode() < 128 && (mText[start].isLetterOrNumber() || mText[start] == '@' || // allow @ to find invalid email addresses allowedSpecialChars.find(mText[start]) != -1)) { --start; } ++start; // we assume that an email address starts with a letter or a digit while (allowedSpecialChars.find(mText[start]) != -1) ++start; // determine the domain part of the email address int end = mPos + 1; while (end < (int)mText.length() && mText[end].unicode() < 128 && (mText[end].isLetterOrNumber() || mText[end] == '@' || // allow @ to find invalid email addresses allowedSpecialChars.find(mText[end]) != -1)) { ++end; } // we assume that an email address ends with a letter or a digit while (allowedSpecialChars.find(mText[end - 1]) != -1) --end; address = mText.mid(start, end - start); if(isEmptyAddress(address) || end - start > maxAddressLen() || address.contains('@') != 1) address = ""; if(!address.isEmpty()) mPos = end - 1; } return address; } bool LinkLocator::isEmptyAddress(const QString& address) { return address.isEmpty() || address[0] == '@' || address[address.length() - 1] == '@'; } QString LinkLocator::convertToHtml(const QString& plainText, bool preserveBlanks, int maxUrlLen, int maxAddressLen) { LinkLocator locator(plainText); locator.setMaxUrlLen(maxUrlLen); locator.setMaxAddressLen(maxAddressLen); QString str; QString result((QChar*)0, (int)locator.mText.length() * 2); QChar ch; int x; bool startOfLine = true; for (locator.mPos = 0, x = 0; locator.mPos < (int)locator.mText.length(); locator.mPos++, x++) { ch = locator.mText[locator.mPos]; if (preserveBlanks) { if (ch==' ') { if (startOfLine) { result += "&nbsp;"; locator.mPos++, x++; startOfLine = false; } while (locator.mText[locator.mPos] == ' ') { result += " "; locator.mPos++, x++; if (locator.mText[locator.mPos] == ' ') { result += "&nbsp;"; locator.mPos++, x++; } } locator.mPos--, x--; continue; } else if (ch=='\t') { do { result += "&nbsp;"; x++; } while((x&7) != 0); x--; startOfLine = false; continue; } } if (ch=='\n') { result += "<br />"; startOfLine = true; x = -1; continue; } startOfLine = false; if (ch=='&') result += "&amp;"; else if (ch=='"') result += "&quot;"; else if (ch=='<') result += "&lt;"; else if (ch=='>') result += "&gt;"; else { int start = locator.mPos; str = locator.getUrl(); if(!str.isEmpty()) { QString hyperlink; if(str.left(4) == "www.") hyperlink = "http://" + str; else if(str.left(4) == "ftp.") hyperlink = "ftp://" + str; else hyperlink = str; result += "<a href=\"" + hyperlink + "\">" + str + "</a>"; x += locator.mPos - start; } else { str = locator.getEmailAddress(); if(!str.isEmpty()) { // len is the length of the local part int len = str.find('@'); QString localPart = str.left(len); // remove the local part from the result (as '&'s have been expanded to // &amp; we have to take care of the 4 additional characters per '&') result.truncate(result.length() - len - (localPart.contains('&')*4)); x -= len; result += "<a href=\"mailto:" + str + "\">" + str + "</a>"; x += str.length() - 1; } else { result += ch; } } } } return result; } <commit_msg>Using QChar::isWhiteSpace doesn't work as we might want to highlight things like <link>www.domain.de</link>. However, if the last character is valid inside an URL let's assume it belongs to this URL.<commit_after>/** * linklocator.cpp * * Copyright (c) 2002 Dave Corrie <kde@davecorrie.com> * * This file is part of KMail. * * KMail is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "linklocator.h" LinkLocator::LinkLocator(const QString& text, int pos) : mText(text), mPos(pos), mMaxUrlLen(4096), mMaxAddressLen(255) { // If you change either of the above values for maxUrlLen or // maxAddressLen, then please also update the documentation for // setMaxUrlLen()/setMaxAddressLen() in the header file AND the // default values used for the maxUrlLen/maxAddressLen parameters // of convertToHtml(). } void LinkLocator::setMaxUrlLen(int length) { mMaxUrlLen = length; } int LinkLocator::maxUrlLen() const { return mMaxUrlLen; } void LinkLocator::setMaxAddressLen(int length) { mMaxAddressLen = length; } int LinkLocator::maxAddressLen() const { return mMaxAddressLen; } QString LinkLocator::getUrl() { QString url; if(atUrl()) { // handle cases like this: <link>http://foobar.org/</link> int start = mPos; while(mPos < (int)mText.length() && mText[mPos] > ' ' && mText[mPos] != '"' && QString("<>()[]").find(mText[mPos]) == -1) { ++mPos; } /* some URLs really end with: # / & */ const QString allowedSpecialChars = QString("#/&"); while(mPos > start && mText[mPos-1].isPunct() && allowedSpecialChars.find(mText[mPos-1]) == -1 ) { --mPos; } url = mText.mid(start, mPos - start); if(isEmptyUrl(url) || mPos - start > maxUrlLen()) { mPos = start; url = ""; } else { --mPos; } } return url; } // keep this in sync with KMMainWin::slotUrlClicked() bool LinkLocator::atUrl() const { // the following characters are allowed in a dot-atom (RFC 2822): // a-z A-Z 0-9 . ! # $ % & ' * + - / = ? ^ _ ` { | } ~ const QString allowedSpecialChars = QString(".!#$%&'*+-/=?^_`{|}~"); // the character directly before the URL must not be a letter, a number or any // other character allowed in a dot-atom (RFC 2822). if( ( mPos > 0 ) && ( mText[mPos-1].isLetterOrNumber() || ( allowedSpecialChars.find(mText[mPos-1]) != -1 ) ) ) return false; QChar ch = mText[mPos]; return (ch=='h' && mText.mid(mPos, 7) == "http://") || (ch=='h' && mText.mid(mPos, 8) == "https://") || (ch=='v' && mText.mid(mPos, 6) == "vnc://") || (ch=='f' && ( mText.mid(mPos, 6) == "ftp://" || mText.mid(mPos, 7) == "ftps://") ) || (ch=='s' && mText.mid(mPos, 7) == "sftp://") || (ch=='s' && mText.mid(mPos, 6) == "smb://") || (ch=='m' && mText.mid(mPos, 7) == "mailto:") || (ch=='w' && mText.mid(mPos, 4) == "www.") || (ch=='f' && mText.mid(mPos, 4) == "ftp."); // note: no "file:" for security reasons } bool LinkLocator::isEmptyUrl(const QString& url) { return url.isEmpty() || url == "http://" || url == "https://" || url == "ftp://" || url == "ftps://" || url == "sftp://" || url == "smb://" || url == "vnc://" || url == "mailto" || url == "www" || url == "ftp"; } QString LinkLocator::getEmailAddress() { QString address; if(mText[mPos] == '@') { // the following characters are allowed in a dot-atom (RFC 2822): // a-z A-Z 0-9 . ! # $ % & ' * + - / = ? ^ _ ` { | } ~ const QString allowedSpecialChars = QString(".!#$%&'*+-/=?^_`{|}~"); // determine the local part of the email address int start = mPos - 1; while (start >= 0 && mText[start].unicode() < 128 && (mText[start].isLetterOrNumber() || mText[start] == '@' || // allow @ to find invalid email addresses allowedSpecialChars.find(mText[start]) != -1)) { --start; } ++start; // we assume that an email address starts with a letter or a digit while (allowedSpecialChars.find(mText[start]) != -1) ++start; // determine the domain part of the email address int end = mPos + 1; while (end < (int)mText.length() && mText[end].unicode() < 128 && (mText[end].isLetterOrNumber() || mText[end] == '@' || // allow @ to find invalid email addresses allowedSpecialChars.find(mText[end]) != -1)) { ++end; } // we assume that an email address ends with a letter or a digit while (allowedSpecialChars.find(mText[end - 1]) != -1) --end; address = mText.mid(start, end - start); if(isEmptyAddress(address) || end - start > maxAddressLen() || address.contains('@') != 1) address = ""; if(!address.isEmpty()) mPos = end - 1; } return address; } bool LinkLocator::isEmptyAddress(const QString& address) { return address.isEmpty() || address[0] == '@' || address[address.length() - 1] == '@'; } QString LinkLocator::convertToHtml(const QString& plainText, bool preserveBlanks, int maxUrlLen, int maxAddressLen) { LinkLocator locator(plainText); locator.setMaxUrlLen(maxUrlLen); locator.setMaxAddressLen(maxAddressLen); QString str; QString result((QChar*)0, (int)locator.mText.length() * 2); QChar ch; int x; bool startOfLine = true; for (locator.mPos = 0, x = 0; locator.mPos < (int)locator.mText.length(); locator.mPos++, x++) { ch = locator.mText[locator.mPos]; if (preserveBlanks) { if (ch==' ') { if (startOfLine) { result += "&nbsp;"; locator.mPos++, x++; startOfLine = false; } while (locator.mText[locator.mPos] == ' ') { result += " "; locator.mPos++, x++; if (locator.mText[locator.mPos] == ' ') { result += "&nbsp;"; locator.mPos++, x++; } } locator.mPos--, x--; continue; } else if (ch=='\t') { do { result += "&nbsp;"; x++; } while((x&7) != 0); x--; startOfLine = false; continue; } } if (ch=='\n') { result += "<br />"; startOfLine = true; x = -1; continue; } startOfLine = false; if (ch=='&') result += "&amp;"; else if (ch=='"') result += "&quot;"; else if (ch=='<') result += "&lt;"; else if (ch=='>') result += "&gt;"; else { int start = locator.mPos; str = locator.getUrl(); if(!str.isEmpty()) { QString hyperlink; if(str.left(4) == "www.") hyperlink = "http://" + str; else if(str.left(4) == "ftp.") hyperlink = "ftp://" + str; else hyperlink = str; result += "<a href=\"" + hyperlink + "\">" + str + "</a>"; x += locator.mPos - start; } else { str = locator.getEmailAddress(); if(!str.isEmpty()) { // len is the length of the local part int len = str.find('@'); QString localPart = str.left(len); // remove the local part from the result (as '&'s have been expanded to // &amp; we have to take care of the 4 additional characters per '&') result.truncate(result.length() - len - (localPart.contains('&')*4)); x -= len; result += "<a href=\"mailto:" + str + "\">" + str + "</a>"; x += str.length() - 1; } else { result += ch; } } } } return result; } <|endoftext|>
<commit_before>#include "Network.IRC.Server.hpp" #include "Network.IRC.Replies.hpp" #include <QtCore/QDebug> #include <QtCore/QCoreApplication> #include <QtCore/QRegularExpression> namespace Network { namespace IRC { Server::Server(QString hostname, int port, QObject *parent) : QObject(parent), socket(new QSslSocket(this)), hostname(hostname), port(port) { QObject::connect(this->socket, SIGNAL(readyRead()), this, SLOT(readData())); QObject::connect(this->socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslError(QList<QSslError>))); QObject::connect(this, SIGNAL(ping(QString)), SLOT(pong(QString))); QObject::connect(this, SIGNAL(newCommand(IrcCommand)), this, SLOT(ircCommand(IrcCommand))); } Server::~Server() { qDebug() << "Closing socket..."; this->socket->close(); delete this->socket; } // public functions void Server::connect(QString nickname, QString realname, bool encrypted) { qDebug() << "Connecting to host" << this->hostname << "on port" << this->port << "..."; if (encrypted) { this->socket->connectToHostEncrypted(this->hostname, this->port); } else { this->socket->connectToHost(this->hostname, this->port); } // Send NICK command this->nick(nickname); qDebug() << "Sending USER command..."; QString userCommand = QString("USER %1 0 * :%2\r\n").arg(nickname).arg(realname); this->socket->write(userCommand.toStdString().c_str()); } // private slots/functions void Server::sslError(QList<QSslError> listOfErrors) { for(QSslError error : listOfErrors) { if(error.error() == QSslError::SelfSignedCertificate) { qWarning() << "Self-signed certificate. Proceeding anyway..."; this->socket->ignoreSslErrors(); return; } qCritical() << "Unknown SSL error!" << error.errorString(); } } void Server::pong(QString id) { qDebug() << "PING recived! Sending PONG..."; QString pongCommand = QString("PONG :%1\r\n").arg(id); this->socket->write(pongCommand.toStdString().c_str()); } void Server::join(QString channel) { qDebug() << "Sending JOIN command. Joining channel" << channel << "..."; if(!channel.startsWith('#')) { channel = channel.prepend('#'); } QString joinCommand = QString("JOIN :%1\r\n").arg(channel); this->socket->write(joinCommand.toStdString().c_str()); } void Server::nick(QString nickname) { qDebug() << "Sending NICK command. New nickname will be " << nickname; QString nickCommand = QString("NICK %1\r\n").arg(nickname); this->socket->write(nickCommand.toStdString().c_str()); } void Server::ircCommand(const IrcCommand &command) { } void Server::readData() { // Get all incoming data and split it by line QList<QByteArray> input = this->socket->readAll().replace("\r", "").split('\n'); // Parse each line of the incoming data for(QByteArray command : input) { if(command.isEmpty()) { continue; } // Source http://www.mybuddymichael.com/writings/a-regular-expression-for-irc-messages.html // Modified slightly so we have named capture groups QRegularExpression input(R"(^(?:[:](?<from>\S+) )?(?<command>\S+)(?: (?!:)(?<recipient>.+?))?(?: [:](?<message>.+))?$)"); QRegularExpressionMatch matchedInput = input.match(command); IrcCommand recivedCommand; if(matchedInput.hasMatch()) { recivedCommand.from = matchedInput.captured("from"); recivedCommand.code_command = matchedInput.captured("command"); recivedCommand.to = matchedInput.captured("recipient"); recivedCommand.message = matchedInput.captured("message"); } else { qWarning() << "Not a valid IRC Command!"; continue; } /* qDebug() << "Parsing command" << command; qDebug() << "Sender:" << matchedInput.captured("from"); qDebug() << "Command/Code:" << matchedInput.captured("command"); qDebug() << "Recipient:" << matchedInput.captured("recipient"); qDebug() << "Message:" << matchedInput.captured("message"); */ // Reply to PING requests if(recivedCommand.code_command.toLower() == "ping") { emit ping(QString(command.mid(6))); continue; } // Check if we are connected successfully if(recivedCommand.code_command.toInt() == CommandResponse::RPL_ENDOFMOTD) { qDebug() << "Recived response 376 (End of MOTD)"; emit connected(); continue; } emit newCommand(recivedCommand); } } } } <commit_msg>Changed QT signal-slot syntax<commit_after>#include "Network.IRC.Server.hpp" #include "Network.IRC.Replies.hpp" #include <QtCore/QDebug> #include <QtCore/QCoreApplication> #include <QtCore/QRegularExpression> namespace Network { namespace IRC { Server::Server(QString hostname, int port, QObject *parent) : QObject(parent), socket(new QSslSocket(this)), hostname(hostname), port(port) { QObject::connect(this->socket, &QSslSocket::readyRead, this, &Server::readData); // Cast because signal is overloaded void (QSslSocket:: *sslError)(const QList<QSslError> &error) = &QSslSocket::sslErrors; QObject::connect(this->socket, sslError, this, &Server::sslError); QObject::connect(this, &Server::ping, &Server::pong); QObject::connect(this, &Server::newCommand, &Server::ircCommand); } Server::~Server() { qDebug() << "Closing socket..."; this->socket->close(); delete this->socket; } // public functions void Server::connect(QString nickname, QString realname, bool encrypted) { qDebug() << "Connecting to host" << this->hostname << "on port" << this->port << "..."; if (encrypted) { this->socket->connectToHostEncrypted(this->hostname, this->port); } else { this->socket->connectToHost(this->hostname, this->port); } // Send NICK command this->nick(nickname); qDebug() << "Sending USER command..."; QString userCommand = QString("USER %1 0 * :%2\r\n").arg(nickname).arg(realname); this->socket->write(userCommand.toStdString().c_str()); } // private slots/functions void Server::sslError(QList<QSslError> listOfErrors) { for(QSslError error : listOfErrors) { if(error.error() == QSslError::SelfSignedCertificate) { qWarning() << "Self-signed certificate. Proceeding anyway..."; this->socket->ignoreSslErrors(); return; } qCritical() << "Unknown SSL error!" << error.errorString(); } } void Server::pong(QString id) { qDebug() << "PING recived! Sending PONG..."; QString pongCommand = QString("PONG :%1\r\n").arg(id); this->socket->write(pongCommand.toStdString().c_str()); } void Server::join(QString channel) { qDebug() << "Sending JOIN command. Joining channel" << channel << "..."; if(!channel.startsWith('#')) { channel = channel.prepend('#'); } QString joinCommand = QString("JOIN :%1\r\n").arg(channel); this->socket->write(joinCommand.toStdString().c_str()); } void Server::nick(QString nickname) { qDebug() << "Sending NICK command. New nickname will be " << nickname; QString nickCommand = QString("NICK %1\r\n").arg(nickname); this->socket->write(nickCommand.toStdString().c_str()); } void Server::ircCommand(const IrcCommand &command) { } void Server::readData() { // Get all incoming data and split it by line QList<QByteArray> input = this->socket->readAll().replace("\r", "").split('\n'); // Parse each line of the incoming data for(QByteArray command : input) { if(command.isEmpty()) { continue; } // Source http://www.mybuddymichael.com/writings/a-regular-expression-for-irc-messages.html // Modified slightly so we have named capture groups QRegularExpression input(R"(^(?:[:](?<from>\S+) )?(?<command>\S+)(?: (?!:)(?<recipient>.+?))?(?: [:](?<message>.+))?$)"); QRegularExpressionMatch matchedInput = input.match(command); IrcCommand recivedCommand; if(matchedInput.hasMatch()) { recivedCommand.from = matchedInput.captured("from"); recivedCommand.code_command = matchedInput.captured("command"); recivedCommand.to = matchedInput.captured("recipient"); recivedCommand.message = matchedInput.captured("message"); } else { qWarning() << "Not a valid IRC Command!"; continue; } /* qDebug() << "Parsing command" << command; qDebug() << "Sender:" << matchedInput.captured("from"); qDebug() << "Command/Code:" << matchedInput.captured("command"); qDebug() << "Recipient:" << matchedInput.captured("recipient"); qDebug() << "Message:" << matchedInput.captured("message"); */ // Reply to PING requests if(recivedCommand.code_command.toLower() == "ping") { emit ping(QString(command.mid(6))); continue; } // Check if we are connected successfully if(recivedCommand.code_command.toInt() == CommandResponse::RPL_ENDOFMOTD) { qDebug() << "Recived response 376 (End of MOTD)"; emit connected(); continue; } emit newCommand(recivedCommand); } } } } <|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. * */ #include <quic/codec/Types.h> #include <quic/QuicException.h> namespace quic { LongHeaderInvariant::LongHeaderInvariant( QuicVersion ver, ConnectionId scid, ConnectionId dcid) : version(ver), srcConnId(std::move(scid)), dstConnId(std::move(dcid)) {} HeaderForm getHeaderForm(uint8_t headerValue) { if (headerValue & kHeaderFormMask) { return HeaderForm::Long; } return HeaderForm::Short; } PacketHeader::PacketHeader(ShortHeader&& shortHeaderIn) : headerForm_(HeaderForm::Short) { new (&shortHeader) ShortHeader(std::move(shortHeaderIn)); } PacketHeader::PacketHeader(LongHeader&& longHeaderIn) : headerForm_(HeaderForm::Long) { new (&longHeader) LongHeader(std::move(longHeaderIn)); } PacketHeader::PacketHeader(const PacketHeader& other) : headerForm_(other.headerForm_) { switch (other.headerForm_) { case HeaderForm::Long: new (&longHeader) LongHeader(other.longHeader); break; case HeaderForm::Short: new (&shortHeader) ShortHeader(other.shortHeader); break; } } PacketHeader::PacketHeader(PacketHeader&& other) noexcept : headerForm_(other.headerForm_) { switch (other.headerForm_) { case HeaderForm::Long: new (&longHeader) LongHeader(std::move(other.longHeader)); break; case HeaderForm::Short: new (&shortHeader) ShortHeader(std::move(other.shortHeader)); break; } } PacketHeader& PacketHeader::operator=(PacketHeader&& other) noexcept { destroyHeader(); switch (other.headerForm_) { case HeaderForm::Long: new (&longHeader) LongHeader(std::move(other.longHeader)); break; case HeaderForm::Short: new (&shortHeader) ShortHeader(std::move(other.shortHeader)); break; } headerForm_ = other.headerForm_; return *this; } PacketHeader& PacketHeader::operator=(const PacketHeader& other) { destroyHeader(); switch (other.headerForm_) { case HeaderForm::Long: new (&longHeader) LongHeader(other.longHeader); break; case HeaderForm::Short: new (&shortHeader) ShortHeader(other.shortHeader); break; } headerForm_ = other.headerForm_; return *this; } PacketHeader::~PacketHeader() { destroyHeader(); } void PacketHeader::destroyHeader() { switch (headerForm_) { case HeaderForm::Long: longHeader.~LongHeader(); break; case HeaderForm::Short: shortHeader.~ShortHeader(); break; } } LongHeader* PacketHeader::asLong() { switch (headerForm_) { case HeaderForm::Long: return &longHeader; case HeaderForm::Short: return nullptr; } } ShortHeader* PacketHeader::asShort() { switch (headerForm_) { case HeaderForm::Long: return nullptr; case HeaderForm::Short: return &shortHeader; } } const LongHeader* PacketHeader::asLong() const { switch (headerForm_) { case HeaderForm::Long: return &longHeader; case HeaderForm::Short: return nullptr; } } const ShortHeader* PacketHeader::asShort() const { switch (headerForm_) { case HeaderForm::Long: return nullptr; case HeaderForm::Short: return &shortHeader; } } PacketNum PacketHeader::getPacketSequenceNum() const { switch (headerForm_) { case HeaderForm::Long: return longHeader.getPacketSequenceNum(); case HeaderForm::Short: return shortHeader.getPacketSequenceNum(); } } HeaderForm PacketHeader::getHeaderForm() const { return headerForm_; } ProtectionType PacketHeader::getProtectionType() const { switch (headerForm_) { case HeaderForm::Long: return longHeader.getProtectionType(); case HeaderForm::Short: return shortHeader.getProtectionType(); } } PacketNumberSpace PacketHeader::getPacketNumberSpace() const { switch (headerForm_) { case HeaderForm::Long: return longHeader.getPacketNumberSpace(); case HeaderForm::Short: return shortHeader.getPacketNumberSpace(); } } LongHeader::LongHeader( Types type, LongHeaderInvariant invariant, const std::string& token, folly::Optional<ConnectionId> originalDstConnId) : longHeaderType_(type), invariant_(std::move(invariant)), token_(token), originalDstConnId_(originalDstConnId) {} LongHeader::LongHeader( Types type, const ConnectionId& srcConnId, const ConnectionId& dstConnId, PacketNum packetNum, QuicVersion version, const std::string& token, folly::Optional<ConnectionId> originalDstConnId) : longHeaderType_(type), invariant_(LongHeaderInvariant(version, srcConnId, dstConnId)), token_(token), originalDstConnId_(originalDstConnId) { setPacketNumber(packetNum); } LongHeader::Types LongHeader::getHeaderType() const noexcept { return longHeaderType_; } const ConnectionId& LongHeader::getSourceConnId() const { return invariant_.srcConnId; } const ConnectionId& LongHeader::getDestinationConnId() const { return invariant_.dstConnId; } const folly::Optional<ConnectionId>& LongHeader::getOriginalDstConnId() const { return originalDstConnId_; } QuicVersion LongHeader::getVersion() const { return invariant_.version; } bool LongHeader::hasToken() const { return !token_.empty(); } const std::string& LongHeader::getToken() const { return token_; } PacketNum LongHeader::getPacketSequenceNum() const { return packetSequenceNum_; } void LongHeader::setPacketNumber(PacketNum packetNum) { packetSequenceNum_ = packetNum; } ProtectionType LongHeader::getProtectionType() const { return longHeaderTypeToProtectionType(getHeaderType()); } PacketNumberSpace LongHeader::getPacketNumberSpace() const { return longHeaderTypeToPacketNumberSpace(getHeaderType()); } ProtectionType longHeaderTypeToProtectionType( LongHeader::Types longHeaderType) { switch (longHeaderType) { case LongHeader::Types::Initial: case LongHeader::Types::Retry: return ProtectionType::Initial; case LongHeader::Types::Handshake: return ProtectionType::Handshake; case LongHeader::Types::ZeroRtt: return ProtectionType::ZeroRtt; } folly::assume_unreachable(); } ShortHeaderInvariant::ShortHeaderInvariant(ConnectionId dcid) : destinationConnId(std::move(dcid)) {} PacketNumberSpace longHeaderTypeToPacketNumberSpace( LongHeader::Types longHeaderType) { switch (longHeaderType) { case LongHeader::Types::Initial: case LongHeader::Types::Retry: return PacketNumberSpace::Initial; case LongHeader::Types::Handshake: return PacketNumberSpace::Handshake; case LongHeader::Types::ZeroRtt: return PacketNumberSpace::AppData; } folly::assume_unreachable(); } ShortHeader::ShortHeader( ProtectionType protectionType, ConnectionId connId, PacketNum packetNum) : protectionType_(protectionType), connectionId_(std::move(connId)) { if (protectionType_ != ProtectionType::KeyPhaseZero && protectionType_ != ProtectionType::KeyPhaseOne) { throw QuicInternalException( "bad short header protection type", LocalErrorCode::CODEC_ERROR); } setPacketNumber(packetNum); } ShortHeader::ShortHeader(ProtectionType protectionType, ConnectionId connId) : protectionType_(protectionType), connectionId_(std::move(connId)) { if (protectionType_ != ProtectionType::KeyPhaseZero && protectionType_ != ProtectionType::KeyPhaseOne) { throw QuicInternalException( "bad short header protection type", LocalErrorCode::CODEC_ERROR); } } ProtectionType ShortHeader::getProtectionType() const { return protectionType_; } PacketNumberSpace ShortHeader::getPacketNumberSpace() const { return PacketNumberSpace::AppData; } const ConnectionId& ShortHeader::getConnectionId() const { return connectionId_; } PacketNum ShortHeader::getPacketSequenceNum() const { return packetSequenceNum_; } void ShortHeader::setPacketNumber(PacketNum packetNum) { packetSequenceNum_ = packetNum; } bool StreamTypeField::hasDataLength() const { return field_ & kDataLengthBit; } bool StreamTypeField::hasFin() const { return field_ & kFinBit; } bool StreamTypeField::hasOffset() const { return field_ & kOffsetBit; } uint8_t StreamTypeField::fieldValue() const { return field_; } StreamTypeField::Builder& StreamTypeField::Builder::setFin() { field_ |= StreamTypeField::kFinBit; return *this; } StreamTypeField::Builder& StreamTypeField::Builder::setOffset() { field_ |= StreamTypeField::kOffsetBit; return *this; } StreamTypeField::Builder& StreamTypeField::Builder::setLength() { field_ |= StreamTypeField::kDataLengthBit; return *this; } StreamTypeField StreamTypeField::Builder::build() { return StreamTypeField(field_); } std::string toString(PacketNumberSpace pnSpace) { switch (pnSpace) { case PacketNumberSpace::Initial: return "InitialSpace"; case PacketNumberSpace::Handshake: return "HandshakeSpace"; case PacketNumberSpace::AppData: return "AppDataSpace"; } CHECK(false) << "Unknown packet number space"; folly::assume_unreachable(); } std::string toString(ProtectionType protectionType) { switch (protectionType) { case ProtectionType::Initial: return "Initial"; case ProtectionType::Handshake: return "Handshake"; case ProtectionType::ZeroRtt: return "ZeroRtt"; case ProtectionType::KeyPhaseZero: return "KeyPhaseZero"; case ProtectionType::KeyPhaseOne: return "KeyPhaseOne"; } CHECK(false) << "Unknown protection type"; folly::assume_unreachable(); } std::string toString(FrameType frame) { switch (frame) { case FrameType::PADDING: return "PADDING"; case FrameType::PING: return "PING"; case FrameType::ACK: return "ACK"; case FrameType::ACK_ECN: return "ACK_ECN"; case FrameType::RST_STREAM: return "RST_STREAM"; case FrameType::STOP_SENDING: return "STOP_SENDING"; case FrameType::CRYPTO_FRAME: return "CRYPTO_FRAME"; case FrameType::NEW_TOKEN: return "NEW_TOKEN"; case FrameType::STREAM: case FrameType::STREAM_FIN: case FrameType::STREAM_LEN: case FrameType::STREAM_LEN_FIN: case FrameType::STREAM_OFF: case FrameType::STREAM_OFF_FIN: case FrameType::STREAM_OFF_LEN: case FrameType::STREAM_OFF_LEN_FIN: return "STREAM"; case FrameType::MAX_DATA: return "MAX_DATA"; case FrameType::MAX_STREAM_DATA: return "MAX_STREAM_DATA"; case FrameType::MAX_STREAMS_BIDI: return "MAX_STREAMS_BIDI"; case FrameType::MAX_STREAMS_UNI: return "MAX_STREAMS_UNI"; case FrameType::DATA_BLOCKED: return "DATA_BLOCKED"; case FrameType::STREAM_DATA_BLOCKED: return "STREAM_DATA_BLOCKED"; case FrameType::STREAMS_BLOCKED_BIDI: return "STREAMS_BLOCKED_BIDI"; case FrameType::STREAMS_BLOCKED_UNI: return "STREAMS_BLOCKED_UNI"; case FrameType::NEW_CONNECTION_ID: return "NEW_CONNECTION_ID"; case FrameType::RETIRE_CONNECTION_ID: return "RETIRE_CONNECTION_ID"; case FrameType::PATH_CHALLENGE: return "PATH_CHALLENGE"; case FrameType::PATH_RESPONSE: return "PATH_RESPONSE"; case FrameType::CONNECTION_CLOSE: return "CONNECTION_CLOSE"; case FrameType::APPLICATION_CLOSE: return "APPLICATION_CLOSE"; case FrameType::MIN_STREAM_DATA: return "MIN_STREAM_DATA"; case FrameType::EXPIRED_STREAM_DATA: return "EXPIRED_STREAM_DATA"; } LOG(WARNING) << "toString has unhandled frame type"; return "UNKNOWN"; } std::string toString(QuicVersion version) { switch (version) { case QuicVersion::VERSION_NEGOTIATION: return "VERSION_NEGOTIATION"; case QuicVersion::MVFST_OLD: return "MVFST_OLD"; case QuicVersion::MVFST: return "MVFST"; case QuicVersion::QUIC_DRAFT_22: return "QUIC_DRAFT_22"; case QuicVersion::QUIC_DRAFT: return "QUIC_DRAFT"; case QuicVersion::MVFST_INVALID: return "MVFST_INVALID"; } LOG(WARNING) << "toString has unhandled version type"; return "UNKNOWN"; } std::string toString(LongHeader::Types type) { switch (type) { case LongHeader::Types::Initial: return "INITIAL"; case LongHeader::Types::Retry: return "RETRY"; case LongHeader::Types::Handshake: return "HANDSHAKE"; case LongHeader::Types::ZeroRtt: return "ZERORTT"; } LOG(WARNING) << "toString has unhandled long header type"; return "UNKNOWN"; } } // namespace quic <commit_msg>Fix MSVC warnings in quic (default branch)<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. * */ #include <quic/codec/Types.h> #include <quic/QuicException.h> namespace quic { LongHeaderInvariant::LongHeaderInvariant( QuicVersion ver, ConnectionId scid, ConnectionId dcid) : version(ver), srcConnId(std::move(scid)), dstConnId(std::move(dcid)) {} HeaderForm getHeaderForm(uint8_t headerValue) { if (headerValue & kHeaderFormMask) { return HeaderForm::Long; } return HeaderForm::Short; } PacketHeader::PacketHeader(ShortHeader&& shortHeaderIn) : headerForm_(HeaderForm::Short) { new (&shortHeader) ShortHeader(std::move(shortHeaderIn)); } PacketHeader::PacketHeader(LongHeader&& longHeaderIn) : headerForm_(HeaderForm::Long) { new (&longHeader) LongHeader(std::move(longHeaderIn)); } PacketHeader::PacketHeader(const PacketHeader& other) : headerForm_(other.headerForm_) { switch (other.headerForm_) { case HeaderForm::Long: new (&longHeader) LongHeader(other.longHeader); break; case HeaderForm::Short: new (&shortHeader) ShortHeader(other.shortHeader); break; } } PacketHeader::PacketHeader(PacketHeader&& other) noexcept : headerForm_(other.headerForm_) { switch (other.headerForm_) { case HeaderForm::Long: new (&longHeader) LongHeader(std::move(other.longHeader)); break; case HeaderForm::Short: new (&shortHeader) ShortHeader(std::move(other.shortHeader)); break; } } PacketHeader& PacketHeader::operator=(PacketHeader&& other) noexcept { destroyHeader(); switch (other.headerForm_) { case HeaderForm::Long: new (&longHeader) LongHeader(std::move(other.longHeader)); break; case HeaderForm::Short: new (&shortHeader) ShortHeader(std::move(other.shortHeader)); break; } headerForm_ = other.headerForm_; return *this; } PacketHeader& PacketHeader::operator=(const PacketHeader& other) { destroyHeader(); switch (other.headerForm_) { case HeaderForm::Long: new (&longHeader) LongHeader(other.longHeader); break; case HeaderForm::Short: new (&shortHeader) ShortHeader(other.shortHeader); break; } headerForm_ = other.headerForm_; return *this; } PacketHeader::~PacketHeader() { destroyHeader(); } void PacketHeader::destroyHeader() { switch (headerForm_) { case HeaderForm::Long: longHeader.~LongHeader(); break; case HeaderForm::Short: shortHeader.~ShortHeader(); break; } } LongHeader* PacketHeader::asLong() { switch (headerForm_) { case HeaderForm::Long: return &longHeader; case HeaderForm::Short: return nullptr; default: folly::assume_unreachable(); } } ShortHeader* PacketHeader::asShort() { switch (headerForm_) { case HeaderForm::Long: return nullptr; case HeaderForm::Short: return &shortHeader; default: folly::assume_unreachable(); } } const LongHeader* PacketHeader::asLong() const { switch (headerForm_) { case HeaderForm::Long: return &longHeader; case HeaderForm::Short: return nullptr; default: folly::assume_unreachable(); } } const ShortHeader* PacketHeader::asShort() const { switch (headerForm_) { case HeaderForm::Long: return nullptr; case HeaderForm::Short: return &shortHeader; default: folly::assume_unreachable(); } } PacketNum PacketHeader::getPacketSequenceNum() const { switch (headerForm_) { case HeaderForm::Long: return longHeader.getPacketSequenceNum(); case HeaderForm::Short: return shortHeader.getPacketSequenceNum(); default: folly::assume_unreachable(); } } HeaderForm PacketHeader::getHeaderForm() const { return headerForm_; } ProtectionType PacketHeader::getProtectionType() const { switch (headerForm_) { case HeaderForm::Long: return longHeader.getProtectionType(); case HeaderForm::Short: return shortHeader.getProtectionType(); default: folly::assume_unreachable(); } } PacketNumberSpace PacketHeader::getPacketNumberSpace() const { switch (headerForm_) { case HeaderForm::Long: return longHeader.getPacketNumberSpace(); case HeaderForm::Short: return shortHeader.getPacketNumberSpace(); default: folly::assume_unreachable(); } } LongHeader::LongHeader( Types type, LongHeaderInvariant invariant, const std::string& token, folly::Optional<ConnectionId> originalDstConnId) : longHeaderType_(type), invariant_(std::move(invariant)), token_(token), originalDstConnId_(originalDstConnId) {} LongHeader::LongHeader( Types type, const ConnectionId& srcConnId, const ConnectionId& dstConnId, PacketNum packetNum, QuicVersion version, const std::string& token, folly::Optional<ConnectionId> originalDstConnId) : longHeaderType_(type), invariant_(LongHeaderInvariant(version, srcConnId, dstConnId)), token_(token), originalDstConnId_(originalDstConnId) { setPacketNumber(packetNum); } LongHeader::Types LongHeader::getHeaderType() const noexcept { return longHeaderType_; } const ConnectionId& LongHeader::getSourceConnId() const { return invariant_.srcConnId; } const ConnectionId& LongHeader::getDestinationConnId() const { return invariant_.dstConnId; } const folly::Optional<ConnectionId>& LongHeader::getOriginalDstConnId() const { return originalDstConnId_; } QuicVersion LongHeader::getVersion() const { return invariant_.version; } bool LongHeader::hasToken() const { return !token_.empty(); } const std::string& LongHeader::getToken() const { return token_; } PacketNum LongHeader::getPacketSequenceNum() const { return packetSequenceNum_; } void LongHeader::setPacketNumber(PacketNum packetNum) { packetSequenceNum_ = packetNum; } ProtectionType LongHeader::getProtectionType() const { return longHeaderTypeToProtectionType(getHeaderType()); } PacketNumberSpace LongHeader::getPacketNumberSpace() const { return longHeaderTypeToPacketNumberSpace(getHeaderType()); } ProtectionType longHeaderTypeToProtectionType( LongHeader::Types longHeaderType) { switch (longHeaderType) { case LongHeader::Types::Initial: case LongHeader::Types::Retry: return ProtectionType::Initial; case LongHeader::Types::Handshake: return ProtectionType::Handshake; case LongHeader::Types::ZeroRtt: return ProtectionType::ZeroRtt; } folly::assume_unreachable(); } ShortHeaderInvariant::ShortHeaderInvariant(ConnectionId dcid) : destinationConnId(std::move(dcid)) {} PacketNumberSpace longHeaderTypeToPacketNumberSpace( LongHeader::Types longHeaderType) { switch (longHeaderType) { case LongHeader::Types::Initial: case LongHeader::Types::Retry: return PacketNumberSpace::Initial; case LongHeader::Types::Handshake: return PacketNumberSpace::Handshake; case LongHeader::Types::ZeroRtt: return PacketNumberSpace::AppData; } folly::assume_unreachable(); } ShortHeader::ShortHeader( ProtectionType protectionType, ConnectionId connId, PacketNum packetNum) : protectionType_(protectionType), connectionId_(std::move(connId)) { if (protectionType_ != ProtectionType::KeyPhaseZero && protectionType_ != ProtectionType::KeyPhaseOne) { throw QuicInternalException( "bad short header protection type", LocalErrorCode::CODEC_ERROR); } setPacketNumber(packetNum); } ShortHeader::ShortHeader(ProtectionType protectionType, ConnectionId connId) : protectionType_(protectionType), connectionId_(std::move(connId)) { if (protectionType_ != ProtectionType::KeyPhaseZero && protectionType_ != ProtectionType::KeyPhaseOne) { throw QuicInternalException( "bad short header protection type", LocalErrorCode::CODEC_ERROR); } } ProtectionType ShortHeader::getProtectionType() const { return protectionType_; } PacketNumberSpace ShortHeader::getPacketNumberSpace() const { return PacketNumberSpace::AppData; } const ConnectionId& ShortHeader::getConnectionId() const { return connectionId_; } PacketNum ShortHeader::getPacketSequenceNum() const { return packetSequenceNum_; } void ShortHeader::setPacketNumber(PacketNum packetNum) { packetSequenceNum_ = packetNum; } bool StreamTypeField::hasDataLength() const { return field_ & kDataLengthBit; } bool StreamTypeField::hasFin() const { return field_ & kFinBit; } bool StreamTypeField::hasOffset() const { return field_ & kOffsetBit; } uint8_t StreamTypeField::fieldValue() const { return field_; } StreamTypeField::Builder& StreamTypeField::Builder::setFin() { field_ |= StreamTypeField::kFinBit; return *this; } StreamTypeField::Builder& StreamTypeField::Builder::setOffset() { field_ |= StreamTypeField::kOffsetBit; return *this; } StreamTypeField::Builder& StreamTypeField::Builder::setLength() { field_ |= StreamTypeField::kDataLengthBit; return *this; } StreamTypeField StreamTypeField::Builder::build() { return StreamTypeField(field_); } std::string toString(PacketNumberSpace pnSpace) { switch (pnSpace) { case PacketNumberSpace::Initial: return "InitialSpace"; case PacketNumberSpace::Handshake: return "HandshakeSpace"; case PacketNumberSpace::AppData: return "AppDataSpace"; } CHECK(false) << "Unknown packet number space"; folly::assume_unreachable(); } std::string toString(ProtectionType protectionType) { switch (protectionType) { case ProtectionType::Initial: return "Initial"; case ProtectionType::Handshake: return "Handshake"; case ProtectionType::ZeroRtt: return "ZeroRtt"; case ProtectionType::KeyPhaseZero: return "KeyPhaseZero"; case ProtectionType::KeyPhaseOne: return "KeyPhaseOne"; } CHECK(false) << "Unknown protection type"; folly::assume_unreachable(); } std::string toString(FrameType frame) { switch (frame) { case FrameType::PADDING: return "PADDING"; case FrameType::PING: return "PING"; case FrameType::ACK: return "ACK"; case FrameType::ACK_ECN: return "ACK_ECN"; case FrameType::RST_STREAM: return "RST_STREAM"; case FrameType::STOP_SENDING: return "STOP_SENDING"; case FrameType::CRYPTO_FRAME: return "CRYPTO_FRAME"; case FrameType::NEW_TOKEN: return "NEW_TOKEN"; case FrameType::STREAM: case FrameType::STREAM_FIN: case FrameType::STREAM_LEN: case FrameType::STREAM_LEN_FIN: case FrameType::STREAM_OFF: case FrameType::STREAM_OFF_FIN: case FrameType::STREAM_OFF_LEN: case FrameType::STREAM_OFF_LEN_FIN: return "STREAM"; case FrameType::MAX_DATA: return "MAX_DATA"; case FrameType::MAX_STREAM_DATA: return "MAX_STREAM_DATA"; case FrameType::MAX_STREAMS_BIDI: return "MAX_STREAMS_BIDI"; case FrameType::MAX_STREAMS_UNI: return "MAX_STREAMS_UNI"; case FrameType::DATA_BLOCKED: return "DATA_BLOCKED"; case FrameType::STREAM_DATA_BLOCKED: return "STREAM_DATA_BLOCKED"; case FrameType::STREAMS_BLOCKED_BIDI: return "STREAMS_BLOCKED_BIDI"; case FrameType::STREAMS_BLOCKED_UNI: return "STREAMS_BLOCKED_UNI"; case FrameType::NEW_CONNECTION_ID: return "NEW_CONNECTION_ID"; case FrameType::RETIRE_CONNECTION_ID: return "RETIRE_CONNECTION_ID"; case FrameType::PATH_CHALLENGE: return "PATH_CHALLENGE"; case FrameType::PATH_RESPONSE: return "PATH_RESPONSE"; case FrameType::CONNECTION_CLOSE: return "CONNECTION_CLOSE"; case FrameType::APPLICATION_CLOSE: return "APPLICATION_CLOSE"; case FrameType::MIN_STREAM_DATA: return "MIN_STREAM_DATA"; case FrameType::EXPIRED_STREAM_DATA: return "EXPIRED_STREAM_DATA"; } LOG(WARNING) << "toString has unhandled frame type"; return "UNKNOWN"; } std::string toString(QuicVersion version) { switch (version) { case QuicVersion::VERSION_NEGOTIATION: return "VERSION_NEGOTIATION"; case QuicVersion::MVFST_OLD: return "MVFST_OLD"; case QuicVersion::MVFST: return "MVFST"; case QuicVersion::QUIC_DRAFT_22: return "QUIC_DRAFT_22"; case QuicVersion::QUIC_DRAFT: return "QUIC_DRAFT"; case QuicVersion::MVFST_INVALID: return "MVFST_INVALID"; } LOG(WARNING) << "toString has unhandled version type"; return "UNKNOWN"; } std::string toString(LongHeader::Types type) { switch (type) { case LongHeader::Types::Initial: return "INITIAL"; case LongHeader::Types::Retry: return "RETRY"; case LongHeader::Types::Handshake: return "HANDSHAKE"; case LongHeader::Types::ZeroRtt: return "ZERORTT"; } LOG(WARNING) << "toString has unhandled long header type"; return "UNKNOWN"; } } // namespace quic <|endoftext|>
<commit_before>/* This file is part of Kontact. Copyright (C) 2003 Tobias Koenig <tokoe@kde.org> Copyright (C) 2004 Reinhold Kainhofer <reinhold@kainhofer.com> 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; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <kaboutdata.h> #include <kgenericfactory.h> #include <kparts/componentfactory.h> #include "core.h" #include "summarywidget.h" #include "kpilot_plugin.h" #include "options.h" typedef KGenericFactory< KPilotPlugin, Kontact::Core > KPilotPluginFactory; K_EXPORT_COMPONENT_FACTORY( libkontact_kpilotplugin, KPilotPluginFactory( "kontact_kpilotplugin" ) ) KPilotPlugin::KPilotPlugin( Kontact::Core *core, const char *name, const QStringList& ) : Kontact::Plugin( core, core, name ), mAboutData( 0 ) { setInstance( KPilotPluginFactory::instance() ); // TODO: Make sure kpilotDaemon is running! } Kontact::Summary *KPilotPlugin::createSummaryWidget( QWidget *parentWidget ) { return new SummaryWidget( parentWidget ); } const KAboutData *KPilotPlugin::aboutData() { if ( !mAboutData ) { mAboutData = new KAboutData("kpilotplugin", I18N_NOOP("KPilot Information"), KPILOT_VERSION, I18N_NOOP("KPilot - HotSync software for KDE\n\n"), KAboutData::License_GPL, "(c) 2004 Reinhold Kainhofer"); mAboutData->addAuthor("Reinhold Kainhofer", I18N_NOOP("Plugin Developer"), "reinhold@kainhofer.com", "http://reinhold.kainhofer.com/Linux/"); mAboutData->addAuthor("Dan Pilone", I18N_NOOP("Project Leader"), 0, "http://www.kpilot.org/"); mAboutData->addAuthor("Adriaan de Groot", I18N_NOOP("Maintainer"), "groot@kde.org", "http://people.fruitsalad.org/adridg/"); } return mAboutData; } <commit_msg>Make sure the translation catalogue is loaded, by making sure we pass our correct name to the Kontact::Plugin base class. (proko2 issue 1087)<commit_after>/* This file is part of Kontact. Copyright (C) 2003 Tobias Koenig <tokoe@kde.org> Copyright (C) 2004 Reinhold Kainhofer <reinhold@kainhofer.com> 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; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <kaboutdata.h> #include <kgenericfactory.h> #include <kparts/componentfactory.h> #include "core.h" #include "summarywidget.h" #include "kpilot_plugin.h" #include "options.h" typedef KGenericFactory< KPilotPlugin, Kontact::Core > KPilotPluginFactory; K_EXPORT_COMPONENT_FACTORY( libkontact_kpilotplugin, KPilotPluginFactory( "kontact_kpilotplugin" ) ) KPilotPlugin::KPilotPlugin( Kontact::Core *core, const char *name, const QStringList& ) : Kontact::Plugin( core, core, "kpilot" ), mAboutData( 0 ) { setInstance( KPilotPluginFactory::instance() ); // TODO: Make sure kpilotDaemon is running! } Kontact::Summary *KPilotPlugin::createSummaryWidget( QWidget *parentWidget ) { return new SummaryWidget( parentWidget ); } const KAboutData *KPilotPlugin::aboutData() { if ( !mAboutData ) { mAboutData = new KAboutData("kpilotplugin", I18N_NOOP("KPilot Information"), KPILOT_VERSION, I18N_NOOP("KPilot - HotSync software for KDE\n\n"), KAboutData::License_GPL, "(c) 2004 Reinhold Kainhofer"); mAboutData->addAuthor("Reinhold Kainhofer", I18N_NOOP("Plugin Developer"), "reinhold@kainhofer.com", "http://reinhold.kainhofer.com/Linux/"); mAboutData->addAuthor("Dan Pilone", I18N_NOOP("Project Leader"), 0, "http://www.kpilot.org/"); mAboutData->addAuthor("Adriaan de Groot", I18N_NOOP("Maintainer"), "groot@kde.org", "http://people.fruitsalad.org/adridg/"); } return mAboutData; } <|endoftext|>
<commit_before><commit_msg>(Identical to 159254 which I had in a messed up client) Fix an off-by-one in the zip filename reading code. It's pretty harmless, and caused by a fairly lousy minizip API. It could lead to an out-of-bounds read due to lack of null termination. No way to reliably test.<commit_after><|endoftext|>
<commit_before>/** \brief Parses XML and generates MARC-21 data. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2016 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <list> #include <map> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "MarcUtil.h" #include "MarcXmlWriter.h" #include "MiscUtil.h" #include "RegexMatcher.h" #include "SimpleXmlParser.h" #include "StringUtil.h" #include "util.h" __attribute__((noreturn)) void Usage() { std::cerr << "Usage: " << ::progname << " [--verbose] --output-format=(marc_binary|marc_xml) config_file oai_pmh_dc_input marc_output\n"; std::exit(EXIT_FAILURE); } // An instance of this class specifies a rule for if and how to extract XML data and how to map it to a MARC-21 // field and subfield. class Matcher { std::string field_tag_; char subfield_code_; const RegexMatcher * const matching_regex_; const RegexMatcher * const extraction_regex_; public: Matcher(const std::string &field_tag, const char subfield_code, const RegexMatcher * const matching_regex = nullptr, const RegexMatcher * const extraction_regex = nullptr) : field_tag_(field_tag), subfield_code_(subfield_code), matching_regex_(matching_regex), extraction_regex_(extraction_regex) { } inline bool matched(const std::string &character_data) const { return (matching_regex_ == nullptr) ? true : matching_regex_->matched(character_data); } /** \return That part of the character data that ought to be inserted into a MARC record. */ std::string getInsertionData(const std::string &character_data) const; inline const std::string &getMarcFieldTag() const { return field_tag_; } inline char getMarcSubfieldCode() const { return subfield_code_; } }; std::string Matcher::getInsertionData(const std::string &character_data) const { if (extraction_regex_ == nullptr) return character_data; if (not extraction_regex_->matched(character_data)) return ""; return (*extraction_regex_)[1]; } // Expects the "string" that we extract to either contain no spaces or to be enclosed in double quotes. // Optional comments start with a hash sign. std::string ExtractOptionallyQuotedString(std::string::const_iterator &ch, const std::string::const_iterator &end) { if (ch == end) return ""; std::string extracted_string; if (*ch == '"') { // Extract quoted string. ++ch; bool escaped(false); while (ch != end and *ch != '"') { if (unlikely(escaped)) { escaped = false; extracted_string += *ch; } else if (unlikely(*ch == '\\')) escaped = true; else extracted_string += *ch; ++ch; } if (unlikely(*ch != '"')) throw std::runtime_error("missing closing quote!"); ++ch; } else { // Extract non-quoted string. while (ch != end and *ch != ' ') extracted_string += *ch++; } return extracted_string; } void SkipSpaces(std::string::const_iterator &ch, const std::string::const_iterator &end) { while (ch != end and *ch == ' ') ++ch; } // Loads a config file that specifies the mapping from XML elements to MARC fields. An entry looks like this // // xml_tag_name marc_field_and_subfield optional_match_regex optional_extraction_regex // // "xml_tag_name" is the tag for which the rule applies. "marc_field_and_subfield" is the field which gets created // when we have a match. "optional_match_regex" when present has to match the character data following the tag for // the rule to apply and "optional_extraction_regex" specifies which part of the data will be used (group 1). void LoadConfig(File * const input, std::map<std::string, std::list<Matcher>> * const xml_tag_to_marc_entry_map) { xml_tag_to_marc_entry_map->clear(); unsigned line_no(0); while (not input->eof()) { std::string line(input->getline()); ++line_no; // Process optional comment: const std::string::size_type first_hash_pos(line.find('#')); if (first_hash_pos != std::string::npos) line.resize(first_hash_pos); StringUtil::TrimWhite(&line); if (line.empty()) continue; try { auto ch(line.cbegin()); const auto end(line.cend()); SkipSpaces(ch, end); const std::string xml_tag(ExtractOptionallyQuotedString(ch, end)); if (unlikely(xml_tag.empty())) throw std::runtime_error("missing or empty XML tag!"); SkipSpaces(ch, end); const std::string marc_tag_and_subfield_code(ExtractOptionallyQuotedString(ch, end)); if (unlikely(marc_tag_and_subfield_code.length() != DirectoryEntry::TAG_LENGTH + 1)) throw std::runtime_error("bad MARC tag and subfield code!"); SkipSpaces(ch, end); RegexMatcher *matching_regex(nullptr), *extraction_regex(nullptr); if (ch != end) { const std::string matching_regex_string(ExtractOptionallyQuotedString(ch, end)); std::string err_msg; matching_regex = RegexMatcher::RegexMatcherFactory(matching_regex_string, &err_msg); if (unlikely(not err_msg.empty())) throw std::runtime_error("failed to compile regular expression for the matching regex! (" + err_msg + ")"); SkipSpaces(ch, end); if (ch != end) { const std::string extraction_regex_string(ExtractOptionallyQuotedString(ch, end)); extraction_regex = RegexMatcher::RegexMatcherFactory(extraction_regex_string, &err_msg); if (unlikely(not err_msg.empty())) throw std::runtime_error("failed to compile regular expression for the extraction regex! (" + err_msg + ")"); if (unlikely(extraction_regex->getNoOfGroups() != 1)) throw std::runtime_error("regular expression for the extraction regex needs exactly one " "capture group!"); } } Matcher new_matcher(marc_tag_and_subfield_code.substr(0, DirectoryEntry::TAG_LENGTH), marc_tag_and_subfield_code[DirectoryEntry::TAG_LENGTH], matching_regex, extraction_regex); const auto xml_tag_and_entries(xml_tag_to_marc_entry_map->find(xml_tag)); if (xml_tag_and_entries == xml_tag_to_marc_entry_map->end()) xml_tag_to_marc_entry_map->emplace(xml_tag, std::list<Matcher>{ new_matcher }); else xml_tag_and_entries->second.push_back(new_matcher); } catch (const std::exception &x) { throw std::runtime_error("error while parsing line #" + std::to_string(line_no) + " in \"" + input->getPath() + "\"! (" + std::string(x.what()) + ")"); } } } /** Generates a PPN by counting down from the largest possible PPN. */ std::string GeneratePPN() { static unsigned next_ppn(99999999); const std::string ppn_without_checksum_digit(StringUtil::ToString(next_ppn, /* radix = */10, /* width = */8)); --next_ppn; return ppn_without_checksum_digit + MiscUtil::GeneratePPNChecksumDigit(ppn_without_checksum_digit); } enum OutputFormat { MARC_BINARY, MARC_XML }; void ProcessRecords(const bool verbose, const OutputFormat output_format, File * const input, File * const output, const std::map<std::string, std::list<Matcher>> &xml_tag_to_marc_entry_map) { MarcXmlWriter *xml_writer; if (output_format == MARC_XML) xml_writer = new MarcXmlWriter(output); else xml_writer = nullptr; SimpleXmlParser::Type type; std::string data; std::map<std::string, std::string> attrib_map; SimpleXmlParser xml_parser(input); MarcUtil::Record record; unsigned record_count(0); bool collect_character_data; std::string character_data; while (xml_parser.getNext(&type, &attrib_map, &data)) { switch (type) { case SimpleXmlParser::END_OF_DOCUMENT: if (verbose) std::cout << "Found " << record_count << " record(s) in the XML input stream.\n"; delete xml_writer; return; case SimpleXmlParser::OPENING_TAG: if (data == "record") { record = MarcUtil::Record(); record.insertField("001", GeneratePPN()); collect_character_data = false; } else if (xml_tag_to_marc_entry_map.find(data) != xml_tag_to_marc_entry_map.cend()) { character_data.clear(); collect_character_data = true; } else collect_character_data = false; break; case SimpleXmlParser::CLOSING_TAG: if (data == "record") { (xml_writer == nullptr) ? record.write(output) : record.write(xml_writer); ++record_count; } else { const auto xml_tag_and_entries(xml_tag_to_marc_entry_map.find(data)); if (xml_tag_and_entries == xml_tag_to_marc_entry_map.cend()) continue; for (auto matcher(xml_tag_and_entries->second.cbegin()); matcher != xml_tag_and_entries->second.cend(); ++matcher) { if (matcher->matched(character_data)) { record.insertSubfield(matcher->getMarcFieldTag(), matcher->getMarcSubfieldCode(), matcher->getInsertionData(character_data)); continue; } } } break; case SimpleXmlParser::CHARACTERS: if (collect_character_data) character_data += data; break; default: /* Intentionally empty! */; } } Error("XML parsing error: " + xml_parser.getLastErrorMessage()); } int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc != 5 and argc != 6) Usage(); bool verbose(false); if (argc == 6) { if (std::strcmp(argv[1], "--verbose") != 0) Usage(); verbose = true; --argc, ++argv; } OutputFormat output_format; if (std::strcmp(argv[1], "--output-format=marc_binary") == 0) output_format = MARC_BINARY; else if (std::strcmp(argv[1], "--output-format=marc_xml") == 0) output_format = MARC_XML; else Usage(); const std::unique_ptr<File> config_input(FileUtil::OpenInputFileOrDie(argv[2])); const std::unique_ptr<File> input(FileUtil::OpenInputFileOrDie(argv[3])); const std::unique_ptr<File> output(FileUtil::OpenOutputFileOrDie(argv[4])); try { std::map<std::string, std::list<Matcher>> xml_tag_to_marc_entry_map; LoadConfig(config_input.get(), &xml_tag_to_marc_entry_map); ProcessRecords(verbose, output_format, input.get(), output.get(), xml_tag_to_marc_entry_map); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <commit_msg>Added support for "required" matches.<commit_after>/** \brief Parses XML and generates MARC-21 data. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2016 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <list> #include <map> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "MarcUtil.h" #include "MarcXmlWriter.h" #include "MiscUtil.h" #include "RegexMatcher.h" #include "SimpleXmlParser.h" #include "StringUtil.h" #include "util.h" __attribute__((noreturn)) void Usage() { std::cerr << "Usage: " << ::progname << " [--verbose] --output-format=(marc_binary|marc_xml) config_file oai_pmh_dc_input marc_output\n"; std::exit(EXIT_FAILURE); } // An instance of this class specifies a rule for if and how to extract XML data and how to map it to a MARC-21 // field and subfield. class Matcher { std::string field_tag_; char subfield_code_; const RegexMatcher * const matching_regex_; const RegexMatcher * const extraction_regex_; public: Matcher(const std::string &field_tag, const char subfield_code, const RegexMatcher * const matching_regex = nullptr, const RegexMatcher * const extraction_regex = nullptr) : field_tag_(field_tag), subfield_code_(subfield_code), matching_regex_(matching_regex), extraction_regex_(extraction_regex) { } inline bool matched(const std::string &character_data) const { return (matching_regex_ == nullptr) ? true : matching_regex_->matched(character_data); } /** \return That part of the character data that ought to be inserted into a MARC record. */ std::string getInsertionData(const std::string &character_data) const; inline const std::string &getMarcFieldTag() const { return field_tag_; } inline char getMarcSubfieldCode() const { return subfield_code_; } }; std::string Matcher::getInsertionData(const std::string &character_data) const { if (extraction_regex_ == nullptr) return character_data; if (not extraction_regex_->matched(character_data)) return ""; return (*extraction_regex_)[1]; } // Expects the "string" that we extract to either contain no spaces or to be enclosed in double quotes. // Optional comments start with a hash sign. std::string ExtractOptionallyQuotedString(std::string::const_iterator &ch, const std::string::const_iterator &end) { if (ch == end) return ""; std::string extracted_string; if (*ch == '"') { // Extract quoted string. ++ch; bool escaped(false); while (ch != end and *ch != '"') { if (unlikely(escaped)) { escaped = false; extracted_string += *ch; } else if (unlikely(*ch == '\\')) escaped = true; else extracted_string += *ch; ++ch; } if (unlikely(*ch != '"')) throw std::runtime_error("missing closing quote!"); ++ch; } else { // Extract non-quoted string. while (ch != end and *ch != ' ') extracted_string += *ch++; } return extracted_string; } void SkipSpaces(std::string::const_iterator &ch, const std::string::const_iterator &end) { while (ch != end and *ch == ' ') ++ch; } // Loads a config file that specifies the mapping from XML elements to MARC fields. An entry looks like this // // xml_tag_name marc_field_and_subfield optional_match_regex optional_extraction_regex // or // "required" xml_tag_name match_regex // // "xml_tag_name" is the tag for which the rule applies. "marc_field_and_subfield" is the field which gets created // when we have a match. "optional_match_regex" when present has to match the character data following the tag for // the rule to apply and "optional_extraction_regex" specifies which part of the data will be used (group 1). void LoadConfig(File * const input, std::map<std::string, std::list<Matcher>> * const xml_tag_to_marc_entry_map, std::map<std::string, std::list<Matcher>> * const required_matchers) { xml_tag_to_marc_entry_map->clear(); required_matchers->clear(); unsigned line_no(0); while (not input->eof()) { std::string line(input->getline()); ++line_no; // Process optional comment: const std::string::size_type first_hash_pos(line.find('#')); if (first_hash_pos != std::string::npos) line.resize(first_hash_pos); StringUtil::TrimWhite(&line); if (line.empty()) continue; try { auto ch(line.cbegin()); const auto end(line.cend()); SkipSpaces(ch, end); const std::string xml_tag_or_required(ExtractOptionallyQuotedString(ch, end)); if (unlikely(xml_tag_or_required.empty())) throw std::runtime_error("missing or empty XML tag!"); SkipSpaces(ch, end); RegexMatcher *matching_regex(nullptr); if (xml_tag_or_required == "required") { const std::string xml_tag(ExtractOptionallyQuotedString(ch, end)); if (unlikely(xml_tag.empty())) throw std::runtime_error("missing or empty XML tag after \"required\" keyword!"); SkipSpaces(ch, end); const std::string matching_regex_string(ExtractOptionallyQuotedString(ch, end)); std::string err_msg; matching_regex = RegexMatcher::RegexMatcherFactory(matching_regex_string, &err_msg); if (unlikely(not err_msg.empty())) throw std::runtime_error("failed to compile the regular expression for the matching regex for a " "required condition! (" + err_msg + ")"); SkipSpaces(ch, end); if (unlikely(ch != end)) throw std::runtime_error("junk after regular expression!"); const Matcher new_matcher("", '\0', matching_regex); const auto xml_tag_and_matchers(required_matchers->find(xml_tag)); if (xml_tag_and_matchers == required_matchers->end()) required_matchers->emplace(xml_tag, std::list<Matcher>{ new_matcher }); else xml_tag_and_matchers->second.push_back(new_matcher); } const std::string marc_tag_and_subfield_code(ExtractOptionallyQuotedString(ch, end)); if (unlikely(marc_tag_and_subfield_code.length() != DirectoryEntry::TAG_LENGTH + 1)) throw std::runtime_error("bad MARC tag and subfield code!"); SkipSpaces(ch, end); RegexMatcher *extraction_regex(nullptr); if (ch != end) { const std::string matching_regex_string(ExtractOptionallyQuotedString(ch, end)); std::string err_msg; matching_regex = RegexMatcher::RegexMatcherFactory(matching_regex_string, &err_msg); if (unlikely(not err_msg.empty())) throw std::runtime_error("failed to compile regular expression for the matching regex! (" + err_msg + ")"); SkipSpaces(ch, end); if (ch != end) { const std::string extraction_regex_string(ExtractOptionallyQuotedString(ch, end)); extraction_regex = RegexMatcher::RegexMatcherFactory(extraction_regex_string, &err_msg); if (unlikely(not err_msg.empty())) throw std::runtime_error("failed to compile regular expression for the extraction regex! (" + err_msg + ")"); if (unlikely(extraction_regex->getNoOfGroups() != 1)) throw std::runtime_error("regular expression for the extraction regex needs exactly one " "capture group!"); } SkipSpaces(ch, end); if (unlikely(ch != end)) throw std::runtime_error("junk after regular expression!"); } const Matcher new_matcher(marc_tag_and_subfield_code.substr(0, DirectoryEntry::TAG_LENGTH), marc_tag_and_subfield_code[DirectoryEntry::TAG_LENGTH], matching_regex, extraction_regex); const auto xml_tag_and_matchers(xml_tag_to_marc_entry_map->find(xml_tag_or_required)); if (xml_tag_and_matchers == xml_tag_to_marc_entry_map->end()) xml_tag_to_marc_entry_map->emplace(xml_tag_or_required, std::list<Matcher>{ new_matcher }); else xml_tag_and_matchers->second.push_back(new_matcher); } catch (const std::exception &x) { throw std::runtime_error("error while parsing line #" + std::to_string(line_no) + " in \"" + input->getPath() + "\"! (" + std::string(x.what()) + ")"); } } } /** Generates a PPN by counting down from the largest possible PPN. */ std::string GeneratePPN() { static unsigned next_ppn(99999999); const std::string ppn_without_checksum_digit(StringUtil::ToString(next_ppn, /* radix = */10, /* width = */8)); --next_ppn; return ppn_without_checksum_digit + MiscUtil::GeneratePPNChecksumDigit(ppn_without_checksum_digit); } enum OutputFormat { MARC_BINARY, MARC_XML }; void ProcessRecords(const bool verbose, const OutputFormat output_format, File * const input, File * const output, const std::map<std::string, std::list<Matcher>> &xml_tag_to_marc_entry_map, const std::map<std::string, std::list<Matcher>> &required_matchers) { MarcXmlWriter *xml_writer; if (output_format == MARC_XML) xml_writer = new MarcXmlWriter(output); else xml_writer = nullptr; SimpleXmlParser::Type type; std::string data; std::map<std::string, std::string> attrib_map; SimpleXmlParser xml_parser(input); MarcUtil::Record record; unsigned record_count(0), written_record_count(0); bool collect_character_data; std::string character_data; unsigned met_required_conditions_count; while (xml_parser.getNext(&type, &attrib_map, &data)) { switch (type) { case SimpleXmlParser::END_OF_DOCUMENT: if (verbose) std::cout << "Wrote " << written_record_count << " record(s) of " << record_count << " record(s) which were found in the XML input stream.\n"; delete xml_writer; return; case SimpleXmlParser::OPENING_TAG: if (data == "record") { record = MarcUtil::Record(); record.insertField("001", GeneratePPN()); collect_character_data = false; met_required_conditions_count = 0; } else if (xml_tag_to_marc_entry_map.find(data) != xml_tag_to_marc_entry_map.cend()) { character_data.clear(); collect_character_data = true; } else collect_character_data = false; break; case SimpleXmlParser::CLOSING_TAG: if (data == "record") { if (met_required_conditions_count == required_matchers.size()) { (xml_writer == nullptr) ? record.write(output) : record.write(xml_writer); ++written_record_count; } ++record_count; } else { const auto xml_tag_and_required_matchers(required_matchers.find(data)); if (xml_tag_and_required_matchers != required_matchers.cend()) { for (const auto &matcher : xml_tag_and_required_matchers->second) { if (matcher.matched(character_data)) ++met_required_conditions_count; } } const auto xml_tag_and_matchers(xml_tag_to_marc_entry_map.find(data)); if (xml_tag_and_matchers == xml_tag_to_marc_entry_map.cend()) continue; for (const auto &matcher : xml_tag_and_matchers->second) { if (matcher.matched(character_data)) { record.insertSubfield(matcher.getMarcFieldTag(), matcher.getMarcSubfieldCode(), matcher.getInsertionData(character_data)); break; } } } break; case SimpleXmlParser::CHARACTERS: if (collect_character_data) character_data += data; break; default: /* Intentionally empty! */; } } Error("XML parsing error: " + xml_parser.getLastErrorMessage()); } int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc != 5 and argc != 6) Usage(); bool verbose(false); if (argc == 6) { if (std::strcmp(argv[1], "--verbose") != 0) Usage(); verbose = true; --argc, ++argv; } OutputFormat output_format; if (std::strcmp(argv[1], "--output-format=marc_binary") == 0) output_format = MARC_BINARY; else if (std::strcmp(argv[1], "--output-format=marc_xml") == 0) output_format = MARC_XML; else Usage(); const std::unique_ptr<File> config_input(FileUtil::OpenInputFileOrDie(argv[2])); const std::unique_ptr<File> input(FileUtil::OpenInputFileOrDie(argv[3])); const std::unique_ptr<File> output(FileUtil::OpenOutputFileOrDie(argv[4])); try { std::map<std::string, std::list<Matcher>> xml_tag_to_marc_entry_map, required_matchers; LoadConfig(config_input.get(), &xml_tag_to_marc_entry_map, &required_matchers); ProcessRecords(verbose, output_format, input.get(), output.get(), xml_tag_to_marc_entry_map, required_matchers); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>/** \file Elasticsearch.cc * \brief Implementation of the Elasticsearch class. * \author Dr. Johannes Ruscheinski * \author Mario Trojan * * \copyright 2018,2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Elasticsearch.h" #include "FileUtil.h" #include "IniFile.h" #include "UBTools.h" #include "Url.h" const std::string DEFAULT_CONFIG_FILE_PATH(UBTools::GetTuelibPath() + "Elasticsearch.conf"); static void LoadIniParameters(const std::string &config_file_path, std::string * const host, std::string * const username, std::string * const password, bool * const ignore_ssl_certificates) { if (not FileUtil::Exists(config_file_path)) LOG_ERROR("Elasticsearch config file missing: " + config_file_path); const IniFile ini_file(config_file_path); *host = ini_file.getString("Elasticsearch", "host"); *username = ini_file.getString("Elasticsearch", "username", ""); *password = ini_file.getString("Elasticsearch", "password", ""); *ignore_ssl_certificates = ini_file.getBool("Elasticsearch", "ignore_ssl_certificates", false); } Elasticsearch::Elasticsearch(const std::string &index, const std::string &type): index_(index), type_(type) { LoadIniParameters(DEFAULT_CONFIG_FILE_PATH, &host_, &username_, &password_, &ignore_ssl_certificates_); } size_t Elasticsearch::size() const { return JSON::LookupInteger("/indices/" + index_ + "/total/count", query("_stats", REST::GET, JSON::ObjectNode(), /* add_type */ false)); } void Elasticsearch::simpleInsert(const std::map<std::string, std::string> &fields_and_values) { query("", REST::POST, JSON::ObjectNode(fields_and_values)); } // A general comment as to the strategy we use in this function: // // We know that there is an _update API endpoint, but as we insert a bunch of chunks, the number of which can change, // we have to use a "wildcard" strategy to first delete possibly existing chunks as the number of new chunks may be greater or // fewer than what may already be stored. void Elasticsearch::insertOrUpdateDocument(const std::string &document_id, const std::string &document) { deleteDocument(document_id); simpleInsert({ { "id", document_id }, { "document", document } }); } bool Elasticsearch::deleteDocument(const std::string &document_id) { const JSON::ObjectNode match_node("{ \"query\":" " { \"match\":" " { \"id\": \"" + JSON::EscapeString(document_id) + "\" }" " }" "}"); const auto result_node(query("_delete_by_query", REST::POST, match_node)); return result_node->getIntegerNode("deleted")->getValue() > 0; } std::unordered_set<std::string> Elasticsearch::selectAll(const std::string &field) const { const std::vector<std::map<std::string, std::string>> result(simpleSelect({ field })); std::unordered_set<std::string> unique_values; for (const auto &map : result) { const auto key_and_value(map.find(field)); if (key_and_value != map.cend()) unique_values.emplace(key_and_value->second); } return unique_values; } std::vector<std::map<std::string, std::string>> Elasticsearch::simpleSelect(const std::set<std::string> &fields, const std::map<std::string, std::string> &filter, const int max_count) const { std::string query_string("{\n"); if (not fields.empty()) { query_string += " \"_source\": ["; for (const auto &field : fields) query_string += "\"" + field + "\", "; query_string.resize(query_string.size() - 2); // Remove trailing comma and space. query_string += "],\n"; } query_string += " \"query\": {"; if (filter.empty()) query_string += " \"match_all\": {}"; else { query_string += "\"bool\" : { \"filter\": [\n"; for (const auto &field_and_value : filter) query_string += " { \"term\": { \"" + field_and_value.first + "\": \"" + field_and_value.second + "\"} },\n"; query_string.resize(query_string.size() - 2); // Remove the last comma and newline. query_string += "\n ] }"; } query_string += " },\n"; query_string += " \"size\": " + std::to_string(max_count) + "\n"; query_string += "}\n"; const auto result_node(query("_search", REST::POST, JSON::ObjectNode(query_string))); const auto hits_object_node(result_node->getObjectNode("hits")); if (unlikely(hits_object_node == nullptr)) LOG_ERROR("missing \"hits\" object node in Elasticsearch result node!"); const auto hits_array_node(hits_object_node->getArrayNode("hits")); if (unlikely(hits_array_node == nullptr)) LOG_ERROR("missing \"hits\" array node in Elasticsearch result node!"); std::vector<std::map<std::string, std::string>> search_results; search_results.reserve(hits_array_node->size()); for (const auto entry_node : *hits_array_node) { std::map<std::string, std::string> new_map; const auto entry_object_node(JSON::JSONNode::CastToObjectNodeOrDie("entry_object_node", entry_node)); for (const auto &entry : *entry_object_node) { if (fields.empty() or fields.find(entry.first) != fields.cend() or entry.first == "_source") { // Copy existing fields but flatten the contents of _source if (entry.first == "_source") { const auto source_object_node(JSON::JSONNode::CastToObjectNodeOrDie("source_object_node", entry.second)); for (const auto &source_entry : *source_object_node) new_map[source_entry.first] = JSON::JSONNode::CastToStringNodeOrDie("new_map[source_entry.first]", source_entry.second)->getValue(); } else new_map[entry.first] = JSON::JSONNode::CastToStringNodeOrDie("new_map[entry.first]", entry.second)->getValue(); } } search_results.resize(search_results.size() + 1); std::swap(search_results.back(), new_map); } return search_results; } static std::string ToString(const Elasticsearch::RangeOperator op) { switch (op) { case Elasticsearch::RO_GT: return "gt"; case Elasticsearch::RO_GTE: return "gte"; case Elasticsearch::RO_LT: return "lt"; case Elasticsearch::RO_LTE: return "lte"; default: LOG_ERROR("we should *never* get here!"); } } bool Elasticsearch::deleteRange(const std::string &field, const RangeOperator operator1, const std::string &operand1, const RangeOperator operator2, const std::string &operand2) { const std::string range_node((operator2 == RO_NOOP or operand2.empty()) ? "{ \"query\":" " { \"range\":" " \"" + field + "\": {" " \"" + ToString(operator1) + "\"" + operand1 + "\"" + ((operator2 == RO_NOOP or operand2.empty()) ? std::string() : " ,\"" + ToString(operator2) + "\"" + operand2 + "\"") + " }" " }" "}" : ""); const auto result_node(query("_delete", REST::POST, range_node)); return result_node->getIntegerNode("deleted")->getValue() > 0; } bool Elasticsearch::fieldWithValueExists(const std::string &field, const std::string &value) { const auto result_node( query("_search", REST::POST, "{" " \"query\": {" " \"match\" : { \"" + field + "\" : \"" + value + "\" }" " }" "}" )); const auto hits_node(result_node->getObjectNode("hits")); if (hits_node == nullptr) LOG_ERROR("No \"hits\" node in results"); const auto total_node = hits_node->getIntegerNode("total"); if (total_node == nullptr) LOG_ERROR("No \"total\" node found"); return total_node->getValue() == 0 ? false : true; } std::shared_ptr<JSON::ObjectNode> Elasticsearch::query(const std::string &action, const REST::QueryType query_type, const JSON::ObjectNode &data, const bool add_type) const { Downloader::Params downloader_params; downloader_params.authentication_username_ = username_; downloader_params.authentication_password_ = password_; downloader_params.ignore_ssl_certificates_ = ignore_ssl_certificates_; downloader_params.additional_headers_.push_back("Content-Type: application/json"); Url url; if (add_type) url = Url(host_ + "/" + index_ + "/" + type_ + (action.empty() ? "" : "/" + action)); else url = Url(host_ + "/" + index_ + (action.empty() ? "" : "/" + action)); std::shared_ptr<JSON::JSONNode> result(REST::QueryJSON(url, query_type, &data, downloader_params)); std::shared_ptr<JSON::ObjectNode> result_object(JSON::JSONNode::CastToObjectNodeOrDie("Elasticsearch result", result)); if (result_object->hasNode("error")) LOG_ERROR("Elasticsearch " + action + " query failed: " + result_object->getNode("error")->toString()); return result_object; } <commit_msg>fixed Elasticsearch::size() problem<commit_after>/** \file Elasticsearch.cc * \brief Implementation of the Elasticsearch class. * \author Dr. Johannes Ruscheinski * \author Mario Trojan * * \copyright 2018,2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Elasticsearch.h" #include "FileUtil.h" #include "IniFile.h" #include "UBTools.h" #include "Url.h" const std::string DEFAULT_CONFIG_FILE_PATH(UBTools::GetTuelibPath() + "Elasticsearch.conf"); static void LoadIniParameters(const std::string &config_file_path, std::string * const host, std::string * const username, std::string * const password, bool * const ignore_ssl_certificates) { if (not FileUtil::Exists(config_file_path)) LOG_ERROR("Elasticsearch config file missing: " + config_file_path); const IniFile ini_file(config_file_path); *host = ini_file.getString("Elasticsearch", "host"); *username = ini_file.getString("Elasticsearch", "username", ""); *password = ini_file.getString("Elasticsearch", "password", ""); *ignore_ssl_certificates = ini_file.getBool("Elasticsearch", "ignore_ssl_certificates", false); } Elasticsearch::Elasticsearch(const std::string &index, const std::string &type): index_(index), type_(type) { LoadIniParameters(DEFAULT_CONFIG_FILE_PATH, &host_, &username_, &password_, &ignore_ssl_certificates_); } size_t Elasticsearch::size() const { return JSON::LookupInteger("/indices/" + index_ + "/total/docs/count", query("_stats", REST::GET, JSON::ObjectNode(), /* add_type */ false)); } void Elasticsearch::simpleInsert(const std::map<std::string, std::string> &fields_and_values) { query("", REST::POST, JSON::ObjectNode(fields_and_values)); } // A general comment as to the strategy we use in this function: // // We know that there is an _update API endpoint, but as we insert a bunch of chunks, the number of which can change, // we have to use a "wildcard" strategy to first delete possibly existing chunks as the number of new chunks may be greater or // fewer than what may already be stored. void Elasticsearch::insertOrUpdateDocument(const std::string &document_id, const std::string &document) { deleteDocument(document_id); simpleInsert({ { "id", document_id }, { "document", document } }); } bool Elasticsearch::deleteDocument(const std::string &document_id) { const JSON::ObjectNode match_node("{ \"query\":" " { \"match\":" " { \"id\": \"" + JSON::EscapeString(document_id) + "\" }" " }" "}"); const auto result_node(query("_delete_by_query", REST::POST, match_node)); return result_node->getIntegerNode("deleted")->getValue() > 0; } std::unordered_set<std::string> Elasticsearch::selectAll(const std::string &field) const { const std::vector<std::map<std::string, std::string>> result(simpleSelect({ field })); std::unordered_set<std::string> unique_values; for (const auto &map : result) { const auto key_and_value(map.find(field)); if (key_and_value != map.cend()) unique_values.emplace(key_and_value->second); } return unique_values; } std::vector<std::map<std::string, std::string>> Elasticsearch::simpleSelect(const std::set<std::string> &fields, const std::map<std::string, std::string> &filter, const int max_count) const { std::string query_string("{\n"); if (not fields.empty()) { query_string += " \"_source\": ["; for (const auto &field : fields) query_string += "\"" + field + "\", "; query_string.resize(query_string.size() - 2); // Remove trailing comma and space. query_string += "],\n"; } query_string += " \"query\": {"; if (filter.empty()) query_string += " \"match_all\": {}"; else { query_string += "\"bool\" : { \"filter\": [\n"; for (const auto &field_and_value : filter) query_string += " { \"term\": { \"" + field_and_value.first + "\": \"" + field_and_value.second + "\"} },\n"; query_string.resize(query_string.size() - 2); // Remove the last comma and newline. query_string += "\n ] }"; } query_string += " },\n"; query_string += " \"size\": " + std::to_string(max_count) + "\n"; query_string += "}\n"; const auto result_node(query("_search", REST::POST, JSON::ObjectNode(query_string))); const auto hits_object_node(result_node->getObjectNode("hits")); if (unlikely(hits_object_node == nullptr)) LOG_ERROR("missing \"hits\" object node in Elasticsearch result node!"); const auto hits_array_node(hits_object_node->getArrayNode("hits")); if (unlikely(hits_array_node == nullptr)) LOG_ERROR("missing \"hits\" array node in Elasticsearch result node!"); std::vector<std::map<std::string, std::string>> search_results; search_results.reserve(hits_array_node->size()); for (const auto entry_node : *hits_array_node) { std::map<std::string, std::string> new_map; const auto entry_object_node(JSON::JSONNode::CastToObjectNodeOrDie("entry_object_node", entry_node)); for (const auto &entry : *entry_object_node) { if (fields.empty() or fields.find(entry.first) != fields.cend() or entry.first == "_source") { // Copy existing fields but flatten the contents of _source if (entry.first == "_source") { const auto source_object_node(JSON::JSONNode::CastToObjectNodeOrDie("source_object_node", entry.second)); for (const auto &source_entry : *source_object_node) new_map[source_entry.first] = JSON::JSONNode::CastToStringNodeOrDie("new_map[source_entry.first]", source_entry.second)->getValue(); } else new_map[entry.first] = JSON::JSONNode::CastToStringNodeOrDie("new_map[entry.first]", entry.second)->getValue(); } } search_results.resize(search_results.size() + 1); std::swap(search_results.back(), new_map); } return search_results; } static std::string ToString(const Elasticsearch::RangeOperator op) { switch (op) { case Elasticsearch::RO_GT: return "gt"; case Elasticsearch::RO_GTE: return "gte"; case Elasticsearch::RO_LT: return "lt"; case Elasticsearch::RO_LTE: return "lte"; default: LOG_ERROR("we should *never* get here!"); } } bool Elasticsearch::deleteRange(const std::string &field, const RangeOperator operator1, const std::string &operand1, const RangeOperator operator2, const std::string &operand2) { const std::string range_node((operator2 == RO_NOOP or operand2.empty()) ? "{ \"query\":" " { \"range\":" " \"" + field + "\": {" " \"" + ToString(operator1) + "\"" + operand1 + "\"" + ((operator2 == RO_NOOP or operand2.empty()) ? std::string() : " ,\"" + ToString(operator2) + "\"" + operand2 + "\"") + " }" " }" "}" : ""); const auto result_node(query("_delete", REST::POST, range_node)); return result_node->getIntegerNode("deleted")->getValue() > 0; } bool Elasticsearch::fieldWithValueExists(const std::string &field, const std::string &value) { const auto result_node( query("_search", REST::POST, "{" " \"query\": {" " \"match\" : { \"" + field + "\" : \"" + value + "\" }" " }" "}" )); const auto hits_node(result_node->getObjectNode("hits")); if (hits_node == nullptr) LOG_ERROR("No \"hits\" node in results"); const auto total_node = hits_node->getIntegerNode("total"); if (total_node == nullptr) LOG_ERROR("No \"total\" node found"); return total_node->getValue() == 0 ? false : true; } std::shared_ptr<JSON::ObjectNode> Elasticsearch::query(const std::string &action, const REST::QueryType query_type, const JSON::ObjectNode &data, const bool add_type) const { Downloader::Params downloader_params; downloader_params.authentication_username_ = username_; downloader_params.authentication_password_ = password_; downloader_params.ignore_ssl_certificates_ = ignore_ssl_certificates_; downloader_params.additional_headers_.push_back("Content-Type: application/json"); Url url; if (add_type) url = Url(host_ + "/" + index_ + "/" + type_ + (action.empty() ? "" : "/" + action)); else url = Url(host_ + "/" + index_ + (action.empty() ? "" : "/" + action)); std::shared_ptr<JSON::JSONNode> result(REST::QueryJSON(url, query_type, &data, downloader_params)); std::shared_ptr<JSON::ObjectNode> result_object(JSON::JSONNode::CastToObjectNodeOrDie("Elasticsearch result", result)); if (result_object->hasNode("error")) LOG_ERROR("Elasticsearch " + action + " query failed: " + result_object->getNode("error")->toString()); return result_object; } <|endoftext|>
<commit_before>/** \file rss_subset_aggregator.cc * \brief Aggregates RSS feeds. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2021 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <map> #include <unordered_map> #include <unordered_set> #include <cinttypes> #include <cstring> #include "Compiler.h" #include "DbConnection.h" #include "DbResultSet.h" #include "EmailSender.h" #include "FileUtil.h" #include "HtmlUtil.h" #include "SqlUtil.h" #include "StringUtil.h" #include "SyndicationFormat.h" #include "Template.h" #include "UBTools.h" #include "util.h" #include "VuFind.h" #include "XmlWriter.h" namespace { [[noreturn]] void Usage() { ::Usage("email_address"); } struct HarvestedRSSItem { SyndicationFormat::Item item_; std::string feed_title_; std::string feed_url_; HarvestedRSSItem(const SyndicationFormat::Item item, const std::string feed_title, const std::string feed_url) : item_(item), feed_title_(feed_title), feed_url_(feed_url) {} }; struct ChannelDesc { std::string title_; std::string link_; public: ChannelDesc(const std::string &title, const std::string &link) : title_(title), link_(link) { } }; const std::map<std::string, ChannelDesc> subsystem_type_to_channel_desc_map = { { "relbib", ChannelDesc("RelBib Aggregator", "https://relbib.de/") }, { "ixtheo", ChannelDesc("IxTheo Aggregator", "https://itheo.de/") }, { "krimdok", ChannelDesc("KrimDok Aggregator", "https://krimdok.uni-tuebingen.de/") }, }; std::string GetChannelDescEntry(const std::string &subsystem_type, const std::string &entry) { const auto subsystem_type_and_channel_desc(subsystem_type_to_channel_desc_map.find(subsystem_type)); if (subsystem_type_and_channel_desc == subsystem_type_to_channel_desc_map.cend()) LOG_ERROR("unknown subsystem type \"" + subsystem_type + "\"!"); if (entry == "title") return subsystem_type_and_channel_desc->second.title_; if (entry == "link") return subsystem_type_and_channel_desc->second.link_; LOG_ERROR("unknown entry name \"" + entry + "\"!"); } void WriteRSSFeedXMLOutput(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items, XmlWriter * const xml_writer) { xml_writer->openTag("rss", { { "version", "2.0" }, { "xmlns:tuefind", "https://github.com/ubtue/tuefind" } }); xml_writer->openTag("channel"); xml_writer->writeTagsWithData("title", GetChannelDescEntry(subsystem_type, "title")); xml_writer->writeTagsWithData("link", GetChannelDescEntry(subsystem_type, "link")); xml_writer->writeTagsWithData("description", "RSS Aggregator"); for (const auto &harvested_item : harvested_items) { xml_writer->openTag("item"); const auto title(harvested_item.item_.getTitle()); if (not title.empty()) xml_writer->writeTagsWithData("title", harvested_item.item_.getTitle()); xml_writer->writeTagsWithData("link", harvested_item.item_.getLink()); const auto description(HtmlUtil::ShortenText(harvested_item.item_.getDescription(), /*max_length = */500)); if (not description.empty()) xml_writer->writeTagsWithData("description", description); xml_writer->writeTagsWithData("pubDate", TimeUtil::TimeTToString(harvested_item.item_.getPubDate(), TimeUtil::RFC822_FORMAT, TimeUtil::UTC)); xml_writer->writeTagsWithData("guid", harvested_item.item_.getId()); xml_writer->writeTagsWithData("tuefind:rss_title", harvested_item.feed_title_); xml_writer->writeTagsWithData("tuefind:rss_url", harvested_item.feed_url_); xml_writer->closeTag("item", /* suppress_indent */ false); } xml_writer->closeTag("channel"); xml_writer->closeTag("rss"); } struct FeedNameAndURL { std::string name_; std::string url_; public: FeedNameAndURL() = default; FeedNameAndURL(const FeedNameAndURL &other) = default; FeedNameAndURL(const std::string &name, const std::string &url) : name_(name), url_(url) { } }; void SendEmail(const std::string &email_sender, const std::string &user_email, const std::string &user_address, const std::string &language, const std::vector<HarvestedRSSItem> &harvested_items) { const auto template_filename_prefix(UBTools::GetTuelibPath() + "rss_email.template"); std::string template_filename(template_filename_prefix + "." + language); if (not FileUtil::Exists(template_filename)) template_filename = template_filename_prefix + ".en"; static const std::string email_template(FileUtil::ReadStringOrDie(template_filename)); Template::Map names_to_values_map; names_to_values_map.insertScalar("user_email", user_email); names_to_values_map.insertScalar("user_address", user_address); std::vector<std::string> titles, links, descriptions; for (const auto &harvested_item : harvested_items) { titles.emplace_back(HtmlUtil::HtmlEscape(harvested_item.item_.getTitle())); links.emplace_back(harvested_item.item_.getLink()); descriptions.emplace_back(HtmlUtil::HtmlEscape(harvested_item.item_.getDescription())); } names_to_values_map.insertArray("titles", titles); names_to_values_map.insertArray("links", links); names_to_values_map.insertArray("descriptions", descriptions); const auto email_body(Template::ExpandTemplate(email_template, names_to_values_map)); const auto retcode(EmailSender::SimplerSendEmail(email_sender, { user_email }, "RSS Feeds Update", email_body, EmailSender::DO_NOT_SET_PRIORITY, EmailSender::HTML)); if (retcode > 299) LOG_WARNING("EmailSender::SimplerSendEmail returned " + std::to_string(retcode) + " while trying to send to \"" + user_email + "\"!"); } const unsigned DEFAULT_XML_INDENT_AMOUNT(2); void GenerateFeed(const std::string &user_id, const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items) { static const std::string PATH_PREFIX("/var/www/custom_rss_feeds/"); const std::string xml_output_filename(PATH_PREFIX + subsystem_type + "_" + user_id + "_rss.xml"); XmlWriter xml_writer(FileUtil::OpenOutputFileOrDie(xml_output_filename).release(), XmlWriter::WriteTheXmlDeclaration, DEFAULT_XML_INDENT_AMOUNT); WriteRSSFeedXMLOutput(subsystem_type, harvested_items, &xml_writer); } void ProcessFeeds(const std::string &user_id, const std::string &email_sender, const std::string &user_email, const std::string &user_address, const std::string &language, const std::string &rss_feed_notification_type, const std::string &subsystem_type, DbConnection * const db_connection) { db_connection->queryOrDie("SELECT rss_feeds_id FROM tuefind_rss_subscriptions WHERE user_id=" + user_id); auto rss_subscriptions_result_set(db_connection->getLastResultSet()); std::vector<std::string> feed_ids; while (const auto row = rss_subscriptions_result_set.getNextRow())\ feed_ids.emplace_back(row["rss_feeds_id"]); if (feed_ids.empty()) return; std::vector<HarvestedRSSItem> harvested_items; for (const auto &feed_id : feed_ids) { db_connection->queryOrDie("SELECT feed_name,feed_url FROM tuefind_rss_feeds WHERE id=" + feed_id); auto feed_result_set(db_connection->getLastResultSet()); const auto feed_row(feed_result_set.getNextRow()); const auto feed_name(feed_row["feed_name"]); const auto feed_url(feed_row["feed_url"]); feed_result_set.~DbResultSet(); db_connection->queryOrDie("SELECT item_title,item_description,item_url,item_id,pub_date FROM " "tuefind_rss_items WHERE rss_feeds_id=" + feed_id); auto items_result_set(db_connection->getLastResultSet()); while (const auto item_row = items_result_set.getNextRow()) harvested_items.emplace_back(SyndicationFormat::Item(item_row["item_title"], item_row["item_description"], item_row["item_url"], item_row["item_id"], SqlUtil::DatetimeToTimeT(item_row["pub_date"])), feed_name, feed_url); } if (rss_feed_notification_type == "email") SendEmail(email_sender, user_email, user_address, language, harvested_items); else GenerateFeed(user_id, subsystem_type, harvested_items); } // Yes, this function has a confusing name but I could not think of a better one. // What is meant is how to address a user! std::string GenerateUserAddress(const std::string &appellation, const std::string &first_name, const std::string &last_name) { if (last_name.empty()) return first_name; if (appellation.empty()) return first_name + " " + last_name; return appellation + " " + last_name; } } // unnamed namespace struct UserInfo { std::string user_id_; std::string first_name_; std::string last_name_; std::string email_; std::string rss_feed_notification_type_; time_t rss_feed_last_notification_; public: UserInfo() = default; UserInfo(const UserInfo &other) = default; UserInfo(const std::string &user_id, const std::string &first_name, const std::string &last_name, const std::string &email, const std::string &rss_feed_notification_type, const time_t rss_feed_last_notification) : user_id_(user_id), first_name_(first_name), last_name_(last_name), email_(email), rss_feed_notification_type_(rss_feed_notification_type), rss_feed_last_notification_(rss_feed_last_notification) { } }; int Main(int argc, char *argv[]) { if (argc != 2) Usage(); const std::string email_address(argv[1]); const auto db_connection(VuFind::GetDbConnection()); db_connection->queryOrDie("SELECT id,firstname,lastname,email,tuefind_rss_feed_notification_type" ",tuefind_rss_feed_last_notification FROM user " "WHERE tuefind_rss_feed_notification_type IS NOT NULL"); auto user_result_set(db_connection->getLastResultSet()); std::unordered_map<std::string, UserInfo> ids_to_user_infos_map; while (const auto user_row = user_result_set.getNextRow()) ids_to_user_infos_map[user_row["id"]] = UserInfo(user_row["id"], user_row["firstname"], user_row["lastname"], user_row["email"], user_row["tuefind_rss_feed_notification_type"], TimeUtil::StringToTimeT(user_row["tuefind_rss_feed_last_notification"])); unsigned feed_generation_count(0), email_sent_count(0); for (const auto &[user_id, user_info] : ids_to_user_infos_map) { if (user_info.rss_feed_notification_type_ == "email" and not EmailSender::IsValidEmailAddress(user_info.email_)) { LOG_WARNING("no valid email address for vfind.user.id " + user_id + "!"); continue; } db_connection->queryOrDie("SELECT appellation,language,user_type FROM ixtheo_user"); auto ixtheo_user_row(db_connection->getLastResultSet().getNextRow()); const auto appellation(ixtheo_user_row.getValue("appellation")); const auto language(ixtheo_user_row.getValue("language", "en")); const auto subsystem_type(ixtheo_user_row["user_type"]); ProcessFeeds(user_id, email_address, user_info.email_, GenerateUserAddress(appellation, user_info.first_name_, user_info.last_name_), language, user_info.rss_feed_notification_type_, subsystem_type, db_connection.get()); user_info.rss_feed_notification_type_ == "email" ? ++email_sent_count : ++feed_generation_count; } LOG_INFO("Generated " + std::to_string(feed_generation_count) + " RSS feed(s) and sent " + std::to_string(email_sent_count) + " email(s)."); return EXIT_SUCCESS; } <commit_msg>Only notify<commit_after>/** \file rss_subset_aggregator.cc * \brief Aggregates RSS feeds. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2021 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <map> #include <unordered_map> #include <unordered_set> #include <cinttypes> #include <cstring> #include "Compiler.h" #include "DbConnection.h" #include "DbResultSet.h" #include "EmailSender.h" #include "FileUtil.h" #include "HtmlUtil.h" #include "SqlUtil.h" #include "StringUtil.h" #include "SyndicationFormat.h" #include "Template.h" #include "UBTools.h" #include "util.h" #include "VuFind.h" #include "XmlWriter.h" namespace { [[noreturn]] void Usage() { ::Usage("email_address"); } struct HarvestedRSSItem { SyndicationFormat::Item item_; std::string feed_title_; std::string feed_url_; HarvestedRSSItem(const SyndicationFormat::Item item, const std::string feed_title, const std::string feed_url) : item_(item), feed_title_(feed_title), feed_url_(feed_url) {} }; struct ChannelDesc { std::string title_; std::string link_; public: ChannelDesc(const std::string &title, const std::string &link) : title_(title), link_(link) { } }; const std::map<std::string, ChannelDesc> subsystem_type_to_channel_desc_map = { { "relbib", ChannelDesc("RelBib Aggregator", "https://relbib.de/") }, { "ixtheo", ChannelDesc("IxTheo Aggregator", "https://itheo.de/") }, { "krimdok", ChannelDesc("KrimDok Aggregator", "https://krimdok.uni-tuebingen.de/") }, }; std::string GetChannelDescEntry(const std::string &subsystem_type, const std::string &entry) { const auto subsystem_type_and_channel_desc(subsystem_type_to_channel_desc_map.find(subsystem_type)); if (subsystem_type_and_channel_desc == subsystem_type_to_channel_desc_map.cend()) LOG_ERROR("unknown subsystem type \"" + subsystem_type + "\"!"); if (entry == "title") return subsystem_type_and_channel_desc->second.title_; if (entry == "link") return subsystem_type_and_channel_desc->second.link_; LOG_ERROR("unknown entry name \"" + entry + "\"!"); } void WriteRSSFeedXMLOutput(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items, XmlWriter * const xml_writer) { xml_writer->openTag("rss", { { "version", "2.0" }, { "xmlns:tuefind", "https://github.com/ubtue/tuefind" } }); xml_writer->openTag("channel"); xml_writer->writeTagsWithData("title", GetChannelDescEntry(subsystem_type, "title")); xml_writer->writeTagsWithData("link", GetChannelDescEntry(subsystem_type, "link")); xml_writer->writeTagsWithData("description", "RSS Aggregator"); for (const auto &harvested_item : harvested_items) { xml_writer->openTag("item"); const auto title(harvested_item.item_.getTitle()); if (not title.empty()) xml_writer->writeTagsWithData("title", harvested_item.item_.getTitle()); xml_writer->writeTagsWithData("link", harvested_item.item_.getLink()); const auto description(HtmlUtil::ShortenText(harvested_item.item_.getDescription(), /*max_length = */500)); if (not description.empty()) xml_writer->writeTagsWithData("description", description); xml_writer->writeTagsWithData("pubDate", TimeUtil::TimeTToString(harvested_item.item_.getPubDate(), TimeUtil::RFC822_FORMAT, TimeUtil::UTC)); xml_writer->writeTagsWithData("guid", harvested_item.item_.getId()); xml_writer->writeTagsWithData("tuefind:rss_title", harvested_item.feed_title_); xml_writer->writeTagsWithData("tuefind:rss_url", harvested_item.feed_url_); xml_writer->closeTag("item", /* suppress_indent */ false); } xml_writer->closeTag("channel"); xml_writer->closeTag("rss"); } struct FeedNameAndURL { std::string name_; std::string url_; public: FeedNameAndURL() = default; FeedNameAndURL(const FeedNameAndURL &other) = default; FeedNameAndURL(const std::string &name, const std::string &url) : name_(name), url_(url) { } }; void SendEmail(const std::string &email_sender, const std::string &user_email, const std::string &user_address, const std::string &language, const std::vector<HarvestedRSSItem> &harvested_items) { const auto template_filename_prefix(UBTools::GetTuelibPath() + "rss_email.template"); std::string template_filename(template_filename_prefix + "." + language); if (not FileUtil::Exists(template_filename)) template_filename = template_filename_prefix + ".en"; static const std::string email_template(FileUtil::ReadStringOrDie(template_filename)); Template::Map names_to_values_map; names_to_values_map.insertScalar("user_email", user_email); names_to_values_map.insertScalar("user_address", user_address); std::vector<std::string> titles, links, descriptions; for (const auto &harvested_item : harvested_items) { titles.emplace_back(HtmlUtil::HtmlEscape(harvested_item.item_.getTitle())); links.emplace_back(harvested_item.item_.getLink()); descriptions.emplace_back(HtmlUtil::HtmlEscape(harvested_item.item_.getDescription())); } names_to_values_map.insertArray("titles", titles); names_to_values_map.insertArray("links", links); names_to_values_map.insertArray("descriptions", descriptions); const auto email_body(Template::ExpandTemplate(email_template, names_to_values_map)); const auto retcode(EmailSender::SimplerSendEmail(email_sender, { user_email }, "RSS Feeds Update", email_body, EmailSender::DO_NOT_SET_PRIORITY, EmailSender::HTML)); if (retcode > 299) LOG_WARNING("EmailSender::SimplerSendEmail returned " + std::to_string(retcode) + " while trying to send to \"" + user_email + "\"!"); } const unsigned DEFAULT_XML_INDENT_AMOUNT(2); void GenerateFeed(const std::string &user_id, const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items) { static const std::string PATH_PREFIX("/var/www/custom_rss_feeds/"); const std::string xml_output_filename(PATH_PREFIX + subsystem_type + "_" + user_id + "_rss.xml"); XmlWriter xml_writer(FileUtil::OpenOutputFileOrDie(xml_output_filename).release(), XmlWriter::WriteTheXmlDeclaration, DEFAULT_XML_INDENT_AMOUNT); WriteRSSFeedXMLOutput(subsystem_type, harvested_items, &xml_writer); } void ProcessFeeds(const std::string &user_id, const std::string &rss_feed_last_notification, const std::string &email_sender, const std::string &user_email, const std::string &user_address, const std::string &language, const std::string &rss_feed_notification_type, const std::string &subsystem_type, DbConnection * const db_connection) { db_connection->queryOrDie("SELECT rss_feeds_id FROM tuefind_rss_subscriptions WHERE user_id=" + user_id); auto rss_subscriptions_result_set(db_connection->getLastResultSet()); std::vector<std::string> feed_ids; while (const auto row = rss_subscriptions_result_set.getNextRow())\ feed_ids.emplace_back(row["rss_feeds_id"]); if (feed_ids.empty()) return; std::vector<HarvestedRSSItem> harvested_items; std::string max_insertion_time; for (const auto &feed_id : feed_ids) { db_connection->queryOrDie("SELECT feed_name,feed_url FROM tuefind_rss_feeds WHERE id=" + feed_id); auto feed_result_set(db_connection->getLastResultSet()); const auto feed_row(feed_result_set.getNextRow()); const auto feed_name(feed_row["feed_name"]); const auto feed_url(feed_row["feed_url"]); feed_result_set.~DbResultSet(); db_connection->queryOrDie("SELECT item_title,item_description,item_url,item_id,pub_date,insertion_time FROM " "tuefind_rss_items WHERE rss_feeds_id=" + feed_id + " AND insertion_time > '" + rss_feed_last_notification + "'"); auto items_result_set(db_connection->getLastResultSet()); while (const auto item_row = items_result_set.getNextRow()) { harvested_items.emplace_back(SyndicationFormat::Item(item_row["item_title"], item_row["item_description"], item_row["item_url"], item_row["item_id"], SqlUtil::DatetimeToTimeT(item_row["pub_date"])), feed_name, feed_url); const auto insertion_time(item_row["insertion_time"]); if (insertion_time > max_insertion_time) max_insertion_time = insertion_time; } } if (rss_feed_notification_type == "email") SendEmail(email_sender, user_email, user_address, language, harvested_items); else GenerateFeed(user_id, subsystem_type, harvested_items); db_connection->queryOrDie("INSERT INTO user SET tuefind_rss_feed_last_notification='" + max_insertion_time + "' WHERE id=" + user_id); } // Yes, this function has a confusing name but I could not think of a better one. // What is meant is how to address a user! std::string GenerateUserAddress(const std::string &appellation, const std::string &first_name, const std::string &last_name) { if (last_name.empty()) return first_name; if (appellation.empty()) return first_name + " " + last_name; return appellation + " " + last_name; } } // unnamed namespace struct UserInfo { std::string user_id_; std::string first_name_; std::string last_name_; std::string email_; std::string rss_feed_notification_type_; std::string rss_feed_last_notification_; public: UserInfo() = default; UserInfo(const UserInfo &other) = default; UserInfo(const std::string &user_id, const std::string &first_name, const std::string &last_name, const std::string &email, const std::string &rss_feed_notification_type, const std::string &rss_feed_last_notification) : user_id_(user_id), first_name_(first_name), last_name_(last_name), email_(email), rss_feed_notification_type_(rss_feed_notification_type), rss_feed_last_notification_(rss_feed_last_notification) { } }; int Main(int argc, char *argv[]) { if (argc != 2) Usage(); const std::string email_address(argv[1]); const auto db_connection(VuFind::GetDbConnection()); db_connection->queryOrDie("SELECT id,firstname,lastname,email,tuefind_rss_feed_notification_type" ",tuefind_rss_feed_last_notification FROM user " "WHERE tuefind_rss_feed_notification_type IS NOT NULL"); auto user_result_set(db_connection->getLastResultSet()); std::unordered_map<std::string, UserInfo> ids_to_user_infos_map; while (const auto user_row = user_result_set.getNextRow()) ids_to_user_infos_map[user_row["id"]] = UserInfo(user_row["id"], user_row["firstname"], user_row["lastname"], user_row["email"], user_row["tuefind_rss_feed_notification_type"], user_row["tuefind_rss_feed_last_notification"]); unsigned feed_generation_count(0), email_sent_count(0); for (const auto &[user_id, user_info] : ids_to_user_infos_map) { if (user_info.rss_feed_notification_type_ == "email" and not EmailSender::IsValidEmailAddress(user_info.email_)) { LOG_WARNING("no valid email address for vfind.user.id " + user_id + "!"); continue; } db_connection->queryOrDie("SELECT appellation,language,user_type FROM ixtheo_user"); auto ixtheo_user_row(db_connection->getLastResultSet().getNextRow()); const auto appellation(ixtheo_user_row.getValue("appellation")); const auto language(ixtheo_user_row.getValue("language", "en")); const auto subsystem_type(ixtheo_user_row["user_type"]); ProcessFeeds(user_id, user_info.rss_feed_last_notification_, email_address, user_info.email_, GenerateUserAddress(appellation, user_info.first_name_, user_info.last_name_), language, user_info.rss_feed_notification_type_, subsystem_type, db_connection.get()); user_info.rss_feed_notification_type_ == "email" ? ++email_sent_count : ++feed_generation_count; } LOG_INFO("Generated " + std::to_string(feed_generation_count) + " RSS feed(s) and sent " + std::to_string(email_sent_count) + " email(s)."); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** \file rss_subset_aggregator.cc * \brief Aggregates RSS feeds. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2021 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <map> #include <unordered_map> #include <unordered_set> #include <cinttypes> #include <cstring> #include "Compiler.h" #include "DbConnection.h" #include "DbResultSet.h" #include "EmailSender.h" #include "FileUtil.h" #include "HtmlUtil.h" #include "SqlUtil.h" #include "StringUtil.h" #include "SyndicationFormat.h" #include "Template.h" #include "UBTools.h" #include "util.h" #include "VuFind.h" #include "XmlWriter.h" namespace { [[noreturn]] void Usage() { ::Usage("email_address [user_id]\n" "If a user ID has been specified, an RSS feed only for that ID will be generated,o/w aggregate processing takes place."); } struct HarvestedRSSItem { SyndicationFormat::Item item_; std::string feed_title_; std::string feed_url_; HarvestedRSSItem(const SyndicationFormat::Item item, const std::string feed_title, const std::string feed_url) : item_(item), feed_title_(feed_title), feed_url_(feed_url) {} }; struct ChannelDesc { std::string title_; std::string link_; public: ChannelDesc(const std::string &title, const std::string &link) : title_(title), link_(link) { } }; const std::map<std::string, ChannelDesc> subsystem_type_to_channel_desc_map = { { "relbib", ChannelDesc("RelBib RSS Aggregator", "https://relbib.de/") }, { "ixtheo", ChannelDesc("IxTheo RSS Aggregator", "https://itheo.de/") }, { "krimdok", ChannelDesc("KrimDok RSS Aggregator", "https://krimdok.uni-tuebingen.de/") }, }; std::string GetChannelDescEntry(const std::string &subsystem_type, const std::string &entry) { const auto subsystem_type_and_channel_desc(subsystem_type_to_channel_desc_map.find(subsystem_type)); if (subsystem_type_and_channel_desc == subsystem_type_to_channel_desc_map.cend()) LOG_ERROR("unknown subsystem type \"" + subsystem_type + "\"!"); if (entry == "title") return subsystem_type_and_channel_desc->second.title_; if (entry == "link") return subsystem_type_and_channel_desc->second.link_; LOG_ERROR("unknown entry name \"" + entry + "\"!"); } void WriteRSSFeedXMLOutput(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items, XmlWriter * const xml_writer) { xml_writer->openTag("rss", { { "version", "2.0" } }); xml_writer->openTag("channel"); xml_writer->writeTagsWithData("title", GetChannelDescEntry(subsystem_type, "title")); xml_writer->writeTagsWithData("link", GetChannelDescEntry(subsystem_type, "link")); xml_writer->writeTagsWithData("description", "RSS Aggregator"); for (const auto &harvested_item : harvested_items) { xml_writer->openTag("item"); const auto title(harvested_item.item_.getTitle()); if (not title.empty()) xml_writer->writeTagsWithData("title", harvested_item.item_.getTitle()); xml_writer->writeTagsWithData("link", harvested_item.item_.getLink()); const auto description(HtmlUtil::ShortenText(harvested_item.item_.getDescription(), /*max_length = */500)); if (not description.empty()) xml_writer->writeTagsWithData("description", description); xml_writer->writeTagsWithData("pubDate", TimeUtil::TimeTToString(harvested_item.item_.getPubDate(), TimeUtil::RFC822_FORMAT, TimeUtil::UTC)); xml_writer->writeTagsWithData("guid", harvested_item.item_.getId()); xml_writer->closeTag("item", /* suppress_indent */ false); } xml_writer->closeTag("channel"); xml_writer->closeTag("rss"); } struct FeedNameAndURL { std::string name_; std::string url_; public: FeedNameAndURL() = default; FeedNameAndURL(const FeedNameAndURL &other) = default; FeedNameAndURL(const std::string &name, const std::string &url) : name_(name), url_(url) { } }; // \return True if a notification email was sent successfully, o/w false. bool SendEmail(const std::string &subsystem_type, const std::string &email_sender, const std::string &user_email, const std::string &user_address, const std::string &language, const std::vector<HarvestedRSSItem> &harvested_items) { const auto template_filename_prefix(UBTools::GetTuelibPath() + "rss_email.template"); std::string template_filename(template_filename_prefix + "." + language); if (not FileUtil::Exists(template_filename)) template_filename = template_filename_prefix + ".en"; static const std::string email_template(FileUtil::ReadStringOrDie(template_filename)); Template::Map names_to_values_map; names_to_values_map.insertScalar("user_email", user_email); names_to_values_map.insertScalar("user_address", user_address); std::vector<std::string> titles, links, descriptions; for (const auto &harvested_item : harvested_items) { titles.emplace_back(HtmlUtil::HtmlEscape(harvested_item.item_.getTitle())); links.emplace_back(harvested_item.item_.getLink()); descriptions.emplace_back(HtmlUtil::HtmlEscape(harvested_item.item_.getDescription())); } names_to_values_map.insertArray("titles", titles); names_to_values_map.insertArray("links", links); names_to_values_map.insertArray("descriptions", descriptions); const auto email_body(Template::ExpandTemplate(email_template, names_to_values_map)); const auto retcode(EmailSender::SimplerSendEmail(email_sender, { user_email }, GetChannelDescEntry(subsystem_type, "title"), email_body, EmailSender::DO_NOT_SET_PRIORITY, EmailSender::HTML)); if (retcode <= 299) return true; LOG_WARNING("EmailSender::SimplerSendEmail returned " + std::to_string(retcode) + " while trying to send to \"" + user_email + "\"!"); return false; } const unsigned DEFAULT_XML_INDENT_AMOUNT(2); void GenerateFeed(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items) { XmlWriter xml_writer(FileUtil::OpenOutputFileOrDie("/dev/stdout").release(), XmlWriter::WriteTheXmlDeclaration, DEFAULT_XML_INDENT_AMOUNT); WriteRSSFeedXMLOutput(subsystem_type, harvested_items, &xml_writer); } bool ProcessFeeds(const std::string &user_id, const std::string &rss_feed_last_notification, const std::string &email_sender, const std::string &user_email, const std::string &user_address, const std::string &language, const bool send_email, const std::string &subsystem_type, DbConnection * const db_connection) { db_connection->queryOrDie("SELECT rss_feeds_id FROM tuefind_rss_subscriptions WHERE user_id=" + user_id); auto rss_subscriptions_result_set(db_connection->getLastResultSet()); std::vector<std::string> feed_ids; while (const auto row = rss_subscriptions_result_set.getNextRow())\ feed_ids.emplace_back(row["rss_feeds_id"]); if (feed_ids.empty()) return false; std::vector<HarvestedRSSItem> harvested_items; std::string max_insertion_time; for (const auto &feed_id : feed_ids) { db_connection->queryOrDie("SELECT feed_name,feed_url FROM tuefind_rss_feeds WHERE id=" + feed_id); auto feed_result_set(db_connection->getLastResultSet()); const auto feed_row(feed_result_set.getNextRow()); const auto feed_name(feed_row["feed_name"]); const auto feed_url(feed_row["feed_url"]); feed_result_set.~DbResultSet(); db_connection->queryOrDie("SELECT item_title,item_description,item_url,item_id,pub_date,insertion_time FROM " "tuefind_rss_items WHERE rss_feeds_id=" + feed_id + " AND insertion_time > '" + rss_feed_last_notification + "'"); auto items_result_set(db_connection->getLastResultSet()); while (const auto item_row = items_result_set.getNextRow()) { harvested_items.emplace_back(SyndicationFormat::Item(item_row["item_title"], item_row["item_description"], item_row["item_url"], item_row["item_id"], SqlUtil::DatetimeToTimeT(item_row["pub_date"])), feed_name, feed_url); const auto insertion_time(item_row["insertion_time"]); if (insertion_time > max_insertion_time) max_insertion_time = insertion_time; } } if (harvested_items.empty()) return false; GenerateFeed(subsystem_type, harvested_items); if (send_email) { if (not SendEmail(subsystem_type, email_sender, user_email, user_address, language, harvested_items)) return true; db_connection->queryOrDie("INSERT INTO user SET tuefind_rss_feed_last_notification='" + max_insertion_time + "' WHERE id=" + user_id); } return true; } // Yes, this function has a confusing name but I could not think of a better one. :-( // What is meant is how to address a user! std::string GenerateUserAddress(const std::string &appellation, const std::string &first_name, const std::string &last_name) { if (last_name.empty()) return first_name; if (appellation.empty()) return first_name + " " + last_name; return appellation + " " + last_name; } } // unnamed namespace struct UserInfo { std::string user_id_; std::string first_name_; std::string last_name_; std::string email_; bool rss_feed_send_emails_; std::string rss_feed_last_notification_; public: UserInfo() = default; UserInfo(const UserInfo &other) = default; UserInfo(const std::string &user_id, const std::string &first_name, const std::string &last_name, const std::string &email, const bool &rss_feed_send_emails, const std::string &rss_feed_last_notification) : user_id_(user_id), first_name_(first_name), last_name_(last_name), email_(email), rss_feed_send_emails_(rss_feed_send_emails), rss_feed_last_notification_(rss_feed_last_notification) { } }; int Main(int argc, char *argv[]) { if (argc != 2 and argc != 3) Usage(); const std::string email_address(argv[1]); std::string single_user; if (argc == 3) single_user = argv[2]; const auto db_connection(VuFind::GetDbConnection()); db_connection->queryOrDie("SELECT id,firstname,lastname,email,tuefind_rss_feed_send_emails" ",tuefind_rss_feed_last_notification FROM user" + std::string(single_user.empty() ? "" : " WHERE id=" + db_connection->escapeAndQuoteString(single_user))); auto user_result_set(db_connection->getLastResultSet()); std::unordered_map<std::string, UserInfo> ids_to_user_infos_map; while (const auto user_row = user_result_set.getNextRow()) ids_to_user_infos_map[user_row["id"]] = UserInfo(user_row["id"], user_row["firstname"], user_row["lastname"], user_row["email"], (single_user.empty() ? StringUtil::ToBool(user_row["tuefind_rss_feed_send_emails"]) : false), user_row["tuefind_rss_feed_last_notification"]); unsigned feed_generation_count(0), email_sent_count(0); for (const auto &[user_id, user_info] : ids_to_user_infos_map) { if (user_info.rss_feed_send_emails_ and not EmailSender::IsValidEmailAddress(user_info.email_)) { LOG_WARNING("no valid email address for vfind.user.id " + user_id + "!"); continue; } db_connection->queryOrDie("SELECT appellation,language,user_type FROM ixtheo_user"); auto ixtheo_user_row(db_connection->getLastResultSet().getNextRow()); const auto appellation(ixtheo_user_row.getValue("appellation")); const auto language(ixtheo_user_row.getValue("language", "en")); const auto subsystem_type(ixtheo_user_row["user_type"]); if (ProcessFeeds(user_id, user_info.rss_feed_last_notification_, email_address, user_info.email_, GenerateUserAddress(appellation, user_info.first_name_, user_info.last_name_), language, user_info.rss_feed_send_emails_, subsystem_type, db_connection.get())) { if (user_info.rss_feed_send_emails_) ++email_sent_count; ++feed_generation_count; } } LOG_INFO("Generated " + std::to_string(feed_generation_count) + " RSS feed(s) and sent " + std::to_string(email_sent_count) + " email(s)."); return EXIT_SUCCESS; } <commit_msg>Major cleanup.<commit_after>/** \file rss_subset_aggregator.cc * \brief Aggregates RSS feeds. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2021 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <map> #include <unordered_map> #include <unordered_set> #include <cinttypes> #include <cstring> #include "Compiler.h" #include "DbConnection.h" #include "DbResultSet.h" #include "EmailSender.h" #include "FileUtil.h" #include "HtmlUtil.h" #include "SqlUtil.h" #include "StringUtil.h" #include "SyndicationFormat.h" #include "Template.h" #include "UBTools.h" #include "util.h" #include "VuFind.h" #include "XmlWriter.h" namespace { [[noreturn]] void Usage() { ::Usage("--mode=(email|rss_xml) (user_id|error_email_address)]\n" "If the mode is \"email\" a VuFind user_id needs to be specified, o/w an error email address should be provided."); } struct HarvestedRSSItem { SyndicationFormat::Item item_; std::string feed_title_; std::string feed_url_; HarvestedRSSItem(const SyndicationFormat::Item item, const std::string feed_title, const std::string feed_url) : item_(item), feed_title_(feed_title), feed_url_(feed_url) {} }; struct ChannelDesc { std::string title_; std::string link_; public: ChannelDesc(const std::string &title, const std::string &link) : title_(title), link_(link) { } }; const std::map<std::string, ChannelDesc> subsystem_type_to_channel_desc_map = { { "relbib", ChannelDesc("RelBib RSS Aggregator", "https://relbib.de/") }, { "ixtheo", ChannelDesc("IxTheo RSS Aggregator", "https://itheo.de/") }, { "krimdok", ChannelDesc("KrimDok RSS Aggregator", "https://krimdok.uni-tuebingen.de/") }, }; std::string GetChannelDescEntry(const std::string &subsystem_type, const std::string &entry) { const auto subsystem_type_and_channel_desc(subsystem_type_to_channel_desc_map.find(subsystem_type)); if (subsystem_type_and_channel_desc == subsystem_type_to_channel_desc_map.cend()) LOG_ERROR("unknown subsystem type \"" + subsystem_type + "\"!"); if (entry == "title") return subsystem_type_and_channel_desc->second.title_; if (entry == "link") return subsystem_type_and_channel_desc->second.link_; LOG_ERROR("unknown entry name \"" + entry + "\"!"); } void WriteRSSFeedXMLOutput(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items, XmlWriter * const xml_writer) { xml_writer->openTag("rss", { { "version", "2.0" } }); xml_writer->openTag("channel"); xml_writer->writeTagsWithData("title", GetChannelDescEntry(subsystem_type, "title")); xml_writer->writeTagsWithData("link", GetChannelDescEntry(subsystem_type, "link")); xml_writer->writeTagsWithData("description", "RSS Aggregator"); for (const auto &harvested_item : harvested_items) { xml_writer->openTag("item"); const auto title(harvested_item.item_.getTitle()); if (not title.empty()) xml_writer->writeTagsWithData("title", harvested_item.item_.getTitle()); xml_writer->writeTagsWithData("link", harvested_item.item_.getLink()); const auto description(HtmlUtil::ShortenText(harvested_item.item_.getDescription(), /*max_length = */500)); if (not description.empty()) xml_writer->writeTagsWithData("description", description); xml_writer->writeTagsWithData("pubDate", TimeUtil::TimeTToString(harvested_item.item_.getPubDate(), TimeUtil::RFC822_FORMAT, TimeUtil::UTC)); xml_writer->writeTagsWithData("guid", harvested_item.item_.getId()); xml_writer->closeTag("item", /* suppress_indent */ false); } xml_writer->closeTag("channel"); xml_writer->closeTag("rss"); } struct FeedNameAndURL { std::string name_; std::string url_; public: FeedNameAndURL() = default; FeedNameAndURL(const FeedNameAndURL &other) = default; FeedNameAndURL(const std::string &name, const std::string &url) : name_(name), url_(url) { } }; // \return True if a notification email was sent successfully, o/w false. bool SendEmail(const std::string &subsystem_type, const std::string &email_sender, const std::string &user_email, const std::string &user_address, const std::string &language, const std::vector<HarvestedRSSItem> &harvested_items) { const auto template_filename_prefix(UBTools::GetTuelibPath() + "rss_email.template"); std::string template_filename(template_filename_prefix + "." + language); if (not FileUtil::Exists(template_filename)) template_filename = template_filename_prefix + ".en"; static const std::string email_template(FileUtil::ReadStringOrDie(template_filename)); Template::Map names_to_values_map; names_to_values_map.insertScalar("user_email", user_email); names_to_values_map.insertScalar("user_address", user_address); std::vector<std::string> titles, links, descriptions; for (const auto &harvested_item : harvested_items) { titles.emplace_back(HtmlUtil::HtmlEscape(harvested_item.item_.getTitle())); links.emplace_back(harvested_item.item_.getLink()); descriptions.emplace_back(HtmlUtil::HtmlEscape(harvested_item.item_.getDescription())); } names_to_values_map.insertArray("titles", titles); names_to_values_map.insertArray("links", links); names_to_values_map.insertArray("descriptions", descriptions); const auto email_body(Template::ExpandTemplate(email_template, names_to_values_map)); const auto retcode(EmailSender::SimplerSendEmail(email_sender, { user_email }, GetChannelDescEntry(subsystem_type, "title"), email_body, EmailSender::DO_NOT_SET_PRIORITY, EmailSender::HTML)); if (retcode <= 299) return true; LOG_WARNING("EmailSender::SimplerSendEmail returned " + std::to_string(retcode) + " while trying to send to \"" + user_email + "\"!"); return false; } const unsigned DEFAULT_XML_INDENT_AMOUNT(2); void GenerateFeed(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items) { XmlWriter xml_writer(FileUtil::OpenOutputFileOrDie("/dev/stdout").release(), XmlWriter::WriteTheXmlDeclaration, DEFAULT_XML_INDENT_AMOUNT); WriteRSSFeedXMLOutput(subsystem_type, harvested_items, &xml_writer); } bool ProcessFeeds(const std::string &user_id, const std::string &rss_feed_last_notification, const std::string &email_sender, const std::string &user_email, const std::string &user_address, const std::string &language, const bool send_email, const std::string &subsystem_type, DbConnection * const db_connection) { db_connection->queryOrDie("SELECT rss_feeds_id FROM tuefind_rss_subscriptions WHERE user_id=" + user_id); auto rss_subscriptions_result_set(db_connection->getLastResultSet()); std::vector<std::string> feed_ids; while (const auto row = rss_subscriptions_result_set.getNextRow())\ feed_ids.emplace_back(row["rss_feeds_id"]); if (feed_ids.empty()) return false; std::vector<HarvestedRSSItem> harvested_items; std::string max_insertion_time; for (const auto &feed_id : feed_ids) { db_connection->queryOrDie("SELECT feed_name,feed_url FROM tuefind_rss_feeds WHERE id=" + feed_id); auto feed_result_set(db_connection->getLastResultSet()); const auto feed_row(feed_result_set.getNextRow()); const auto feed_name(feed_row["feed_name"]); const auto feed_url(feed_row["feed_url"]); feed_result_set.~DbResultSet(); db_connection->queryOrDie("SELECT item_title,item_description,item_url,item_id,pub_date,insertion_time FROM " "tuefind_rss_items WHERE rss_feeds_id=" + feed_id + " AND insertion_time > '" + rss_feed_last_notification + "'"); auto items_result_set(db_connection->getLastResultSet()); while (const auto item_row = items_result_set.getNextRow()) { harvested_items.emplace_back(SyndicationFormat::Item(item_row["item_title"], item_row["item_description"], item_row["item_url"], item_row["item_id"], SqlUtil::DatetimeToTimeT(item_row["pub_date"])), feed_name, feed_url); const auto insertion_time(item_row["insertion_time"]); if (insertion_time > max_insertion_time) max_insertion_time = insertion_time; } } if (harvested_items.empty()) return false; if (send_email) { if (not SendEmail(subsystem_type, email_sender, user_email, user_address, language, harvested_items)) return true; db_connection->queryOrDie("INSERT INTO user SET tuefind_rss_feed_last_notification='" + max_insertion_time + "' WHERE id=" + user_id); } else GenerateFeed(subsystem_type, harvested_items); return true; } // Yes, this function has a confusing name but I could not think of a better one. :-( // What is meant is how to address a user! std::string GenerateUserAddress(const std::string &appellation, const std::string &first_name, const std::string &last_name) { if (last_name.empty()) return first_name; if (appellation.empty()) return first_name + " " + last_name; return appellation + " " + last_name; } } // unnamed namespace struct UserInfo { std::string user_id_; std::string first_name_; std::string last_name_; std::string email_; std::string rss_feed_last_notification_; public: UserInfo() = default; UserInfo(const UserInfo &other) = default; UserInfo(const std::string &user_id, const std::string &first_name, const std::string &last_name, const std::string &email, const std::string &rss_feed_last_notification) : user_id_(user_id), first_name_(first_name), last_name_(last_name), email_(email), rss_feed_last_notification_(rss_feed_last_notification) { } }; int Main(int argc, char *argv[]) { if (argc != 3) Usage(); std::string error_email_address, vufind_user_id; if (std::strcmp(argv[1], "--mode=email") == 0) vufind_user_id = argv[1]; else if (std::strcmp(argv[1], "--mode=rss_xml") == 0) vufind_user_id = argv[1]; else Usage(); const auto db_connection(VuFind::GetDbConnection()); std::string sql_query("SELECT id,firstname,lastname,email,tuefind_rss_feed_send_emails" ",tuefind_rss_feed_last_notification FROM user"); if (vufind_user_id.empty()) sql_query += " WHERE tuefind_rss_feed_send_emails IS TRUE"; else sql_query += " WHERE id=" + db_connection->escapeAndQuoteString(vufind_user_id); db_connection->queryOrDie(sql_query); auto user_result_set(db_connection->getLastResultSet()); std::unordered_map<std::string, UserInfo> ids_to_user_infos_map; while (const auto user_row = user_result_set.getNextRow()) ids_to_user_infos_map[user_row["id"]] = UserInfo(user_row["id"], user_row["firstname"], user_row["lastname"], user_row["email"], user_row["tuefind_rss_feed_last_notification"]); unsigned feed_generation_count(0), email_sent_count(0); for (const auto &[user_id, user_info] : ids_to_user_infos_map) { if (vufind_user_id.empty() and not EmailSender::IsValidEmailAddress(user_info.email_)) { LOG_WARNING("no valid email address for vfind.user.id " + user_id + "!"); continue; } db_connection->queryOrDie("SELECT appellation,language,user_type FROM ixtheo_user"); auto ixtheo_user_row(db_connection->getLastResultSet().getNextRow()); const auto appellation(ixtheo_user_row.getValue("appellation")); const auto language(ixtheo_user_row.getValue("language", "en")); const auto subsystem_type(ixtheo_user_row["user_type"]); if (ProcessFeeds(user_id, user_info.rss_feed_last_notification_, error_email_address, user_info.email_, GenerateUserAddress(appellation, user_info.first_name_, user_info.last_name_), language, vufind_user_id.empty(), subsystem_type, db_connection.get())) { if (vufind_user_id.empty()) ++email_sent_count; ++feed_generation_count; } } LOG_INFO("Generated " + std::to_string(feed_generation_count) + " RSS feed(s) and sent " + std::to_string(email_sent_count) + " email(s)."); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* Copyright (c) 2008, 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/session.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/file_pool.hpp" #include "libtorrent/storage.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/create_torrent.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include <fstream> #include "test.hpp" #include "setup_transfer.hpp" using namespace boost::filesystem; using namespace libtorrent; // proxy: 0=none, 1=socks4, 2=socks5, 3=socks5_pw 4=http 5=http_pw void test_transfer(boost::intrusive_ptr<torrent_info> torrent_file, int proxy) { using namespace libtorrent; session ses; session_settings settings; settings.ignore_limits_on_local_network = false; ses.set_settings(settings); ses.set_severity_level(alert::debug); ses.listen_on(std::make_pair(51000, 52000)); ses.set_download_rate_limit(torrent_file->total_size() / 10); remove_all("./tmp1"); char const* test_name[] = {"no", "SOCKS4", "SOCKS5", "SOCKS5 password", "HTTP", "HTTP password"}; std::cerr << " ==== TESTING " << test_name[proxy] << " proxy ====" << std::endl; if (proxy) { start_proxy(8002, proxy); proxy_settings ps; ps.hostname = "127.0.0.1"; ps.port = 8002; ps.username = "testuser"; ps.password = "testpass"; ps.type = (proxy_settings::proxy_type)proxy; ses.set_web_seed_proxy(ps); } torrent_handle th = ses.add_torrent(*torrent_file, "./tmp1"); std::vector<announce_entry> empty; th.replace_trackers(empty); const size_type total_size = torrent_file->total_size(); float rate_sum = 0.f; float ses_rate_sum = 0.f; for (int i = 0; i < 30; ++i) { torrent_status s = th.status(); session_status ss = ses.status(); std::cerr << (s.progress * 100.f) << " %" << " torrent rate: " << (s.download_rate / 1000.f) << " kB/s" << " session rate: " << (ss.download_rate / 1000.f) << " kB/s" << " session total: " << ss.total_payload_download << " torrent total: " << s.total_payload_download << std::endl; rate_sum += s.download_payload_rate; ses_rate_sum += ss.payload_download_rate; print_alerts(ses, "ses"); if (th.is_seed() && ss.download_rate == 0.f) { TEST_CHECK(ses.status().total_payload_download == total_size); TEST_CHECK(th.status().total_payload_download == total_size); break; } test_sleep(1000); } std::cerr << "total_size: " << total_size << " rate_sum: " << rate_sum << " session_rate_sum: " << ses_rate_sum << std::endl; // the rates for each second should sum up to the total, with a 10% error margin TEST_CHECK(fabs(rate_sum - total_size) < total_size * .1f); TEST_CHECK(fabs(ses_rate_sum - total_size) < total_size * .1f); TEST_CHECK(th.is_seed()); if (proxy) stop_proxy(8002); remove_all("./tmp1"); } int test_main() { using namespace libtorrent; using namespace boost::filesystem; create_directory("test_torrent"); char random_data[300000]; std::srand(std::time(0)); std::generate(random_data, random_data + sizeof(random_data), &std::rand); std::ofstream("./test_torrent/test1").write(random_data, 35); std::ofstream("./test_torrent/test2").write(random_data, 16536 - 35); std::ofstream("./test_torrent/test3").write(random_data, 16536); std::ofstream("./test_torrent/test4").write(random_data, 17); std::ofstream("./test_torrent/test5").write(random_data, 16536); std::ofstream("./test_torrent/test6").write(random_data, 300000); std::ofstream("./test_torrent/test7").write(random_data, 300000); file_storage fs; add_files(fs, path("test_torrent")); libtorrent::create_torrent t(fs, 16 * 1024); t.add_url_seed("http://127.0.0.1:8000/"); start_web_server(8000); // calculate the hash for all pieces int num = t.num_pieces(); std::vector<char> buf(t.piece_length()); file_pool fp; boost::scoped_ptr<storage_interface> s(default_storage_constructor( fs, ".", fp)); for (int i = 0; i < num; ++i) { s->read(&buf[0], i, 0, fs.piece_size(i)); hasher h(&buf[0], fs.piece_size(i)); t.set_hash(i, h.final()); } boost::intrusive_ptr<torrent_info> torrent_file(new torrent_info(t.generate())); for (int i = 0; i < 6; ++i) test_transfer(torrent_file, i); stop_web_server(8000); remove_all("./test_torrent"); return 0; } <commit_msg>fix to test_web_seed<commit_after>/* Copyright (c) 2008, 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/session.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/file_pool.hpp" #include "libtorrent/storage.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/create_torrent.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include <fstream> #include "test.hpp" #include "setup_transfer.hpp" using namespace boost::filesystem; using namespace libtorrent; // proxy: 0=none, 1=socks4, 2=socks5, 3=socks5_pw 4=http 5=http_pw void test_transfer(boost::intrusive_ptr<torrent_info> torrent_file, int proxy) { using namespace libtorrent; session ses; session_settings settings; settings.ignore_limits_on_local_network = false; ses.set_settings(settings); ses.set_severity_level(alert::debug); ses.listen_on(std::make_pair(51000, 52000)); ses.set_download_rate_limit(torrent_file->total_size() / 10); remove_all("./tmp1"); char const* test_name[] = {"no", "SOCKS4", "SOCKS5", "SOCKS5 password", "HTTP", "HTTP password"}; std::cerr << " ==== TESTING " << test_name[proxy] << " proxy ====" << std::endl; if (proxy) { start_proxy(8002, proxy); proxy_settings ps; ps.hostname = "127.0.0.1"; ps.port = 8002; ps.username = "testuser"; ps.password = "testpass"; ps.type = (proxy_settings::proxy_type)proxy; ses.set_web_seed_proxy(ps); } torrent_handle th = ses.add_torrent(*torrent_file, "./tmp1"); std::vector<announce_entry> empty; th.replace_trackers(empty); const size_type total_size = torrent_file->total_size(); float rate_sum = 0.f; float ses_rate_sum = 0.f; for (int i = 0; i < 30; ++i) { torrent_status s = th.status(); session_status ss = ses.status(); std::cerr << (s.progress * 100.f) << " %" << " torrent rate: " << (s.download_rate / 1000.f) << " kB/s" << " session rate: " << (ss.download_rate / 1000.f) << " kB/s" << " session total: " << ss.total_payload_download << " torrent total: " << s.total_payload_download << std::endl; rate_sum += s.download_payload_rate; ses_rate_sum += ss.payload_download_rate; print_alerts(ses, "ses"); if (th.is_seed() && ss.download_rate == 0.f) { TEST_CHECK(ses.status().total_payload_download == total_size); TEST_CHECK(th.status().total_payload_download == total_size); break; } test_sleep(1000); } std::cerr << "total_size: " << total_size << " rate_sum: " << rate_sum << " session_rate_sum: " << ses_rate_sum << std::endl; // the rates for each second should sum up to the total, with a 10% error margin TEST_CHECK(fabs(rate_sum - total_size) < total_size * .1f); TEST_CHECK(fabs(ses_rate_sum - total_size) < total_size * .1f); TEST_CHECK(th.is_seed()); if (proxy) stop_proxy(8002); remove_all("./tmp1"); } int test_main() { using namespace libtorrent; using namespace boost::filesystem; try { create_directory("test_torrent"); } catch (std::exception&) {} char random_data[300000]; std::srand(std::time(0)); std::generate(random_data, random_data + sizeof(random_data), &std::rand); std::ofstream("./test_torrent/test1").write(random_data, 35); std::ofstream("./test_torrent/test2").write(random_data, 16536 - 35); std::ofstream("./test_torrent/test3").write(random_data, 16536); std::ofstream("./test_torrent/test4").write(random_data, 17); std::ofstream("./test_torrent/test5").write(random_data, 16536); std::ofstream("./test_torrent/test6").write(random_data, 300000); std::ofstream("./test_torrent/test7").write(random_data, 300000); file_storage fs; add_files(fs, path("test_torrent")); libtorrent::create_torrent t(fs, 16 * 1024); t.add_url_seed("http://127.0.0.1:8000/"); start_web_server(8000); // calculate the hash for all pieces int num = t.num_pieces(); std::vector<char> buf(t.piece_length()); file_pool fp; boost::scoped_ptr<storage_interface> s(default_storage_constructor( fs, ".", fp)); for (int i = 0; i < num; ++i) { s->read(&buf[0], i, 0, fs.piece_size(i)); hasher h(&buf[0], fs.piece_size(i)); t.set_hash(i, h.final()); } boost::intrusive_ptr<torrent_info> torrent_file(new torrent_info(t.generate())); for (int i = 0; i < 6; ++i) test_transfer(torrent_file, i); stop_web_server(8000); remove_all("./test_torrent"); return 0; } <|endoftext|>
<commit_before>#include "catch.hpp" #include "util.h" #include <tokenizer.h> #include <grammar_loader.h> using namespace shl; TEST_CASE("Tokenizer Tests") { Tokenizer tokenizer; GrammarLoader loader; SECTION("can load grammar and tokenizer string") { string data = load_string("fixture/hello.json"); string source = "hello world!"; Grammar g = loader.load(data); auto tokens = tokenizer.tokenize(g, source); REQUIRE( tokens.size() == 4 ); REQUIRE( tokens[0].first.substr(source) == source ); REQUIRE( tokens[0].second.name() == "source.hello" ); REQUIRE( tokens[1].first.substr(source) == "hello" ); REQUIRE( tokens[1].second.name() == "source.hello prefix.hello" ); REQUIRE( tokens[2].first.substr(source) == "world!" ); REQUIRE( tokens[2].second.name() == "source.hello suffix.hello" ); REQUIRE( tokens[3].first.substr(source) == "!" ); REQUIRE( tokens[3].second.name() == "source.hello suffix.hello emphasis.hello" ); } SECTION("return a single token when matches a single pattern with no capture groups") { string data = load_string("fixture/coffee-script.json"); string source = "return"; Grammar g = loader.load(data); auto tokens = tokenizer.tokenize(g, source); REQUIRE( tokens.size() == 2 ); REQUIRE( tokens[1].first.substr(source) == "return" ); REQUIRE( tokens[1].second.name() == "source.coffee keyword.control.coffee" ); } SECTION("return several tokens when matches a single pattern with capture gorups") { string data = load_string("fixture/coffee-script.json"); string source = "new foo.bar.Baz"; Grammar g = loader.load(data); auto tokens = tokenizer.tokenize(g, source); REQUIRE( tokens.size() == 4 ); REQUIRE( tokens[1].first.substr(source) == source ); REQUIRE( tokens[1].second.name() == "source.coffee meta.class.instance.constructor" ); REQUIRE( tokens[2].first.substr(source) == "new" ); REQUIRE( tokens[2].second.name() == "source.coffee meta.class.instance.constructor keyword.operator.new.coffee" ); REQUIRE( tokens[3].first.substr(source) == "foo.bar.Baz" ); REQUIRE( tokens[3].second.name() == "source.coffee meta.class.instance.constructor entity.name.type.instance.coffee" ); } SECTION("return grammar top level token when no match at all") { string data = load_string("fixture/text.json"); string source = "abc def"; Grammar g = loader.load(data); auto tokens = tokenizer.tokenize(g, source); REQUIRE( tokens.size() == 1 ); REQUIRE( tokens[0].first.substr(source) == source ); REQUIRE( tokens[0].second.name() == "text.plain" ); } } <commit_msg>add some test<commit_after>#include "catch.hpp" #include "util.h" #include <tokenizer.h> #include <grammar_loader.h> using namespace shl; TEST_CASE("Tokenizer Tests") { Tokenizer tokenizer; GrammarLoader loader; SECTION("can load grammar and tokenizer string") { string data = load_string("fixture/hello.json"); string source = "hello world!"; Grammar g = loader.load(data); auto tokens = tokenizer.tokenize(g, source); REQUIRE( tokens.size() == 4 ); REQUIRE( tokens[0].first.substr(source) == source ); REQUIRE( tokens[0].second.name() == "source.hello" ); REQUIRE( tokens[1].first.substr(source) == "hello" ); REQUIRE( tokens[1].second.name() == "source.hello prefix.hello" ); REQUIRE( tokens[2].first.substr(source) == "world!" ); REQUIRE( tokens[2].second.name() == "source.hello suffix.hello" ); REQUIRE( tokens[3].first.substr(source) == "!" ); REQUIRE( tokens[3].second.name() == "source.hello suffix.hello emphasis.hello" ); } SECTION("return a single token when matches a single pattern with no capture groups") { string data = load_string("fixture/coffee-script.json"); string source = "return"; Grammar g = loader.load(data); auto tokens = tokenizer.tokenize(g, source); REQUIRE( tokens.size() == 2 ); REQUIRE( tokens[1].first.substr(source) == "return" ); REQUIRE( tokens[1].second.name() == "source.coffee keyword.control.coffee" ); } SECTION("return several tokens when matches a single pattern with capture gorups") { string data = load_string("fixture/coffee-script.json"); string source = "new foo.bar.Baz"; Grammar g = loader.load(data); auto tokens = tokenizer.tokenize(g, source); REQUIRE( tokens.size() == 4 ); REQUIRE( tokens[1].first.substr(source) == source ); REQUIRE( tokens[1].second.name() == "source.coffee meta.class.instance.constructor" ); REQUIRE( tokens[2].first.substr(source) == "new" ); REQUIRE( tokens[2].second.name() == "source.coffee meta.class.instance.constructor keyword.operator.new.coffee" ); REQUIRE( tokens[3].first.substr(source) == "foo.bar.Baz" ); REQUIRE( tokens[3].second.name() == "source.coffee meta.class.instance.constructor entity.name.type.instance.coffee" ); } SECTION("return grammar top level token when no match at all") { string data = load_string("fixture/text.json"); string source = " "; Grammar g = loader.load(data); auto tokens = tokenizer.tokenize(g, source); REQUIRE( tokens.size() == 1 ); REQUIRE( tokens[0].first.substr(source) == source ); REQUIRE( tokens[0].second.name() == "text.plain" ); } SECTION("the enclosing scope will cover the sub-scopes") { string data = load_string("fixture/coffee-script.json"); string source = " return new foo.bar.Baz "; Grammar g = loader.load(data); auto tokens = tokenizer.tokenize(g, source); REQUIRE( tokens.size() == 5 ); REQUIRE (tokens[0].first.substr(source) == source ); REQUIRE (tokens[0].second.name() == "source.coffee" ); REQUIRE (tokens[1].first.substr(source) == "return" ); REQUIRE (tokens[1].second.name() == "source.coffee keyword.control.coffee" ); REQUIRE (tokens[2].first.substr(source) == "new foo.bar.Baz" ); REQUIRE (tokens[2].second.name() == "source.coffee meta.class.instance.constructor" ); REQUIRE (tokens[3].first.substr(source) == "new" ); REQUIRE (tokens[3].second.name() == "source.coffee meta.class.instance.constructor keyword.operator.new.coffee" ); REQUIRE (tokens[4].first.substr(source) == "foo.bar.Baz" ); REQUIRE (tokens[4].second.name() == "source.coffee meta.class.instance.constructor entity.name.type.instance.coffee" ); } SECTION("only return matched capture groups when match rule has an optional captre groups") { string data = load_string("fixture/coffee-script.json"); string source = "class Foo"; Grammar g = loader.load(data); auto tokens = tokenizer.tokenize(g, source); REQUIRE( tokens.size() == 4 ); REQUIRE( tokens[0].first.substr(source) == source ); REQUIRE (tokens[0].second.name() == "source.coffee" ); REQUIRE( tokens[1].first.substr(source) == source ); REQUIRE (tokens[1].second.name() == "source.coffee meta.class.coffee" ); REQUIRE( tokens[2].first.substr(source) == "class" ); REQUIRE (tokens[2].second.name() == "source.coffee meta.class.coffee storage.type.class.coffee" ); REQUIRE( tokens[3].first.substr(source) == "Foo" ); REQUIRE (tokens[3].second.name() == "source.coffee meta.class.coffee entity.name.type.class.coffee" ); } } <|endoftext|>
<commit_before>// Copyright (c) 2017 Franka Emika GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #include <array> #include <atomic> #include <cmath> #include <functional> #include <iostream> #include <iterator> #include <mutex> #include <thread> #include <franka/duration.h> #include <franka/exception.h> #include <franka/model.h> #include <franka/robot.h> namespace { template <class T, size_t N> std::ostream& operator<<(std::ostream& ostream, const std::array<T, N>& array) { ostream << "["; std::copy(array.cbegin(), array.cend() - 1, std::ostream_iterator<T>(ostream, ",")); std::copy(array.cend() - 1, array.cend(), std::ostream_iterator<T>(ostream)); ostream << "]"; return ostream; } } // anonymous namespace /** * @example joint_impedance_control.cpp * An example showing a joint impedance type control that executes a Cartesian motion in the shape * of a circle. The example illustrates how to use the internal inverse kinematics to map a * Cartesian trajectory to joint space. The joint space target is tracked by an impedance control * that additionally compensates coriolis terms using the libfranka model library. This example also * serves to compare commanded vs. measured torques. The results are printed from a separate thread * to avoid blocking print functions in the real-time loop. */ int main(int argc, char** argv) { // Check whether the required arguments were passed. if (argc != 5) { std::cerr << "Usage: ./" << argv[0] << " <robot-hostname>" << " <radius in [m]>" << " <vel_max in [m/s]>" << " <print_rate in [Hz]>" << std::endl; return -1; } // Set and initialize trajectory parameters. const double radius = std::stod(argv[2]); const double vel_max = std::stod(argv[3]); const double acceleration_time = 2.0; double vel_current = 0.0; double angle = 0.0; double time = 0.0; const double run_time = 20.0; // Set print rate for comparing commanded vs. measured torques. double print_rate = std::stod(argv[4]); if (print_rate < 0.0) { std::cerr << "print_rate too small, must be >= 0.0" << std::endl; return -1; } // Initialize data fields for the print thread. struct { std::mutex mutex; bool has_data; std::array<double, 7> tau_d_last; franka::RobotState robot_state; std::array<double, 7> gravity; } print_data{}; std::atomic_bool running{true}; // Start print thread. std::thread print_thread([print_rate, &print_data, &running]() { while (running) { // Sleep to achieve the desired print rate. std::this_thread::sleep_for( std::chrono::milliseconds(static_cast<int>((1.0 / print_rate * 1000.0)))); // Try to lock data to avoid read write collisions. if (print_data.mutex.try_lock() && print_data.has_data) { std::array<double, 7> tau_error{}; double error_rms(0.0); std::array<double, 7> tau_d_actual{}; for (size_t i = 0; i < 7; ++i) { tau_d_actual[i] = print_data.tau_d_last[i] + print_data.gravity[i]; tau_error[i] = tau_d_actual[i] - print_data.robot_state.tau_J[i]; error_rms += std::sqrt(std::pow(tau_error[i], 2.0)) / tau_error.size(); } // Print data to console std::cout << "tau_error [Nm]: " << tau_error << std::endl << "tau_commanded [Nm]: " << tau_d_actual << std::endl << "tau_measured [Nm]: " << print_data.robot_state.tau_J << std::endl << "root mean square of tau_error [Nm]: " << error_rms << std::endl << "-----------------------" << std::endl; print_data.has_data = false; print_data.mutex.unlock(); } } }); try { // Connect to robot. franka::Robot robot(argv[1]); // Set collision behavior. robot.setCollisionBehavior( {{20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0}}, {{20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0}}, {{20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0}}, {{20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0}}, {{20.0, 20.0, 20.0, 25.0, 25.0, 25.0}}, {{20.0, 20.0, 20.0, 25.0, 25.0, 25.0}}, {{20.0, 20.0, 20.0, 25.0, 25.0, 25.0}}, {{20.0, 20.0, 20.0, 25.0, 25.0, 25.0}}); // Load the kinematics and dynamics model. franka::Model model = robot.loadModel(); // Read the initial pose to start the motion from there. std::array<double, 16> initial_pose = robot.readOnce().O_T_EE; // Define callback function to send Cartesian pose goals to get inverse kinematics solved. std::function<franka::CartesianPose(const franka::RobotState&, franka::Duration)> cartesian_pose_callback = [=, &time, &vel_current, &running, &angle]( const franka::RobotState& /*state*/, franka::Duration period) -> franka::CartesianPose { // Update time. time += period.toSec(); // Compute Cartesian velocity. if (vel_current < vel_max && time < run_time) { vel_current += period.toSec() * std::fabs(vel_max / acceleration_time); } if (vel_current > 0.0 && time > run_time) { vel_current -= period.toSec() * std::fabs(vel_max / acceleration_time); } vel_current = std::fmax(vel_current, 0.0); vel_current = std::fmin(vel_current, vel_max); // Compute new angle for our circular trajectory. angle += period.toSec() * vel_current / std::fabs(radius); if (angle > 2 * M_PI) { angle -= 2 * M_PI; } // Compute relative y and z positions of desired pose. double delta_y = radius * (1 - std::cos(angle)); double delta_z = radius * std::sin(angle); franka::CartesianPose pose_desired = initial_pose; pose_desired.O_T_EE[13] += delta_y; pose_desired.O_T_EE[14] += delta_z; // Send desired pose. if (time >= run_time + acceleration_time) { running = false; return franka::MotionFinished(pose_desired); } return pose_desired; }; // Set gains for the joint impedance control. // Stiffness const std::array<double, 7> k_gains = {{1000.0, 1000.0, 1000.0, 1000.0, 500.0, 300.0, 100.0}}; // Damping const std::array<double, 7> d_gains = {{100.0, 100.0, 100.0, 100.0, 50.0, 30.0, 10.0}}; // Define callback for the joint torque control loop. std::function<franka::Torques(const franka::RobotState&, franka::Duration)> impedance_control_callback = [&print_data, &model, k_gains, d_gains]( const franka::RobotState& state, franka::Duration /*period*/) -> franka::Torques { // Read current coriolis terms from model. std::array<double, 7> coriolis = model.coriolis( state, {{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}}, 0.0, {{0.0, 0.0, 0.0}}); // Compute torque command from joint impedance control law. // Note: The answer to our Cartesian pose inverse kinematics is always in state.q_d with one // time step delay. std::array<double, 7> tau_d; for (size_t i = 0; i < 7; i++) { tau_d[i] = k_gains[i] * (state.q_d[i] - state.q[i]) - d_gains[i] * state.dq[i] + coriolis[i]; } // Update data to print. if (print_data.mutex.try_lock()) { print_data.has_data = true; print_data.robot_state = state; print_data.tau_d_last = tau_d; print_data.gravity = model.gravity(state, 0.0, {{0.0, 0.0, 0.0}}); print_data.mutex.unlock(); } // Send torque command. return tau_d; }; // Start real-time control loop. robot.control(impedance_control_callback, cartesian_pose_callback); } catch (const franka::Exception& ex) { running = false; std::cerr << ex.what() << std::endl; } if (print_thread.joinable()) { print_thread.join(); } return 0; } <commit_msg>Add warning about endeffector in the description<commit_after>// Copyright (c) 2017 Franka Emika GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #include <array> #include <atomic> #include <cmath> #include <functional> #include <iostream> #include <iterator> #include <mutex> #include <thread> #include <franka/duration.h> #include <franka/exception.h> #include <franka/model.h> #include <franka/robot.h> namespace { template <class T, size_t N> std::ostream& operator<<(std::ostream& ostream, const std::array<T, N>& array) { ostream << "["; std::copy(array.cbegin(), array.cend() - 1, std::ostream_iterator<T>(ostream, ",")); std::copy(array.cend() - 1, array.cend(), std::ostream_iterator<T>(ostream)); ostream << "]"; return ostream; } } // anonymous namespace /** * @example joint_impedance_control.cpp * An example showing a joint impedance type control that executes a Cartesian motion in the shape * of a circle. The example illustrates how to use the internal inverse kinematics to map a * Cartesian trajectory to joint space. The joint space target is tracked by an impedance control * that additionally compensates coriolis terms using the libfranka model library. This example * also serves to compare commanded vs. measured torques. The results are printed from a separate * thread to avoid blocking print functions in the real-time loop. * * @warning This example assumes that no endeffector is mounted. */ int main(int argc, char** argv) { // Check whether the required arguments were passed. if (argc != 5) { std::cerr << "Usage: ./" << argv[0] << " <robot-hostname>" << " <radius in [m]>" << " <vel_max in [m/s]>" << " <print_rate in [Hz]>" << std::endl; return -1; } // Set and initialize trajectory parameters. const double radius = std::stod(argv[2]); const double vel_max = std::stod(argv[3]); const double acceleration_time = 2.0; double vel_current = 0.0; double angle = 0.0; double time = 0.0; const double run_time = 20.0; // Set print rate for comparing commanded vs. measured torques. double print_rate = std::stod(argv[4]); if (print_rate < 0.0) { std::cerr << "print_rate too small, must be >= 0.0" << std::endl; return -1; } // Initialize data fields for the print thread. struct { std::mutex mutex; bool has_data; std::array<double, 7> tau_d_last; franka::RobotState robot_state; std::array<double, 7> gravity; } print_data{}; std::atomic_bool running{true}; // Start print thread. std::thread print_thread([print_rate, &print_data, &running]() { while (running) { // Sleep to achieve the desired print rate. std::this_thread::sleep_for( std::chrono::milliseconds(static_cast<int>((1.0 / print_rate * 1000.0)))); // Try to lock data to avoid read write collisions. if (print_data.mutex.try_lock() && print_data.has_data) { std::array<double, 7> tau_error{}; double error_rms(0.0); std::array<double, 7> tau_d_actual{}; for (size_t i = 0; i < 7; ++i) { tau_d_actual[i] = print_data.tau_d_last[i] + print_data.gravity[i]; tau_error[i] = tau_d_actual[i] - print_data.robot_state.tau_J[i]; error_rms += std::sqrt(std::pow(tau_error[i], 2.0)) / tau_error.size(); } // Print data to console std::cout << "tau_error [Nm]: " << tau_error << std::endl << "tau_commanded [Nm]: " << tau_d_actual << std::endl << "tau_measured [Nm]: " << print_data.robot_state.tau_J << std::endl << "root mean square of tau_error [Nm]: " << error_rms << std::endl << "-----------------------" << std::endl; print_data.has_data = false; print_data.mutex.unlock(); } } }); try { // Connect to robot. franka::Robot robot(argv[1]); // Set collision behavior. robot.setCollisionBehavior( {{20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0}}, {{20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0}}, {{20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0}}, {{20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0}}, {{20.0, 20.0, 20.0, 25.0, 25.0, 25.0}}, {{20.0, 20.0, 20.0, 25.0, 25.0, 25.0}}, {{20.0, 20.0, 20.0, 25.0, 25.0, 25.0}}, {{20.0, 20.0, 20.0, 25.0, 25.0, 25.0}}); // Load the kinematics and dynamics model. franka::Model model = robot.loadModel(); // Read the initial pose to start the motion from there. std::array<double, 16> initial_pose = robot.readOnce().O_T_EE; // Define callback function to send Cartesian pose goals to get inverse kinematics solved. std::function<franka::CartesianPose(const franka::RobotState&, franka::Duration)> cartesian_pose_callback = [=, &time, &vel_current, &running, &angle]( const franka::RobotState& /*state*/, franka::Duration period) -> franka::CartesianPose { // Update time. time += period.toSec(); // Compute Cartesian velocity. if (vel_current < vel_max && time < run_time) { vel_current += period.toSec() * std::fabs(vel_max / acceleration_time); } if (vel_current > 0.0 && time > run_time) { vel_current -= period.toSec() * std::fabs(vel_max / acceleration_time); } vel_current = std::fmax(vel_current, 0.0); vel_current = std::fmin(vel_current, vel_max); // Compute new angle for our circular trajectory. angle += period.toSec() * vel_current / std::fabs(radius); if (angle > 2 * M_PI) { angle -= 2 * M_PI; } // Compute relative y and z positions of desired pose. double delta_y = radius * (1 - std::cos(angle)); double delta_z = radius * std::sin(angle); franka::CartesianPose pose_desired = initial_pose; pose_desired.O_T_EE[13] += delta_y; pose_desired.O_T_EE[14] += delta_z; // Send desired pose. if (time >= run_time + acceleration_time) { running = false; return franka::MotionFinished(pose_desired); } return pose_desired; }; // Set gains for the joint impedance control. // Stiffness const std::array<double, 7> k_gains = {{1000.0, 1000.0, 1000.0, 1000.0, 500.0, 300.0, 100.0}}; // Damping const std::array<double, 7> d_gains = {{100.0, 100.0, 100.0, 100.0, 50.0, 30.0, 10.0}}; // Define callback for the joint torque control loop. std::function<franka::Torques(const franka::RobotState&, franka::Duration)> impedance_control_callback = [&print_data, &model, k_gains, d_gains]( const franka::RobotState& state, franka::Duration /*period*/) -> franka::Torques { // Read current coriolis terms from model. std::array<double, 7> coriolis = model.coriolis( state, {{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}}, 0.0, {{0.0, 0.0, 0.0}}); // Compute torque command from joint impedance control law. // Note: The answer to our Cartesian pose inverse kinematics is always in state.q_d with one // time step delay. std::array<double, 7> tau_d; for (size_t i = 0; i < 7; i++) { tau_d[i] = k_gains[i] * (state.q_d[i] - state.q[i]) - d_gains[i] * state.dq[i] + coriolis[i]; } // Update data to print. if (print_data.mutex.try_lock()) { print_data.has_data = true; print_data.robot_state = state; print_data.tau_d_last = tau_d; print_data.gravity = model.gravity(state, 0.0, {{0.0, 0.0, 0.0}}); print_data.mutex.unlock(); } // Send torque command. return tau_d; }; // Start real-time control loop. robot.control(impedance_control_callback, cartesian_pose_callback); } catch (const franka::Exception& ex) { running = false; std::cerr << ex.what() << std::endl; } if (print_thread.joinable()) { print_thread.join(); } return 0; } <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <random> #include "CompileConfig.h" #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) #include <sys/time.h> #endif #if defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) #include <sys/syslog.h> #endif #ifdef OUZEL_PLATFORM_WINDOWS #include <windows.h> #include <strsafe.h> #endif #ifdef OUZEL_PLATFORM_ANDROID #include <android/log.h> #endif #include "Utils.h" namespace ouzel { char TEMP_BUFFER[65536]; void log(const char* format, ...) { va_list list; va_start(list, format); vsprintf(TEMP_BUFFER, format, list); va_end(list); #if defined(OUZEL_PLATFORM_OSX) printf("%s\n", TEMP_BUFFER); #elif defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) syslog(LOG_WARNING, "%s", TEMP_BUFFER); printf("%s\n", TEMP_BUFFER); #elif defined(OUZEL_PLATFORM_WINDOWS) wchar_t szBuffer[MAX_PATH]; MultiByteToWideChar(CP_UTF8, 0, TEMP_BUFFER, -1, szBuffer, MAX_PATH); StringCchCat(szBuffer, sizeof(szBuffer), L"\n"); OutputDebugString(szBuffer); #elif defined(OUZEL_PLATFORM_ANDROID) __android_log_print(ANDROID_LOG_DEBUG, "Ouzel", "%s", TEMP_BUFFER); #endif } uint64_t getCurrentMicroSeconds() { #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) || defined(OUZEL_PLATFORM_ANDROID) struct timeval currentTime; gettimeofday(&currentTime, NULL); return static_cast<uint64_t>(currentTime.tv_sec) * 1000000UL + static_cast<uint64_t>(currentTime.tv_usec); #elif defined(OUZEL_PLATFORM_WINDOWS) static double invFrequency = 0.0; LARGE_INTEGER li; if (invFrequency == 0.0f) { if (!QueryPerformanceFrequency(&li)) { log("Failed to query frequency"); return 0; } invFrequency = 1000000.0 / li.QuadPart; } QueryPerformanceCounter(&li); return static_cast<uint64_t>(li.QuadPart * invFrequency); #else return 0; #endif } std::vector<std::string> ARGS; void setArgs(const std::vector<std::string>& args) { ARGS = args; } const std::vector<std::string>& getArgs() { return ARGS; } static std::mt19937 engine(std::random_device{}()); uint32_t random(uint32_t min, uint32_t max) { return std::uniform_int_distribution<uint32_t>{min, max}(engine); } float randomf(float min, float max) { float diff = max - min; float rand = static_cast<float>(engine()) / engine.max(); return rand * diff + min; } } <commit_msg>Fix min max problem on Windows<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <random> #include "CompileConfig.h" #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) #include <sys/time.h> #endif #if defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) #include <sys/syslog.h> #endif #ifdef OUZEL_PLATFORM_WINDOWS #define NOMINMAX #include <windows.h> #include <strsafe.h> #endif #ifdef OUZEL_PLATFORM_ANDROID #include <android/log.h> #endif #include "Utils.h" namespace ouzel { char TEMP_BUFFER[65536]; void log(const char* format, ...) { va_list list; va_start(list, format); vsprintf(TEMP_BUFFER, format, list); va_end(list); #if defined(OUZEL_PLATFORM_OSX) printf("%s\n", TEMP_BUFFER); #elif defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) syslog(LOG_WARNING, "%s", TEMP_BUFFER); printf("%s\n", TEMP_BUFFER); #elif defined(OUZEL_PLATFORM_WINDOWS) wchar_t szBuffer[MAX_PATH]; MultiByteToWideChar(CP_UTF8, 0, TEMP_BUFFER, -1, szBuffer, MAX_PATH); StringCchCat(szBuffer, sizeof(szBuffer), L"\n"); OutputDebugString(szBuffer); #elif defined(OUZEL_PLATFORM_ANDROID) __android_log_print(ANDROID_LOG_DEBUG, "Ouzel", "%s", TEMP_BUFFER); #endif } uint64_t getCurrentMicroSeconds() { #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) || defined(OUZEL_PLATFORM_ANDROID) struct timeval currentTime; gettimeofday(&currentTime, NULL); return static_cast<uint64_t>(currentTime.tv_sec) * 1000000UL + static_cast<uint64_t>(currentTime.tv_usec); #elif defined(OUZEL_PLATFORM_WINDOWS) static double invFrequency = 0.0; LARGE_INTEGER li; if (invFrequency == 0.0f) { if (!QueryPerformanceFrequency(&li)) { log("Failed to query frequency"); return 0; } invFrequency = 1000000.0 / li.QuadPart; } QueryPerformanceCounter(&li); return static_cast<uint64_t>(li.QuadPart * invFrequency); #else return 0; #endif } std::vector<std::string> ARGS; void setArgs(const std::vector<std::string>& args) { ARGS = args; } const std::vector<std::string>& getArgs() { return ARGS; } static std::mt19937 engine(std::random_device{}()); uint32_t random(uint32_t min, uint32_t max) { return std::uniform_int_distribution<uint32_t>{min, max}(engine); } float randomf(float min, float max) { float diff = max - min; float rand = static_cast<float>(engine()) / engine.max(); return rand * diff + min; } } <|endoftext|>
<commit_before>//===-- UnreachableBlockElim.cpp - Remove unreachable blocks for codegen --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass is an extremely simple version of the SimplifyCFG pass. Its sole // job is to delete LLVM basic blocks that are not reachable from the entry // node. To do this, it performs a simple depth first traversal of the CFG, // then deletes any unvisited nodes. // // Note that this pass is really a hack. In particular, the instruction // selectors for various targets should just not generate code for unreachable // blocks. Until LLVM has a more systematic way of defining instruction // selectors, however, we cannot really expect them to handle additional // complexity. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/Passes.h" #include "llvm/Constant.h" #include "llvm/Instructions.h" #include "llvm/Function.h" #include "llvm/Pass.h" #include "llvm/Type.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/CFG.h" #include "llvm/Support/Compiler.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/ADT/DepthFirstIterator.h" using namespace llvm; namespace { class VISIBILITY_HIDDEN UnreachableBlockElim : public FunctionPass { virtual bool runOnFunction(Function &F); public: static char ID; // Pass identification, replacement for typeid UnreachableBlockElim() : FunctionPass((intptr_t)&ID) {} }; } char UnreachableBlockElim::ID = 0; static RegisterPass<UnreachableBlockElim> X("unreachableblockelim", "Remove unreachable blocks from the CFG"); FunctionPass *llvm::createUnreachableBlockEliminationPass() { return new UnreachableBlockElim(); } bool UnreachableBlockElim::runOnFunction(Function &F) { std::set<BasicBlock*> Reachable; // Mark all reachable blocks. for (df_ext_iterator<Function*> I = df_ext_begin(&F, Reachable), E = df_ext_end(&F, Reachable); I != E; ++I) /* Mark all reachable blocks */; // Loop over all dead blocks, remembering them and deleting all instructions // in them. std::vector<BasicBlock*> DeadBlocks; for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) if (!Reachable.count(I)) { BasicBlock *BB = I; DeadBlocks.push_back(BB); while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { PN->replaceAllUsesWith(Constant::getNullValue(PN->getType())); BB->getInstList().pop_front(); } for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) (*SI)->removePredecessor(BB); BB->dropAllReferences(); } // Actually remove the blocks now. for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i) DeadBlocks[i]->eraseFromParent(); return DeadBlocks.size(); } namespace { class VISIBILITY_HIDDEN UnreachableMachineBlockElim : public MachineFunctionPass { virtual bool runOnMachineFunction(MachineFunction &F); public: static char ID; // Pass identification, replacement for typeid UnreachableMachineBlockElim() : MachineFunctionPass((intptr_t)&ID) {} }; } char UnreachableMachineBlockElim::ID = 0; static RegisterPass<UnreachableMachineBlockElim> Y("unreachable-mbb-elimination", "Remove unreachable machine basic blocks"); const PassInfo *const llvm::UnreachableMachineBlockElimID = &Y; bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) { std::set<MachineBasicBlock*> Reachable; // Mark all reachable blocks. for (df_ext_iterator<MachineFunction*> I = df_ext_begin(&F, Reachable), E = df_ext_end(&F, Reachable); I != E; ++I) /* Mark all reachable blocks */; // Loop over all dead blocks, remembering them and deleting all instructions // in them. std::vector<MachineBasicBlock*> DeadBlocks; for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) if (!Reachable.count(I)) { MachineBasicBlock *BB = I; DeadBlocks.push_back(BB); while (BB->succ_begin() != BB->succ_end()) { MachineBasicBlock* succ = *BB->succ_begin(); MachineBasicBlock::iterator start = succ->begin(); while (start != succ->end() && start->getOpcode() == TargetInstrInfo::PHI) { for (unsigned i = start->getNumOperands() - 1; i >= 2; i-=2) if (start->getOperand(i).isMBB() && start->getOperand(i).getMBB() == BB) { start->RemoveOperand(i); start->RemoveOperand(i-1); } if (start->getNumOperands() == 3) { MachineInstr* phi = start; unsigned Input = phi->getOperand(1).getReg(); unsigned Output = phi->getOperand(0).getReg(); start++; phi->eraseFromParent(); F.getRegInfo().replaceRegWith(Output, Input); } else start++; } BB->removeSuccessor(BB->succ_begin()); } } // Actually remove the blocks now. for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i) DeadBlocks[i]->eraseFromParent(); F.RenumberBlocks(); return DeadBlocks.size(); } <commit_msg>Fix breakage on ARM/2008-04-10-ScavengerAssert.ll.<commit_after>//===-- UnreachableBlockElim.cpp - Remove unreachable blocks for codegen --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass is an extremely simple version of the SimplifyCFG pass. Its sole // job is to delete LLVM basic blocks that are not reachable from the entry // node. To do this, it performs a simple depth first traversal of the CFG, // then deletes any unvisited nodes. // // Note that this pass is really a hack. In particular, the instruction // selectors for various targets should just not generate code for unreachable // blocks. Until LLVM has a more systematic way of defining instruction // selectors, however, we cannot really expect them to handle additional // complexity. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/Passes.h" #include "llvm/Constant.h" #include "llvm/Instructions.h" #include "llvm/Function.h" #include "llvm/Pass.h" #include "llvm/Type.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/CFG.h" #include "llvm/Support/Compiler.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/ADT/DepthFirstIterator.h" using namespace llvm; namespace { class VISIBILITY_HIDDEN UnreachableBlockElim : public FunctionPass { virtual bool runOnFunction(Function &F); public: static char ID; // Pass identification, replacement for typeid UnreachableBlockElim() : FunctionPass((intptr_t)&ID) {} }; } char UnreachableBlockElim::ID = 0; static RegisterPass<UnreachableBlockElim> X("unreachableblockelim", "Remove unreachable blocks from the CFG"); FunctionPass *llvm::createUnreachableBlockEliminationPass() { return new UnreachableBlockElim(); } bool UnreachableBlockElim::runOnFunction(Function &F) { std::set<BasicBlock*> Reachable; // Mark all reachable blocks. for (df_ext_iterator<Function*> I = df_ext_begin(&F, Reachable), E = df_ext_end(&F, Reachable); I != E; ++I) /* Mark all reachable blocks */; // Loop over all dead blocks, remembering them and deleting all instructions // in them. std::vector<BasicBlock*> DeadBlocks; for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) if (!Reachable.count(I)) { BasicBlock *BB = I; DeadBlocks.push_back(BB); while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { PN->replaceAllUsesWith(Constant::getNullValue(PN->getType())); BB->getInstList().pop_front(); } for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) (*SI)->removePredecessor(BB); BB->dropAllReferences(); } // Actually remove the blocks now. for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i) DeadBlocks[i]->eraseFromParent(); return DeadBlocks.size(); } namespace { class VISIBILITY_HIDDEN UnreachableMachineBlockElim : public MachineFunctionPass { virtual bool runOnMachineFunction(MachineFunction &F); public: static char ID; // Pass identification, replacement for typeid UnreachableMachineBlockElim() : MachineFunctionPass((intptr_t)&ID) {} }; } char UnreachableMachineBlockElim::ID = 0; static RegisterPass<UnreachableMachineBlockElim> Y("unreachable-mbb-elimination", "Remove unreachable machine basic blocks"); const PassInfo *const llvm::UnreachableMachineBlockElimID = &Y; bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) { std::set<MachineBasicBlock*> Reachable; // Mark all reachable blocks. for (df_ext_iterator<MachineFunction*> I = df_ext_begin(&F, Reachable), E = df_ext_end(&F, Reachable); I != E; ++I) /* Mark all reachable blocks */; // Loop over all dead blocks, remembering them and deleting all instructions // in them. std::vector<MachineBasicBlock*> DeadBlocks; for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) if (!Reachable.count(I)) { MachineBasicBlock *BB = I; DeadBlocks.push_back(BB); while (BB->succ_begin() != BB->succ_end()) { MachineBasicBlock* succ = *BB->succ_begin(); MachineBasicBlock::iterator start = succ->begin(); while (start != succ->end() && start->getOpcode() == TargetInstrInfo::PHI) { for (unsigned i = start->getNumOperands() - 1; i >= 2; i-=2) if (start->getOperand(i).isMBB() && start->getOperand(i).getMBB() == BB) { start->RemoveOperand(i); start->RemoveOperand(i-1); } if (start->getNumOperands() == 3) { MachineInstr* phi = start; unsigned Input = phi->getOperand(1).getReg(); unsigned Output = phi->getOperand(0).getReg(); start++; phi->eraseFromParent(); if (Input != Output) F.getRegInfo().replaceRegWith(Output, Input); } else start++; } BB->removeSuccessor(BB->succ_begin()); } } // Actually remove the blocks now. for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i) DeadBlocks[i]->eraseFromParent(); F.RenumberBlocks(); return DeadBlocks.size(); } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <manasij7479@gmail.com> // author: Vassil Vassilev <vvasilev@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Path.h" #include "clang/Sema/Sema.h" #include "clang/Basic/Diagnostic.h" #include "clang/AST/AST.h" #include "clang/AST/ASTContext.h" // for operator new[](unsigned long, ASTCtx..) #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/DeclVisitor.h" #include "clang/Lex/Preprocessor.h" #include "clang/Frontend/CompilerInstance.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/AutoloadCallback.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/Output.h" #include "DeclUnloader.h" #include <clang/Lex/HeaderSearch.h> namespace { static const char annoTag[] = "$clingAutoload$"; static const size_t lenAnnoTag = sizeof(annoTag) - 1; } using namespace clang; namespace cling { void AutoloadCallback::report(clang::SourceLocation l, llvm::StringRef name, llvm::StringRef header) { Sema& sema= m_Interpreter->getSema(); unsigned id = sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning, "Note: '%0' can be found in %1"); /* unsigned idn //TODO: To be enabled after we have a way to get the full path = sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note, "Type : %0 , Full Path: %1")*/; if (header.startswith(llvm::StringRef(annoTag, lenAnnoTag))) sema.Diags.Report(l, id) << name << header.drop_front(lenAnnoTag); } bool AutoloadCallback::LookupObject (TagDecl *t) { if (m_ShowSuggestions && t->hasAttr<AnnotateAttr>()) report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation()); return false; } class AutoloadingVisitor: public RecursiveASTVisitor<AutoloadingVisitor> { private: ///\brief Flag determining the visitor's actions. If true, register autoload /// entries, i.e. remember the connection between filename and the declaration /// that needs to be updated on #include of the filename. /// If false, react on an #include by adjusting the forward decls, e.g. by /// removing the default tremplate arguments (that will now be provided by /// the definition read from the include) and by removing enum declarations /// that would otherwise be duplicates. bool m_IsStoringState; bool m_IsAutloadEntry; // True during the traversal of an explicitly annotated decl. AutoloadCallback::FwdDeclsMap* m_Map; clang::Preprocessor* m_PP; clang::Sema* m_Sema; std::pair<const clang::FileEntry*,const clang::FileEntry*> m_PrevFE; std::pair<std::string,std::string> m_PrevFileName; private: bool IsAutoloadEntry(Decl *D) { for(auto attr = D->specific_attr_begin<AnnotateAttr>(), end = D->specific_attr_end<AnnotateAttr> (); attr != end; ++attr) { // cling::errs() << "Annotation: " << c->getAnnotation() << "\n"; if (!attr->isInherited()) { llvm::StringRef annotation = attr->getAnnotation(); assert(!annotation.empty() && "Empty annotation!"); if (annotation.startswith(llvm::StringRef(annoTag, lenAnnoTag))) { // autoload annotation. return true; } } } return false; } using Annotations_t = std::pair<llvm::StringRef,llvm::StringRef>; void InsertIntoAutoloadingState(Decl* decl, Annotations_t FileNames) { assert(m_PP); auto addFile = [this,decl](llvm::StringRef FileName, bool warn) { if (FileName.empty()) return (const FileEntry*)nullptr; const FileEntry* FE = 0; SourceLocation fileNameLoc; // Remember this file wth full path, not "./File.h" (ROOT-8863). bool isAngled = true; const DirectoryLookup* FromDir = 0; const FileEntry* FromFile = 0; const DirectoryLookup* CurDir = 0; bool needCacheUpdate = false; if (FileName.equals(m_PrevFileName.first)) FE = m_PrevFE.first; else if (FileName.equals(m_PrevFileName.second)) FE = m_PrevFE.second; else { FE = m_PP->LookupFile(fileNameLoc, FileName, isAngled, FromDir, FromFile, CurDir, /*SearchPath*/0, /*RelativePath*/ 0, /*suggestedModule*/0, /*IsMapped*/0, /*SkipCache*/ false, /*OpenFile*/ false, /*CacheFail*/ true); needCacheUpdate = true; } if (FE) { auto& Vec = (*m_Map)[FE]; Vec.push_back(decl); if (needCacheUpdate) return FE; else return (const FileEntry*)nullptr; } else if (warn) { // If the top level header is expected to be findable at run-time, // the direct header might not because the include path might be // different enough and only the top-header is guaranteed to be seen // by the user as an interface header to be available on the // run-time include path. cling::errs() << "Error in cling::AutoloadingVisitor::InsertIntoAutoloadingState:\n" " Missing FileEntry for " << FileName << "\n"; if (NamedDecl* ND = dyn_cast<NamedDecl>(decl)) { cling::errs() << " requested to autoload type "; ND->getNameForDiagnostic(cling::errs(), ND->getASTContext().getPrintingPolicy(), true /*qualified*/); cling::errs() << "\n"; } return (const FileEntry*)nullptr; } else { // Case of the direct header that is not a top level header, no // warning in this case (to likely to be a false positive). return (const FileEntry*)nullptr; } }; const FileEntry* cacheUpdate; if ( (cacheUpdate = addFile(FileNames.first,true)) ) { m_PrevFE.first = cacheUpdate; m_PrevFileName.first = FileNames.first; } if ( (cacheUpdate = addFile(FileNames.second,false)) ) { m_PrevFE.second = cacheUpdate; m_PrevFileName.second = FileNames.second; } } public: AutoloadingVisitor(): m_IsStoringState(false), m_IsAutloadEntry(false), m_Map(0), m_PP(0), m_Sema(0), m_PrevFE({nullptr,nullptr}) {} void RemoveDefaultArgsOf(Decl* D, Sema* S) { m_Sema = S; auto cursor = D->getMostRecentDecl(); m_IsAutloadEntry = IsAutoloadEntry(cursor); TraverseDecl(cursor); while (cursor != D && (cursor = cursor->getPreviousDecl())) { m_IsAutloadEntry = IsAutoloadEntry(cursor); TraverseDecl(cursor); } m_IsAutloadEntry = false; } void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map, Preprocessor& PP) { m_IsStoringState = true; m_Map = &map; m_PP = &PP; TraverseDecl(D); m_PP = 0; m_Map = 0; m_IsStoringState = false; } bool shouldVisitTemplateInstantiations() { return true; } bool VisitDecl(Decl* D) { if (!m_IsStoringState) return true; if (!D->hasAttr<AnnotateAttr>()) return true; Annotations_t annotations; for(auto attr = D->specific_attr_begin<AnnotateAttr> (), end = D->specific_attr_end<AnnotateAttr> (); attr != end; ++attr) { if (!attr->isInherited()) { auto annot = attr->getAnnotation(); if (annot.startswith(llvm::StringRef(annoTag, lenAnnoTag))) { if (annotations.first.empty()) { annotations.first = annot.drop_front(lenAnnoTag); } else { annotations.second = annot.drop_front(lenAnnoTag); } } } } InsertIntoAutoloadingState(D, annotations); return true; } bool VisitCXXRecordDecl(CXXRecordDecl* D) { // Since we are only interested in fixing forward declaration // there is no need to continue on when we see a complete definition. if (D->isCompleteDefinition()) return false; if (!D->hasAttr<AnnotateAttr>()) return true; if (ClassTemplateDecl* TmplD = D->getDescribedClassTemplate()) return VisitTemplateDecl(TmplD); return true; } bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } else { if (D->hasDefaultArgument() && D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } return true; } bool VisitTemplateDecl(TemplateDecl* D) { if (D->getTemplatedDecl() && !D->getTemplatedDecl()->hasAttr<AnnotateAttr>()) return true; // If we have a definition we might be about to re-#include the // same header containing definition that was #included previously, // i.e. we might have multiple fwd decls for the same template. // DO NOT remove the defaults here; the definition needs to keep it. // (ROOT-7037) if (ClassTemplateDecl* CTD = dyn_cast<ClassTemplateDecl>(D)) if (CXXRecordDecl* TemplatedD = CTD->getTemplatedDecl()) if (TemplatedD->getDefinition()) return true; for(auto P: D->getTemplateParameters()->asArray()) TraverseDecl(P); return true; } bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } else { if (D->hasDefaultArgument() && D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } return true; } bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } else { if (D->hasDefaultArgument() && D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } return true; } bool VisitParmVarDecl(ParmVarDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArg() && !D->hasInheritedDefaultArg()) D->setDefaultArg(nullptr); } else { if (D->hasDefaultArg() && D->hasInheritedDefaultArg()) D->setDefaultArg(nullptr); } return true; } bool VisitEnumDecl(EnumDecl* D) { if (m_IsStoringState) return true; // Now that we will read the full enum, unload the forward decl. if (IsAutoloadEntry(D)) UnloadDecl(m_Sema, D); return true; } }; void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc, const clang::Token &IncludeTok, llvm::StringRef FileName, bool IsAngled, clang::CharSourceRange FilenameRange, const clang::FileEntry *File, llvm::StringRef SearchPath, llvm::StringRef RelativePath, const clang::Module *Imported) { // If File is 0 this means that the #included file doesn't exist. if (!File) return; auto found = m_Map.find(File); if (found == m_Map.end()) return; // nothing to do, file not referred in any annotation AutoloadingVisitor defaultArgsCleaner; for (auto D : found->second) { defaultArgsCleaner.RemoveDefaultArgsOf(D, &getInterpreter()->getSema()); } // Don't need to keep track of cleaned up decls from file. m_Map.erase(found); } AutoloadCallback::~AutoloadCallback() { } void AutoloadCallback::TransactionCommitted(const Transaction &T) { if (T.decls_begin() == T.decls_end()) return; if (T.decls_begin()->m_DGR.isNull()) return; // The first decl must be // extern int __Cling_Autoloading_Map; bool HaveAutoloadingMapMarker = false; for (auto I = T.decls_begin(), E = T.decls_end(); !HaveAutoloadingMapMarker && I != E; ++I) { if (I->m_Call != cling::Transaction::kCCIHandleTopLevelDecl) return; for (auto&& D: I->m_DGR) { if (isa<EmptyDecl>(D)) continue; else if (auto VD = dyn_cast<VarDecl>(D)) { HaveAutoloadingMapMarker = VD->hasExternalStorage() && VD->getIdentifier() && VD->getName().equals("__Cling_Autoloading_Map"); if (!HaveAutoloadingMapMarker) return; break; } else return; } } if (!HaveAutoloadingMapMarker) return; AutoloadingVisitor defaultArgsStateCollector; Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor(); for (auto I = T.decls_begin(), E = T.decls_end(); I != E; ++I) for (auto&& D: I->m_DGR) defaultArgsStateCollector.TrackDefaultArgStateOf(D, m_Map, PP); } } //end namespace cling <commit_msg>Do not unload enum fwd decl but silence redecl diag (ROOT-9363 ROOT-9114).<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <manasij7479@gmail.com> // author: Vassil Vassilev <vvasilev@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Path.h" #include "clang/Sema/Sema.h" #include "clang/Basic/Diagnostic.h" #include "clang/AST/AST.h" #include "clang/AST/ASTContext.h" // for operator new[](unsigned long, ASTCtx..) #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/DeclVisitor.h" #include "clang/Lex/Preprocessor.h" #include "clang/Frontend/CompilerInstance.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/AutoloadCallback.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/Output.h" #include "DeclUnloader.h" #include <clang/Lex/HeaderSearch.h> namespace { static const char annoTag[] = "$clingAutoload$"; static const size_t lenAnnoTag = sizeof(annoTag) - 1; } using namespace clang; namespace cling { void AutoloadCallback::report(clang::SourceLocation l, llvm::StringRef name, llvm::StringRef header) { Sema& sema= m_Interpreter->getSema(); unsigned id = sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning, "Note: '%0' can be found in %1"); /* unsigned idn //TODO: To be enabled after we have a way to get the full path = sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note, "Type : %0 , Full Path: %1")*/; if (header.startswith(llvm::StringRef(annoTag, lenAnnoTag))) sema.Diags.Report(l, id) << name << header.drop_front(lenAnnoTag); } bool AutoloadCallback::LookupObject (TagDecl *t) { if (m_ShowSuggestions && t->hasAttr<AnnotateAttr>()) report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation()); return false; } class AutoloadingVisitor: public RecursiveASTVisitor<AutoloadingVisitor> { private: ///\brief Flag determining the visitor's actions. If true, register autoload /// entries, i.e. remember the connection between filename and the declaration /// that needs to be updated on #include of the filename. /// If false, react on an #include by adjusting the forward decls, e.g. by /// removing the default template arguments (that will now be provided by /// the definition read from the include). bool m_IsStoringState; bool m_IsAutloadEntry; // True during the traversal of an explicitly annotated decl. AutoloadCallback::FwdDeclsMap* m_Map; clang::Preprocessor* m_PP; clang::Sema* m_Sema; std::pair<const clang::FileEntry*,const clang::FileEntry*> m_PrevFE; std::pair<std::string,std::string> m_PrevFileName; private: bool IsAutoloadEntry(Decl *D) { for(auto attr = D->specific_attr_begin<AnnotateAttr>(), end = D->specific_attr_end<AnnotateAttr> (); attr != end; ++attr) { // cling::errs() << "Annotation: " << c->getAnnotation() << "\n"; if (!attr->isInherited()) { llvm::StringRef annotation = attr->getAnnotation(); assert(!annotation.empty() && "Empty annotation!"); if (annotation.startswith(llvm::StringRef(annoTag, lenAnnoTag))) { // autoload annotation. return true; } } } return false; } using Annotations_t = std::pair<llvm::StringRef,llvm::StringRef>; void InsertIntoAutoloadingState(Decl* decl, Annotations_t FileNames) { assert(m_PP); auto addFile = [this,decl](llvm::StringRef FileName, bool warn) { if (FileName.empty()) return (const FileEntry*)nullptr; const FileEntry* FE = 0; SourceLocation fileNameLoc; // Remember this file wth full path, not "./File.h" (ROOT-8863). bool isAngled = true; const DirectoryLookup* FromDir = 0; const FileEntry* FromFile = 0; const DirectoryLookup* CurDir = 0; bool needCacheUpdate = false; if (FileName.equals(m_PrevFileName.first)) FE = m_PrevFE.first; else if (FileName.equals(m_PrevFileName.second)) FE = m_PrevFE.second; else { FE = m_PP->LookupFile(fileNameLoc, FileName, isAngled, FromDir, FromFile, CurDir, /*SearchPath*/0, /*RelativePath*/ 0, /*suggestedModule*/0, /*IsMapped*/0, /*SkipCache*/ false, /*OpenFile*/ false, /*CacheFail*/ true); needCacheUpdate = true; } if (FE) { auto& Vec = (*m_Map)[FE]; Vec.push_back(decl); if (needCacheUpdate) return FE; else return (const FileEntry*)nullptr; } else if (warn) { // If the top level header is expected to be findable at run-time, // the direct header might not because the include path might be // different enough and only the top-header is guaranteed to be seen // by the user as an interface header to be available on the // run-time include path. cling::errs() << "Error in cling::AutoloadingVisitor::InsertIntoAutoloadingState:\n" " Missing FileEntry for " << FileName << "\n"; if (NamedDecl* ND = dyn_cast<NamedDecl>(decl)) { cling::errs() << " requested to autoload type "; ND->getNameForDiagnostic(cling::errs(), ND->getASTContext().getPrintingPolicy(), true /*qualified*/); cling::errs() << "\n"; } return (const FileEntry*)nullptr; } else { // Case of the direct header that is not a top level header, no // warning in this case (to likely to be a false positive). return (const FileEntry*)nullptr; } }; const FileEntry* cacheUpdate; if ( (cacheUpdate = addFile(FileNames.first,true)) ) { m_PrevFE.first = cacheUpdate; m_PrevFileName.first = FileNames.first; } if ( (cacheUpdate = addFile(FileNames.second,false)) ) { m_PrevFE.second = cacheUpdate; m_PrevFileName.second = FileNames.second; } } public: AutoloadingVisitor(): m_IsStoringState(false), m_IsAutloadEntry(false), m_Map(0), m_PP(0), m_Sema(0), m_PrevFE({nullptr,nullptr}) {} void RemoveDefaultArgsOf(Decl* D, Sema* S) { m_Sema = S; auto cursor = D->getMostRecentDecl(); m_IsAutloadEntry = IsAutoloadEntry(cursor); TraverseDecl(cursor); while (cursor != D && (cursor = cursor->getPreviousDecl())) { m_IsAutloadEntry = IsAutoloadEntry(cursor); TraverseDecl(cursor); } m_IsAutloadEntry = false; } void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map, Preprocessor& PP) { m_IsStoringState = true; m_Map = &map; m_PP = &PP; TraverseDecl(D); m_PP = 0; m_Map = 0; m_IsStoringState = false; } bool shouldVisitTemplateInstantiations() { return true; } bool VisitDecl(Decl* D) { if (!m_IsStoringState) return true; if (!D->hasAttr<AnnotateAttr>()) return true; Annotations_t annotations; for(auto attr = D->specific_attr_begin<AnnotateAttr> (), end = D->specific_attr_end<AnnotateAttr> (); attr != end; ++attr) { if (!attr->isInherited()) { auto annot = attr->getAnnotation(); if (annot.startswith(llvm::StringRef(annoTag, lenAnnoTag))) { if (annotations.first.empty()) { annotations.first = annot.drop_front(lenAnnoTag); } else { annotations.second = annot.drop_front(lenAnnoTag); } } } } InsertIntoAutoloadingState(D, annotations); return true; } bool VisitCXXRecordDecl(CXXRecordDecl* D) { // Since we are only interested in fixing forward declaration // there is no need to continue on when we see a complete definition. if (D->isCompleteDefinition()) return false; if (!D->hasAttr<AnnotateAttr>()) return true; if (ClassTemplateDecl* TmplD = D->getDescribedClassTemplate()) return VisitTemplateDecl(TmplD); return true; } bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } else { if (D->hasDefaultArgument() && D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } return true; } bool VisitTemplateDecl(TemplateDecl* D) { if (D->getTemplatedDecl() && !D->getTemplatedDecl()->hasAttr<AnnotateAttr>()) return true; // If we have a definition we might be about to re-#include the // same header containing definition that was #included previously, // i.e. we might have multiple fwd decls for the same template. // DO NOT remove the defaults here; the definition needs to keep it. // (ROOT-7037) if (ClassTemplateDecl* CTD = dyn_cast<ClassTemplateDecl>(D)) if (CXXRecordDecl* TemplatedD = CTD->getTemplatedDecl()) if (TemplatedD->getDefinition()) return true; for(auto P: D->getTemplateParameters()->asArray()) TraverseDecl(P); return true; } bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } else { if (D->hasDefaultArgument() && D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } return true; } bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } else { if (D->hasDefaultArgument() && D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } return true; } bool VisitParmVarDecl(ParmVarDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArg() && !D->hasInheritedDefaultArg()) D->setDefaultArg(nullptr); } else { if (D->hasDefaultArg() && D->hasInheritedDefaultArg()) D->setDefaultArg(nullptr); } return true; } }; void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc, const clang::Token &IncludeTok, llvm::StringRef FileName, bool IsAngled, clang::CharSourceRange FilenameRange, const clang::FileEntry *File, llvm::StringRef SearchPath, llvm::StringRef RelativePath, const clang::Module *Imported) { // If File is 0 this means that the #included file doesn't exist. if (!File) return; auto found = m_Map.find(File); if (found == m_Map.end()) return; // nothing to do, file not referred in any annotation AutoloadingVisitor defaultArgsCleaner; for (auto D : found->second) { defaultArgsCleaner.RemoveDefaultArgsOf(D, &getInterpreter()->getSema()); } // Don't need to keep track of cleaned up decls from file. m_Map.erase(found); } AutoloadCallback::~AutoloadCallback() { } void AutoloadCallback::TransactionCommitted(const Transaction &T) { if (T.decls_begin() == T.decls_end()) return; if (T.decls_begin()->m_DGR.isNull()) return; // The first decl must be // extern int __Cling_Autoloading_Map; bool HaveAutoloadingMapMarker = false; for (auto I = T.decls_begin(), E = T.decls_end(); !HaveAutoloadingMapMarker && I != E; ++I) { if (I->m_Call != cling::Transaction::kCCIHandleTopLevelDecl) return; for (auto&& D: I->m_DGR) { if (isa<EmptyDecl>(D)) continue; else if (auto VD = dyn_cast<VarDecl>(D)) { HaveAutoloadingMapMarker = VD->hasExternalStorage() && VD->getIdentifier() && VD->getName().equals("__Cling_Autoloading_Map"); if (!HaveAutoloadingMapMarker) return; break; } else return; } } if (!HaveAutoloadingMapMarker) return; AutoloadingVisitor defaultArgsStateCollector; Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor(); for (auto I = T.decls_begin(), E = T.decls_end(); I != E; ++I) for (auto&& D: I->m_DGR) defaultArgsStateCollector.TrackDefaultArgStateOf(D, m_Map, PP); } } //end namespace cling <|endoftext|>
<commit_before>#include <iterator> #include <list> #include <numeric> #include <vector> #include <cassert> #include "RandomPermuter.h" namespace fs_testing { namespace permuter { using std::advance; using std::iota; using std::list; using std::mt19937; using std::uniform_int_distribution; using std::vector; using fs_testing::utils::disk_write; namespace { struct range { unsigned int start; unsigned int end; }; } // namespace void RandomPermuter::init_data_vector(vector<disk_write> *data) { epochs.clear(); log_length = data->size(); unsigned int index = 0; list<range> overlaps; while (index < data->size()) { struct epoch current_epoch; current_epoch.has_barrier = false; current_epoch.overlaps = false; current_epoch.length = 0; // Get all ops in this epoch and add them to either the sync_op or async_op // lists. while (index < data->size() && !(data->at(index)).is_barrier_write()) { disk_write curr = data->at(index); // Find overlapping ranges. unsigned int start = curr.metadata.write_sector; unsigned int end = start + curr.metadata.size; for (auto range_iter = overlaps.begin(); range_iter != overlaps.end(); range_iter++) { range r = *range_iter; if ((r.start <= start && r.end >= start) || (r.start <= end && r.end >= end)) { if (r.start > start) { r.start = start; } if (r.end < end) { r.end = end; } current_epoch.overlaps = true; break; } else if (r.start > end) { // Since this is an ordered list, if the next spot is past where we're // looking now then we won't find anything past here. We may as well // insert an item here. range new_range = {start, end}; overlaps.insert(range_iter, new_range); } } ++current_epoch.length; current_epoch.ops.push_back(data->at(index)); current_epoch.num_meta += data->at(index).is_meta(); ++index; } // Check is the op at the current index is a "barrier." If it is then add it // to the special spot in the epoch, otherwise just push the current epoch // onto the list and move to the next segment of the log. if (index < data->size() && (data->at(index)).is_barrier_write()) { ++current_epoch.length; current_epoch.ops.push_back(data->at(index)); current_epoch.num_meta += data->at(index).is_meta(); current_epoch.has_barrier = true; ++index; } epochs.push_back(current_epoch); } } RandomPermuter::RandomPermuter() { log_length = 0; rand = mt19937(42); } RandomPermuter::RandomPermuter(vector<disk_write> *data) { init_data_vector(data); // TODO(ashmrtn): Make a flag to make it random or not. rand = mt19937(42); } void RandomPermuter::set_data(vector<disk_write> *data) { init_data_vector(data); } bool RandomPermuter::permute(vector<disk_write>& res) { unsigned int total_elements = 0; // Find how many elements we will be returning (randomly determined). uniform_int_distribution<unsigned int> permute_epochs(1, epochs.size()); unsigned int num_epochs = permute_epochs(rand); // Don't subtract 1 from this size so that we can send a complete epoch if we // want. uniform_int_distribution<unsigned int> permute_requests(1, epochs.at(num_epochs - 1).length); unsigned int num_requests = permute_requests(rand); // TODO(ashmrtn): Optimize so that we resize to exactly the number of elements // we will have, not the number of elements in all the epochs. for (unsigned int i = 0; i < num_epochs; ++i) { total_elements += epochs.at(i).length; } res.resize(total_elements); int current_index = 0; auto curr_iter = res.begin(); auto cutoff = res.begin(); for (unsigned int i = 0; i < num_epochs; ++i) { if (epochs.at(i).overlaps || i == num_epochs - 1) { permute_epoch(res, current_index, epochs.at(i)); } else { auto res_iter = curr_iter; // Use a for loop since vector::insert inserts new elements and we resized // above to the exact size we will have. unsigned int adv = (i == num_epochs - 1) ? num_requests : epochs.at(i).length; auto epoch_end = epochs.at(i).ops.begin(); advance(epoch_end, adv); for (auto epoch_iter = epochs.at(i).ops.begin(); epoch_iter != epoch_end; ++epoch_iter) { *res_iter = *epoch_iter; ++res_iter; } } current_index += epochs.at(i).length; advance(curr_iter, epochs.at(i).length); } // Trim the last epoch to a random number of requests. cutoff = res.begin(); advance(cutoff, total_elements - epochs.at(num_epochs - 1).length + num_requests); // Trim off all requests at or after the one we selected above. res.erase(cutoff, res.end()); //res.erase(curr_iter, res.end()); return true; } void RandomPermuter::permute_epoch(vector<disk_write>& res, const int start_index, epoch& epoch) { unsigned int slots = epoch.length; // Place the barrier operation if it exists since the entire vector already // exists (i.e. we won't cause extra shifting when adding the other elements). // Decrement out count of empty slots since we have filled one. if (epoch.has_barrier) { res.at(start_index + slots - 1) = epoch.ops.back(); --slots; } // Fill the list with the empty slots, either [0, epoch.length - 1) or // [0, epoch.length - 2). list<unsigned int> empty_slots(slots); iota(empty_slots.begin(), empty_slots.end(), 0); for (unsigned int i = 0; i < slots; ++i) { // Uniform distribution includes both ends, so we need to subtract 1 from // the size. uniform_int_distribution<unsigned int> uid(0, empty_slots.size() - 1); auto shift = empty_slots.begin(); advance(shift, uid(rand)); res.at(start_index + *shift) = epoch.ops.at(i); empty_slots.erase(shift); } assert(empty_slots.empty()); } } // namespace permuter } // namespace fs_testing extern "C" fs_testing::permuter::Permuter* permuter_get_instance( std::vector<fs_testing::utils::disk_write> *data) { return new fs_testing::permuter::RandomPermuter(data); } extern "C" void permuter_delete_instance(fs_testing::permuter::Permuter* p) { delete p; } <commit_msg>Minor code cleanup.<commit_after>#include <iterator> #include <list> #include <numeric> #include <vector> #include <cassert> #include "RandomPermuter.h" namespace fs_testing { namespace permuter { using std::advance; using std::iota; using std::list; using std::mt19937; using std::uniform_int_distribution; using std::vector; using fs_testing::utils::disk_write; namespace { struct range { unsigned int start; unsigned int end; }; } // namespace void RandomPermuter::init_data_vector(vector<disk_write> *data) { epochs.clear(); log_length = data->size(); unsigned int index = 0; list<range> overlaps; while (index < data->size()) { struct epoch current_epoch; current_epoch.has_barrier = false; current_epoch.overlaps = false; current_epoch.length = 0; // Get all ops in this epoch and add them to either the sync_op or async_op // lists. while (index < data->size() && !(data->at(index)).is_barrier_write()) { disk_write curr = data->at(index); // Find overlapping ranges. unsigned int start = curr.metadata.write_sector; unsigned int end = start + curr.metadata.size; for (auto range_iter = overlaps.begin(); range_iter != overlaps.end(); range_iter++) { range r = *range_iter; if ((r.start <= start && r.end >= start) || (r.start <= end && r.end >= end)) { if (r.start > start) { r.start = start; } if (r.end < end) { r.end = end; } current_epoch.overlaps = true; break; } else if (r.start > end) { // Since this is an ordered list, if the next spot is past where we're // looking now then we won't find anything past here. We may as well // insert an item here. range new_range = {start, end}; overlaps.insert(range_iter, new_range); } } ++current_epoch.length; current_epoch.ops.push_back(data->at(index)); current_epoch.num_meta += data->at(index).is_meta(); ++index; } // Check is the op at the current index is a "barrier." If it is then add it // to the special spot in the epoch, otherwise just push the current epoch // onto the list and move to the next segment of the log. if (index < data->size() && (data->at(index)).is_barrier_write()) { ++current_epoch.length; current_epoch.ops.push_back(data->at(index)); current_epoch.num_meta += data->at(index).is_meta(); current_epoch.has_barrier = true; ++index; } epochs.push_back(current_epoch); } } RandomPermuter::RandomPermuter() { log_length = 0; rand = mt19937(42); } RandomPermuter::RandomPermuter(vector<disk_write> *data) { init_data_vector(data); // TODO(ashmrtn): Make a flag to make it random or not. rand = mt19937(42); } void RandomPermuter::set_data(vector<disk_write> *data) { init_data_vector(data); } bool RandomPermuter::permute(vector<disk_write>& res) { unsigned int total_elements = 0; // Find how many elements we will be returning (randomly determined). uniform_int_distribution<unsigned int> permute_epochs(1, epochs.size()); unsigned int num_epochs = permute_epochs(rand); // Don't subtract 1 from this size so that we can send a complete epoch if we // want. uniform_int_distribution<unsigned int> permute_requests(1, epochs.at(num_epochs - 1).length); unsigned int num_requests = permute_requests(rand); // TODO(ashmrtn): Optimize so that we resize to exactly the number of elements // we will have, not the number of elements in all the epochs. for (unsigned int i = 0; i < num_epochs; ++i) { total_elements += epochs.at(i).length; } res.resize(total_elements); int current_index = 0; auto curr_iter = res.begin(); auto cutoff = res.begin(); for (unsigned int i = 0; i < num_epochs; ++i) { if (epochs.at(i).overlaps || i == num_epochs - 1) { permute_epoch(res, current_index, epochs.at(i)); } else { auto res_iter = curr_iter; // Use a for loop since vector::insert inserts new elements and we resized // above to the exact size we will have. unsigned int adv = (i == num_epochs - 1) ? num_requests : epochs.at(i).length; auto epoch_end = epochs.at(i).ops.begin(); advance(epoch_end, adv); for (auto epoch_iter = epochs.at(i).ops.begin(); epoch_iter != epoch_end; ++epoch_iter) { *res_iter = *epoch_iter; ++res_iter; } } current_index += epochs.at(i).length; advance(curr_iter, epochs.at(i).length); } // Trim the last epoch to a random number of requests. cutoff = res.begin(); advance(cutoff, total_elements - epochs.at(num_epochs - 1).length + num_requests); // Trim off all requests at or after the one we selected above. res.erase(cutoff, res.end()); return true; } void RandomPermuter::permute_epoch(vector<disk_write>& res, const int start_index, epoch& epoch) { unsigned int slots = epoch.length; // Place the barrier operation if it exists since the entire vector already // exists (i.e. we won't cause extra shifting when adding the other elements). // Decrement out count of empty slots since we have filled one. if (epoch.has_barrier) { res.at(start_index + slots - 1) = epoch.ops.back(); --slots; } // Fill the list with the empty slots, either [0, epoch.length - 1) or // [0, epoch.length - 2). list<unsigned int> empty_slots(slots); iota(empty_slots.begin(), empty_slots.end(), 0); for (unsigned int i = 0; i < slots; ++i) { // Uniform distribution includes both ends, so we need to subtract 1 from // the size. uniform_int_distribution<unsigned int> uid(0, empty_slots.size() - 1); auto shift = empty_slots.begin(); advance(shift, uid(rand)); res.at(start_index + *shift) = epoch.ops.at(i); empty_slots.erase(shift); } assert(empty_slots.empty()); } } // namespace permuter } // namespace fs_testing extern "C" fs_testing::permuter::Permuter* permuter_get_instance( std::vector<fs_testing::utils::disk_write> *data) { return new fs_testing::permuter::RandomPermuter(data); } extern "C" void permuter_delete_instance(fs_testing::permuter::Permuter* p) { delete p; } <|endoftext|>
<commit_before>#include "QDataAnalysisView.h" #include "QAction" #include "QHeaderView" #include <algorithm> #include "simvis/color.h" #include "xo/system/log.h" #include "xo/utility/types.h" #include "qtfx.h" #include <array> #include "xo/system/log.h" #include "xo/container/sorted_vector.h" #include "xo/numerical/constants.h" #include "qt_tools.h" QDataAnalysisView::QDataAnalysisView( QDataAnalysisModel* m, QWidget* parent ) : QWidget( parent ), model( m ), currentUpdateIdx( 0 ) { selectBox = new QCheckBox( this ); connect( selectBox, &QCheckBox::stateChanged, this, &QDataAnalysisView::select ); filter = new QLineEdit( this ); connect( filter, &QLineEdit::textChanged, this, &QDataAnalysisView::filterChanged ); auto* header = new QHGroup( this, 0, 4 ); *header << new QLabel( "Filter", this ) << filter << selectBox; itemList = new QTreeWidget( this ); itemList->setRootIsDecorated( false ); itemList->setColumnCount( 2 ); itemList->header()->close(); itemList->resize( 100, 100 ); QStringList headerLabels; headerLabels << "Variable" << "Value"; itemList->setHeaderLabels( headerLabels ); //itemList->setFrameStyle( QFrame::NoFrame ); itemGroup = new QVGroup( this, 0, 4 ); itemGroup->setContentsMargins( 0, 0, 0, 0 ); *itemGroup << header << itemList; connect( itemList, &QTreeWidget::itemChanged, this, &QDataAnalysisView::itemChanged ); splitter = new QSplitter( this ); splitter->setContentsMargins( 0, 0, 0, 0 ); splitter->setFrameShape( QFrame::NoFrame ); splitter->setObjectName( "Analysis.Splitter" ); splitter->addWidget( itemGroup ); QVBoxLayout* layout = new QVBoxLayout( this ); setLayout( layout ); layout->setContentsMargins( 0, 0, 0, 0 ); layout->setSpacing( 4 ); layout->addWidget( splitter ); for ( int i = 0; i < maxSeriesCount; ++i ) freeColors.insert( i ); #if !defined QTFX_NO_QCUSTOMPLOT customPlot = new QCustomPlot(); customPlot->setInteraction( QCP::iRangeZoom, true ); customPlot->setInteraction( QCP::iRangeDrag, true ); customPlot->axisRect()->setRangeDrag( Qt::Horizontal ); customPlot->axisRect()->setRangeZoom( Qt::Horizontal ); customPlot->legend->setVisible( true ); customPlot->legend->setFont( itemList->font() ); customPlot->legend->setRowSpacing( -6 ); customPlotLine = new QCPItemLine( customPlot ); customPlotLine->setHead( QCPLineEnding( QCPLineEnding::esDiamond, 9, 9, true ) ); customPlotLine->setTail( QCPLineEnding( QCPLineEnding::esDiamond, 9, 9, true ) ); customPlot->addItem( customPlotLine ); splitter->addWidget( customPlot ); connect( customPlot, &QCustomPlot::mousePress, this, &QDataAnalysisView::mouseEvent ); connect( customPlot, &QCustomPlot::mouseMove, this, &QDataAnalysisView::mouseEvent ); connect( customPlot->xAxis, SIGNAL( rangeChanged( const QCPRange&, const QCPRange& ) ), this, SLOT( rangeChanged( const QCPRange&, const QCPRange& ) ) ); #else chart = new QtCharts::QChart(); chart->setBackgroundRoundness( 0 ); chart->setMargins( QMargins( 4, 4, 4, 4 ) ); chart->layout()->setContentsMargins( 0, 0, 0, 0 ); chart->legend()->setAlignment( Qt::AlignRight ); chart->createDefaultAxes(); chartView = new QtCharts::QChartView( chart, this ); chartView->setContentsMargins( 0, 0, 0, 0 ); chartView->setRenderHint( QPainter::Antialiasing ); chartView->setRubberBand( QtCharts::QChartView::RectangleRubberBand ); chartView->setBackgroundBrush( QBrush( Qt::red ) ); chartView->resize( 300, 100 ); splitter->addWidget( chartView ); #endif splitter->setSizes( QList< int >{ 100, 300 } ); reset(); } int QDataAnalysisView::decimalPoints( double v ) { if ( v != 0 && xo::less_or_equal( abs( v ), 0.05 ) ) return 6; else return 3; } void QDataAnalysisView::refresh( double time, bool refreshAll ) { if ( itemList->topLevelItemCount() != model->seriesCount() ) return reset(); if ( model->seriesCount() == 0 ) return; // update state currentTime = time; // draw stuff if visible if ( isVisible() ) { int itemCount = refreshAll ? model->seriesCount() : std::min<int>( smallRefreshItemCount, model->seriesCount() ); itemList->setUpdatesEnabled( false ); for ( size_t i = 0; i < itemCount; ++i ) { auto y = model->value( currentUpdateIdx, time ); itemList->topLevelItem( currentUpdateIdx )->setText( 1, QString().sprintf( "%.*f", decimalPoints( y ), y ) ); ++currentUpdateIdx %= model->seriesCount(); } itemList->setUpdatesEnabled( true ); // update graph updateIndicator(); #ifdef QTFX_USE_QCUSTOMPLOT customPlot->replot( QCustomPlot::rpQueued ); #endif } } void QDataAnalysisView::itemChanged( QTreeWidgetItem* item, int column ) { if ( column == 0 ) updateSeries( itemList->indexOfTopLevelItem( item ) ); } void QDataAnalysisView::clearSeries() { while ( !series.empty() ) removeSeries( series.rbegin()->channel ); } void QDataAnalysisView::mouseEvent( QMouseEvent* event ) { #if !defined QTFX_NO_QCUSTOMPLOT if ( event->buttons() & Qt::LeftButton ) { double x = customPlot->xAxis->pixelToCoord( event->pos().x() ); double t = model->timeValue( model->timeIndex( x ) ); emit timeChanged( t ); } #endif } void QDataAnalysisView::rangeChanged( const QCPRange &newRange, const QCPRange &oldRange ) { QCPRange fixedRange = QCPRange( xo::max( newRange.lower, model->timeStart() ), xo::min( newRange.upper, model->timeFinish() ) ); if ( fixedRange != newRange ) { customPlot->xAxis->blockSignals( true ); customPlot->xAxis->setRange( fixedRange ); customPlot->xAxis->blockSignals( false ); } updateSeriesStyle(); } void QDataAnalysisView::filterChanged( const QString& filter ) { updateFilter(); } void QDataAnalysisView::setSelectionState( int state ) { if ( state != Qt::PartiallyChecked ) { for ( size_t i = 0; i < itemList->topLevelItemCount(); ++i ) { auto* item = itemList->topLevelItem( i ); if ( !item->isHidden() && item->checkState( 0 ) != state ) item->setCheckState( 0, Qt::CheckState( state ) ); } } } QColor QDataAnalysisView::getStandardColor( int idx ) { return make_qt( vis::make_unique_color( size_t( idx ) ) ); } void QDataAnalysisView::reset() { itemList->clear(); clearSeries(); for ( size_t i = 0; i < model->seriesCount(); ++i ) { auto* wdg = new QTreeWidgetItem( itemList, QStringList( model->label( i ) ) ); wdg->setTextAlignment( 1, Qt::AlignRight ); wdg->setFlags( wdg->flags() | Qt::ItemIsUserCheckable ); wdg->setCheckState( 0, persistentSerieNames.find( model->label( i ) ) != persistentSerieNames.end() ? Qt::Checked : Qt::Unchecked ); } itemList->resizeColumnToContents( 0 ); currentUpdateIdx = 0; currentTime = 0.0; updateIndicator(); updateFilter(); } void QDataAnalysisView::updateIndicator() { #if !defined QTFX_NO_QCUSTOMPLOT customPlotLine->start->setCoords( currentTime, customPlot->yAxis->range().lower ); customPlotLine->end->setCoords( currentTime, customPlot->yAxis->range().upper ); customPlot->replot(); #else auto pos = chart->mapToPosition( QPointF( currentTime, 0 ) ); #endif } void QDataAnalysisView::updateFilter() { //selectAllButton->setDisabled( filter->text().isEmpty() ); for ( size_t i = 0; i < itemList->topLevelItemCount(); ++i ) { auto* item = itemList->topLevelItem( i ); item->setHidden( !item->text( 0 ).contains( filter->text() ) ); } updateSelectBox(); } void QDataAnalysisView::updateSelectBox() { size_t checked_count = 0; size_t shown_count = 0; for ( size_t i = 0; i < itemList->topLevelItemCount(); ++i ) { auto* item = itemList->topLevelItem( i ); if ( !item->isHidden() ) { shown_count++; checked_count += item->checkState( 0 ) == Qt::Checked; } } selectBox->blockSignals( true ); selectBox->setCheckState( checked_count > 0 ? ( shown_count == checked_count ? Qt::Checked : Qt::Checked ) : Qt::Unchecked ); selectBox->blockSignals( false ); } void QDataAnalysisView::updateSeriesStyle() { auto zoom = currentSeriesInterval * customPlot->xAxis->axisRect()->width() / customPlot->xAxis->range().size(); SeriesStyle newstyle = zoom > 8 ? discStyle : lineStyle; if ( newstyle != seriesStyle ) { seriesStyle = newstyle; QCPScatterStyle ss = QCPScatterStyle( zoom > 8 ? QCPScatterStyle::ssDisc : QCPScatterStyle::ssNone, 4 ); for ( auto& s : series ) { s.graph->setScatterStyle( ss ); s.graph->setLineStyle( QCPGraph::lsLine ); } } } void QDataAnalysisView::updateSeries( int idx ) { auto item = itemList->topLevelItem( idx ); auto series_it = xo::find_if( series, [&]( auto& p ) { return idx == p.channel; } ); if ( item->checkState( 0 ) == Qt::Checked && series_it == series.end() ) { if ( series.size() < maxSeriesCount ) { addSeries( idx ); persistentSerieNames.insert( model->label( idx ) ); } else item->setCheckState( 0, Qt::Unchecked ); } else if ( series_it != series.end() && item->checkState( 0 ) == Qt::Unchecked ) { removeSeries( idx ); persistentSerieNames.remove( model->label( idx ) ); } updateSelectBox(); } void QDataAnalysisView::addSeries( int idx ) { #if !defined QTFX_NO_QCUSTOMPLOT QCPGraph* graph = customPlot->addGraph(); QString name = model->label( idx ); graph->setName( name ); xo_assert( !freeColors.empty() ); graph->setPen( QPen( getStandardColor( freeColors.front() ), lineWidth ) ); auto data = model->getSeries( idx, minSeriesInterval ); for ( auto& e : data ) graph->addData( e.first, e.second ); series.emplace_back( Series{ idx, freeColors.front(), graph } ); freeColors.erase( freeColors.begin() ); currentSeriesInterval = ( data.back().first - data.front().first ) / data.size(); updateSeriesStyle(); auto range = customPlot->xAxis->range(); customPlot->rescaleAxes(); customPlot->xAxis->setRange( range ); updateIndicator(); customPlot->replot(); #else QtCharts::QLineSeries* ls = new QtCharts::QLineSeries; ls->setName( model->label( idx ) ); auto data = model->getSeries( idx, minSeriesInterval ); for ( auto& e : data ) ls->append( e.first, e.second ); chart->addSeries( ls ); chart->createDefaultAxes(); chart->zoomReset(); series[ idx ] = ls; #endif } void QDataAnalysisView::removeSeries( int idx ) { #if !defined QTFX_NO_QCUSTOMPLOT auto range = customPlot->xAxis->range(); auto it = xo::find_if( series, [&]( auto& p ) { return idx == p.channel; } ); auto name = it->graph->name(); freeColors.insert( it->color ); customPlot->removeGraph( it->graph ); series.erase( it ); customPlot->rescaleAxes(); customPlot->xAxis->setRange( range ); updateIndicator(); customPlot->replot(); #else auto it = series.find( idx ); chart->removeSeries( it->second ); chart->zoomReset(); chart->createDefaultAxes(); series.erase( it ); #endif } <commit_msg>F: auto disc on zoom now works ok<commit_after>#include "QDataAnalysisView.h" #include "QAction" #include "QHeaderView" #include <algorithm> #include "simvis/color.h" #include "xo/system/log.h" #include "xo/utility/types.h" #include "qtfx.h" #include <array> #include "xo/system/log.h" #include "xo/container/sorted_vector.h" #include "xo/numerical/constants.h" #include "qt_tools.h" QDataAnalysisView::QDataAnalysisView( QDataAnalysisModel* m, QWidget* parent ) : QWidget( parent ), model( m ), currentUpdateIdx( 0 ) { selectBox = new QCheckBox( this ); connect( selectBox, &QCheckBox::stateChanged, this, &QDataAnalysisView::select ); filter = new QLineEdit( this ); connect( filter, &QLineEdit::textChanged, this, &QDataAnalysisView::filterChanged ); auto* header = new QHGroup( this, 0, 4 ); *header << new QLabel( "Filter", this ) << filter << selectBox; itemList = new QTreeWidget( this ); itemList->setRootIsDecorated( false ); itemList->setColumnCount( 2 ); itemList->header()->close(); itemList->resize( 100, 100 ); QStringList headerLabels; headerLabels << "Variable" << "Value"; itemList->setHeaderLabels( headerLabels ); //itemList->setFrameStyle( QFrame::NoFrame ); itemGroup = new QVGroup( this, 0, 4 ); itemGroup->setContentsMargins( 0, 0, 0, 0 ); *itemGroup << header << itemList; connect( itemList, &QTreeWidget::itemChanged, this, &QDataAnalysisView::itemChanged ); splitter = new QSplitter( this ); splitter->setContentsMargins( 0, 0, 0, 0 ); splitter->setFrameShape( QFrame::NoFrame ); splitter->setObjectName( "Analysis.Splitter" ); splitter->addWidget( itemGroup ); QVBoxLayout* layout = new QVBoxLayout( this ); setLayout( layout ); layout->setContentsMargins( 0, 0, 0, 0 ); layout->setSpacing( 4 ); layout->addWidget( splitter ); for ( int i = 0; i < maxSeriesCount; ++i ) freeColors.insert( i ); #if !defined QTFX_NO_QCUSTOMPLOT customPlot = new QCustomPlot(); customPlot->setInteraction( QCP::iRangeZoom, true ); customPlot->setInteraction( QCP::iRangeDrag, true ); customPlot->axisRect()->setRangeDrag( Qt::Horizontal ); customPlot->axisRect()->setRangeZoom( Qt::Horizontal ); customPlot->legend->setVisible( true ); customPlot->legend->setFont( itemList->font() ); customPlot->legend->setRowSpacing( -6 ); customPlotLine = new QCPItemLine( customPlot ); customPlotLine->setHead( QCPLineEnding( QCPLineEnding::esDiamond, 9, 9, true ) ); customPlotLine->setTail( QCPLineEnding( QCPLineEnding::esDiamond, 9, 9, true ) ); customPlot->addItem( customPlotLine ); splitter->addWidget( customPlot ); connect( customPlot, &QCustomPlot::mousePress, this, &QDataAnalysisView::mouseEvent ); connect( customPlot, &QCustomPlot::mouseMove, this, &QDataAnalysisView::mouseEvent ); connect( customPlot->xAxis, SIGNAL( rangeChanged( const QCPRange&, const QCPRange& ) ), this, SLOT( rangeChanged( const QCPRange&, const QCPRange& ) ) ); #else chart = new QtCharts::QChart(); chart->setBackgroundRoundness( 0 ); chart->setMargins( QMargins( 4, 4, 4, 4 ) ); chart->layout()->setContentsMargins( 0, 0, 0, 0 ); chart->legend()->setAlignment( Qt::AlignRight ); chart->createDefaultAxes(); chartView = new QtCharts::QChartView( chart, this ); chartView->setContentsMargins( 0, 0, 0, 0 ); chartView->setRenderHint( QPainter::Antialiasing ); chartView->setRubberBand( QtCharts::QChartView::RectangleRubberBand ); chartView->setBackgroundBrush( QBrush( Qt::red ) ); chartView->resize( 300, 100 ); splitter->addWidget( chartView ); #endif splitter->setSizes( QList< int >{ 100, 300 } ); reset(); } int QDataAnalysisView::decimalPoints( double v ) { if ( v != 0 && xo::less_or_equal( abs( v ), 0.05 ) ) return 6; else return 3; } void QDataAnalysisView::refresh( double time, bool refreshAll ) { if ( itemList->topLevelItemCount() != model->seriesCount() ) return reset(); if ( model->seriesCount() == 0 ) return; // update state currentTime = time; // draw stuff if visible if ( isVisible() ) { int itemCount = refreshAll ? model->seriesCount() : std::min<int>( smallRefreshItemCount, model->seriesCount() ); itemList->setUpdatesEnabled( false ); for ( size_t i = 0; i < itemCount; ++i ) { auto y = model->value( currentUpdateIdx, time ); itemList->topLevelItem( currentUpdateIdx )->setText( 1, QString().sprintf( "%.*f", decimalPoints( y ), y ) ); ++currentUpdateIdx %= model->seriesCount(); } itemList->setUpdatesEnabled( true ); // update graph updateIndicator(); #ifdef QTFX_USE_QCUSTOMPLOT customPlot->replot( QCustomPlot::rpQueued ); #endif } } void QDataAnalysisView::itemChanged( QTreeWidgetItem* item, int column ) { if ( column == 0 ) updateSeries( itemList->indexOfTopLevelItem( item ) ); } void QDataAnalysisView::clearSeries() { while ( !series.empty() ) removeSeries( series.rbegin()->channel ); } void QDataAnalysisView::mouseEvent( QMouseEvent* event ) { #if !defined QTFX_NO_QCUSTOMPLOT if ( event->buttons() & Qt::LeftButton ) { double x = customPlot->xAxis->pixelToCoord( event->pos().x() ); double t = model->timeValue( model->timeIndex( x ) ); emit timeChanged( t ); } #endif } void QDataAnalysisView::rangeChanged( const QCPRange &newRange, const QCPRange &oldRange ) { QCPRange fixedRange = QCPRange( xo::max( newRange.lower, model->timeStart() ), xo::min( newRange.upper, model->timeFinish() ) ); if ( fixedRange != newRange ) { customPlot->xAxis->blockSignals( true ); customPlot->xAxis->setRange( fixedRange ); customPlot->xAxis->blockSignals( false ); } updateSeriesStyle(); } void QDataAnalysisView::filterChanged( const QString& filter ) { updateFilter(); } void QDataAnalysisView::setSelectionState( int state ) { if ( state != Qt::PartiallyChecked ) { for ( size_t i = 0; i < itemList->topLevelItemCount(); ++i ) { auto* item = itemList->topLevelItem( i ); if ( !item->isHidden() && item->checkState( 0 ) != state ) item->setCheckState( 0, Qt::CheckState( state ) ); } } } QColor QDataAnalysisView::getStandardColor( int idx ) { return make_qt( vis::make_unique_color( size_t( idx ) ) ); } void QDataAnalysisView::reset() { itemList->clear(); clearSeries(); for ( size_t i = 0; i < model->seriesCount(); ++i ) { auto* wdg = new QTreeWidgetItem( itemList, QStringList( model->label( i ) ) ); wdg->setTextAlignment( 1, Qt::AlignRight ); wdg->setFlags( wdg->flags() | Qt::ItemIsUserCheckable ); wdg->setCheckState( 0, persistentSerieNames.find( model->label( i ) ) != persistentSerieNames.end() ? Qt::Checked : Qt::Unchecked ); } itemList->resizeColumnToContents( 0 ); currentUpdateIdx = 0; currentTime = 0.0; updateIndicator(); updateFilter(); } void QDataAnalysisView::updateIndicator() { #if !defined QTFX_NO_QCUSTOMPLOT customPlotLine->start->setCoords( currentTime, customPlot->yAxis->range().lower ); customPlotLine->end->setCoords( currentTime, customPlot->yAxis->range().upper ); customPlot->replot(); #else auto pos = chart->mapToPosition( QPointF( currentTime, 0 ) ); #endif } void QDataAnalysisView::updateFilter() { //selectAllButton->setDisabled( filter->text().isEmpty() ); for ( size_t i = 0; i < itemList->topLevelItemCount(); ++i ) { auto* item = itemList->topLevelItem( i ); item->setHidden( !item->text( 0 ).contains( filter->text() ) ); } updateSelectBox(); } void QDataAnalysisView::updateSelectBox() { size_t checked_count = 0; size_t shown_count = 0; for ( size_t i = 0; i < itemList->topLevelItemCount(); ++i ) { auto* item = itemList->topLevelItem( i ); if ( !item->isHidden() ) { shown_count++; checked_count += item->checkState( 0 ) == Qt::Checked; } } selectBox->blockSignals( true ); selectBox->setCheckState( checked_count > 0 ? ( shown_count == checked_count ? Qt::Checked : Qt::Checked ) : Qt::Unchecked ); selectBox->blockSignals( false ); } void QDataAnalysisView::updateSeriesStyle() { auto zoom = currentSeriesInterval * customPlot->xAxis->axisRect()->width() / customPlot->xAxis->range().size(); SeriesStyle newstyle = zoom > 8 ? discStyle : lineStyle; if ( newstyle != seriesStyle ) { seriesStyle = newstyle; QCPScatterStyle ss = QCPScatterStyle( seriesStyle == discStyle ? QCPScatterStyle::ssDisc : QCPScatterStyle::ssNone, 4 ); for ( auto& s : series ) { s.graph->setScatterStyle( ss ); s.graph->setLineStyle( QCPGraph::lsLine ); } } } void QDataAnalysisView::updateSeries( int idx ) { auto item = itemList->topLevelItem( idx ); auto series_it = xo::find_if( series, [&]( auto& p ) { return idx == p.channel; } ); if ( item->checkState( 0 ) == Qt::Checked && series_it == series.end() ) { if ( series.size() < maxSeriesCount ) { addSeries( idx ); persistentSerieNames.insert( model->label( idx ) ); } else item->setCheckState( 0, Qt::Unchecked ); } else if ( series_it != series.end() && item->checkState( 0 ) == Qt::Unchecked ) { removeSeries( idx ); persistentSerieNames.remove( model->label( idx ) ); } updateSelectBox(); } void QDataAnalysisView::addSeries( int idx ) { #if !defined QTFX_NO_QCUSTOMPLOT QCPGraph* graph = customPlot->addGraph(); QString name = model->label( idx ); graph->setName( name ); xo_assert( !freeColors.empty() ); graph->setScatterStyle( QCPScatterStyle( seriesStyle == discStyle ? QCPScatterStyle::ssDisc : QCPScatterStyle::ssNone, 4 ) ); graph->setPen( QPen( getStandardColor( freeColors.front() ), lineWidth ) ); auto data = model->getSeries( idx, minSeriesInterval ); for ( auto& e : data ) graph->addData( e.first, e.second ); series.emplace_back( Series{ idx, freeColors.front(), graph } ); freeColors.erase( freeColors.begin() ); currentSeriesInterval = ( data.back().first - data.front().first ) / data.size(); updateSeriesStyle(); auto range = customPlot->xAxis->range(); customPlot->rescaleAxes(); customPlot->xAxis->setRange( range ); updateIndicator(); customPlot->replot(); #else QtCharts::QLineSeries* ls = new QtCharts::QLineSeries; ls->setName( model->label( idx ) ); auto data = model->getSeries( idx, minSeriesInterval ); for ( auto& e : data ) ls->append( e.first, e.second ); chart->addSeries( ls ); chart->createDefaultAxes(); chart->zoomReset(); series[ idx ] = ls; #endif } void QDataAnalysisView::removeSeries( int idx ) { #if !defined QTFX_NO_QCUSTOMPLOT auto range = customPlot->xAxis->range(); auto it = xo::find_if( series, [&]( auto& p ) { return idx == p.channel; } ); auto name = it->graph->name(); freeColors.insert( it->color ); customPlot->removeGraph( it->graph ); series.erase( it ); customPlot->rescaleAxes(); customPlot->xAxis->setRange( range ); updateIndicator(); customPlot->replot(); #else auto it = series.find( idx ); chart->removeSeries( it->second ); chart->zoomReset(); chart->createDefaultAxes(); series.erase( it ); #endif } <|endoftext|>
<commit_before>#include "stdafx.h" // From: http://forum.sysinternals.com/howto-enumerate-handles_topic18892.html #include <stdio.h> #include "FileHandles.h" #ifndef UNICODE #define UNICODE #endif #define NT_SUCCESS(x) ((x) >= 0) #define STATUS_INFO_LENGTH_MISMATCH 0xc0000004 #define SystemHandleInformation 16 #define SystemHandleInformationEx 64 #define ObjectBasicInformation 0 #define ObjectNameInformation 1 #define ObjectTypeInformation 2 #define NTAPI __stdcall typedef NTSTATUS(NTAPI *_NtQuerySystemInformation)( ULONG SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength ); typedef NTSTATUS(NTAPI *_NtDuplicateObject)( HANDLE SourceProcessHandle, HANDLE SourceHandle, HANDLE TargetProcessHandle, PHANDLE TargetHandle, ACCESS_MASK DesiredAccess, ULONG Attributes, ULONG Options ); typedef NTSTATUS(NTAPI *_NtQueryObject)( HANDLE ObjectHandle, ULONG ObjectInformationClass, PVOID ObjectInformation, ULONG ObjectInformationLength, PULONG ReturnLength ); typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING, *PUNICODE_STRING; typedef struct _SYSTEM_HANDLE { ULONG ProcessId; BYTE ObjectTypeNumber; BYTE Flags; USHORT Handle; PVOID Object; ACCESS_MASK GrantedAccess; } SYSTEM_HANDLE, *PSYSTEM_HANDLE; typedef struct _SYSTEM_HANDLE_EX { PVOID Object; HANDLE ProcessId; HANDLE Handle; ULONG GrantedAccess; USHORT CreatorBackTraceIndex; USHORT ObjectTypeIndex; ULONG HandleAttributes; ULONG Reserved; } SYSTEM_HANDLE_EX, *PSYSTEM_HANDLE_EX; typedef struct _SYSTEM_HANDLE_INFORMATION { ULONG HandleCount; SYSTEM_HANDLE Handles[1]; } SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION; typedef struct _SYSTEM_HANDLE_INFORMATION_EX { ULONG_PTR HandleCount; ULONG_PTR Reserved; SYSTEM_HANDLE_EX Handles[1]; } SYSTEM_HANDLE_INFORMATION_EX, *PSYSTEM_HANDLE_INFORMATION_EX; typedef enum _POOL_TYPE { NonPagedPool, PagedPool, NonPagedPoolMustSucceed, DontUseThisType, NonPagedPoolCacheAligned, PagedPoolCacheAligned, NonPagedPoolCacheAlignedMustS } POOL_TYPE, *PPOOL_TYPE; typedef struct _OBJECT_TYPE_INFORMATION { UNICODE_STRING Name; ULONG TotalNumberOfObjects; ULONG TotalNumberOfHandles; ULONG TotalPagedPoolUsage; ULONG TotalNonPagedPoolUsage; ULONG TotalNamePoolUsage; ULONG TotalHandleTableUsage; ULONG HighWaterNumberOfObjects; ULONG HighWaterNumberOfHandles; ULONG HighWaterPagedPoolUsage; ULONG HighWaterNonPagedPoolUsage; ULONG HighWaterNamePoolUsage; ULONG HighWaterHandleTableUsage; ULONG InvalidAttributes; GENERIC_MAPPING GenericMapping; ULONG ValidAccess; BOOLEAN SecurityRequired; BOOLEAN MaintainHandleCount; USHORT MaintainTypeList; POOL_TYPE PoolType; ULONG PagedPoolUsage; ULONG NonPagedPoolUsage; } OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION; PVOID GetLibraryProcAddress(LPCSTR LibraryName, LPCSTR ProcName) { return GetProcAddress(GetModuleHandleA(LibraryName), ProcName); } int getOpenFiles(WStringVector &files) { _NtQuerySystemInformation NtQuerySystemInformation = (_NtQuerySystemInformation)GetLibraryProcAddress("ntdll.dll", "NtQuerySystemInformation"); _NtDuplicateObject NtDuplicateObject = (_NtDuplicateObject)GetLibraryProcAddress("ntdll.dll", "NtDuplicateObject"); _NtQueryObject NtQueryObject = (_NtQueryObject)GetLibraryProcAddress("ntdll.dll", "NtQueryObject"); NTSTATUS status; PSYSTEM_HANDLE_INFORMATION_EX handleInfo; ULONG handleInfoSize = 0x400000; HANDLE pid; HANDLE processHandle; ULONG i; files.clear(); if (!NtQuerySystemInformation || !NtDuplicateObject || !NtQueryObject) { return 0; } pid = reinterpret_cast<HANDLE>((uintptr_t)GetCurrentProcessId()); processHandle = GetCurrentProcess(); handleInfo = (PSYSTEM_HANDLE_INFORMATION_EX)malloc(handleInfoSize); /* NtQuerySystemInformation won't give us the correct buffer size, so we guess by doubling the buffer size. */ while ((status = NtQuerySystemInformation( SystemHandleInformationEx, handleInfo, handleInfoSize, NULL )) == STATUS_INFO_LENGTH_MISMATCH) handleInfo = (PSYSTEM_HANDLE_INFORMATION_EX)realloc(handleInfo, handleInfoSize *= 2); /* NtQuerySystemInformation stopped giving us STATUS_INFO_LENGTH_MISMATCH. */ if (!NT_SUCCESS(status)) { //printf("NtQuerySystemInformation failed!\n"); free(handleInfo); return 0; } for (i = 0; i < handleInfo->HandleCount; i++) { SYSTEM_HANDLE_EX handle = handleInfo->Handles[i]; HANDLE dupHandle = NULL; POBJECT_TYPE_INFORMATION objectTypeInfo; PVOID objectNameInfo; UNICODE_STRING objectName; ULONG returnLength; /* Check if this handle belongs to the PID the user specified. */ if (handle.ProcessId != pid) continue; /* Duplicate the handle so we can query it. */ if (!NT_SUCCESS(NtDuplicateObject( processHandle, (HANDLE)handle.Handle, GetCurrentProcess(), &dupHandle, 0, 0, 0 ))) { //printf("[%#x] Error!\n", handle.Handle); continue; } /* * We only want files anyway so lets check the type to ensure its a file. * As in some cases reading a named pipe would cause a hang. (Thanks TOBII ET5) */ DWORD fileType = GetFileType(dupHandle); if (fileType != FILE_TYPE_DISK) { CloseHandle(dupHandle); continue; } /* Query the object type. */ objectTypeInfo = (POBJECT_TYPE_INFORMATION)malloc(0x1000); if (!NT_SUCCESS(NtQueryObject( dupHandle, ObjectTypeInformation, objectTypeInfo, 0x1000, NULL ))) { //printf("[%#x] Error!\n", handle.Handle); CloseHandle(dupHandle); continue; } /* Query the object name (unless it has an access of 0x0012019f, on which NtQueryObject could hang. */ if (handle.GrantedAccess == 0x0012019f) { /* We have the type, so display that. */ /*printf( "[%#x] %.*S: (did not get name)\n", handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer );*/ free(objectTypeInfo); CloseHandle(dupHandle); continue; } objectNameInfo = malloc(0x1000); if (!NT_SUCCESS(NtQueryObject( dupHandle, ObjectNameInformation, objectNameInfo, 0x1000, &returnLength ))) { /* Reallocate the buffer and try again. */ objectNameInfo = realloc(objectNameInfo, returnLength); if (!NT_SUCCESS(NtQueryObject( dupHandle, ObjectNameInformation, objectNameInfo, returnLength, NULL ))) { /* We have the type name, so just display that. */ /*printf( "[%#x] %.*S: (could not get name)\n", handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer );*/ free(objectTypeInfo); free(objectNameInfo); CloseHandle(dupHandle); continue; } } /* Cast our buffer into an UNICODE_STRING. */ objectName = *(PUNICODE_STRING)objectNameInfo; /* Print the information! */ if (objectName.Length) { /* The object has a name. */ /*printf( "[%#x] %.*S: %.*S\n", handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer, objectName.Length / 2, objectName.Buffer );*/ // Only get files // Maybe there is a better way of doing this but this should be called // only once, anyway. if (!wcsncmp(objectTypeInfo->Name.Buffer, L"File", 4)) { //std::wstring fileName(objectName.Buffer, objectName.Length / 2); // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath // The value below isn't completely correct but bah... (see link above) #define MAX_UNICODE_PATH (32767 + 1) const DWORD max_unicode_path_size = MAX_UNICODE_PATH * sizeof(wchar_t); wchar_t tmpPath[max_unicode_path_size]; DWORD max_size = (sizeof(tmpPath) / sizeof(wchar_t)) - 1; // Naming Files, Paths, and Namespaces // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx DWORD retval = GetFinalPathNameByHandleW(dupHandle, tmpPath, max_size, FILE_NAME_OPENED); if (retval && retval < max_size) { files.push_back(tmpPath); } else { //ErrorExit(fileName.c_str()); } } } else { /* Print something else. */ /*printf( "[%#x] %.*S: (unnamed)\n", handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer );*/ } free(objectTypeInfo); free(objectNameInfo); CloseHandle(dupHandle); } free(handleInfo); return 1; } <commit_msg>getOpenFiles only on Windows, for now<commit_after>#include "stdafx.h" // From: http://forum.sysinternals.com/howto-enumerate-handles_topic18892.html #include <stdio.h> #include "FileHandles.h" #ifdef _WIN32 #ifndef UNICODE #define UNICODE #endif #define NT_SUCCESS(x) ((x) >= 0) #define STATUS_INFO_LENGTH_MISMATCH 0xc0000004 #define SystemHandleInformation 16 #define SystemHandleInformationEx 64 #define ObjectBasicInformation 0 #define ObjectNameInformation 1 #define ObjectTypeInformation 2 #define NTAPI __stdcall typedef NTSTATUS(NTAPI *_NtQuerySystemInformation)( ULONG SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength ); typedef NTSTATUS(NTAPI *_NtDuplicateObject)( HANDLE SourceProcessHandle, HANDLE SourceHandle, HANDLE TargetProcessHandle, PHANDLE TargetHandle, ACCESS_MASK DesiredAccess, ULONG Attributes, ULONG Options ); typedef NTSTATUS(NTAPI *_NtQueryObject)( HANDLE ObjectHandle, ULONG ObjectInformationClass, PVOID ObjectInformation, ULONG ObjectInformationLength, PULONG ReturnLength ); typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING, *PUNICODE_STRING; typedef struct _SYSTEM_HANDLE { ULONG ProcessId; BYTE ObjectTypeNumber; BYTE Flags; USHORT Handle; PVOID Object; ACCESS_MASK GrantedAccess; } SYSTEM_HANDLE, *PSYSTEM_HANDLE; typedef struct _SYSTEM_HANDLE_EX { PVOID Object; HANDLE ProcessId; HANDLE Handle; ULONG GrantedAccess; USHORT CreatorBackTraceIndex; USHORT ObjectTypeIndex; ULONG HandleAttributes; ULONG Reserved; } SYSTEM_HANDLE_EX, *PSYSTEM_HANDLE_EX; typedef struct _SYSTEM_HANDLE_INFORMATION { ULONG HandleCount; SYSTEM_HANDLE Handles[1]; } SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION; typedef struct _SYSTEM_HANDLE_INFORMATION_EX { ULONG_PTR HandleCount; ULONG_PTR Reserved; SYSTEM_HANDLE_EX Handles[1]; } SYSTEM_HANDLE_INFORMATION_EX, *PSYSTEM_HANDLE_INFORMATION_EX; typedef enum _POOL_TYPE { NonPagedPool, PagedPool, NonPagedPoolMustSucceed, DontUseThisType, NonPagedPoolCacheAligned, PagedPoolCacheAligned, NonPagedPoolCacheAlignedMustS } POOL_TYPE, *PPOOL_TYPE; typedef struct _OBJECT_TYPE_INFORMATION { UNICODE_STRING Name; ULONG TotalNumberOfObjects; ULONG TotalNumberOfHandles; ULONG TotalPagedPoolUsage; ULONG TotalNonPagedPoolUsage; ULONG TotalNamePoolUsage; ULONG TotalHandleTableUsage; ULONG HighWaterNumberOfObjects; ULONG HighWaterNumberOfHandles; ULONG HighWaterPagedPoolUsage; ULONG HighWaterNonPagedPoolUsage; ULONG HighWaterNamePoolUsage; ULONG HighWaterHandleTableUsage; ULONG InvalidAttributes; GENERIC_MAPPING GenericMapping; ULONG ValidAccess; BOOLEAN SecurityRequired; BOOLEAN MaintainHandleCount; USHORT MaintainTypeList; POOL_TYPE PoolType; ULONG PagedPoolUsage; ULONG NonPagedPoolUsage; } OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION; PVOID GetLibraryProcAddress(LPCSTR LibraryName, LPCSTR ProcName) { return GetProcAddress(GetModuleHandleA(LibraryName), ProcName); } int getOpenFiles(WStringVector &files) { _NtQuerySystemInformation NtQuerySystemInformation = (_NtQuerySystemInformation)GetLibraryProcAddress("ntdll.dll", "NtQuerySystemInformation"); _NtDuplicateObject NtDuplicateObject = (_NtDuplicateObject)GetLibraryProcAddress("ntdll.dll", "NtDuplicateObject"); _NtQueryObject NtQueryObject = (_NtQueryObject)GetLibraryProcAddress("ntdll.dll", "NtQueryObject"); NTSTATUS status; PSYSTEM_HANDLE_INFORMATION_EX handleInfo; ULONG handleInfoSize = 0x400000; HANDLE pid; HANDLE processHandle; ULONG i; files.clear(); if (!NtQuerySystemInformation || !NtDuplicateObject || !NtQueryObject) { return 0; } pid = reinterpret_cast<HANDLE>((uintptr_t)GetCurrentProcessId()); processHandle = GetCurrentProcess(); handleInfo = (PSYSTEM_HANDLE_INFORMATION_EX)malloc(handleInfoSize); /* NtQuerySystemInformation won't give us the correct buffer size, so we guess by doubling the buffer size. */ while ((status = NtQuerySystemInformation( SystemHandleInformationEx, handleInfo, handleInfoSize, NULL )) == STATUS_INFO_LENGTH_MISMATCH) handleInfo = (PSYSTEM_HANDLE_INFORMATION_EX)realloc(handleInfo, handleInfoSize *= 2); /* NtQuerySystemInformation stopped giving us STATUS_INFO_LENGTH_MISMATCH. */ if (!NT_SUCCESS(status)) { //printf("NtQuerySystemInformation failed!\n"); free(handleInfo); return 0; } for (i = 0; i < handleInfo->HandleCount; i++) { SYSTEM_HANDLE_EX handle = handleInfo->Handles[i]; HANDLE dupHandle = NULL; POBJECT_TYPE_INFORMATION objectTypeInfo; PVOID objectNameInfo; UNICODE_STRING objectName; ULONG returnLength; /* Check if this handle belongs to the PID the user specified. */ if (handle.ProcessId != pid) continue; /* Duplicate the handle so we can query it. */ if (!NT_SUCCESS(NtDuplicateObject( processHandle, (HANDLE)handle.Handle, GetCurrentProcess(), &dupHandle, 0, 0, 0 ))) { //printf("[%#x] Error!\n", handle.Handle); continue; } /* * We only want files anyway so lets check the type to ensure its a file. * As in some cases reading a named pipe would cause a hang. (Thanks TOBII ET5) */ DWORD fileType = GetFileType(dupHandle); if (fileType != FILE_TYPE_DISK) { CloseHandle(dupHandle); continue; } /* Query the object type. */ objectTypeInfo = (POBJECT_TYPE_INFORMATION)malloc(0x1000); if (!NT_SUCCESS(NtQueryObject( dupHandle, ObjectTypeInformation, objectTypeInfo, 0x1000, NULL ))) { //printf("[%#x] Error!\n", handle.Handle); CloseHandle(dupHandle); continue; } /* Query the object name (unless it has an access of 0x0012019f, on which NtQueryObject could hang. */ if (handle.GrantedAccess == 0x0012019f) { /* We have the type, so display that. */ /*printf( "[%#x] %.*S: (did not get name)\n", handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer );*/ free(objectTypeInfo); CloseHandle(dupHandle); continue; } objectNameInfo = malloc(0x1000); if (!NT_SUCCESS(NtQueryObject( dupHandle, ObjectNameInformation, objectNameInfo, 0x1000, &returnLength ))) { /* Reallocate the buffer and try again. */ objectNameInfo = realloc(objectNameInfo, returnLength); if (!NT_SUCCESS(NtQueryObject( dupHandle, ObjectNameInformation, objectNameInfo, returnLength, NULL ))) { /* We have the type name, so just display that. */ /*printf( "[%#x] %.*S: (could not get name)\n", handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer );*/ free(objectTypeInfo); free(objectNameInfo); CloseHandle(dupHandle); continue; } } /* Cast our buffer into an UNICODE_STRING. */ objectName = *(PUNICODE_STRING)objectNameInfo; /* Print the information! */ if (objectName.Length) { /* The object has a name. */ /*printf( "[%#x] %.*S: %.*S\n", handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer, objectName.Length / 2, objectName.Buffer );*/ // Only get files // Maybe there is a better way of doing this but this should be called // only once, anyway. if (!wcsncmp(objectTypeInfo->Name.Buffer, L"File", 4)) { //std::wstring fileName(objectName.Buffer, objectName.Length / 2); // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath // The value below isn't completely correct but bah... (see link above) #define MAX_UNICODE_PATH (32767 + 1) const DWORD max_unicode_path_size = MAX_UNICODE_PATH * sizeof(wchar_t); wchar_t tmpPath[max_unicode_path_size]; DWORD max_size = (sizeof(tmpPath) / sizeof(wchar_t)) - 1; // Naming Files, Paths, and Namespaces // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx DWORD retval = GetFinalPathNameByHandleW(dupHandle, tmpPath, max_size, FILE_NAME_OPENED); if (retval && retval < max_size) { files.push_back(tmpPath); } else { //ErrorExit(fileName.c_str()); } } } else { /* Print something else. */ /*printf( "[%#x] %.*S: (unnamed)\n", handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer );*/ } free(objectTypeInfo); free(objectNameInfo); CloseHandle(dupHandle); } free(handleInfo); return 1; } #else // ifdef _WIN32 int getOpenFiles(WStringVector& files) { // TODO: Implement lsof return 0; } #endif // ifdef _WIN32 <|endoftext|>
<commit_before>#include <array> #include <fstream> #include <iostream> #include "png/png.h" #include "png/zlib.h" #include "RaZ/Utils/Image.hpp" namespace Raz { namespace { const uint8_t PNG_HEADER_SIZE = 8; bool validatePng(std::istream& file) { std::array<png_byte, PNG_HEADER_SIZE> header {}; file.read(reinterpret_cast<char*>(header.data()), PNG_HEADER_SIZE); return (png_sig_cmp(header.data(), 0, PNG_HEADER_SIZE) == 0); } } // namespace void Image::readPng(std::ifstream& file, bool reverse) { if (!validatePng(file)) throw std::runtime_error("Error: Not a valid PNG"); png_structp readStruct = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (!readStruct) throw std::runtime_error("Error: Couldn't initialize PNG read struct"); png_infop infoStruct = png_create_info_struct(readStruct); if (!infoStruct) throw std::runtime_error("Error: Couldn't initialize PNG info struct"); png_set_read_fn(readStruct, &file, [] (png_structp pngReadPtr, png_bytep data, png_size_t length) { png_voidp inPtr = png_get_io_ptr(pngReadPtr); static_cast<std::istream*>(inPtr)->read(reinterpret_cast<char*>(data), static_cast<std::streamsize>(length)); }); // Setting the amount signature bytes we've already read png_set_sig_bytes(readStruct, PNG_HEADER_SIZE); png_read_info(readStruct, infoStruct); m_width = png_get_image_width(readStruct, infoStruct); m_height = png_get_image_height(readStruct, infoStruct); m_channelCount = png_get_channels(readStruct, infoStruct); m_bitDepth = png_get_bit_depth(readStruct, infoStruct); const uint8_t colorType = png_get_color_type(readStruct, infoStruct); switch (colorType) { case PNG_COLOR_TYPE_GRAY: if (m_bitDepth < 8) { png_set_expand_gray_1_2_4_to_8(readStruct); m_bitDepth = 8; } m_colorspace = ImageColorspace::GRAY; break; case PNG_COLOR_TYPE_GRAY_ALPHA: m_colorspace = ImageColorspace::GRAY_ALPHA; break; case PNG_COLOR_TYPE_PALETTE: png_set_palette_to_rgb(readStruct); m_channelCount = 3; m_colorspace = ImageColorspace::RGB; break; case PNG_COLOR_TYPE_RGB: default: m_colorspace = ImageColorspace::RGB; break; case PNG_COLOR_TYPE_RGBA: m_colorspace = ImageColorspace::RGBA; break; } if (!png_set_interlace_handling(readStruct)) std::cerr << "Error: Couldn't set PNG interlace handling" << std::endl; png_set_scale_16(readStruct); // Adding full alpha channel to the image if it possesses transparency if (png_get_valid(readStruct, infoStruct, PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(readStruct); m_colorspace = ImageColorspace::RGBA; ++m_channelCount; } png_read_update_info(readStruct, infoStruct); ImageDataBPtr imgData = ImageDataB::create(); imgData->data.resize(m_width * m_height * m_channelCount); std::vector<png_bytep> rowPtrs(m_height); // Mapping row's elements to data's for (std::size_t heightIndex = 0; heightIndex < m_height; ++heightIndex) rowPtrs[(reverse ? heightIndex : m_height - 1 - heightIndex)] = &imgData->data[m_width * m_channelCount * heightIndex]; m_data = std::move(imgData); png_read_image(readStruct, rowPtrs.data()); png_read_end(readStruct, infoStruct); png_destroy_read_struct(&readStruct, nullptr, &infoStruct); } void Image::savePng(std::ofstream& file, bool reverse) const { png_structp writeStruct = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (!writeStruct) throw std::runtime_error("Error: Couldn't initialize PNG write struct"); png_infop infoStruct = png_create_info_struct(writeStruct); if (!infoStruct) throw std::runtime_error("Error: Couldn't initialize PNG info struct"); uint32_t colorType {}; switch (m_colorspace) { case ImageColorspace::GRAY: case ImageColorspace::DEPTH: colorType = PNG_COLOR_TYPE_GRAY; break; case ImageColorspace::GRAY_ALPHA: colorType = PNG_COLOR_TYPE_GRAY_ALPHA; break; case ImageColorspace::RGB: colorType = PNG_COLOR_TYPE_RGB; break; case ImageColorspace::RGBA: colorType = PNG_COLOR_TYPE_RGBA; break; } png_set_compression_level(writeStruct, 6); if (m_channelCount * m_bitDepth >= 16) { png_set_compression_strategy(writeStruct, Z_FILTERED); png_set_filter(writeStruct, 0, PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_PAETH); } else { png_set_compression_strategy(writeStruct, Z_DEFAULT_STRATEGY); } png_set_IHDR(writeStruct, infoStruct, static_cast<png_uint_32>(m_width), static_cast<png_uint_32>(m_height), m_bitDepth, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_set_write_fn(writeStruct, &file, [] (png_structp pngWritePtr, png_bytep data, png_size_t length) { png_voidp outPtr = png_get_io_ptr(pngWritePtr); static_cast<std::ostream*>(outPtr)->write(reinterpret_cast<const char*>(data), length); }, nullptr); png_write_info(writeStruct, infoStruct); const auto dataPtr = static_cast<const uint8_t*>(m_data->getDataPtr()); for (std::size_t heightIndex = 0; heightIndex < m_height; ++heightIndex) png_write_row(writeStruct, &dataPtr[m_width * m_channelCount * (reverse ? m_height - 1 - heightIndex : heightIndex)]); png_write_end(writeStruct, infoStruct); png_destroy_write_struct(&writeStruct, &infoStruct); } } // namespace Raz <commit_msg>[Utils/PngImage] Reversed PNG importation, which imported it flipped<commit_after>#include <array> #include <fstream> #include <iostream> #include "png/png.h" #include "png/zlib.h" #include "RaZ/Utils/Image.hpp" namespace Raz { namespace { const uint8_t PNG_HEADER_SIZE = 8; bool validatePng(std::istream& file) { std::array<png_byte, PNG_HEADER_SIZE> header {}; file.read(reinterpret_cast<char*>(header.data()), PNG_HEADER_SIZE); return (png_sig_cmp(header.data(), 0, PNG_HEADER_SIZE) == 0); } } // namespace void Image::readPng(std::ifstream& file, bool flipVertically) { if (!validatePng(file)) throw std::runtime_error("Error: Not a valid PNG"); png_structp readStruct = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (!readStruct) throw std::runtime_error("Error: Couldn't initialize PNG read struct"); png_infop infoStruct = png_create_info_struct(readStruct); if (!infoStruct) throw std::runtime_error("Error: Couldn't initialize PNG info struct"); png_set_read_fn(readStruct, &file, [] (png_structp pngReadPtr, png_bytep data, png_size_t length) { png_voidp inPtr = png_get_io_ptr(pngReadPtr); static_cast<std::istream*>(inPtr)->read(reinterpret_cast<char*>(data), static_cast<std::streamsize>(length)); }); // Setting the amount signature bytes we've already read png_set_sig_bytes(readStruct, PNG_HEADER_SIZE); png_read_info(readStruct, infoStruct); m_width = png_get_image_width(readStruct, infoStruct); m_height = png_get_image_height(readStruct, infoStruct); m_channelCount = png_get_channels(readStruct, infoStruct); m_bitDepth = png_get_bit_depth(readStruct, infoStruct); const uint8_t colorType = png_get_color_type(readStruct, infoStruct); switch (colorType) { case PNG_COLOR_TYPE_GRAY: if (m_bitDepth < 8) { png_set_expand_gray_1_2_4_to_8(readStruct); m_bitDepth = 8; } m_colorspace = ImageColorspace::GRAY; break; case PNG_COLOR_TYPE_GRAY_ALPHA: m_colorspace = ImageColorspace::GRAY_ALPHA; break; case PNG_COLOR_TYPE_PALETTE: png_set_palette_to_rgb(readStruct); m_channelCount = 3; m_colorspace = ImageColorspace::RGB; break; case PNG_COLOR_TYPE_RGB: default: m_colorspace = ImageColorspace::RGB; break; case PNG_COLOR_TYPE_RGBA: m_colorspace = ImageColorspace::RGBA; break; } if (!png_set_interlace_handling(readStruct)) std::cerr << "Error: Couldn't set PNG interlace handling" << std::endl; png_set_scale_16(readStruct); // Adding full alpha channel to the image if it possesses transparency if (png_get_valid(readStruct, infoStruct, PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(readStruct); m_colorspace = ImageColorspace::RGBA; ++m_channelCount; } png_read_update_info(readStruct, infoStruct); ImageDataBPtr imgData = ImageDataB::create(); imgData->data.resize(m_width * m_height * m_channelCount); std::vector<png_bytep> rowPtrs(m_height); // Mapping row's elements to data's for (std::size_t heightIndex = 0; heightIndex < m_height; ++heightIndex) rowPtrs[(flipVertically ? m_height - 1 - heightIndex : heightIndex)] = &imgData->data[m_width * m_channelCount * heightIndex]; m_data = std::move(imgData); png_read_image(readStruct, rowPtrs.data()); png_read_end(readStruct, infoStruct); png_destroy_read_struct(&readStruct, nullptr, &infoStruct); } void Image::savePng(std::ofstream& file, bool flipVertically) const { png_structp writeStruct = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (!writeStruct) throw std::runtime_error("Error: Couldn't initialize PNG write struct"); png_infop infoStruct = png_create_info_struct(writeStruct); if (!infoStruct) throw std::runtime_error("Error: Couldn't initialize PNG info struct"); uint32_t colorType {}; switch (m_colorspace) { case ImageColorspace::GRAY: case ImageColorspace::DEPTH: colorType = PNG_COLOR_TYPE_GRAY; break; case ImageColorspace::GRAY_ALPHA: colorType = PNG_COLOR_TYPE_GRAY_ALPHA; break; case ImageColorspace::RGB: colorType = PNG_COLOR_TYPE_RGB; break; case ImageColorspace::RGBA: colorType = PNG_COLOR_TYPE_RGBA; break; } png_set_compression_level(writeStruct, 6); if (m_channelCount * m_bitDepth >= 16) { png_set_compression_strategy(writeStruct, Z_FILTERED); png_set_filter(writeStruct, 0, PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_PAETH); } else { png_set_compression_strategy(writeStruct, Z_DEFAULT_STRATEGY); } png_set_IHDR(writeStruct, infoStruct, static_cast<png_uint_32>(m_width), static_cast<png_uint_32>(m_height), m_bitDepth, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_set_write_fn(writeStruct, &file, [] (png_structp pngWritePtr, png_bytep data, png_size_t length) { png_voidp outPtr = png_get_io_ptr(pngWritePtr); static_cast<std::ostream*>(outPtr)->write(reinterpret_cast<const char*>(data), length); }, nullptr); png_write_info(writeStruct, infoStruct); const auto dataPtr = static_cast<const uint8_t*>(m_data->getDataPtr()); for (std::size_t heightIndex = 0; heightIndex < m_height; ++heightIndex) png_write_row(writeStruct, &dataPtr[m_width * m_channelCount * (flipVertically ? m_height - 1 - heightIndex : heightIndex)]); png_write_end(writeStruct, infoStruct); png_destroy_write_struct(&writeStruct, &infoStruct); } } // namespace Raz <|endoftext|>
<commit_before>#include "selection.hh" #include "utf8.hh" #include "buffer_utils.hh" namespace Kakoune { void Selection::merge_with(const Selection& range) { m_cursor = range.m_cursor; if (m_anchor < m_cursor) m_anchor = std::min(m_anchor, range.m_anchor); if (m_anchor > m_cursor) m_anchor = std::max(m_anchor, range.m_anchor); } SelectionList::SelectionList(Buffer& buffer, Selection s, size_t timestamp) : m_buffer(&buffer), m_selections({ s }), m_timestamp(timestamp) { check_invariant(); } SelectionList::SelectionList(Buffer& buffer, Selection s) : SelectionList(buffer, s, buffer.timestamp()) {} SelectionList::SelectionList(Buffer& buffer, std::vector<Selection> s, size_t timestamp) : m_buffer(&buffer), m_selections(std::move(s)), m_timestamp(timestamp) { kak_assert(size() > 0); check_invariant(); } SelectionList::SelectionList(Buffer& buffer, std::vector<Selection> s) : SelectionList(buffer, std::move(s), buffer.timestamp()) {} namespace { ByteCoord update_insert(ByteCoord coord, ByteCoord begin, ByteCoord end) { if (coord < begin) return coord; if (begin.line == coord.line) coord.column += end.column - begin.column; coord.line += end.line - begin.line; kak_assert(coord.line >= 0 and coord.column >= 0); return coord; } ByteCoord update_erase(ByteCoord coord, ByteCoord begin, ByteCoord end) { if (coord < begin) return coord; if (coord <= end) return begin; if (end.line == coord.line) coord.column -= end.column - begin.column; coord.line -= end.line - begin.line; kak_assert(coord.line >= 0 and coord.column >= 0); return coord; } ByteCoord update_pos(ByteCoord coord, const Buffer::Change& change) { if (change.type == Buffer::Change::Insert) return update_insert(coord, change.begin, change.end); else return update_erase(coord, change.begin, change.end); } // This tracks position changes for changes that are done // in a forward way (each change takes place at a position) // *after* the previous one. struct PositionChangesTracker { ByteCoord last_pos; ByteCoord pos_change; void update(const Buffer::Change& change) { if (change.type == Buffer::Change::Insert) { pos_change.line += change.end.line - change.begin.line; if (change.begin.line != last_pos.line) pos_change.column = 0; pos_change.column += change.end.column - change.begin.column; last_pos = change.end; } else if (change.type == Buffer::Change::Erase) { pos_change.line -= change.end.line - change.begin.line; if (last_pos.line != change.end.line) pos_change.column = 0; pos_change.column -= change.end.column - change.begin.column; last_pos = change.begin; } } void update(const Buffer& buffer, size_t& timestamp) { for (auto& change : buffer.changes_since(timestamp)) update(change); timestamp = buffer.timestamp(); } ByteCoord get_new_coord(ByteCoord coord) { if (last_pos.line - pos_change.line == coord.line) coord.column += pos_change.column; coord.line += pos_change.line; return coord; } void update_sel(Selection& sel) { sel.anchor() = get_new_coord(sel.anchor()); sel.cursor() = get_new_coord(sel.cursor()); } }; } void SelectionList::update() { if (m_timestamp == m_buffer->timestamp()) return; auto compare = [](const Buffer::Change& lhs, const Buffer::Change& rhs) { return lhs.begin < rhs.begin; }; auto relevant = [](const Buffer::Change& change, const ByteCoord& coord) { return change.type == Buffer::Change::Insert ? change.begin <= coord : change.begin < coord; }; auto changes = m_buffer->changes_since(m_timestamp); auto change_it = changes.begin(); while (change_it != changes.end()) { auto change_end = std::is_sorted_until(change_it, changes.end(), compare); PositionChangesTracker changes_tracker; auto advance_while_relevant = [&](const ByteCoord& pos) mutable { while (relevant(*change_it, pos) and change_it != change_end) changes_tracker.update(*change_it++); while (change_it != change_end and change_it->begin == changes_tracker.last_pos) changes_tracker.update(*change_it++); }; for (auto& sel : m_selections) { auto& sel_min = sel.min(); auto& sel_max = sel.max(); advance_while_relevant(sel_min); sel_min = changes_tracker.get_new_coord(sel_min); advance_while_relevant(sel_max); sel_max = changes_tracker.get_new_coord(sel_max); } change_it = change_end; } for (auto& sel : m_selections) { sel.anchor() = m_buffer->clamp(sel.anchor()); sel.cursor() = m_buffer->clamp(sel.cursor()); } m_selections.erase(merge_overlapping(begin(), end(), m_main, overlaps), end()); check_invariant(); m_timestamp = m_buffer->timestamp(); } void SelectionList::check_invariant() const { #ifdef KAK_DEBUG auto& buffer = this->buffer(); kak_assert(size() > 0); kak_assert(m_main < size()); for (size_t i = 0; i < size(); ++i) { auto& sel = (*this)[i]; if (i+1 < size()) kak_assert((*this)[i].min() <= (*this)[i+1].min()); kak_assert(buffer.is_valid(sel.anchor())); kak_assert(buffer.is_valid(sel.cursor())); kak_assert(not buffer.is_end(sel.anchor())); kak_assert(not buffer.is_end(sel.cursor())); kak_assert(utf8::is_character_start(buffer.byte_at(sel.anchor()))); kak_assert(utf8::is_character_start(buffer.byte_at(sel.cursor()))); } #endif } void SelectionList::sort_and_merge_overlapping() { if (size() == 1) return; const auto& main = this->main(); const auto main_begin = main.min(); m_main = std::count_if(begin(), end(), [&](const Selection& sel) { auto begin = sel.min(); if (begin == main_begin) return &sel < &main; else return begin < main_begin; }); std::stable_sort(begin(), end(), compare_selections); m_selections.erase(merge_overlapping(begin(), end(), m_main, overlaps), end()); } namespace { inline void _avoid_eol(const Buffer& buffer, ByteCoord& coord) { const auto column = coord.column; const auto& line = buffer[coord.line]; if (column != 0 and column == line.length() - 1) coord.column = line.byte_count_to(line.char_length() - 2); } inline void _avoid_eol(const Buffer& buffer, Selection& sel) { _avoid_eol(buffer, sel.anchor()); _avoid_eol(buffer, sel.cursor()); } } void SelectionList::avoid_eol() { update(); for (auto& sel : m_selections) _avoid_eol(buffer(), sel); } BufferIterator prepare_insert(Buffer& buffer, const Selection& sel, InsertMode mode) { switch (mode) { case InsertMode::Insert: return buffer.iterator_at(sel.min()); case InsertMode::InsertCursor: return buffer.iterator_at(sel.cursor()); case InsertMode::Replace: return erase(buffer, sel); case InsertMode::Append: { // special case for end of lines, append to current line instead auto pos = buffer.iterator_at(sel.max()); return *pos == '\n' ? pos : utf8::next(pos); } case InsertMode::InsertAtLineBegin: return buffer.iterator_at(sel.min().line); case InsertMode::AppendAtLineEnd: return buffer.iterator_at({sel.max().line, buffer[sel.max().line].length() - 1}); case InsertMode::InsertAtNextLineBegin: return buffer.iterator_at(sel.max().line+1); case InsertMode::OpenLineBelow: return buffer.insert(buffer.iterator_at(sel.max().line + 1), "\n"); case InsertMode::OpenLineAbove: return buffer.insert(buffer.iterator_at(sel.min().line), "\n"); } kak_assert(false); return {}; } void SelectionList::insert(memoryview<String> strings, InsertMode mode) { if (strings.empty()) return; update(); PositionChangesTracker changes_tracker; for (size_t index = 0; index < m_selections.size(); ++index) { auto& sel = m_selections[index]; changes_tracker.update_sel(sel); kak_assert(m_buffer->is_valid(sel.anchor())); kak_assert(m_buffer->is_valid(sel.cursor())); auto pos = prepare_insert(*m_buffer, sel, mode); changes_tracker.update(*m_buffer, m_timestamp); const String& str = strings[std::min(index, strings.size()-1)]; pos = m_buffer->insert(pos, str); auto& change = m_buffer->changes_since(m_timestamp).back(); changes_tracker.update(change); m_timestamp = m_buffer->timestamp(); if (mode == InsertMode::Replace) { sel.anchor() = change.begin; sel.cursor() = m_buffer->char_prev(change.end); } else { sel.anchor() = m_buffer->clamp(update_insert(sel.anchor(), change.begin, change.end)); sel.cursor() = m_buffer->clamp(update_insert(sel.cursor(), change.begin, change.end)); } } check_invariant(); m_buffer->check_invariant(); } void SelectionList::erase() { update(); PositionChangesTracker changes_tracker; for (auto& sel : m_selections) { changes_tracker.update_sel(sel); auto pos = Kakoune::erase(*m_buffer, sel); sel.anchor() = sel.cursor() = m_buffer->clamp(pos.coord()); changes_tracker.update(*m_buffer, m_timestamp); } m_buffer->check_invariant(); } void update_insert(std::vector<Selection>& sels, ByteCoord begin, ByteCoord end) { for (auto& sel : sels) { sel.anchor() = update_insert(sel.anchor(), begin, end); sel.cursor() = update_insert(sel.cursor(), begin, end); } } void update_erase(std::vector<Selection>& sels, ByteCoord begin, ByteCoord end) { for (auto& sel : sels) { sel.anchor() = update_erase(sel.anchor(), begin, end); sel.cursor() = update_erase(sel.cursor(), begin, end); } } } <commit_msg>Optimize SelectionList::update in the case where changes are backward<commit_after>#include "selection.hh" #include "utf8.hh" #include "buffer_utils.hh" namespace Kakoune { void Selection::merge_with(const Selection& range) { m_cursor = range.m_cursor; if (m_anchor < m_cursor) m_anchor = std::min(m_anchor, range.m_anchor); if (m_anchor > m_cursor) m_anchor = std::max(m_anchor, range.m_anchor); } SelectionList::SelectionList(Buffer& buffer, Selection s, size_t timestamp) : m_buffer(&buffer), m_selections({ s }), m_timestamp(timestamp) { check_invariant(); } SelectionList::SelectionList(Buffer& buffer, Selection s) : SelectionList(buffer, s, buffer.timestamp()) {} SelectionList::SelectionList(Buffer& buffer, std::vector<Selection> s, size_t timestamp) : m_buffer(&buffer), m_selections(std::move(s)), m_timestamp(timestamp) { kak_assert(size() > 0); check_invariant(); } SelectionList::SelectionList(Buffer& buffer, std::vector<Selection> s) : SelectionList(buffer, std::move(s), buffer.timestamp()) {} namespace { ByteCoord update_insert(ByteCoord coord, ByteCoord begin, ByteCoord end) { if (coord < begin) return coord; if (begin.line == coord.line) coord.column += end.column - begin.column; coord.line += end.line - begin.line; kak_assert(coord.line >= 0 and coord.column >= 0); return coord; } ByteCoord update_erase(ByteCoord coord, ByteCoord begin, ByteCoord end) { if (coord < begin) return coord; if (coord <= end) return begin; if (end.line == coord.line) coord.column -= end.column - begin.column; coord.line -= end.line - begin.line; kak_assert(coord.line >= 0 and coord.column >= 0); return coord; } ByteCoord update_pos(ByteCoord coord, const Buffer::Change& change) { if (change.type == Buffer::Change::Insert) return update_insert(coord, change.begin, change.end); else return update_erase(coord, change.begin, change.end); } // This tracks position changes for changes that are done // in a forward way (each change takes place at a position) // *after* the previous one. struct PositionChangesTracker { ByteCoord last_pos; ByteCoord pos_change; void update(const Buffer::Change& change) { if (change.type == Buffer::Change::Insert) { pos_change.line += change.end.line - change.begin.line; if (change.begin.line != last_pos.line) pos_change.column = 0; pos_change.column += change.end.column - change.begin.column; last_pos = change.end; } else if (change.type == Buffer::Change::Erase) { pos_change.line -= change.end.line - change.begin.line; if (last_pos.line != change.end.line) pos_change.column = 0; pos_change.column -= change.end.column - change.begin.column; last_pos = change.begin; } } void update(const Buffer& buffer, size_t& timestamp) { for (auto& change : buffer.changes_since(timestamp)) update(change); timestamp = buffer.timestamp(); } ByteCoord get_new_coord(ByteCoord coord) { if (last_pos.line - pos_change.line == coord.line) coord.column += pos_change.column; coord.line += pos_change.line; return coord; } void update_sel(Selection& sel) { sel.anchor() = get_new_coord(sel.anchor()); sel.cursor() = get_new_coord(sel.cursor()); } }; bool relevant(const Buffer::Change& change, ByteCoord coord) { return change.type == Buffer::Change::Insert ? change.begin <= coord : change.begin < coord; } void update_forward(memoryview<Buffer::Change> changes, std::vector<Selection>& selections) { PositionChangesTracker changes_tracker; auto change_it = changes.begin(); auto advance_while_relevant = [&](const ByteCoord& pos) mutable { while (relevant(*change_it, changes_tracker.get_new_coord(pos)) and change_it != changes.end()) changes_tracker.update(*change_it++); }; for (auto& sel : selections) { auto& sel_min = sel.min(); auto& sel_max = sel.max(); advance_while_relevant(sel_min); sel_min = changes_tracker.get_new_coord(sel_min); advance_while_relevant(sel_max); sel_max = changes_tracker.get_new_coord(sel_max); } } void update_backward(memoryview<Buffer::Change> changes, std::vector<Selection>& selections) { PositionChangesTracker changes_tracker; using ReverseIt = std::reverse_iterator<const Buffer::Change*>; auto change_it = ReverseIt(changes.end()); auto change_end = ReverseIt(changes.begin()); auto advance_while_relevant = [&](const ByteCoord& pos) mutable { while (change_it != change_end) { auto change = *change_it; change.begin = changes_tracker.get_new_coord(change.begin); change.end = changes_tracker.get_new_coord(change.end); if (not relevant(change, changes_tracker.get_new_coord(pos))) break; changes_tracker.update(change); ++change_it; } }; for (auto& sel : selections) { auto& sel_min = sel.min(); auto& sel_max = sel.max(); advance_while_relevant(sel_min); sel_min = changes_tracker.get_new_coord(sel_min); advance_while_relevant(sel_max); sel_max = changes_tracker.get_new_coord(sel_max); } } } void SelectionList::update() { if (m_timestamp == m_buffer->timestamp()) return; auto forward = [](const Buffer::Change& lhs, const Buffer::Change& rhs) { return lhs.begin < rhs.begin; }; auto backward = [](const Buffer::Change& lhs, const Buffer::Change& rhs) { return lhs.begin > rhs.end; }; auto changes = m_buffer->changes_since(m_timestamp); auto change_it = changes.begin(); while (change_it != changes.end()) { auto forward_end = std::is_sorted_until(change_it, changes.end(), forward); auto backward_end = std::is_sorted_until(change_it, changes.end(), backward); if (forward_end >= backward_end) { update_forward({ change_it, forward_end }, m_selections); change_it = forward_end; } else { update_backward({ change_it, backward_end }, m_selections); change_it = backward_end; } kak_assert(std::is_sorted(m_selections.begin(), m_selections.end(), compare_selections)); } for (auto& sel : m_selections) { sel.anchor() = m_buffer->clamp(sel.anchor()); sel.cursor() = m_buffer->clamp(sel.cursor()); } m_selections.erase(merge_overlapping(begin(), end(), m_main, overlaps), end()); check_invariant(); m_timestamp = m_buffer->timestamp(); } void SelectionList::check_invariant() const { #ifdef KAK_DEBUG auto& buffer = this->buffer(); kak_assert(size() > 0); kak_assert(m_main < size()); for (size_t i = 0; i < size(); ++i) { auto& sel = (*this)[i]; if (i+1 < size()) kak_assert((*this)[i].min() <= (*this)[i+1].min()); kak_assert(buffer.is_valid(sel.anchor())); kak_assert(buffer.is_valid(sel.cursor())); kak_assert(not buffer.is_end(sel.anchor())); kak_assert(not buffer.is_end(sel.cursor())); kak_assert(utf8::is_character_start(buffer.byte_at(sel.anchor()))); kak_assert(utf8::is_character_start(buffer.byte_at(sel.cursor()))); } #endif } void SelectionList::sort_and_merge_overlapping() { if (size() == 1) return; const auto& main = this->main(); const auto main_begin = main.min(); m_main = std::count_if(begin(), end(), [&](const Selection& sel) { auto begin = sel.min(); if (begin == main_begin) return &sel < &main; else return begin < main_begin; }); std::stable_sort(begin(), end(), compare_selections); m_selections.erase(merge_overlapping(begin(), end(), m_main, overlaps), end()); } namespace { inline void _avoid_eol(const Buffer& buffer, ByteCoord& coord) { const auto column = coord.column; const auto& line = buffer[coord.line]; if (column != 0 and column == line.length() - 1) coord.column = line.byte_count_to(line.char_length() - 2); } inline void _avoid_eol(const Buffer& buffer, Selection& sel) { _avoid_eol(buffer, sel.anchor()); _avoid_eol(buffer, sel.cursor()); } } void SelectionList::avoid_eol() { update(); for (auto& sel : m_selections) _avoid_eol(buffer(), sel); } BufferIterator prepare_insert(Buffer& buffer, const Selection& sel, InsertMode mode) { switch (mode) { case InsertMode::Insert: return buffer.iterator_at(sel.min()); case InsertMode::InsertCursor: return buffer.iterator_at(sel.cursor()); case InsertMode::Replace: return erase(buffer, sel); case InsertMode::Append: { // special case for end of lines, append to current line instead auto pos = buffer.iterator_at(sel.max()); return *pos == '\n' ? pos : utf8::next(pos); } case InsertMode::InsertAtLineBegin: return buffer.iterator_at(sel.min().line); case InsertMode::AppendAtLineEnd: return buffer.iterator_at({sel.max().line, buffer[sel.max().line].length() - 1}); case InsertMode::InsertAtNextLineBegin: return buffer.iterator_at(sel.max().line+1); case InsertMode::OpenLineBelow: return buffer.insert(buffer.iterator_at(sel.max().line + 1), "\n"); case InsertMode::OpenLineAbove: return buffer.insert(buffer.iterator_at(sel.min().line), "\n"); } kak_assert(false); return {}; } void SelectionList::insert(memoryview<String> strings, InsertMode mode) { if (strings.empty()) return; update(); PositionChangesTracker changes_tracker; for (size_t index = 0; index < m_selections.size(); ++index) { auto& sel = m_selections[index]; changes_tracker.update_sel(sel); kak_assert(m_buffer->is_valid(sel.anchor())); kak_assert(m_buffer->is_valid(sel.cursor())); auto pos = prepare_insert(*m_buffer, sel, mode); changes_tracker.update(*m_buffer, m_timestamp); const String& str = strings[std::min(index, strings.size()-1)]; pos = m_buffer->insert(pos, str); auto& change = m_buffer->changes_since(m_timestamp).back(); changes_tracker.update(change); m_timestamp = m_buffer->timestamp(); if (mode == InsertMode::Replace) { sel.anchor() = change.begin; sel.cursor() = m_buffer->char_prev(change.end); } else { sel.anchor() = m_buffer->clamp(update_insert(sel.anchor(), change.begin, change.end)); sel.cursor() = m_buffer->clamp(update_insert(sel.cursor(), change.begin, change.end)); } } check_invariant(); m_buffer->check_invariant(); } void SelectionList::erase() { update(); PositionChangesTracker changes_tracker; for (auto& sel : m_selections) { changes_tracker.update_sel(sel); auto pos = Kakoune::erase(*m_buffer, sel); sel.anchor() = sel.cursor() = m_buffer->clamp(pos.coord()); changes_tracker.update(*m_buffer, m_timestamp); } m_buffer->check_invariant(); } void update_insert(std::vector<Selection>& sels, ByteCoord begin, ByteCoord end) { for (auto& sel : sels) { sel.anchor() = update_insert(sel.anchor(), begin, end); sel.cursor() = update_insert(sel.cursor(), begin, end); } } void update_erase(std::vector<Selection>& sels, ByteCoord begin, ByteCoord end) { for (auto& sel : sels) { sel.anchor() = update_erase(sel.anchor(), begin, end); sel.cursor() = update_erase(sel.cursor(), begin, end); } } } <|endoftext|>
<commit_before>//===--- CrashRecoveryContext.cpp - Crash Recovery ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Config/config.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Mutex.h" #include "llvm/Support/ThreadLocal.h" #include <setjmp.h> using namespace llvm; namespace { struct CrashRecoveryContextImpl; static ManagedStatic< sys::ThreadLocal<const CrashRecoveryContextImpl> > CurrentContext; struct CrashRecoveryContextImpl { const CrashRecoveryContextImpl *Next; CrashRecoveryContext *CRC; std::string Backtrace; ::jmp_buf JumpBuffer; volatile unsigned Failed : 1; unsigned SwitchedThread : 1; public: CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC), Failed(false), SwitchedThread(false) { Next = CurrentContext->get(); CurrentContext->set(this); } ~CrashRecoveryContextImpl() { if (!SwitchedThread) CurrentContext->set(Next); } /// \brief Called when the separate crash-recovery thread was finished, to /// indicate that we don't need to clear the thread-local CurrentContext. void setSwitchedThread() { #if defined(LLVM_ENABLE_THREADS) && LLVM_ENABLE_THREADS != 0 SwitchedThread = true; #endif } void HandleCrash() { // Eliminate the current context entry, to avoid re-entering in case the // cleanup code crashes. CurrentContext->set(Next); assert(!Failed && "Crash recovery context already failed!"); Failed = true; // FIXME: Stash the backtrace. // Jump back to the RunSafely we were called under. longjmp(JumpBuffer, 1); } }; } static ManagedStatic<sys::Mutex> gCrashRecoveryContextMutex; static bool gCrashRecoveryEnabled = false; static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContext>> tlIsRecoveringFromCrash; CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {} CrashRecoveryContext::~CrashRecoveryContext() { // Reclaim registered resources. CrashRecoveryContextCleanup *i = head; const CrashRecoveryContext *PC = tlIsRecoveringFromCrash->get(); tlIsRecoveringFromCrash->set(this); while (i) { CrashRecoveryContextCleanup *tmp = i; i = tmp->next; tmp->cleanupFired = true; tmp->recoverResources(); delete tmp; } tlIsRecoveringFromCrash->set(PC); CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl; delete CRCI; } bool CrashRecoveryContext::isRecoveringFromCrash() { return tlIsRecoveringFromCrash->get() != nullptr; } CrashRecoveryContext *CrashRecoveryContext::GetCurrent() { if (!gCrashRecoveryEnabled) return nullptr; const CrashRecoveryContextImpl *CRCI = CurrentContext->get(); if (!CRCI) return nullptr; return CRCI->CRC; } void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup) { if (!cleanup) return; if (head) head->prev = cleanup; cleanup->next = head; head = cleanup; } void CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) { if (!cleanup) return; if (cleanup == head) { head = cleanup->next; if (head) head->prev = nullptr; } else { cleanup->prev->next = cleanup->next; if (cleanup->next) cleanup->next->prev = cleanup->prev; } delete cleanup; } #ifdef LLVM_ON_WIN32 #include "Windows/WindowsSupport.h" // On Windows, we can make use of vectored exception handling to // catch most crashing situations. Note that this does mean // we will be alerted of exceptions *before* structured exception // handling has the opportunity to catch it. But that isn't likely // to cause problems because nowhere in the project is SEH being // used. // // Vectored exception handling is built on top of SEH, and so it // works on a per-thread basis. // // The vectored exception handler functionality was added in Windows // XP, so if support for older versions of Windows is required, // it will have to be added. // // If we want to support as far back as Win2k, we could use the // SetUnhandledExceptionFilter API, but there's a risk of that // being entirely overwritten (it's not a chain). static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo) { // Lookup the current thread local recovery object. const CrashRecoveryContextImpl *CRCI = CurrentContext->get(); if (!CRCI) { // Something has gone horribly wrong, so let's just tell everyone // to keep searching CrashRecoveryContext::Disable(); return EXCEPTION_CONTINUE_SEARCH; } // TODO: We can capture the stack backtrace here and store it on the // implementation if we so choose. // Handle the crash const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash(); // Note that we don't actually get here because HandleCrash calls // longjmp, which means the HandleCrash function never returns. llvm_unreachable("Handled the crash, should have longjmp'ed out of here"); } // Because the Enable and Disable calls are static, it means that // there may not actually be an Impl available, or even a current // CrashRecoveryContext at all. So we make use of a thread-local // exception table. The handles contained in here will either be // non-NULL, valid VEH handles, or NULL. static sys::ThreadLocal<const void> sCurrentExceptionHandle; void CrashRecoveryContext::Enable() { sys::ScopedLock L(*gCrashRecoveryContextMutex); if (gCrashRecoveryEnabled) return; gCrashRecoveryEnabled = true; // We can set up vectored exception handling now. We will install our // handler as the front of the list, though there's no assurances that // it will remain at the front (another call could install itself before // our handler). This 1) isn't likely, and 2) shouldn't cause problems. PVOID handle = ::AddVectoredExceptionHandler(1, ExceptionHandler); sCurrentExceptionHandle.set(handle); } void CrashRecoveryContext::Disable() { sys::ScopedLock L(*gCrashRecoveryContextMutex); if (!gCrashRecoveryEnabled) return; gCrashRecoveryEnabled = false; PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get()); if (currentHandle) { // Now we can remove the vectored exception handler from the chain ::RemoveVectoredExceptionHandler(currentHandle); // Reset the handle in our thread-local set. sCurrentExceptionHandle.set(NULL); } } #else // Generic POSIX implementation. // // This implementation relies on synchronous signals being delivered to the // current thread. We use a thread local object to keep track of the active // crash recovery context, and install signal handlers to invoke HandleCrash on // the active object. // // This implementation does not to attempt to chain signal handlers in any // reliable fashion -- if we get a signal outside of a crash recovery context we // simply disable crash recovery and raise the signal again. #include <signal.h> static const int Signals[] = { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP }; static const unsigned NumSignals = sizeof(Signals) / sizeof(Signals[0]); static struct sigaction PrevActions[NumSignals]; static void CrashRecoverySignalHandler(int Signal) { // Lookup the current thread local recovery object. const CrashRecoveryContextImpl *CRCI = CurrentContext->get(); if (!CRCI) { // We didn't find a crash recovery context -- this means either we got a // signal on a thread we didn't expect it on, the application got a signal // outside of a crash recovery context, or something else went horribly // wrong. // // Disable crash recovery and raise the signal again. The assumption here is // that the enclosing application will terminate soon, and we won't want to // attempt crash recovery again. // // This call of Disable isn't thread safe, but it doesn't actually matter. CrashRecoveryContext::Disable(); raise(Signal); // The signal will be thrown once the signal mask is restored. return; } // Unblock the signal we received. sigset_t SigMask; sigemptyset(&SigMask); sigaddset(&SigMask, Signal); sigprocmask(SIG_UNBLOCK, &SigMask, nullptr); if (CRCI) const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash(); } void CrashRecoveryContext::Enable() { sys::ScopedLock L(*gCrashRecoveryContextMutex); if (gCrashRecoveryEnabled) return; gCrashRecoveryEnabled = true; // Setup the signal handler. struct sigaction Handler; Handler.sa_handler = CrashRecoverySignalHandler; Handler.sa_flags = 0; sigemptyset(&Handler.sa_mask); for (unsigned i = 0; i != NumSignals; ++i) { sigaction(Signals[i], &Handler, &PrevActions[i]); } } void CrashRecoveryContext::Disable() { sys::ScopedLock L(*gCrashRecoveryContextMutex); if (!gCrashRecoveryEnabled) return; gCrashRecoveryEnabled = false; // Restore the previous signal handlers. for (unsigned i = 0; i != NumSignals; ++i) sigaction(Signals[i], &PrevActions[i], nullptr); } #endif bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) { // If crash recovery is disabled, do nothing. if (gCrashRecoveryEnabled) { assert(!Impl && "Crash recovery context already initialized!"); CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this); Impl = CRCI; if (setjmp(CRCI->JumpBuffer) != 0) { return false; } } Fn(); return true; } void CrashRecoveryContext::HandleCrash() { CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl; assert(CRCI && "Crash recovery context never initialized!"); CRCI->HandleCrash(); } const std::string &CrashRecoveryContext::getBacktrace() const { CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *) Impl; assert(CRC && "Crash recovery context never initialized!"); assert(CRC->Failed && "No crash was detected!"); return CRC->Backtrace; } // FIXME: Portability. static void setThreadBackgroundPriority() { #ifdef __APPLE__ setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG); #endif } static bool hasThreadBackgroundPriority() { #ifdef __APPLE__ return getpriority(PRIO_DARWIN_THREAD, 0) == 1; #else return false; #endif } namespace { struct RunSafelyOnThreadInfo { function_ref<void()> Fn; CrashRecoveryContext *CRC; bool UseBackgroundPriority; bool Result; }; } static void RunSafelyOnThread_Dispatch(void *UserData) { RunSafelyOnThreadInfo *Info = reinterpret_cast<RunSafelyOnThreadInfo*>(UserData); if (Info->UseBackgroundPriority) setThreadBackgroundPriority(); Info->Result = Info->CRC->RunSafely(Info->Fn); } bool CrashRecoveryContext::RunSafelyOnThread(function_ref<void()> Fn, unsigned RequestedStackSize) { bool UseBackgroundPriority = hasThreadBackgroundPriority(); RunSafelyOnThreadInfo Info = { Fn, this, UseBackgroundPriority, false }; llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize); if (CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *)Impl) CRC->setSwitchedThread(); return Info.Result; } <commit_msg>Add a comment.<commit_after>//===--- CrashRecoveryContext.cpp - Crash Recovery ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Config/config.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Mutex.h" #include "llvm/Support/ThreadLocal.h" #include <setjmp.h> using namespace llvm; namespace { struct CrashRecoveryContextImpl; static ManagedStatic< sys::ThreadLocal<const CrashRecoveryContextImpl> > CurrentContext; struct CrashRecoveryContextImpl { // When threads are disabled, this links up all active // CrashRecoveryContextImpls. When threads are enabled there's one thread // per CrashRecoveryContext and CurrentContext is a thread-local, so only one // CrashRecoveryContextImpl is active per thread and this is always null. const CrashRecoveryContextImpl *Next; CrashRecoveryContext *CRC; std::string Backtrace; ::jmp_buf JumpBuffer; volatile unsigned Failed : 1; unsigned SwitchedThread : 1; public: CrashRecoveryContextImpl(CrashRecoveryContext *CRC) : CRC(CRC), Failed(false), SwitchedThread(false) { Next = CurrentContext->get(); CurrentContext->set(this); } ~CrashRecoveryContextImpl() { if (!SwitchedThread) CurrentContext->set(Next); } /// \brief Called when the separate crash-recovery thread was finished, to /// indicate that we don't need to clear the thread-local CurrentContext. void setSwitchedThread() { #if defined(LLVM_ENABLE_THREADS) && LLVM_ENABLE_THREADS != 0 SwitchedThread = true; #endif } void HandleCrash() { // Eliminate the current context entry, to avoid re-entering in case the // cleanup code crashes. CurrentContext->set(Next); assert(!Failed && "Crash recovery context already failed!"); Failed = true; // FIXME: Stash the backtrace. // Jump back to the RunSafely we were called under. longjmp(JumpBuffer, 1); } }; } static ManagedStatic<sys::Mutex> gCrashRecoveryContextMutex; static bool gCrashRecoveryEnabled = false; static ManagedStatic<sys::ThreadLocal<const CrashRecoveryContext>> tlIsRecoveringFromCrash; CrashRecoveryContextCleanup::~CrashRecoveryContextCleanup() {} CrashRecoveryContext::~CrashRecoveryContext() { // Reclaim registered resources. CrashRecoveryContextCleanup *i = head; const CrashRecoveryContext *PC = tlIsRecoveringFromCrash->get(); tlIsRecoveringFromCrash->set(this); while (i) { CrashRecoveryContextCleanup *tmp = i; i = tmp->next; tmp->cleanupFired = true; tmp->recoverResources(); delete tmp; } tlIsRecoveringFromCrash->set(PC); CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl; delete CRCI; } bool CrashRecoveryContext::isRecoveringFromCrash() { return tlIsRecoveringFromCrash->get() != nullptr; } CrashRecoveryContext *CrashRecoveryContext::GetCurrent() { if (!gCrashRecoveryEnabled) return nullptr; const CrashRecoveryContextImpl *CRCI = CurrentContext->get(); if (!CRCI) return nullptr; return CRCI->CRC; } void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup) { if (!cleanup) return; if (head) head->prev = cleanup; cleanup->next = head; head = cleanup; } void CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) { if (!cleanup) return; if (cleanup == head) { head = cleanup->next; if (head) head->prev = nullptr; } else { cleanup->prev->next = cleanup->next; if (cleanup->next) cleanup->next->prev = cleanup->prev; } delete cleanup; } #ifdef LLVM_ON_WIN32 #include "Windows/WindowsSupport.h" // On Windows, we can make use of vectored exception handling to // catch most crashing situations. Note that this does mean // we will be alerted of exceptions *before* structured exception // handling has the opportunity to catch it. But that isn't likely // to cause problems because nowhere in the project is SEH being // used. // // Vectored exception handling is built on top of SEH, and so it // works on a per-thread basis. // // The vectored exception handler functionality was added in Windows // XP, so if support for older versions of Windows is required, // it will have to be added. // // If we want to support as far back as Win2k, we could use the // SetUnhandledExceptionFilter API, but there's a risk of that // being entirely overwritten (it's not a chain). static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo) { // Lookup the current thread local recovery object. const CrashRecoveryContextImpl *CRCI = CurrentContext->get(); if (!CRCI) { // Something has gone horribly wrong, so let's just tell everyone // to keep searching CrashRecoveryContext::Disable(); return EXCEPTION_CONTINUE_SEARCH; } // TODO: We can capture the stack backtrace here and store it on the // implementation if we so choose. // Handle the crash const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash(); // Note that we don't actually get here because HandleCrash calls // longjmp, which means the HandleCrash function never returns. llvm_unreachable("Handled the crash, should have longjmp'ed out of here"); } // Because the Enable and Disable calls are static, it means that // there may not actually be an Impl available, or even a current // CrashRecoveryContext at all. So we make use of a thread-local // exception table. The handles contained in here will either be // non-NULL, valid VEH handles, or NULL. static sys::ThreadLocal<const void> sCurrentExceptionHandle; void CrashRecoveryContext::Enable() { sys::ScopedLock L(*gCrashRecoveryContextMutex); if (gCrashRecoveryEnabled) return; gCrashRecoveryEnabled = true; // We can set up vectored exception handling now. We will install our // handler as the front of the list, though there's no assurances that // it will remain at the front (another call could install itself before // our handler). This 1) isn't likely, and 2) shouldn't cause problems. PVOID handle = ::AddVectoredExceptionHandler(1, ExceptionHandler); sCurrentExceptionHandle.set(handle); } void CrashRecoveryContext::Disable() { sys::ScopedLock L(*gCrashRecoveryContextMutex); if (!gCrashRecoveryEnabled) return; gCrashRecoveryEnabled = false; PVOID currentHandle = const_cast<PVOID>(sCurrentExceptionHandle.get()); if (currentHandle) { // Now we can remove the vectored exception handler from the chain ::RemoveVectoredExceptionHandler(currentHandle); // Reset the handle in our thread-local set. sCurrentExceptionHandle.set(NULL); } } #else // Generic POSIX implementation. // // This implementation relies on synchronous signals being delivered to the // current thread. We use a thread local object to keep track of the active // crash recovery context, and install signal handlers to invoke HandleCrash on // the active object. // // This implementation does not to attempt to chain signal handlers in any // reliable fashion -- if we get a signal outside of a crash recovery context we // simply disable crash recovery and raise the signal again. #include <signal.h> static const int Signals[] = { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP }; static const unsigned NumSignals = sizeof(Signals) / sizeof(Signals[0]); static struct sigaction PrevActions[NumSignals]; static void CrashRecoverySignalHandler(int Signal) { // Lookup the current thread local recovery object. const CrashRecoveryContextImpl *CRCI = CurrentContext->get(); if (!CRCI) { // We didn't find a crash recovery context -- this means either we got a // signal on a thread we didn't expect it on, the application got a signal // outside of a crash recovery context, or something else went horribly // wrong. // // Disable crash recovery and raise the signal again. The assumption here is // that the enclosing application will terminate soon, and we won't want to // attempt crash recovery again. // // This call of Disable isn't thread safe, but it doesn't actually matter. CrashRecoveryContext::Disable(); raise(Signal); // The signal will be thrown once the signal mask is restored. return; } // Unblock the signal we received. sigset_t SigMask; sigemptyset(&SigMask); sigaddset(&SigMask, Signal); sigprocmask(SIG_UNBLOCK, &SigMask, nullptr); if (CRCI) const_cast<CrashRecoveryContextImpl*>(CRCI)->HandleCrash(); } void CrashRecoveryContext::Enable() { sys::ScopedLock L(*gCrashRecoveryContextMutex); if (gCrashRecoveryEnabled) return; gCrashRecoveryEnabled = true; // Setup the signal handler. struct sigaction Handler; Handler.sa_handler = CrashRecoverySignalHandler; Handler.sa_flags = 0; sigemptyset(&Handler.sa_mask); for (unsigned i = 0; i != NumSignals; ++i) { sigaction(Signals[i], &Handler, &PrevActions[i]); } } void CrashRecoveryContext::Disable() { sys::ScopedLock L(*gCrashRecoveryContextMutex); if (!gCrashRecoveryEnabled) return; gCrashRecoveryEnabled = false; // Restore the previous signal handlers. for (unsigned i = 0; i != NumSignals; ++i) sigaction(Signals[i], &PrevActions[i], nullptr); } #endif bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) { // If crash recovery is disabled, do nothing. if (gCrashRecoveryEnabled) { assert(!Impl && "Crash recovery context already initialized!"); CrashRecoveryContextImpl *CRCI = new CrashRecoveryContextImpl(this); Impl = CRCI; if (setjmp(CRCI->JumpBuffer) != 0) { return false; } } Fn(); return true; } void CrashRecoveryContext::HandleCrash() { CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl; assert(CRCI && "Crash recovery context never initialized!"); CRCI->HandleCrash(); } const std::string &CrashRecoveryContext::getBacktrace() const { CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *) Impl; assert(CRC && "Crash recovery context never initialized!"); assert(CRC->Failed && "No crash was detected!"); return CRC->Backtrace; } // FIXME: Portability. static void setThreadBackgroundPriority() { #ifdef __APPLE__ setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG); #endif } static bool hasThreadBackgroundPriority() { #ifdef __APPLE__ return getpriority(PRIO_DARWIN_THREAD, 0) == 1; #else return false; #endif } namespace { struct RunSafelyOnThreadInfo { function_ref<void()> Fn; CrashRecoveryContext *CRC; bool UseBackgroundPriority; bool Result; }; } static void RunSafelyOnThread_Dispatch(void *UserData) { RunSafelyOnThreadInfo *Info = reinterpret_cast<RunSafelyOnThreadInfo*>(UserData); if (Info->UseBackgroundPriority) setThreadBackgroundPriority(); Info->Result = Info->CRC->RunSafely(Info->Fn); } bool CrashRecoveryContext::RunSafelyOnThread(function_ref<void()> Fn, unsigned RequestedStackSize) { bool UseBackgroundPriority = hasThreadBackgroundPriority(); RunSafelyOnThreadInfo Info = { Fn, this, UseBackgroundPriority, false }; llvm_execute_on_thread(RunSafelyOnThread_Dispatch, &Info, RequestedStackSize); if (CrashRecoveryContextImpl *CRC = (CrashRecoveryContextImpl *)Impl) CRC->setSwitchedThread(); return Info.Result; } <|endoftext|>
<commit_before>#include "grid.h" #include "cell.h" #include "gtest/gtest.h" #include "unit/test_util.h" namespace bdm { template <typename TContainer> void CellFactory(TContainer* cells, size_t cells_per_dim) { const double space = 20; cells->reserve(cells_per_dim * cells_per_dim * cells_per_dim); for (size_t i = 0; i < cells_per_dim; i++) { for (size_t j = 0; j < cells_per_dim; j++) { for (size_t k = 0; k < cells_per_dim; k++) { Cell cell({k * space, j * space, i * space}); cell.SetDiameter(30); cells->push_back(cell); } } } } TEST(GridTest, SetupGrid) { auto rm = ResourceManager<>::Get(); rm->Clear(); auto cells = rm->Get<Cell>(); CellFactory(cells, 4); auto& grid = Grid<>::GetInstance(); grid.Initialize(); vector<vector<SoHandle>> neighbors(cells->size()); // Lambda that fills a vector of neighbors for each cell (excluding itself) #pragma omp parallel for for (size_t i = 0; i < cells->size(); i++) { auto&& cell = (*cells)[i]; auto fill_neighbor_list = [&](auto&& neighbor, SoHandle handle) { if (i != handle.GetElementIdx()) { neighbors[i].push_back(handle); } }; grid.ForEachNeighborWithinRadius(fill_neighbor_list, cell, SoHandle(0, i), 1201); } std::vector<SoHandle> expected_0 = { SoHandle(0, 1), SoHandle(0, 4), SoHandle(0, 5), SoHandle(0, 16), SoHandle(0, 17), SoHandle(0, 20), SoHandle(0, 21)}; std::vector<SoHandle> expected_4 = { SoHandle(0, 0), SoHandle(0, 1), SoHandle(0, 5), SoHandle(0, 8), SoHandle(0, 9), SoHandle(0, 16), SoHandle(0, 17), SoHandle(0, 20), SoHandle(0, 21), SoHandle(0, 24), SoHandle(0, 25)}; std::vector<SoHandle> expected_42 = { SoHandle(0, 21), SoHandle(0, 22), SoHandle(0, 23), SoHandle(0, 25), SoHandle(0, 26), SoHandle(0, 27), SoHandle(0, 29), SoHandle(0, 30), SoHandle(0, 31), SoHandle(0, 37), SoHandle(0, 38), SoHandle(0, 39), SoHandle(0, 41), SoHandle(0, 43), SoHandle(0, 45), SoHandle(0, 46), SoHandle(0, 47), SoHandle(0, 53), SoHandle(0, 54), SoHandle(0, 55), SoHandle(0, 57), SoHandle(0, 58), SoHandle(0, 59), SoHandle(0, 61), SoHandle(0, 62), SoHandle(0, 63)}; std::vector<SoHandle> expected_63 = { SoHandle(0, 42), SoHandle(0, 43), SoHandle(0, 46), SoHandle(0, 47), SoHandle(0, 58), SoHandle(0, 59), SoHandle(0, 62)}; std::sort(neighbors[0].begin(), neighbors[0].end()); std::sort(neighbors[4].begin(), neighbors[4].end()); std::sort(neighbors[42].begin(), neighbors[42].end()); std::sort(neighbors[63].begin(), neighbors[63].end()); EXPECT_EQ(expected_0, neighbors[0]); EXPECT_EQ(expected_4, neighbors[4]); EXPECT_EQ(expected_42, neighbors[42]); EXPECT_EQ(expected_63, neighbors[63]); } template <typename TContainer> void RunUpdateGridTest(TContainer* cells) { auto& grid = Grid<>::GetInstance(); // Update the grid grid.UpdateGrid(); vector<vector<SoHandle>> neighbors(cells->size()); // Lambda that fills a vector of neighbors for each cell (excluding itself) #pragma omp parallel for for (size_t i = 0; i < cells->size(); i++) { auto&& cell = (*cells)[i]; auto fill_neighbor_list = [&](auto&& neighbor, SoHandle handle) { if (i != handle.GetElementIdx()) { neighbors[i].push_back(handle); } }; grid.ForEachNeighborWithinRadius(fill_neighbor_list, cell, SoHandle(0, i), 1201); } std::vector<SoHandle> expected_0 = {SoHandle(0, 4), SoHandle(0, 5), SoHandle(0, 16), SoHandle(0, 17), SoHandle(0, 20), SoHandle(0, 21)}; std::vector<SoHandle> expected_5 = { SoHandle(0, 0), SoHandle(0, 2), SoHandle(0, 4), SoHandle(0, 6), SoHandle(0, 8), SoHandle(0, 9), SoHandle(0, 10), SoHandle(0, 16), SoHandle(0, 17), SoHandle(0, 18), SoHandle(0, 20), SoHandle(0, 21), SoHandle(0, 22), SoHandle(0, 24), SoHandle(0, 25), SoHandle(0, 26)}; std::vector<SoHandle> expected_41 = { SoHandle(0, 20), SoHandle(0, 21), SoHandle(0, 22), SoHandle(0, 24), SoHandle(0, 25), SoHandle(0, 26), SoHandle(0, 28), SoHandle(0, 29), SoHandle(0, 30), SoHandle(0, 36), SoHandle(0, 37), SoHandle(0, 38), SoHandle(0, 40), SoHandle(0, 42), SoHandle(0, 44), SoHandle(0, 45), SoHandle(0, 46), SoHandle(0, 52), SoHandle(0, 53), SoHandle(0, 54), SoHandle(0, 56), SoHandle(0, 57), SoHandle(0, 58), SoHandle(0, 60), SoHandle(0, 61)}; std::vector<SoHandle> expected_61 = { SoHandle(0, 40), SoHandle(0, 41), SoHandle(0, 42), SoHandle(0, 44), SoHandle(0, 45), SoHandle(0, 46), SoHandle(0, 56), SoHandle(0, 57), SoHandle(0, 58), SoHandle(0, 60)}; std::sort(neighbors[0].begin(), neighbors[0].end()); std::sort(neighbors[5].begin(), neighbors[5].end()); std::sort(neighbors[41].begin(), neighbors[41].end()); std::sort(neighbors[61].begin(), neighbors[61].end()); EXPECT_EQ(expected_0, neighbors[0]); EXPECT_EQ(expected_5, neighbors[5]); EXPECT_EQ(expected_41, neighbors[41]); EXPECT_EQ(expected_61, neighbors[61]); } TEST(GridTest, UpdateGrid) { auto rm = ResourceManager<>::Get(); rm->Clear(); auto cells = rm->Get<Cell>(); CellFactory(cells, 4); auto& grid = Grid<>::GetInstance(); grid.Initialize(); // Remove cells 1 and 42 (they are swapped with the last two cells) cells->DelayedRemove(1); cells->DelayedRemove(42); cells->Commit(); RunUpdateGridTest(cells); } TEST(GridTest, NoRaceConditionDuringUpdate) { auto rm = ResourceManager<>::Get(); rm->Clear(); auto cells = rm->Get<Cell>(); CellFactory(cells, 4); // make sure that there are multiple cells per box (*cells)[0].SetDiameter(60); auto& grid = Grid<>::GetInstance(); grid.Initialize(); // Remove cells 1 and 42 (they are swapped with the last two cells) cells->DelayedRemove(1); cells->DelayedRemove(42); cells->Commit(); // run 100 times to increase possibility of race condition due to different // scheduling of threads for (uint16_t i = 0; i < 100; i++) { RunUpdateGridTest(cells); } } TEST(GridTest, GetBoxIndex) { auto rm = ResourceManager<>::Get(); rm->Clear(); auto cells = rm->Get<Cell>(); CellFactory(cells, 3); auto& grid = Grid<>::GetInstance(); grid.Initialize(); std::array<double, 3> position_0 = {{0, 0, 0}}; std::array<double, 3> position_1 = {{1e-15, 1e-15, 1e-15}}; std::array<double, 3> position_2 = {{-1e-15, 1e-15, 1e-15}}; size_t expected_idx_0 = 21; size_t expected_idx_1 = 21; size_t expected_idx_2 = 20; size_t idx_0 = grid.GetBoxIndex(position_0); size_t idx_1 = grid.GetBoxIndex(position_1); size_t idx_2 = grid.GetBoxIndex(position_2); EXPECT_EQ(expected_idx_0, idx_0); EXPECT_EQ(expected_idx_1, idx_1); EXPECT_EQ(expected_idx_2, idx_2); } TEST(GridTest, GridDimensions) { auto rm = ResourceManager<>::Get(); rm->Clear(); auto cells = rm->Get<Cell>(); CellFactory(cells, 3); auto& grid = Grid<>::GetInstance(); grid.Initialize(); std::array<int32_t, 6> expected_dim_0 = {{-30, 90, -30, 90, -30, 90}}; auto& dim_0 = grid.GetGridDimensions(); EXPECT_EQ(expected_dim_0, dim_0); ((*cells)[0]).SetPosition({{100, 0, 0}}); grid.UpdateGrid(); std::array<int32_t, 6> expected_dim_1 = {{-30, 150, -30, 90, -30, 90}}; auto& dim_1 = grid.GetGridDimensions(); EXPECT_EQ(expected_dim_1, dim_1); } TEST(GridTest, GetBoxCoordinates) { auto rm = ResourceManager<>::Get(); rm->Clear(); auto cells = rm->Get<Cell>(); CellFactory(cells, 3); // expecting a 4 * 4 * 4 grid auto& grid = Grid<>::GetInstance(); grid.Initialize(); EXPECT_ARR_EQ({3, 0, 0}, grid.GetBoxCoordinates(3)); EXPECT_ARR_EQ({1, 2, 0}, grid.GetBoxCoordinates(9)); EXPECT_ARR_EQ({1, 2, 3}, grid.GetBoxCoordinates(57)); } // TODO(lukas) test with different kind of cells } // namespace bdm <commit_msg>Add test to exclude race condition in ForEachNeighborPair<commit_after>#include "grid.h" #include "cell.h" #include "gtest/gtest.h" #include "unit/test_util.h" namespace bdm { template <typename TContainer> void CellFactory(TContainer* cells, size_t cells_per_dim) { const double space = 20; cells->reserve(cells_per_dim * cells_per_dim * cells_per_dim); for (size_t i = 0; i < cells_per_dim; i++) { for (size_t j = 0; j < cells_per_dim; j++) { for (size_t k = 0; k < cells_per_dim; k++) { Cell cell({k * space, j * space, i * space}); cell.SetDiameter(30); cells->push_back(cell); } } } } TEST(GridTest, SetupGrid) { auto rm = ResourceManager<>::Get(); rm->Clear(); auto cells = rm->Get<Cell>(); CellFactory(cells, 4); auto& grid = Grid<>::GetInstance(); grid.Initialize(); vector<vector<SoHandle>> neighbors(cells->size()); // Lambda that fills a vector of neighbors for each cell (excluding itself) #pragma omp parallel for for (size_t i = 0; i < cells->size(); i++) { auto&& cell = (*cells)[i]; auto fill_neighbor_list = [&](auto&& neighbor, SoHandle handle) { if (i != handle.GetElementIdx()) { neighbors[i].push_back(handle); } }; grid.ForEachNeighborWithinRadius(fill_neighbor_list, cell, SoHandle(0, i), 1201); } std::vector<SoHandle> expected_0 = { SoHandle(0, 1), SoHandle(0, 4), SoHandle(0, 5), SoHandle(0, 16), SoHandle(0, 17), SoHandle(0, 20), SoHandle(0, 21)}; std::vector<SoHandle> expected_4 = { SoHandle(0, 0), SoHandle(0, 1), SoHandle(0, 5), SoHandle(0, 8), SoHandle(0, 9), SoHandle(0, 16), SoHandle(0, 17), SoHandle(0, 20), SoHandle(0, 21), SoHandle(0, 24), SoHandle(0, 25)}; std::vector<SoHandle> expected_42 = { SoHandle(0, 21), SoHandle(0, 22), SoHandle(0, 23), SoHandle(0, 25), SoHandle(0, 26), SoHandle(0, 27), SoHandle(0, 29), SoHandle(0, 30), SoHandle(0, 31), SoHandle(0, 37), SoHandle(0, 38), SoHandle(0, 39), SoHandle(0, 41), SoHandle(0, 43), SoHandle(0, 45), SoHandle(0, 46), SoHandle(0, 47), SoHandle(0, 53), SoHandle(0, 54), SoHandle(0, 55), SoHandle(0, 57), SoHandle(0, 58), SoHandle(0, 59), SoHandle(0, 61), SoHandle(0, 62), SoHandle(0, 63)}; std::vector<SoHandle> expected_63 = { SoHandle(0, 42), SoHandle(0, 43), SoHandle(0, 46), SoHandle(0, 47), SoHandle(0, 58), SoHandle(0, 59), SoHandle(0, 62)}; std::sort(neighbors[0].begin(), neighbors[0].end()); std::sort(neighbors[4].begin(), neighbors[4].end()); std::sort(neighbors[42].begin(), neighbors[42].end()); std::sort(neighbors[63].begin(), neighbors[63].end()); EXPECT_EQ(expected_0, neighbors[0]); EXPECT_EQ(expected_4, neighbors[4]); EXPECT_EQ(expected_42, neighbors[42]); EXPECT_EQ(expected_63, neighbors[63]); } template <typename TContainer> void RunUpdateGridTest(TContainer* cells) { auto& grid = Grid<>::GetInstance(); // Update the grid grid.UpdateGrid(); vector<vector<SoHandle>> neighbors(cells->size()); // Lambda that fills a vector of neighbors for each cell (excluding itself) #pragma omp parallel for for (size_t i = 0; i < cells->size(); i++) { auto&& cell = (*cells)[i]; auto fill_neighbor_list = [&](auto&& neighbor, SoHandle handle) { if (i != handle.GetElementIdx()) { neighbors[i].push_back(handle); } }; grid.ForEachNeighborWithinRadius(fill_neighbor_list, cell, SoHandle(0, i), 1201); } std::vector<SoHandle> expected_0 = {SoHandle(0, 4), SoHandle(0, 5), SoHandle(0, 16), SoHandle(0, 17), SoHandle(0, 20), SoHandle(0, 21)}; std::vector<SoHandle> expected_5 = { SoHandle(0, 0), SoHandle(0, 2), SoHandle(0, 4), SoHandle(0, 6), SoHandle(0, 8), SoHandle(0, 9), SoHandle(0, 10), SoHandle(0, 16), SoHandle(0, 17), SoHandle(0, 18), SoHandle(0, 20), SoHandle(0, 21), SoHandle(0, 22), SoHandle(0, 24), SoHandle(0, 25), SoHandle(0, 26)}; std::vector<SoHandle> expected_41 = { SoHandle(0, 20), SoHandle(0, 21), SoHandle(0, 22), SoHandle(0, 24), SoHandle(0, 25), SoHandle(0, 26), SoHandle(0, 28), SoHandle(0, 29), SoHandle(0, 30), SoHandle(0, 36), SoHandle(0, 37), SoHandle(0, 38), SoHandle(0, 40), SoHandle(0, 42), SoHandle(0, 44), SoHandle(0, 45), SoHandle(0, 46), SoHandle(0, 52), SoHandle(0, 53), SoHandle(0, 54), SoHandle(0, 56), SoHandle(0, 57), SoHandle(0, 58), SoHandle(0, 60), SoHandle(0, 61)}; std::vector<SoHandle> expected_61 = { SoHandle(0, 40), SoHandle(0, 41), SoHandle(0, 42), SoHandle(0, 44), SoHandle(0, 45), SoHandle(0, 46), SoHandle(0, 56), SoHandle(0, 57), SoHandle(0, 58), SoHandle(0, 60)}; std::sort(neighbors[0].begin(), neighbors[0].end()); std::sort(neighbors[5].begin(), neighbors[5].end()); std::sort(neighbors[41].begin(), neighbors[41].end()); std::sort(neighbors[61].begin(), neighbors[61].end()); EXPECT_EQ(expected_0, neighbors[0]); EXPECT_EQ(expected_5, neighbors[5]); EXPECT_EQ(expected_41, neighbors[41]); EXPECT_EQ(expected_61, neighbors[61]); } TEST(GridTest, UpdateGrid) { auto rm = ResourceManager<>::Get(); rm->Clear(); auto cells = rm->Get<Cell>(); CellFactory(cells, 4); auto& grid = Grid<>::GetInstance(); grid.Initialize(); // Remove cells 1 and 42 (they are swapped with the last two cells) cells->DelayedRemove(1); cells->DelayedRemove(42); cells->Commit(); RunUpdateGridTest(cells); } TEST(GridTest, NoRaceConditionDuringUpdate) { auto rm = ResourceManager<>::Get(); rm->Clear(); auto cells = rm->Get<Cell>(); CellFactory(cells, 4); // make sure that there are multiple cells per box (*cells)[0].SetDiameter(60); auto& grid = Grid<>::GetInstance(); grid.Initialize(); // Remove cells 1 and 42 (they are swapped with the last two cells) cells->DelayedRemove(1); cells->DelayedRemove(42); cells->Commit(); // run 100 times to increase possibility of race condition due to different // scheduling of threads for (uint16_t i = 0; i < 100; i++) { RunUpdateGridTest(cells); } } TEST(GridTest, GetBoxIndex) { auto rm = ResourceManager<>::Get(); rm->Clear(); auto cells = rm->Get<Cell>(); CellFactory(cells, 3); auto& grid = Grid<>::GetInstance(); grid.Initialize(); std::array<double, 3> position_0 = {{0, 0, 0}}; std::array<double, 3> position_1 = {{1e-15, 1e-15, 1e-15}}; std::array<double, 3> position_2 = {{-1e-15, 1e-15, 1e-15}}; size_t expected_idx_0 = 21; size_t expected_idx_1 = 21; size_t expected_idx_2 = 20; size_t idx_0 = grid.GetBoxIndex(position_0); size_t idx_1 = grid.GetBoxIndex(position_1); size_t idx_2 = grid.GetBoxIndex(position_2); EXPECT_EQ(expected_idx_0, idx_0); EXPECT_EQ(expected_idx_1, idx_1); EXPECT_EQ(expected_idx_2, idx_2); } TEST(GridTest, GridDimensions) { auto rm = ResourceManager<>::Get(); rm->Clear(); auto cells = rm->Get<Cell>(); CellFactory(cells, 3); auto& grid = Grid<>::GetInstance(); grid.Initialize(); std::array<int32_t, 6> expected_dim_0 = {{-30, 90, -30, 90, -30, 90}}; auto& dim_0 = grid.GetGridDimensions(); EXPECT_EQ(expected_dim_0, dim_0); ((*cells)[0]).SetPosition({{100, 0, 0}}); grid.UpdateGrid(); std::array<int32_t, 6> expected_dim_1 = {{-30, 150, -30, 90, -30, 90}}; auto& dim_1 = grid.GetGridDimensions(); EXPECT_EQ(expected_dim_1, dim_1); } TEST(GridTest, GetBoxCoordinates) { auto rm = ResourceManager<>::Get(); rm->Clear(); auto cells = rm->Get<Cell>(); CellFactory(cells, 3); // expecting a 4 * 4 * 4 grid auto& grid = Grid<>::GetInstance(); grid.Initialize(); EXPECT_ARR_EQ({3, 0, 0}, grid.GetBoxCoordinates(3)); EXPECT_ARR_EQ({1, 2, 0}, grid.GetBoxCoordinates(9)); EXPECT_ARR_EQ({1, 2, 3}, grid.GetBoxCoordinates(57)); } void RunNoRaceConditionForEachPairTest() { auto rm = ResourceManager<>::Get(); rm->Clear(); auto cells = rm->Get<Cell>(); CellFactory(cells, 3); // expecting a 4 * 4 * 4 grid auto& grid = Grid<>::GetInstance(); grid.Initialize(); std::vector<int> result(cells->size()); auto lambda = [&](auto&& lhs, SoHandle lhs_id, auto&& rhs, SoHandle rhs_id) { result[lhs_id.GetElementIdx()]++; result[rhs_id.GetElementIdx()]++; }; // space between cells is 20 -> 20^2 + 1 = 401 grid.ForEachNeighborPairWithinRadius(lambda, 401); EXPECT_EQ(3, result[0]); EXPECT_EQ(4, result[1]); EXPECT_EQ(3, result[2]); EXPECT_EQ(4, result[3]); EXPECT_EQ(5, result[4]); EXPECT_EQ(4, result[5]); EXPECT_EQ(3, result[6]); EXPECT_EQ(4, result[7]); EXPECT_EQ(3, result[8]); EXPECT_EQ(4, result[9]); EXPECT_EQ(5, result[10]); EXPECT_EQ(4, result[11]); EXPECT_EQ(5, result[12]); EXPECT_EQ(6, result[13]); EXPECT_EQ(5, result[14]); EXPECT_EQ(4, result[15]); EXPECT_EQ(5, result[16]); EXPECT_EQ(4, result[17]); EXPECT_EQ(3, result[18]); EXPECT_EQ(4, result[19]); EXPECT_EQ(3, result[20]); EXPECT_EQ(4, result[21]); EXPECT_EQ(5, result[22]); EXPECT_EQ(4, result[23]); EXPECT_EQ(3, result[24]); EXPECT_EQ(4, result[25]); EXPECT_EQ(3, result[26]); } TEST(GridTest, NoRaceConditionForEachPair) { for (int i = 0; i < 10; i++) { RunNoRaceConditionForEachPairTest(); } } // TODO(lukas) test with different kind of cells } // namespace bdm <|endoftext|>
<commit_before>//===-- MipsISelDAGToDAG.cpp - A dag to dag inst selector for Mips --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an instruction selector for the MIPS target. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "mips-isel" #include "Mips.h" #include "MipsMachineFunction.h" #include "MipsRegisterInfo.h" #include "MipsSubtarget.h" #include "MipsTargetMachine.h" #include "llvm/GlobalValue.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/Support/CFG.h" #include "llvm/Type.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/SelectionDAGISel.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; //===----------------------------------------------------------------------===// // Instruction Selector Implementation //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // MipsDAGToDAGISel - MIPS specific code to select MIPS machine // instructions for SelectionDAG operations. //===----------------------------------------------------------------------===// namespace { class MipsDAGToDAGISel : public SelectionDAGISel { /// TM - Keep a reference to MipsTargetMachine. MipsTargetMachine &TM; /// Subtarget - Keep a pointer to the MipsSubtarget around so that we can /// make the right decision when generating code for different targets. const MipsSubtarget &Subtarget; public: explicit MipsDAGToDAGISel(MipsTargetMachine &tm) : SelectionDAGISel(tm), TM(tm), Subtarget(tm.getSubtarget<MipsSubtarget>()) {} // Pass Name virtual const char *getPassName() const { return "MIPS DAG->DAG Pattern Instruction Selection"; } private: // Include the pieces autogenerated from the target description. #include "MipsGenDAGISel.inc" /// getTargetMachine - Return a reference to the TargetMachine, casted /// to the target-specific type. const MipsTargetMachine &getTargetMachine() { return static_cast<const MipsTargetMachine &>(TM); } /// getInstrInfo - Return a reference to the TargetInstrInfo, casted /// to the target-specific type. const MipsInstrInfo *getInstrInfo() { return getTargetMachine().getInstrInfo(); } SDNode *getGlobalBaseReg(); SDNode *Select(SDNode *N); // Complex Pattern. bool SelectAddr(SDValue N, SDValue &Base, SDValue &Offset); // getI32Imm - Return a target constant with the specified // value. inline SDValue getImm(const SDNode *Node, unsigned Imm) { return CurDAG->getTargetConstant(Imm, Node->getValueType(0)); } virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode, std::vector<SDValue> &OutOps); }; } /// getGlobalBaseReg - Output the instructions required to put the /// GOT address into a register. SDNode *MipsDAGToDAGISel::getGlobalBaseReg() { unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF); return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode(); } /// ComplexPattern used on MipsInstrInfo /// Used on Mips Load/Store instructions bool MipsDAGToDAGISel:: SelectAddr(SDValue Addr, SDValue &Base, SDValue &Offset) { EVT ValTy = Addr.getValueType(); unsigned GPReg = ValTy == MVT::i32 ? Mips::GP : Mips::GP_64; // if Address is FI, get the TargetFrameIndex. if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) { Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy); Offset = CurDAG->getTargetConstant(0, ValTy); return true; } // on PIC code Load GA if (TM.getRelocationModel() == Reloc::PIC_) { if (Addr.getOpcode() == MipsISD::WrapperPIC) { Base = CurDAG->getRegister(GPReg, ValTy); Offset = Addr.getOperand(0); return true; } } else { if ((Addr.getOpcode() == ISD::TargetExternalSymbol || Addr.getOpcode() == ISD::TargetGlobalAddress)) return false; else if (Addr.getOpcode() == ISD::TargetGlobalTLSAddress) { Base = CurDAG->getRegister(GPReg, ValTy); Offset = Addr; return true; } } // Addresses of the form FI+const or FI|const if (CurDAG->isBaseWithConstantOffset(Addr)) { ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)); if (isInt<16>(CN->getSExtValue())) { // If the first operand is a FI, get the TargetFI Node if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode> (Addr.getOperand(0))) Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy); else Base = Addr.getOperand(0); Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy); return true; } } // Operand is a result from an ADD. if (Addr.getOpcode() == ISD::ADD) { // When loading from constant pools, load the lower address part in // the instruction itself. Example, instead of: // lui $2, %hi($CPI1_0) // addiu $2, $2, %lo($CPI1_0) // lwc1 $f0, 0($2) // Generate: // lui $2, %hi($CPI1_0) // lwc1 $f0, %lo($CPI1_0)($2) if ((Addr.getOperand(0).getOpcode() == MipsISD::Hi || Addr.getOperand(0).getOpcode() == ISD::LOAD) && Addr.getOperand(1).getOpcode() == MipsISD::Lo) { SDValue LoVal = Addr.getOperand(1); if (isa<ConstantPoolSDNode>(LoVal.getOperand(0)) || isa<GlobalAddressSDNode>(LoVal.getOperand(0))) { Base = Addr.getOperand(0); Offset = LoVal.getOperand(0); return true; } } } Base = Addr; Offset = CurDAG->getTargetConstant(0, ValTy); return true; } /// Select instructions not customized! Used for /// expanded, promoted and normal instructions SDNode* MipsDAGToDAGISel::Select(SDNode *Node) { unsigned Opcode = Node->getOpcode(); DebugLoc dl = Node->getDebugLoc(); // Dump information about the Node being selected DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n"); // If we have a custom node, we already have selected! if (Node->isMachineOpcode()) { DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n"); return NULL; } /// // Instruction Selection not handled by the auto-generated // tablegen selection should be handled here. /// switch(Opcode) { default: break; case ISD::SUBE: case ISD::ADDE: { SDValue InFlag = Node->getOperand(2), CmpLHS; unsigned Opc = InFlag.getOpcode(); (void)Opc; assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) || (Opc == ISD::SUBC || Opc == ISD::SUBE)) && "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn"); unsigned MOp; if (Opcode == ISD::ADDE) { CmpLHS = InFlag.getValue(0); MOp = Mips::ADDu; } else { CmpLHS = InFlag.getOperand(0); MOp = Mips::SUBu; } SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) }; SDValue LHS = Node->getOperand(0); SDValue RHS = Node->getOperand(1); EVT VT = LHS.getValueType(); SDNode *Carry = CurDAG->getMachineNode(Mips::SLTu, dl, VT, Ops, 2); SDNode *AddCarry = CurDAG->getMachineNode(Mips::ADDu, dl, VT, SDValue(Carry,0), RHS); return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue, LHS, SDValue(AddCarry,0)); } /// Mul with two results case ISD::SMUL_LOHI: case ISD::UMUL_LOHI: { assert(Node->getValueType(0) != MVT::i64 && "64-bit multiplication with two results not handled."); SDValue Op1 = Node->getOperand(0); SDValue Op2 = Node->getOperand(1); unsigned Op; Op = (Opcode == ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT); SDNode *Mul = CurDAG->getMachineNode(Op, dl, MVT::Glue, Op1, Op2); SDValue InFlag = SDValue(Mul, 0); SDNode *Lo = CurDAG->getMachineNode(Mips::MFLO, dl, MVT::i32, MVT::Glue, InFlag); InFlag = SDValue(Lo,1); SDNode *Hi = CurDAG->getMachineNode(Mips::MFHI, dl, MVT::i32, InFlag); if (!SDValue(Node, 0).use_empty()) ReplaceUses(SDValue(Node, 0), SDValue(Lo,0)); if (!SDValue(Node, 1).use_empty()) ReplaceUses(SDValue(Node, 1), SDValue(Hi,0)); return NULL; } /// Special Muls case ISD::MUL: // Mips32 has a 32-bit three operand mul instruction. if (Subtarget.hasMips32() && Node->getValueType(0) == MVT::i32) break; case ISD::MULHS: case ISD::MULHU: { assert((Opcode == ISD::MUL || Node->getValueType(0) != MVT::i64) && "64-bit MULH* not handled."); EVT Ty = Node->getValueType(0); SDValue MulOp1 = Node->getOperand(0); SDValue MulOp2 = Node->getOperand(1); unsigned MulOp = (Opcode == ISD::MULHU ? Mips::MULTu : (Ty == MVT::i32 ? Mips::MULT : Mips::DMULT)); SDNode *MulNode = CurDAG->getMachineNode(MulOp, dl, MVT::Glue, MulOp1, MulOp2); SDValue InFlag = SDValue(MulNode, 0); if (Opcode == ISD::MUL) { unsigned Opc = (Ty == MVT::i32 ? Mips::MFLO : Mips::MFLO64); return CurDAG->getMachineNode(Opc, dl, Ty, InFlag); } else return CurDAG->getMachineNode(Mips::MFHI, dl, MVT::i32, InFlag); } // Get target GOT address. case ISD::GLOBAL_OFFSET_TABLE: return getGlobalBaseReg(); case ISD::ConstantFP: { ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node); if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) { SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, Mips::ZERO, MVT::i32); return CurDAG->getMachineNode(Mips::BuildPairF64, dl, MVT::f64, Zero, Zero); } break; } case MipsISD::ThreadPointer: { unsigned SrcReg = Mips::HWR29; unsigned DestReg = Mips::V1; SDNode *Rdhwr = CurDAG->getMachineNode(Mips::RDHWR, Node->getDebugLoc(), Node->getValueType(0), CurDAG->getRegister(SrcReg, MVT::i32)); SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, DestReg, SDValue(Rdhwr, 0)); SDValue ResNode = CurDAG->getCopyFromReg(Chain, dl, DestReg, MVT::i32); ReplaceUses(SDValue(Node, 0), ResNode); return ResNode.getNode(); } } // Select the default instruction SDNode *ResNode = SelectCode(Node); DEBUG(errs() << "=> "); if (ResNode == NULL || ResNode == Node) DEBUG(Node->dump(CurDAG)); else DEBUG(ResNode->dump(CurDAG)); DEBUG(errs() << "\n"); return ResNode; } bool MipsDAGToDAGISel:: SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode, std::vector<SDValue> &OutOps) { assert(ConstraintCode == 'm' && "unexpected asm memory constraint"); OutOps.push_back(Op); return false; } /// createMipsISelDag - This pass converts a legalized DAG into a /// MIPS-specific DAG, ready for instruction scheduling. FunctionPass *llvm::createMipsISelDag(MipsTargetMachine &TM) { return new MipsDAGToDAGISel(TM); } <commit_msg>Fix comment.<commit_after>//===-- MipsISelDAGToDAG.cpp - A dag to dag inst selector for Mips --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an instruction selector for the MIPS target. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "mips-isel" #include "Mips.h" #include "MipsMachineFunction.h" #include "MipsRegisterInfo.h" #include "MipsSubtarget.h" #include "MipsTargetMachine.h" #include "llvm/GlobalValue.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/Support/CFG.h" #include "llvm/Type.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/SelectionDAGISel.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; //===----------------------------------------------------------------------===// // Instruction Selector Implementation //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // MipsDAGToDAGISel - MIPS specific code to select MIPS machine // instructions for SelectionDAG operations. //===----------------------------------------------------------------------===// namespace { class MipsDAGToDAGISel : public SelectionDAGISel { /// TM - Keep a reference to MipsTargetMachine. MipsTargetMachine &TM; /// Subtarget - Keep a pointer to the MipsSubtarget around so that we can /// make the right decision when generating code for different targets. const MipsSubtarget &Subtarget; public: explicit MipsDAGToDAGISel(MipsTargetMachine &tm) : SelectionDAGISel(tm), TM(tm), Subtarget(tm.getSubtarget<MipsSubtarget>()) {} // Pass Name virtual const char *getPassName() const { return "MIPS DAG->DAG Pattern Instruction Selection"; } private: // Include the pieces autogenerated from the target description. #include "MipsGenDAGISel.inc" /// getTargetMachine - Return a reference to the TargetMachine, casted /// to the target-specific type. const MipsTargetMachine &getTargetMachine() { return static_cast<const MipsTargetMachine &>(TM); } /// getInstrInfo - Return a reference to the TargetInstrInfo, casted /// to the target-specific type. const MipsInstrInfo *getInstrInfo() { return getTargetMachine().getInstrInfo(); } SDNode *getGlobalBaseReg(); SDNode *Select(SDNode *N); // Complex Pattern. bool SelectAddr(SDValue N, SDValue &Base, SDValue &Offset); // getImm - Return a target constant with the specified value. inline SDValue getImm(const SDNode *Node, unsigned Imm) { return CurDAG->getTargetConstant(Imm, Node->getValueType(0)); } virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode, std::vector<SDValue> &OutOps); }; } /// getGlobalBaseReg - Output the instructions required to put the /// GOT address into a register. SDNode *MipsDAGToDAGISel::getGlobalBaseReg() { unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF); return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode(); } /// ComplexPattern used on MipsInstrInfo /// Used on Mips Load/Store instructions bool MipsDAGToDAGISel:: SelectAddr(SDValue Addr, SDValue &Base, SDValue &Offset) { EVT ValTy = Addr.getValueType(); unsigned GPReg = ValTy == MVT::i32 ? Mips::GP : Mips::GP_64; // if Address is FI, get the TargetFrameIndex. if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) { Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy); Offset = CurDAG->getTargetConstant(0, ValTy); return true; } // on PIC code Load GA if (TM.getRelocationModel() == Reloc::PIC_) { if (Addr.getOpcode() == MipsISD::WrapperPIC) { Base = CurDAG->getRegister(GPReg, ValTy); Offset = Addr.getOperand(0); return true; } } else { if ((Addr.getOpcode() == ISD::TargetExternalSymbol || Addr.getOpcode() == ISD::TargetGlobalAddress)) return false; else if (Addr.getOpcode() == ISD::TargetGlobalTLSAddress) { Base = CurDAG->getRegister(GPReg, ValTy); Offset = Addr; return true; } } // Addresses of the form FI+const or FI|const if (CurDAG->isBaseWithConstantOffset(Addr)) { ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)); if (isInt<16>(CN->getSExtValue())) { // If the first operand is a FI, get the TargetFI Node if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode> (Addr.getOperand(0))) Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy); else Base = Addr.getOperand(0); Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy); return true; } } // Operand is a result from an ADD. if (Addr.getOpcode() == ISD::ADD) { // When loading from constant pools, load the lower address part in // the instruction itself. Example, instead of: // lui $2, %hi($CPI1_0) // addiu $2, $2, %lo($CPI1_0) // lwc1 $f0, 0($2) // Generate: // lui $2, %hi($CPI1_0) // lwc1 $f0, %lo($CPI1_0)($2) if ((Addr.getOperand(0).getOpcode() == MipsISD::Hi || Addr.getOperand(0).getOpcode() == ISD::LOAD) && Addr.getOperand(1).getOpcode() == MipsISD::Lo) { SDValue LoVal = Addr.getOperand(1); if (isa<ConstantPoolSDNode>(LoVal.getOperand(0)) || isa<GlobalAddressSDNode>(LoVal.getOperand(0))) { Base = Addr.getOperand(0); Offset = LoVal.getOperand(0); return true; } } } Base = Addr; Offset = CurDAG->getTargetConstant(0, ValTy); return true; } /// Select instructions not customized! Used for /// expanded, promoted and normal instructions SDNode* MipsDAGToDAGISel::Select(SDNode *Node) { unsigned Opcode = Node->getOpcode(); DebugLoc dl = Node->getDebugLoc(); // Dump information about the Node being selected DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n"); // If we have a custom node, we already have selected! if (Node->isMachineOpcode()) { DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n"); return NULL; } /// // Instruction Selection not handled by the auto-generated // tablegen selection should be handled here. /// switch(Opcode) { default: break; case ISD::SUBE: case ISD::ADDE: { SDValue InFlag = Node->getOperand(2), CmpLHS; unsigned Opc = InFlag.getOpcode(); (void)Opc; assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) || (Opc == ISD::SUBC || Opc == ISD::SUBE)) && "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn"); unsigned MOp; if (Opcode == ISD::ADDE) { CmpLHS = InFlag.getValue(0); MOp = Mips::ADDu; } else { CmpLHS = InFlag.getOperand(0); MOp = Mips::SUBu; } SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) }; SDValue LHS = Node->getOperand(0); SDValue RHS = Node->getOperand(1); EVT VT = LHS.getValueType(); SDNode *Carry = CurDAG->getMachineNode(Mips::SLTu, dl, VT, Ops, 2); SDNode *AddCarry = CurDAG->getMachineNode(Mips::ADDu, dl, VT, SDValue(Carry,0), RHS); return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue, LHS, SDValue(AddCarry,0)); } /// Mul with two results case ISD::SMUL_LOHI: case ISD::UMUL_LOHI: { assert(Node->getValueType(0) != MVT::i64 && "64-bit multiplication with two results not handled."); SDValue Op1 = Node->getOperand(0); SDValue Op2 = Node->getOperand(1); unsigned Op; Op = (Opcode == ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT); SDNode *Mul = CurDAG->getMachineNode(Op, dl, MVT::Glue, Op1, Op2); SDValue InFlag = SDValue(Mul, 0); SDNode *Lo = CurDAG->getMachineNode(Mips::MFLO, dl, MVT::i32, MVT::Glue, InFlag); InFlag = SDValue(Lo,1); SDNode *Hi = CurDAG->getMachineNode(Mips::MFHI, dl, MVT::i32, InFlag); if (!SDValue(Node, 0).use_empty()) ReplaceUses(SDValue(Node, 0), SDValue(Lo,0)); if (!SDValue(Node, 1).use_empty()) ReplaceUses(SDValue(Node, 1), SDValue(Hi,0)); return NULL; } /// Special Muls case ISD::MUL: // Mips32 has a 32-bit three operand mul instruction. if (Subtarget.hasMips32() && Node->getValueType(0) == MVT::i32) break; case ISD::MULHS: case ISD::MULHU: { assert((Opcode == ISD::MUL || Node->getValueType(0) != MVT::i64) && "64-bit MULH* not handled."); EVT Ty = Node->getValueType(0); SDValue MulOp1 = Node->getOperand(0); SDValue MulOp2 = Node->getOperand(1); unsigned MulOp = (Opcode == ISD::MULHU ? Mips::MULTu : (Ty == MVT::i32 ? Mips::MULT : Mips::DMULT)); SDNode *MulNode = CurDAG->getMachineNode(MulOp, dl, MVT::Glue, MulOp1, MulOp2); SDValue InFlag = SDValue(MulNode, 0); if (Opcode == ISD::MUL) { unsigned Opc = (Ty == MVT::i32 ? Mips::MFLO : Mips::MFLO64); return CurDAG->getMachineNode(Opc, dl, Ty, InFlag); } else return CurDAG->getMachineNode(Mips::MFHI, dl, MVT::i32, InFlag); } // Get target GOT address. case ISD::GLOBAL_OFFSET_TABLE: return getGlobalBaseReg(); case ISD::ConstantFP: { ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node); if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) { SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, Mips::ZERO, MVT::i32); return CurDAG->getMachineNode(Mips::BuildPairF64, dl, MVT::f64, Zero, Zero); } break; } case MipsISD::ThreadPointer: { unsigned SrcReg = Mips::HWR29; unsigned DestReg = Mips::V1; SDNode *Rdhwr = CurDAG->getMachineNode(Mips::RDHWR, Node->getDebugLoc(), Node->getValueType(0), CurDAG->getRegister(SrcReg, MVT::i32)); SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, DestReg, SDValue(Rdhwr, 0)); SDValue ResNode = CurDAG->getCopyFromReg(Chain, dl, DestReg, MVT::i32); ReplaceUses(SDValue(Node, 0), ResNode); return ResNode.getNode(); } } // Select the default instruction SDNode *ResNode = SelectCode(Node); DEBUG(errs() << "=> "); if (ResNode == NULL || ResNode == Node) DEBUG(Node->dump(CurDAG)); else DEBUG(ResNode->dump(CurDAG)); DEBUG(errs() << "\n"); return ResNode; } bool MipsDAGToDAGISel:: SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode, std::vector<SDValue> &OutOps) { assert(ConstraintCode == 'm' && "unexpected asm memory constraint"); OutOps.push_back(Op); return false; } /// createMipsISelDag - This pass converts a legalized DAG into a /// MIPS-specific DAG, ready for instruction scheduling. FunctionPass *llvm::createMipsISelDag(MipsTargetMachine &TM) { return new MipsDAGToDAGISel(TM); } <|endoftext|>
<commit_before>//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass implements a simple loop unroller. It works best when loops have // been canonicalized by the -indvars pass, allowing it to determine the trip // counts of loops easily. //===----------------------------------------------------------------------===// #define DEBUG_TYPE "loop-unroll" #include "llvm/IntrinsicInst.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Utils/UnrollLoop.h" #include <climits> using namespace llvm; static cl::opt<unsigned> UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden, cl::desc("The cut-off point for automatic loop unrolling")); static cl::opt<unsigned> UnrollCount("unroll-count", cl::init(0), cl::Hidden, cl::desc("Use this unroll count for all loops, for testing purposes")); static cl::opt<bool> UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden, cl::desc("Allows loops to be partially unrolled until " "-unroll-threshold loop size is reached.")); namespace { class VISIBILITY_HIDDEN LoopUnroll : public LoopPass { public: static char ID; // Pass ID, replacement for typeid LoopUnroll() : LoopPass(&ID) {} /// A magic value for use with the Threshold parameter to indicate /// that the loop unroll should be performed regardless of how much /// code expansion would result. static const unsigned NoThreshold = UINT_MAX; bool runOnLoop(Loop *L, LPPassManager &LPM); /// This transformation requires natural loop information & requires that /// loop preheaders be inserted into the CFG... /// virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequiredID(LoopSimplifyID); AU.addRequiredID(LCSSAID); AU.addRequired<LoopInfo>(); AU.addPreservedID(LCSSAID); AU.addPreserved<LoopInfo>(); // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info. // If loop unroll does not preserve dom info then LCSSA pass on next // loop will receive invalid dom info. // For now, recreate dom info, if loop is unrolled. AU.addPreserved<DominatorTree>(); AU.addPreserved<DominanceFrontier>(); } }; } char LoopUnroll::ID = 0; static RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops"); Pass *llvm::createLoopUnrollPass() { return new LoopUnroll(); } /// ApproximateLoopSize - Approximate the size of the loop. static unsigned ApproximateLoopSize(const Loop *L) { unsigned Size = 0; for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E; ++I) { BasicBlock *BB = *I; Instruction *Term = BB->getTerminator(); for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { if (isa<PHINode>(I) && BB == L->getHeader()) { // Ignore PHI nodes in the header. } else if (I->hasOneUse() && I->use_back() == Term) { // Ignore instructions only used by the loop terminator. } else if (isa<DbgInfoIntrinsic>(I)) { // Ignore debug instructions } else if (isa<GetElementPtrInst>(I) && I->hasOneUse()) { // Ignore GEP as they generally are subsumed into a load or store. } else if (isa<CallInst>(I)) { // Estimate size overhead introduced by call instructions which // is higher than other instructions. Here 3 and 10 are magic // numbers that help one isolated test case from PR2067 without // negatively impacting measured benchmarks. if (isa<IntrinsicInst>(I)) Size = Size + 3; else Size = Size + 10; } else { ++Size; } // TODO: Ignore expressions derived from PHI and constants if inval of phi // is a constant, or if operation is associative. This will get induction // variables. } } return Size; } bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) { assert(L->isLCSSAForm()); LoopInfo *LI = &getAnalysis<LoopInfo>(); BasicBlock *Header = L->getHeader(); DEBUG(errs() << "Loop Unroll: F[" << Header->getParent()->getName() << "] Loop %" << Header->getName() << "\n"); (void)Header; // Find trip count unsigned TripCount = L->getSmallConstantTripCount(); unsigned Count = UnrollCount; // Automatically select an unroll count. if (Count == 0) { // Conservative heuristic: if we know the trip count, see if we can // completely unroll (subject to the threshold, checked below); otherwise // try to find greatest modulo of the trip count which is still under // threshold value. if (TripCount != 0) { Count = TripCount; } else { return false; } } // Enforce the threshold. if (UnrollThreshold != NoThreshold) { unsigned LoopSize = ApproximateLoopSize(L); DOUT << " Loop Size = " << LoopSize << "\n"; uint64_t Size = (uint64_t)LoopSize*Count; if (TripCount != 1 && Size > UnrollThreshold) { DOUT << " Too large to fully unroll with count: " << Count << " because size: " << Size << ">" << UnrollThreshold << "\n"; if (UnrollAllowPartial) { // Reduce unroll count to be modulo of TripCount for partial unrolling Count = UnrollThreshold / LoopSize; while (Count != 0 && TripCount%Count != 0) { Count--; } if (Count < 2) { DOUT << " could not unroll partially\n"; return false; } else { DOUT << " partially unrolling with count: " << Count << "\n"; } } else { DOUT << " will not try to unroll partially because " << "-unroll-allow-partial not given\n"; return false; } } } // Unroll the loop. Function *F = L->getHeader()->getParent(); if (!UnrollLoop(L, Count, LI, &LPM)) return false; // FIXME: Reconstruct dom info, because it is not preserved properly. DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>(); if (DT) { DT->runOnFunction(*F); DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>(); if (DF) DF->runOnFunction(*F); } return true; } <commit_msg>DEBUGify some DOUTs.<commit_after>//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass implements a simple loop unroller. It works best when loops have // been canonicalized by the -indvars pass, allowing it to determine the trip // counts of loops easily. //===----------------------------------------------------------------------===// #define DEBUG_TYPE "loop-unroll" #include "llvm/IntrinsicInst.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Utils/UnrollLoop.h" #include <climits> using namespace llvm; static cl::opt<unsigned> UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden, cl::desc("The cut-off point for automatic loop unrolling")); static cl::opt<unsigned> UnrollCount("unroll-count", cl::init(0), cl::Hidden, cl::desc("Use this unroll count for all loops, for testing purposes")); static cl::opt<bool> UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden, cl::desc("Allows loops to be partially unrolled until " "-unroll-threshold loop size is reached.")); namespace { class VISIBILITY_HIDDEN LoopUnroll : public LoopPass { public: static char ID; // Pass ID, replacement for typeid LoopUnroll() : LoopPass(&ID) {} /// A magic value for use with the Threshold parameter to indicate /// that the loop unroll should be performed regardless of how much /// code expansion would result. static const unsigned NoThreshold = UINT_MAX; bool runOnLoop(Loop *L, LPPassManager &LPM); /// This transformation requires natural loop information & requires that /// loop preheaders be inserted into the CFG... /// virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequiredID(LoopSimplifyID); AU.addRequiredID(LCSSAID); AU.addRequired<LoopInfo>(); AU.addPreservedID(LCSSAID); AU.addPreserved<LoopInfo>(); // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info. // If loop unroll does not preserve dom info then LCSSA pass on next // loop will receive invalid dom info. // For now, recreate dom info, if loop is unrolled. AU.addPreserved<DominatorTree>(); AU.addPreserved<DominanceFrontier>(); } }; } char LoopUnroll::ID = 0; static RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops"); Pass *llvm::createLoopUnrollPass() { return new LoopUnroll(); } /// ApproximateLoopSize - Approximate the size of the loop. static unsigned ApproximateLoopSize(const Loop *L) { unsigned Size = 0; for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E; ++I) { BasicBlock *BB = *I; Instruction *Term = BB->getTerminator(); for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { if (isa<PHINode>(I) && BB == L->getHeader()) { // Ignore PHI nodes in the header. } else if (I->hasOneUse() && I->use_back() == Term) { // Ignore instructions only used by the loop terminator. } else if (isa<DbgInfoIntrinsic>(I)) { // Ignore debug instructions } else if (isa<GetElementPtrInst>(I) && I->hasOneUse()) { // Ignore GEP as they generally are subsumed into a load or store. } else if (isa<CallInst>(I)) { // Estimate size overhead introduced by call instructions which // is higher than other instructions. Here 3 and 10 are magic // numbers that help one isolated test case from PR2067 without // negatively impacting measured benchmarks. if (isa<IntrinsicInst>(I)) Size = Size + 3; else Size = Size + 10; } else { ++Size; } // TODO: Ignore expressions derived from PHI and constants if inval of phi // is a constant, or if operation is associative. This will get induction // variables. } } return Size; } bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) { assert(L->isLCSSAForm()); LoopInfo *LI = &getAnalysis<LoopInfo>(); BasicBlock *Header = L->getHeader(); DEBUG(errs() << "Loop Unroll: F[" << Header->getParent()->getName() << "] Loop %" << Header->getName() << "\n"); (void)Header; // Find trip count unsigned TripCount = L->getSmallConstantTripCount(); unsigned Count = UnrollCount; // Automatically select an unroll count. if (Count == 0) { // Conservative heuristic: if we know the trip count, see if we can // completely unroll (subject to the threshold, checked below); otherwise // try to find greatest modulo of the trip count which is still under // threshold value. if (TripCount != 0) { Count = TripCount; } else { return false; } } // Enforce the threshold. if (UnrollThreshold != NoThreshold) { unsigned LoopSize = ApproximateLoopSize(L); DEBUG(errs() << " Loop Size = " << LoopSize << "\n"); uint64_t Size = (uint64_t)LoopSize*Count; if (TripCount != 1 && Size > UnrollThreshold) { DEBUG(errs() << " Too large to fully unroll with count: " << Count << " because size: " << Size << ">" << UnrollThreshold << "\n"); if (UnrollAllowPartial) { // Reduce unroll count to be modulo of TripCount for partial unrolling Count = UnrollThreshold / LoopSize; while (Count != 0 && TripCount%Count != 0) { Count--; } if (Count < 2) { DEBUG(errs() << " could not unroll partially\n"); return false; } else { DEBUG(errs() << " partially unrolling with count: " << Count << "\n"); } } else { DEBUG(errs() << " will not try to unroll partially because " << "-unroll-allow-partial not given\n"); return false; } } } // Unroll the loop. Function *F = L->getHeader()->getParent(); if (!UnrollLoop(L, Count, LI, &LPM)) return false; // FIXME: Reconstruct dom info, because it is not preserved properly. DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>(); if (DT) { DT->runOnFunction(*F); DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>(); if (DF) DF->runOnFunction(*F); } return true; } <|endoftext|>
<commit_before>// SampSharp // Copyright 2018 Tim Potze // // 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 "pathutil.h" #include "platforms.h" #include <assert.h> #include <string.h> #if SAMPSHARP_WINDOWS # include "Windows.h" # include "Shlwapi.h" #elif SAMPSHARP_LINUX # include <unistd.h> # include <dirent.h> #endif #if !defined(PATH_MAX) && defined(MAX_PATH) # define PATH_MAX MAX_PATH #endif #ifdef __DIR_SEPARATOR_FORWARD # define NOT_DIR_SEPARATOR "\\" #else # define NOT_DIR_SEPARATOR "/" #endif bool path_has_extension(const char *path, const char *ext) { if(!path || !ext) { return false; } size_t path_len = strlen(path); size_t ext_len = strlen(ext); if(path_len < ext_len) { return false; } return _strcmpi(path + (path_len - ext_len), ext) == 0; } void path_change_extension(const char *path, const char *ext, std::string &result) { if(!path || !ext) { return; } result.assign(path); // Remove extension size_t last_dot = result.find_last_of('.'); if(last_dot != std::string::npos) { result = result.substr(0, last_dot); } result.append(ext); } void path_append(const char *path, const char *append, std::string &result) { // Normalize path std::string tmp; get_absolute_path(path, tmp); // Append if(!append) { result = tmp; return; } std::string appends = std::string(append); if(appends.length() > 0 && appends[0] == NOT_DIR_SEPARATOR[0]) { appends[0] = DIR_SEPARATOR[0]; } if(appends[0] != DIR_SEPARATOR[0]) { tmp.append(DIR_SEPARATOR); } tmp.append(appends); // Normalize with supplement get_absolute_path(tmp.c_str(), result); } bool dir_exists(const char *path) { #if SAMPSHARP_WINDOWS DWORD attrib = GetFileAttributes(path); return attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY); #elif SAMPSHARP_LINUX DIR* dir = opendir(path); if (dir) { closedir(dir); return true; } else { return false; } #endif } bool file_exists(const char *path) { #if SAMPSHARP_WINDOWS return PathFileExists(path); #elif SAMPSHARP_LINUX return access(path, F_OK) != -1; #endif } bool get_absolute_path(const char *path, std::string &absolute_path) { char cpath[PATH_MAX]; #if SAMPSHARP_LINUX strcpy(cpath, path); #elif SAMPSHARP_WINDOWS strcpy_s(cpath, path); #endif for(int i = strlen(cpath) - 1; i >= 0; i--) { if(cpath[i] == NOT_DIR_SEPARATOR[0]) { cpath[i] = DIR_SEPARATOR[0]; } } #if SAMPSHARP_LINUX char real_path[PATH_MAX]; if (realpath(cpath, real_path) != nullptr && real_path[0] != '\0') { absolute_path.assign(real_path); // realpath should return canonicalized path without the trailing slash assert(absolute_path.back() != DIR_SEPARATOR[0]); return true; } return false; #elif SAMPSHARP_WINDOWS wchar_t wreal_path[PATH_MAX]; wchar_t wpath[PATH_MAX]; mbstowcs_s(nullptr, wpath, cpath, PATH_MAX); GetFullPathNameW(wpath, PATH_MAX, wreal_path, nullptr); std::wstring wreal_path_s(wreal_path); absolute_path = std::string(wreal_path_s.begin(), wreal_path_s.end()); // not sure if GetFullPathNameW could return a trailing slash if(absolute_path.back() == DIR_SEPARATOR[0]) { absolute_path.pop_back(); } return true; #endif } bool get_directory(const char* absolute_path, std::string& directory) { directory.assign(absolute_path); size_t fwd = directory.rfind('/'); size_t bwd = directory.rfind('\\'); size_t last_slash; if(fwd == std::string::npos) { last_slash = bwd; } else if(bwd == std::string::npos) { last_slash = fwd; } else { last_slash = fwd > bwd ? fwd : bwd; } if (last_slash != std::string::npos) { directory.erase(last_slash); return true; } return false; } <commit_msg>Use strcmpi on linux instead of _strcmpi<commit_after>// SampSharp // Copyright 2018 Tim Potze // // 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 "pathutil.h" #include "platforms.h" #include <assert.h> #include <string.h> #if SAMPSHARP_WINDOWS # include "Windows.h" # include "Shlwapi.h" #elif SAMPSHARP_LINUX # include <unistd.h> # include <dirent.h> #endif #if !defined(PATH_MAX) && defined(MAX_PATH) # define PATH_MAX MAX_PATH #endif #ifdef __DIR_SEPARATOR_FORWARD # define NOT_DIR_SEPARATOR "\\" #else # define NOT_DIR_SEPARATOR "/" #endif bool path_has_extension(const char *path, const char *ext) { if(!path || !ext) { return false; } size_t path_len = strlen(path); size_t ext_len = strlen(ext); if(path_len < ext_len) { return false; } #if SAMPSHARP_WINDOWS return _strcmpi(path + (path_len - ext_len), ext) == 0; #elif SAMPSHARP_LINUX return strcmpi(path + (path_len - ext_len), ext) == 0; #endif } void path_change_extension(const char *path, const char *ext, std::string &result) { if(!path || !ext) { return; } result.assign(path); // Remove extension size_t last_dot = result.find_last_of('.'); if(last_dot != std::string::npos) { result = result.substr(0, last_dot); } result.append(ext); } void path_append(const char *path, const char *append, std::string &result) { // Normalize path std::string tmp; get_absolute_path(path, tmp); // Append if(!append) { result = tmp; return; } std::string appends = std::string(append); if(appends.length() > 0 && appends[0] == NOT_DIR_SEPARATOR[0]) { appends[0] = DIR_SEPARATOR[0]; } if(appends[0] != DIR_SEPARATOR[0]) { tmp.append(DIR_SEPARATOR); } tmp.append(appends); // Normalize with supplement get_absolute_path(tmp.c_str(), result); } bool dir_exists(const char *path) { #if SAMPSHARP_WINDOWS DWORD attrib = GetFileAttributes(path); return attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY); #elif SAMPSHARP_LINUX DIR* dir = opendir(path); if (dir) { closedir(dir); return true; } else { return false; } #endif } bool file_exists(const char *path) { #if SAMPSHARP_WINDOWS return PathFileExists(path); #elif SAMPSHARP_LINUX return access(path, F_OK) != -1; #endif } bool get_absolute_path(const char *path, std::string &absolute_path) { char cpath[PATH_MAX]; #if SAMPSHARP_LINUX strcpy(cpath, path); #elif SAMPSHARP_WINDOWS strcpy_s(cpath, path); #endif for(int i = strlen(cpath) - 1; i >= 0; i--) { if(cpath[i] == NOT_DIR_SEPARATOR[0]) { cpath[i] = DIR_SEPARATOR[0]; } } #if SAMPSHARP_LINUX char real_path[PATH_MAX]; if (realpath(cpath, real_path) != nullptr && real_path[0] != '\0') { absolute_path.assign(real_path); // realpath should return canonicalized path without the trailing slash assert(absolute_path.back() != DIR_SEPARATOR[0]); return true; } return false; #elif SAMPSHARP_WINDOWS wchar_t wreal_path[PATH_MAX]; wchar_t wpath[PATH_MAX]; mbstowcs_s(nullptr, wpath, cpath, PATH_MAX); GetFullPathNameW(wpath, PATH_MAX, wreal_path, nullptr); std::wstring wreal_path_s(wreal_path); absolute_path = std::string(wreal_path_s.begin(), wreal_path_s.end()); // not sure if GetFullPathNameW could return a trailing slash if(absolute_path.back() == DIR_SEPARATOR[0]) { absolute_path.pop_back(); } return true; #endif } bool get_directory(const char* absolute_path, std::string& directory) { directory.assign(absolute_path); size_t fwd = directory.rfind('/'); size_t bwd = directory.rfind('\\'); size_t last_slash; if(fwd == std::string::npos) { last_slash = bwd; } else if(bwd == std::string::npos) { last_slash = fwd; } else { last_slash = fwd > bwd ? fwd : bwd; } if (last_slash != std::string::npos) { directory.erase(last_slash); return true; } return false; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "unzip.h" #include "Resource.h" #include "UpdateRunner.h" void CUpdateRunner::DisplayErrorMessage(CString& errorMessage) { CTaskDialog dlg; // TODO: Something about contacting support? dlg.SetCommonButtons(TDCBF_OK_BUTTON); dlg.SetMainInstructionText(L"Installation has failed"); dlg.SetContentText(errorMessage); dlg.SetMainIcon(TD_ERROR_ICON); dlg.DoModal(); } int CUpdateRunner::ExtractUpdaterAndRun(wchar_t* lpCommandLine) { PROCESS_INFORMATION pi = { 0 }; STARTUPINFO si = { 0 }; CResource zipResource; wchar_t targetDir[MAX_PATH]; ExpandEnvironmentStrings(L"%LocalAppData%\\SquirrelTemp", targetDir, _countof(targetDir)); if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) { goto failedExtract; } if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) { goto failedExtract; } DWORD dwSize = zipResource.GetSize(); if (dwSize < 0x100) { goto failedExtract; } BYTE* pData = (BYTE*)zipResource.Lock(); HZIP zipFile = OpenZip(pData, dwSize, NULL); SetUnzipBaseDir(zipFile, targetDir); // NB: This library is kind of a disaster ZRESULT zr; int index = 0; do { ZIPENTRY zentry; zr = GetZipItem(zipFile, index, &zentry); if (zr != ZR_OK && zr != ZR_MORE) { break; } zr = UnzipItem(zipFile, index, zentry.name); index++; } while (zr == ZR_MORE); CloseZip(zipFile); zipResource.Release(); // nfi if the zip extract actually worked, check for Update.exe wchar_t updateExePath[MAX_PATH]; swprintf_s(updateExePath, L"%s\\%s", targetDir, L"Update.exe"); if (GetFileAttributes(updateExePath) == INVALID_FILE_ATTRIBUTES) { goto failedExtract; } // Run Update.exe si.cb = sizeof(STARTUPINFO); si.wShowWindow = SW_SHOW; si.dwFlags = STARTF_USESHOWWINDOW; if (!CreateProcess(updateExePath, lpCommandLine, NULL, NULL, false, 0, NULL, NULL, &si, &pi)) { goto failedExtract; } WaitForSingleObject(pi.hProcess, INFINITE); DWORD dwExitCode; if (!GetExitCodeProcess(pi.hProcess, &dwExitCode)) { dwExitCode = (DWORD)-1; } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return (int) dwExitCode; failedExtract: DisplayErrorMessage(CString(L"Failed to extract installer")); return (int) dwExitCode; }<commit_msg>Fix up oopses in UpdateRunner<commit_after>#include "stdafx.h" #include "unzip.h" #include "Resource.h" #include "UpdateRunner.h" void CUpdateRunner::DisplayErrorMessage(CString& errorMessage) { CTaskDialog dlg; // TODO: Something about contacting support? dlg.SetCommonButtons(TDCBF_OK_BUTTON); dlg.SetMainInstructionText(L"Installation has failed"); dlg.SetContentText(errorMessage); dlg.SetMainIcon(TD_ERROR_ICON); dlg.DoModal(); } int CUpdateRunner::ExtractUpdaterAndRun(wchar_t* lpCommandLine) { PROCESS_INFORMATION pi = { 0 }; STARTUPINFO si = { 0 }; CResource zipResource; wchar_t targetDir[MAX_PATH]; ExpandEnvironmentStrings(L"%LocalAppData%\\SquirrelTemp", targetDir, _countof(targetDir)); if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) { goto failedExtract; } if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) { goto failedExtract; } DWORD dwSize = zipResource.GetSize(); if (dwSize < 0x100) { goto failedExtract; } BYTE* pData = (BYTE*)zipResource.Lock(); HZIP zipFile = OpenZip(pData, dwSize, NULL); SetUnzipBaseDir(zipFile, targetDir); // NB: This library is kind of a disaster ZRESULT zr; int index = 0; do { ZIPENTRY zentry; zr = GetZipItem(zipFile, index, &zentry); if (zr != ZR_OK && zr != ZR_MORE) { break; } if (UnzipItem(zipFile, index, zentry.name) != ZR_OK) break; index++; } while (zr == ZR_MORE || zr == ZR_OK); CloseZip(zipFile); zipResource.Release(); // nfi if the zip extract actually worked, check for Update.exe wchar_t updateExePath[MAX_PATH]; swprintf_s(updateExePath, L"%s\\%s", targetDir, L"Update.exe"); if (GetFileAttributes(updateExePath) == INVALID_FILE_ATTRIBUTES) { goto failedExtract; } // Run Update.exe si.cb = sizeof(STARTUPINFO); si.wShowWindow = SW_SHOW; si.dwFlags = STARTF_USESHOWWINDOW; if (!lpCommandLine || wcsnlen_s(lpCommandLine, MAX_PATH) < 1) { lpCommandLine = L"--install ."; } wchar_t cmd[MAX_PATH]; swprintf_s(cmd, L"%s %s", updateExePath, lpCommandLine); if (!CreateProcess(NULL, cmd, NULL, NULL, false, 0, NULL, targetDir, &si, &pi)) { goto failedExtract; } WaitForSingleObject(pi.hProcess, INFINITE); DWORD dwExitCode; if (!GetExitCodeProcess(pi.hProcess, &dwExitCode)) { dwExitCode = (DWORD)-1; } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return (int) dwExitCode; failedExtract: DisplayErrorMessage(CString(L"Failed to extract installer")); return (int) dwExitCode; }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLShapeStyleContext.cxx,v $ * * $Revision: 1.16 $ * * last change: $Author: rt $ $Date: 2007-01-29 14:48: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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #include <tools/debug.hxx> #ifndef _XMLOFF_XMLSHAPESTYLECONTEXT_HXX #include "XMLShapeStyleContext.hxx" #endif #ifndef _XMLOFF_XMLSHAPEPROPERTYSETCONTEXT_HXX #include "XMLShapePropertySetContext.hxx" #endif #ifndef _XMLOFF_CONTEXTID_HXX_ #include "contextid.hxx" #endif #ifndef _COM_SUN_STAR_DRAWING_XCONTROLSHAPE_HPP_ #include <com/sun/star/drawing/XControlShape.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_ #include "com/sun/star/beans/XPropertySetInfo.hpp" #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLOFF_XMLNUMI_HXX #include "xmlnumi.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLERROR_HXX #include "xmlerror.hxx" #endif #ifndef _XMLOFF_PROPMAPPINGTYPES_HXX #include "maptype.hxx" #endif #include "sdpropls.hxx" using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using ::xmloff::token::IsXMLToken; using ::xmloff::token::XML_TEXT_PROPERTIES; using ::xmloff::token::XML_GRAPHIC_PROPERTIES; using ::xmloff::token::XML_PARAGRAPH_PROPERTIES; ////////////////////////////////////////////////////////////////////////////// TYPEINIT1( XMLShapeStyleContext, XMLPropStyleContext ); XMLShapeStyleContext::XMLShapeStyleContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const uno::Reference< xml::sax::XAttributeList >& xAttrList, SvXMLStylesContext& rStyles, sal_uInt16 nFamily) : XMLPropStyleContext(rImport, nPrfx, rLName, xAttrList, rStyles, nFamily ), m_bIsNumRuleAlreadyConverted( sal_False ) { } XMLShapeStyleContext::~XMLShapeStyleContext() { } void XMLShapeStyleContext::SetAttribute( sal_uInt16 nPrefixKey, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue ) { if ((0 == m_sControlDataStyleName.getLength()) && (::xmloff::token::GetXMLToken(::xmloff::token::XML_DATA_STYLE_NAME) == rLocalName)) { m_sControlDataStyleName = rValue; } else if( (XML_NAMESPACE_STYLE == nPrefixKey) && IsXMLToken( rLocalName, ::xmloff::token::XML_LIST_STYLE_NAME ) ) { m_sListStyleName = rValue; } else { XMLPropStyleContext::SetAttribute( nPrefixKey, rLocalName, rValue ); if( (XML_NAMESPACE_STYLE == nPrefixKey) && ( IsXMLToken( rLocalName, ::xmloff::token::XML_NAME ) || IsXMLToken( rLocalName, ::xmloff::token::XML_DISPLAY_NAME ) ) ) { if( GetName().getLength() && GetDisplayName().getLength() && GetName() != GetDisplayName() ) { const_cast< SvXMLImport&>( GetImport() ). AddStyleDisplayName( GetFamily(), GetName(), GetDisplayName() ); } } } } SvXMLImportContext *XMLShapeStyleContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; if( XML_NAMESPACE_STYLE == nPrefix ) { sal_uInt32 nFamily = 0; if( IsXMLToken( rLocalName, XML_TEXT_PROPERTIES ) ) nFamily = XML_TYPE_PROP_TEXT; else if( IsXMLToken( rLocalName, XML_PARAGRAPH_PROPERTIES ) ) nFamily = XML_TYPE_PROP_PARAGRAPH; else if( IsXMLToken( rLocalName, XML_GRAPHIC_PROPERTIES ) ) nFamily = XML_TYPE_PROP_GRAPHIC; if( nFamily ) { UniReference < SvXMLImportPropertyMapper > xImpPrMap = GetStyles()->GetImportPropertyMapper( GetFamily() ); if( xImpPrMap.is() ) pContext = new XMLShapePropertySetContext( GetImport(), nPrefix, rLocalName, xAttrList, nFamily, GetProperties(), xImpPrMap ); } } if( !pContext ) pContext = XMLPropStyleContext::CreateChildContext( nPrefix, rLocalName, xAttrList ); return pContext; } void XMLShapeStyleContext::FillPropertySet( const Reference< beans::XPropertySet > & rPropSet ) { if( !m_bIsNumRuleAlreadyConverted ) { m_bIsNumRuleAlreadyConverted = sal_True; // for compatibility to beta files, search for CTF_SD_NUMBERINGRULES_NAME to // import numbering rules from the style:properties element const UniReference< XMLPropertySetMapper >&rMapper = GetStyles()->GetImportPropertyMapper( GetFamily() )->getPropertySetMapper(); ::std::vector< XMLPropertyState > &rProperties = GetProperties(); ::std::vector< XMLPropertyState >::iterator end( rProperties.end() ); ::std::vector< XMLPropertyState >::iterator property; // first, look for the old format, where we had a text:list-style-name // attribute in the style:properties element for( property = rProperties.begin(); property != end; property++ ) { // find properties with context if( (property->mnIndex != -1) && (rMapper->GetEntryContextId( property->mnIndex ) == CTF_SD_NUMBERINGRULES_NAME) ) break; } // if we did not find an old list-style-name in the properties, and we need one // because we got a style:list-style attribute in the style-style element // we generate one if( (property == end) && ( 0 != m_sListStyleName.getLength() ) ) { sal_Int32 nIndex = rMapper->FindEntryIndex( CTF_SD_NUMBERINGRULES_NAME ); DBG_ASSERT( -1 != nIndex, "can't find numbering rules property entry, can't set numbering rule!" ); XMLPropertyState aNewState( nIndex ); rProperties.push_back( aNewState ); end = rProperties.end(); property = end - 1; } // so, if we have an old or a new list style name, we set its value to // a numbering rule if( property != end ) { if( 0 == m_sListStyleName.getLength() ) { property->maValue >>= m_sListStyleName; } const SvxXMLListStyleContext *pListStyle = GetImport().GetTextImport()->FindAutoListStyle( m_sListStyleName ); DBG_ASSERT( pListStyle, "list-style not found for shape style" ); if( pListStyle ) { uno::Reference< container::XIndexReplace > xNumRule( pListStyle->CreateNumRule( GetImport().GetModel() ) ); pListStyle->FillUnoNumRule(xNumRule, NULL /* const SvI18NMap * ??? */ ); property->maValue <<= xNumRule; } else { property->mnIndex = -1; } } } struct _ContextID_Index_Pair aContextIDs[] = { { CTF_DASHNAME , -1 }, { CTF_LINESTARTNAME , -1 }, { CTF_LINEENDNAME , -1 }, { CTF_FILLGRADIENTNAME, -1 }, { CTF_FILLTRANSNAME , -1 }, { CTF_FILLHATCHNAME , -1 }, { CTF_FILLBITMAPNAME , -1 }, { CTF_SD_OLE_VIS_AREA_IMPORT_LEFT, -1 }, { CTF_SD_OLE_VIS_AREA_IMPORT_TOP, -1 }, { CTF_SD_OLE_VIS_AREA_IMPORT_WIDTH, -1 }, { CTF_SD_OLE_VIS_AREA_IMPORT_HEIGHT, -1 }, { -1, -1 } }; static sal_uInt16 aFamilies[] = { XML_STYLE_FAMILY_SD_STROKE_DASH_ID, XML_STYLE_FAMILY_SD_MARKER_ID, XML_STYLE_FAMILY_SD_MARKER_ID, XML_STYLE_FAMILY_SD_GRADIENT_ID, XML_STYLE_FAMILY_SD_GRADIENT_ID, XML_STYLE_FAMILY_SD_HATCH_ID, XML_STYLE_FAMILY_SD_FILL_IMAGE_ID }; UniReference < SvXMLImportPropertyMapper > xImpPrMap = GetStyles()->GetImportPropertyMapper( GetFamily() ); DBG_ASSERT( xImpPrMap.is(), "There is the import prop mapper" ); if( xImpPrMap.is() ) xImpPrMap->FillPropertySet( GetProperties(), rPropSet, aContextIDs ); Reference< XPropertySetInfo > xInfo; // get property set mapper UniReference<XMLPropertySetMapper> xPropMapper( xImpPrMap->getPropertySetMapper() ); for( sal_uInt16 i=0; aContextIDs[i].nContextID != -1; i++ ) { sal_Int32 nIndex = aContextIDs[i].nIndex; if( nIndex != -1 ) switch( aContextIDs[i].nContextID ) { case CTF_DASHNAME: case CTF_LINESTARTNAME: case CTF_LINEENDNAME: case CTF_FILLGRADIENTNAME: case CTF_FILLTRANSNAME: case CTF_FILLHATCHNAME: case CTF_FILLBITMAPNAME: { struct XMLPropertyState& rState = GetProperties()[nIndex]; OUString sStyleName; rState.maValue >>= sStyleName; sStyleName = GetImport().GetStyleDisplayName( aFamilies[i], sStyleName ); try { // set property const OUString& rPropertyName = xPropMapper->GetEntryAPIName(rState.mnIndex); if( !xInfo.is() ) xInfo = rPropSet->getPropertySetInfo(); if ( xInfo->hasPropertyByName( rPropertyName ) ) { rPropSet->setPropertyValue( rPropertyName, Any( sStyleName ) ); } } catch ( ::com::sun::star::lang::IllegalArgumentException& e ) { Sequence<OUString> aSeq(1); aSeq[0] = sStyleName; GetImport().SetError( XMLERROR_STYLE_PROP_VALUE | XMLERROR_FLAG_ERROR, aSeq, e.Message, NULL ); } break; } case CTF_SD_OLE_VIS_AREA_IMPORT_LEFT: case CTF_SD_OLE_VIS_AREA_IMPORT_TOP: case CTF_SD_OLE_VIS_AREA_IMPORT_WIDTH: case CTF_SD_OLE_VIS_AREA_IMPORT_HEIGHT: { struct XMLPropertyState& rState = GetProperties()[nIndex]; const OUString& rPropertyName = xPropMapper->GetEntryAPIName(rState.mnIndex); try { if( !xInfo.is() ) xInfo = rPropSet->getPropertySetInfo(); if ( xInfo->hasPropertyByName( rPropertyName ) ) { rPropSet->setPropertyValue( rPropertyName, rState.maValue ); } } catch ( ::com::sun::star::lang::IllegalArgumentException& e ) { Sequence<OUString> aSeq; GetImport().SetError( XMLERROR_STYLE_PROP_VALUE | XMLERROR_FLAG_ERROR, aSeq, e.Message, NULL ); } break; } } } if (m_sControlDataStyleName.getLength()) { // we had a data-style-name attribute // set the formatting on the control model of the control shape uno::Reference< drawing::XControlShape > xControlShape(rPropSet, uno::UNO_QUERY); DBG_ASSERT(xControlShape.is(), "XMLShapeStyleContext::FillPropertySet: data style for a non-control shape!"); if (xControlShape.is()) { uno::Reference< beans::XPropertySet > xControlModel(xControlShape->getControl(), uno::UNO_QUERY); DBG_ASSERT(xControlModel.is(), "XMLShapeStyleContext::FillPropertySet: no control model for the shape!"); if (xControlModel.is()) { GetImport().GetFormImport()->applyControlNumberStyle(xControlModel, m_sControlDataStyleName); } } } } void XMLShapeStyleContext::Finish( sal_Bool /*bOverwrite*/ ) { } <commit_msg>INTEGRATION: CWS vgbugs07 (1.16.46); FILE MERGED 2007/06/04 13:23:23 vg 1.16.46.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLShapeStyleContext.cxx,v $ * * $Revision: 1.17 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:00:31 $ * * 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_xmloff.hxx" #include <tools/debug.hxx> #ifndef _XMLOFF_XMLSHAPESTYLECONTEXT_HXX #include <xmloff/XMLShapeStyleContext.hxx> #endif #ifndef _XMLOFF_XMLSHAPEPROPERTYSETCONTEXT_HXX #include "XMLShapePropertySetContext.hxx" #endif #ifndef _XMLOFF_CONTEXTID_HXX_ #include <xmloff/contextid.hxx> #endif #ifndef _COM_SUN_STAR_DRAWING_XCONTROLSHAPE_HPP_ #include <com/sun/star/drawing/XControlShape.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_ #include "com/sun/star/beans/XPropertySetInfo.hpp" #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _XMLOFF_XMLNUMI_HXX #include <xmloff/xmlnumi.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLERROR_HXX #include "xmlerror.hxx" #endif #ifndef _XMLOFF_PROPMAPPINGTYPES_HXX #include <xmloff/maptype.hxx> #endif #include "sdpropls.hxx" using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using ::xmloff::token::IsXMLToken; using ::xmloff::token::XML_TEXT_PROPERTIES; using ::xmloff::token::XML_GRAPHIC_PROPERTIES; using ::xmloff::token::XML_PARAGRAPH_PROPERTIES; ////////////////////////////////////////////////////////////////////////////// TYPEINIT1( XMLShapeStyleContext, XMLPropStyleContext ); XMLShapeStyleContext::XMLShapeStyleContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const uno::Reference< xml::sax::XAttributeList >& xAttrList, SvXMLStylesContext& rStyles, sal_uInt16 nFamily) : XMLPropStyleContext(rImport, nPrfx, rLName, xAttrList, rStyles, nFamily ), m_bIsNumRuleAlreadyConverted( sal_False ) { } XMLShapeStyleContext::~XMLShapeStyleContext() { } void XMLShapeStyleContext::SetAttribute( sal_uInt16 nPrefixKey, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue ) { if ((0 == m_sControlDataStyleName.getLength()) && (::xmloff::token::GetXMLToken(::xmloff::token::XML_DATA_STYLE_NAME) == rLocalName)) { m_sControlDataStyleName = rValue; } else if( (XML_NAMESPACE_STYLE == nPrefixKey) && IsXMLToken( rLocalName, ::xmloff::token::XML_LIST_STYLE_NAME ) ) { m_sListStyleName = rValue; } else { XMLPropStyleContext::SetAttribute( nPrefixKey, rLocalName, rValue ); if( (XML_NAMESPACE_STYLE == nPrefixKey) && ( IsXMLToken( rLocalName, ::xmloff::token::XML_NAME ) || IsXMLToken( rLocalName, ::xmloff::token::XML_DISPLAY_NAME ) ) ) { if( GetName().getLength() && GetDisplayName().getLength() && GetName() != GetDisplayName() ) { const_cast< SvXMLImport&>( GetImport() ). AddStyleDisplayName( GetFamily(), GetName(), GetDisplayName() ); } } } } SvXMLImportContext *XMLShapeStyleContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; if( XML_NAMESPACE_STYLE == nPrefix ) { sal_uInt32 nFamily = 0; if( IsXMLToken( rLocalName, XML_TEXT_PROPERTIES ) ) nFamily = XML_TYPE_PROP_TEXT; else if( IsXMLToken( rLocalName, XML_PARAGRAPH_PROPERTIES ) ) nFamily = XML_TYPE_PROP_PARAGRAPH; else if( IsXMLToken( rLocalName, XML_GRAPHIC_PROPERTIES ) ) nFamily = XML_TYPE_PROP_GRAPHIC; if( nFamily ) { UniReference < SvXMLImportPropertyMapper > xImpPrMap = GetStyles()->GetImportPropertyMapper( GetFamily() ); if( xImpPrMap.is() ) pContext = new XMLShapePropertySetContext( GetImport(), nPrefix, rLocalName, xAttrList, nFamily, GetProperties(), xImpPrMap ); } } if( !pContext ) pContext = XMLPropStyleContext::CreateChildContext( nPrefix, rLocalName, xAttrList ); return pContext; } void XMLShapeStyleContext::FillPropertySet( const Reference< beans::XPropertySet > & rPropSet ) { if( !m_bIsNumRuleAlreadyConverted ) { m_bIsNumRuleAlreadyConverted = sal_True; // for compatibility to beta files, search for CTF_SD_NUMBERINGRULES_NAME to // import numbering rules from the style:properties element const UniReference< XMLPropertySetMapper >&rMapper = GetStyles()->GetImportPropertyMapper( GetFamily() )->getPropertySetMapper(); ::std::vector< XMLPropertyState > &rProperties = GetProperties(); ::std::vector< XMLPropertyState >::iterator end( rProperties.end() ); ::std::vector< XMLPropertyState >::iterator property; // first, look for the old format, where we had a text:list-style-name // attribute in the style:properties element for( property = rProperties.begin(); property != end; property++ ) { // find properties with context if( (property->mnIndex != -1) && (rMapper->GetEntryContextId( property->mnIndex ) == CTF_SD_NUMBERINGRULES_NAME) ) break; } // if we did not find an old list-style-name in the properties, and we need one // because we got a style:list-style attribute in the style-style element // we generate one if( (property == end) && ( 0 != m_sListStyleName.getLength() ) ) { sal_Int32 nIndex = rMapper->FindEntryIndex( CTF_SD_NUMBERINGRULES_NAME ); DBG_ASSERT( -1 != nIndex, "can't find numbering rules property entry, can't set numbering rule!" ); XMLPropertyState aNewState( nIndex ); rProperties.push_back( aNewState ); end = rProperties.end(); property = end - 1; } // so, if we have an old or a new list style name, we set its value to // a numbering rule if( property != end ) { if( 0 == m_sListStyleName.getLength() ) { property->maValue >>= m_sListStyleName; } const SvxXMLListStyleContext *pListStyle = GetImport().GetTextImport()->FindAutoListStyle( m_sListStyleName ); DBG_ASSERT( pListStyle, "list-style not found for shape style" ); if( pListStyle ) { uno::Reference< container::XIndexReplace > xNumRule( pListStyle->CreateNumRule( GetImport().GetModel() ) ); pListStyle->FillUnoNumRule(xNumRule, NULL /* const SvI18NMap * ??? */ ); property->maValue <<= xNumRule; } else { property->mnIndex = -1; } } } struct _ContextID_Index_Pair aContextIDs[] = { { CTF_DASHNAME , -1 }, { CTF_LINESTARTNAME , -1 }, { CTF_LINEENDNAME , -1 }, { CTF_FILLGRADIENTNAME, -1 }, { CTF_FILLTRANSNAME , -1 }, { CTF_FILLHATCHNAME , -1 }, { CTF_FILLBITMAPNAME , -1 }, { CTF_SD_OLE_VIS_AREA_IMPORT_LEFT, -1 }, { CTF_SD_OLE_VIS_AREA_IMPORT_TOP, -1 }, { CTF_SD_OLE_VIS_AREA_IMPORT_WIDTH, -1 }, { CTF_SD_OLE_VIS_AREA_IMPORT_HEIGHT, -1 }, { -1, -1 } }; static sal_uInt16 aFamilies[] = { XML_STYLE_FAMILY_SD_STROKE_DASH_ID, XML_STYLE_FAMILY_SD_MARKER_ID, XML_STYLE_FAMILY_SD_MARKER_ID, XML_STYLE_FAMILY_SD_GRADIENT_ID, XML_STYLE_FAMILY_SD_GRADIENT_ID, XML_STYLE_FAMILY_SD_HATCH_ID, XML_STYLE_FAMILY_SD_FILL_IMAGE_ID }; UniReference < SvXMLImportPropertyMapper > xImpPrMap = GetStyles()->GetImportPropertyMapper( GetFamily() ); DBG_ASSERT( xImpPrMap.is(), "There is the import prop mapper" ); if( xImpPrMap.is() ) xImpPrMap->FillPropertySet( GetProperties(), rPropSet, aContextIDs ); Reference< XPropertySetInfo > xInfo; // get property set mapper UniReference<XMLPropertySetMapper> xPropMapper( xImpPrMap->getPropertySetMapper() ); for( sal_uInt16 i=0; aContextIDs[i].nContextID != -1; i++ ) { sal_Int32 nIndex = aContextIDs[i].nIndex; if( nIndex != -1 ) switch( aContextIDs[i].nContextID ) { case CTF_DASHNAME: case CTF_LINESTARTNAME: case CTF_LINEENDNAME: case CTF_FILLGRADIENTNAME: case CTF_FILLTRANSNAME: case CTF_FILLHATCHNAME: case CTF_FILLBITMAPNAME: { struct XMLPropertyState& rState = GetProperties()[nIndex]; OUString sStyleName; rState.maValue >>= sStyleName; sStyleName = GetImport().GetStyleDisplayName( aFamilies[i], sStyleName ); try { // set property const OUString& rPropertyName = xPropMapper->GetEntryAPIName(rState.mnIndex); if( !xInfo.is() ) xInfo = rPropSet->getPropertySetInfo(); if ( xInfo->hasPropertyByName( rPropertyName ) ) { rPropSet->setPropertyValue( rPropertyName, Any( sStyleName ) ); } } catch ( ::com::sun::star::lang::IllegalArgumentException& e ) { Sequence<OUString> aSeq(1); aSeq[0] = sStyleName; GetImport().SetError( XMLERROR_STYLE_PROP_VALUE | XMLERROR_FLAG_ERROR, aSeq, e.Message, NULL ); } break; } case CTF_SD_OLE_VIS_AREA_IMPORT_LEFT: case CTF_SD_OLE_VIS_AREA_IMPORT_TOP: case CTF_SD_OLE_VIS_AREA_IMPORT_WIDTH: case CTF_SD_OLE_VIS_AREA_IMPORT_HEIGHT: { struct XMLPropertyState& rState = GetProperties()[nIndex]; const OUString& rPropertyName = xPropMapper->GetEntryAPIName(rState.mnIndex); try { if( !xInfo.is() ) xInfo = rPropSet->getPropertySetInfo(); if ( xInfo->hasPropertyByName( rPropertyName ) ) { rPropSet->setPropertyValue( rPropertyName, rState.maValue ); } } catch ( ::com::sun::star::lang::IllegalArgumentException& e ) { Sequence<OUString> aSeq; GetImport().SetError( XMLERROR_STYLE_PROP_VALUE | XMLERROR_FLAG_ERROR, aSeq, e.Message, NULL ); } break; } } } if (m_sControlDataStyleName.getLength()) { // we had a data-style-name attribute // set the formatting on the control model of the control shape uno::Reference< drawing::XControlShape > xControlShape(rPropSet, uno::UNO_QUERY); DBG_ASSERT(xControlShape.is(), "XMLShapeStyleContext::FillPropertySet: data style for a non-control shape!"); if (xControlShape.is()) { uno::Reference< beans::XPropertySet > xControlModel(xControlShape->getControl(), uno::UNO_QUERY); DBG_ASSERT(xControlModel.is(), "XMLShapeStyleContext::FillPropertySet: no control model for the shape!"); if (xControlModel.is()) { GetImport().GetFormImport()->applyControlNumberStyle(xControlModel, m_sControlDataStyleName); } } } } void XMLShapeStyleContext::Finish( sal_Bool /*bOverwrite*/ ) { } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLMsgLoader.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLUni.hpp> #include <windows.h> #include "Win32MsgLoader.hpp" XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Public Constructors and Destructor // --------------------------------------------------------------------------- HINSTANCE globalModuleHandle; BOOL APIENTRY DllMain(HINSTANCE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: globalModuleHandle = hModule; break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } return TRUE; } // --------------------------------------------------------------------------- // Global module handle // --------------------------------------------------------------------------- Win32MsgLoader::Win32MsgLoader(const XMLCh* const msgDomain) : fDomainOfs(0) , fModHandle(0) , fMsgDomain(0) { // Try to get the module handle fModHandle = globalModuleHandle; if (!fModHandle) { // // If we didn't find it, its probably because its a development // build which is built as separate DLLs, so lets look for the DLL // that we are part of. // static const char* const privDLLName = "IXUTIL"; fModHandle = ::GetModuleHandleA(privDLLName); // If neither exists, then we give up if (!fModHandle) { // Probably have to call panic here } } // Store the domain name fMsgDomain = XMLString::replicate(msgDomain); // And precalc the id offset we use for this domain if (XMLString::equals(fMsgDomain, XMLUni::fgXMLErrDomain)) fDomainOfs = 0; else if (XMLString::equals(fMsgDomain, XMLUni::fgExceptDomain)) fDomainOfs = 0x2000; else if (XMLString::equals(fMsgDomain, XMLUni::fgValidityDomain)) fDomainOfs = 0x4000; else XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain); } Win32MsgLoader::~Win32MsgLoader() { delete [] fMsgDomain; } // --------------------------------------------------------------------------- // Implementation of the virtual message loader API // --------------------------------------------------------------------------- // // This is the method that actually does the work of loading a message from // the attached resources. Note that we don't use LoadStringW here, since it // won't work on Win98. So we go the next level down and do what LoadStringW // would have done, since this will work on either platform. // bool Win32MsgLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars) { // In case we error return, and they don't check it... toFill[0] = 0; // Adjust the message id by the domain offset const unsigned int theMsgId = msgToLoad + fDomainOfs; // // Figure out the actual id the id, adjusting it by the domain offset. // Then first we calculate the particular 16 string block that this id // is in, and the offset within that block of the string in question. // const unsigned int theBlock = (theMsgId >> 4) + 1; const unsigned int theOfs = theMsgId & 0x000F; // Try to find this resource. If we fail to find it, return false HRSRC hMsgRsc = ::FindResourceExA ( fModHandle , RT_STRING , MAKEINTRESOURCE(theBlock) , MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) ); if (!hMsgRsc) return false; // We found it, so load the block. If this fails, also return a false HGLOBAL hGbl = ::LoadResource(fModHandle, hMsgRsc); if (!hGbl) return false; // Lock this resource into memory. Again, if it fails, just return false const XMLCh* pBlock = (const XMLCh*)::LockResource(hGbl); if (!pBlock) return false; // // Look through the block for our desired message. Its stored such that // the zeroth entry has the length minus the separator null. // for (unsigned int index = 0; index < theOfs; index++) pBlock += *pBlock + 1; // Calculate how many actual chars we will end up with const unsigned int actualChars = ((maxChars < *pBlock) ? maxChars : *pBlock); // Ok, finally now copy as much as we can into the caller's buffer wcsncpy(toFill, pBlock + 1, actualChars); toFill[actualChars] = 0; return true; } bool Win32MsgLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars , const XMLCh* const repText1 , const XMLCh* const repText2 , const XMLCh* const repText3 , const XMLCh* const repText4) { // Call the other version to load up the message if (!loadMsg(msgToLoad, toFill, maxChars)) return false; // And do the token replacement XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4); return true; } bool Win32MsgLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars , const char* const repText1 , const char* const repText2 , const char* const repText3 , const char* const repText4) { // // Transcode the provided parameters and call the other version, // which will do the replacement work. // XMLCh* tmp1 = 0; XMLCh* tmp2 = 0; XMLCh* tmp3 = 0; XMLCh* tmp4 = 0; bool bRet = false; if (repText1) tmp1 = XMLString::transcode(repText1); if (repText2) tmp2 = XMLString::transcode(repText2); if (repText3) tmp3 = XMLString::transcode(repText3); if (repText4) tmp4 = XMLString::transcode(repText4); bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4); if (tmp1) delete [] tmp1; if (tmp2) delete [] tmp2; if (tmp3) delete [] tmp3; if (tmp4) delete [] tmp4; return bRet; } XERCES_CPP_NAMESPACE_END <commit_msg>C++ Namespace Support.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLMsgLoader.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLUni.hpp> #include <windows.h> #include "Win32MsgLoader.hpp" // --------------------------------------------------------------------------- // Public Constructors and Destructor // --------------------------------------------------------------------------- HINSTANCE globalModuleHandle; BOOL APIENTRY DllMain(HINSTANCE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: globalModuleHandle = hModule; break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } return TRUE; } XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Global module handle // --------------------------------------------------------------------------- Win32MsgLoader::Win32MsgLoader(const XMLCh* const msgDomain) : fDomainOfs(0) , fModHandle(0) , fMsgDomain(0) { // Try to get the module handle fModHandle = globalModuleHandle; if (!fModHandle) { // // If we didn't find it, its probably because its a development // build which is built as separate DLLs, so lets look for the DLL // that we are part of. // static const char* const privDLLName = "IXUTIL"; fModHandle = ::GetModuleHandleA(privDLLName); // If neither exists, then we give up if (!fModHandle) { // Probably have to call panic here } } // Store the domain name fMsgDomain = XMLString::replicate(msgDomain); // And precalc the id offset we use for this domain if (XMLString::equals(fMsgDomain, XMLUni::fgXMLErrDomain)) fDomainOfs = 0; else if (XMLString::equals(fMsgDomain, XMLUni::fgExceptDomain)) fDomainOfs = 0x2000; else if (XMLString::equals(fMsgDomain, XMLUni::fgValidityDomain)) fDomainOfs = 0x4000; else XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain); } Win32MsgLoader::~Win32MsgLoader() { delete [] fMsgDomain; } // --------------------------------------------------------------------------- // Implementation of the virtual message loader API // --------------------------------------------------------------------------- // // This is the method that actually does the work of loading a message from // the attached resources. Note that we don't use LoadStringW here, since it // won't work on Win98. So we go the next level down and do what LoadStringW // would have done, since this will work on either platform. // bool Win32MsgLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars) { // In case we error return, and they don't check it... toFill[0] = 0; // Adjust the message id by the domain offset const unsigned int theMsgId = msgToLoad + fDomainOfs; // // Figure out the actual id the id, adjusting it by the domain offset. // Then first we calculate the particular 16 string block that this id // is in, and the offset within that block of the string in question. // const unsigned int theBlock = (theMsgId >> 4) + 1; const unsigned int theOfs = theMsgId & 0x000F; // Try to find this resource. If we fail to find it, return false HRSRC hMsgRsc = ::FindResourceExA ( fModHandle , RT_STRING , MAKEINTRESOURCE(theBlock) , MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) ); if (!hMsgRsc) return false; // We found it, so load the block. If this fails, also return a false HGLOBAL hGbl = ::LoadResource(fModHandle, hMsgRsc); if (!hGbl) return false; // Lock this resource into memory. Again, if it fails, just return false const XMLCh* pBlock = (const XMLCh*)::LockResource(hGbl); if (!pBlock) return false; // // Look through the block for our desired message. Its stored such that // the zeroth entry has the length minus the separator null. // for (unsigned int index = 0; index < theOfs; index++) pBlock += *pBlock + 1; // Calculate how many actual chars we will end up with const unsigned int actualChars = ((maxChars < *pBlock) ? maxChars : *pBlock); // Ok, finally now copy as much as we can into the caller's buffer wcsncpy(toFill, pBlock + 1, actualChars); toFill[actualChars] = 0; return true; } bool Win32MsgLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars , const XMLCh* const repText1 , const XMLCh* const repText2 , const XMLCh* const repText3 , const XMLCh* const repText4) { // Call the other version to load up the message if (!loadMsg(msgToLoad, toFill, maxChars)) return false; // And do the token replacement XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4); return true; } bool Win32MsgLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars , const char* const repText1 , const char* const repText2 , const char* const repText3 , const char* const repText4) { // // Transcode the provided parameters and call the other version, // which will do the replacement work. // XMLCh* tmp1 = 0; XMLCh* tmp2 = 0; XMLCh* tmp3 = 0; XMLCh* tmp4 = 0; bool bRet = false; if (repText1) tmp1 = XMLString::transcode(repText1); if (repText2) tmp2 = XMLString::transcode(repText2); if (repText3) tmp3 = XMLString::transcode(repText3); if (repText4) tmp4 = XMLString::transcode(repText4); bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4); if (tmp1) delete [] tmp1; if (tmp2) delete [] tmp2; if (tmp3) delete [] tmp3; if (tmp4) delete [] tmp4; return bRet; } XERCES_CPP_NAMESPACE_END <|endoftext|>
<commit_before>// Intercept the implicit 'this' argument of class member functions. // // RUN: %clangxx_xray -g -std=c++11 %s -o %t // RUN: rm log-args-this-* || true // RUN: XRAY_OPTIONS="patch_premain=true verbosity=1 xray_logfile_base=log-args-this-" %run %t // // XFAIL: freebsd | arm || aarch64 || mips // UNSUPPORTED: powerpc64le #include "xray/xray_interface.h" #include <cassert> class A { public: [[clang::xray_always_instrument, clang::xray_log_args(1)]] void f() { // does nothing. } }; volatile uint64_t captured = 0; void handler(int32_t, XRayEntryType, uint64_t arg1) { captured = arg1; } int main() { __xray_set_handler_arg1(handler); A instance; instance.f(); __xray_remove_handler_arg1(); assert(captured == (uint64_t)&instance); } <commit_msg>Try to fix the syntax in test<commit_after>// Intercept the implicit 'this' argument of class member functions. // // RUN: %clangxx_xray -g -std=c++11 %s -o %t // RUN: rm log-args-this-* || true // RUN: XRAY_OPTIONS="patch_premain=true verbosity=1 xray_logfile_base=log-args-this-" %run %t // // XFAIL: freebsd || arm || aarch64 || mips // UNSUPPORTED: powerpc64le #include "xray/xray_interface.h" #include <cassert> class A { public: [[clang::xray_always_instrument, clang::xray_log_args(1)]] void f() { // does nothing. } }; volatile uint64_t captured = 0; void handler(int32_t, XRayEntryType, uint64_t arg1) { captured = arg1; } int main() { __xray_set_handler_arg1(handler); A instance; instance.f(); __xray_remove_handler_arg1(); assert(captured == (uint64_t)&instance); } <|endoftext|>
<commit_before>// Time: O(1) // Space: O(1) class Solution { public: int bulbSwitch(int n) { return static_cast<int>(sqrt(n)); } }; <commit_msg>Update bulb-switcher.cpp<commit_after>// Time: O(1) // Space: O(1) class Solution { public: int bulbSwitch(int n) { // The number of full squares. return static_cast<int>(sqrt(n)); } }; <|endoftext|>
<commit_before>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "interpreter.h" #include <cassert> #include <stdexcept> namespace reil { Interpreter::Interpreter() {} Interpreter::~Interpreter() {} Immediate Interpreter::GetOperand(const Operand &op) const { if (absl::holds_alternative<Immediate>(op)) { return absl::get<Immediate>(op); } else if (absl::holds_alternative<Register>(op)) { return registers_.at(absl::get<Register>(op).index); } else if (absl::holds_alternative<Temporary>(op)) { return temporaries_.at(absl::get<Temporary>(op).index); } else { // unreachable abort(); } } void Interpreter::SetOperand(const Operand &op, Immediate value) { if (absl::holds_alternative<Register>(op)) { registers_[absl::get<Register>(op).index] = value; } else if (absl::holds_alternative<Temporary>(op)) { temporaries_[absl::get<Temporary>(op).index] = value; } else { // unreachable abort(): } } void Interpreter::Add(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a + b); } void Interpreter::And(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a & b); } void Interpreter::Bisz(const Instruction &ri) { Immediate a = GetOperand(ri.input0); SetOperand(ri.output, Immediate(Size(ri.output), a ? 0 : 1)); } void Interpreter::Bsh(const Instruction &ri) {} void Interpreter::Div(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a / b); } void Interpreter::Jcc(const Instruction &ri) { Immediate a = GetOperand(ri.input0); if (a) { if (ri.output.index() == kOffset) { Offset target = absl::get<Offset>(ri.output); offset_ = target.offset; } else { Immediate target = GetOperand(ri.output); pc_ = static_cast<uint64_t>(target); offset_ = 0xffff; } } } void Interpreter::Ldm(const Instruction &ri) { Immediate a = GetOperand(ri.input0); uint64_t address = static_cast<uint64_t>(a); std::vector<uint8_t> bytes = GetMemory(address, Size(ri.output) / 8); SetOperand(ri.output, Immediate(bytes)); } void Interpreter::Mod(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a % b); } void Interpreter::Mul(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a * b); } void Interpreter::Nop(const Instruction &ri) {} void Interpreter::Or(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a | b); } void Interpreter::Stm(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.output); uint64_t address = static_cast<uint64_t>(b); std::vector<uint8_t> bytes = a.bytes(); SetMemory(address, bytes); } void Interpreter::Str(const Instruction &ri) { Immediate a = GetOperand(ri.input0); uint16_t result_size = Size(ri.output); if (result_size < a.size()) { SetOperand(ri.output, a.Extract(result_size)); } else if (a.size() < result_size) { SetOperand(ri.output, a.ZeroExtend(Size(ri.output))); } else { SetOperand(ri.output, a); } } void Interpreter::Sub(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a - b); } void Interpreter::Undef(const Instruction &ri) { if (absl::holds_alternative<Register>(ri.output)) { // TODO: } else if (absl::holds_alternative<Temporary>(ri.output)) { // TODO: } } void Interpreter::Unkn(const Instruction &ri) {} void Interpreter::Xor(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a ^ b); } void Interpreter::Bisnz(const Instruction &ri) { Immediate a = GetOperand(ri.input0); SetOperand(ri.output, Immediate(Size(ri.output), a ? 1 : 0)); } void Interpreter::Equ(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, Immediate(Size(ri.output), a == b ? 1 : 0)); } void Interpreter::Lshl(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a << b); } void Interpreter::Lshr(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a >> b); } void Interpreter::Ashr(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); uint16_t size = a.size(); if (Immediate::SignBit(size, size) & a) { a >>= b; a |= Immediate::Mask(size, size) << (size - (uint64_t)b); } else { a >>= b; } SetOperand(ri.output, a); } void Interpreter::Sex(const Instruction &ri) { Immediate a = GetOperand(ri.input0); uint16_t result_size = Size(ri.output); if (result_size < a.size()) { SetOperand(ri.output, a.Extract(result_size)); } else if (a.size() < result_size) { SetOperand(ri.output, a.SignExtend(Size(ri.output))); } else { SetOperand(ri.output, a); } } void Interpreter::Sys(const Instruction &ri) {} void Interpreter::Ite(const Instruction &ri) { Immediate cond = GetOperand(ri.input0); Immediate if_value = GetOperand(ri.input1); Immediate else_value = GetOperand(ri.input2); if (cond) { SetOperand(ri.output, if_value); } else { SetOperand(ri.output, else_value); } } void Interpreter::Start(NativeInstruction ni) { assert(ni.reil.size() < 0xffff); instructions_ = ni.reil; offset_ = 0; pc_ = ni.address; temporaries_.clear(); } uint16_t Interpreter::SingleStep() { const Instruction &ri = instructions_[offset_++]; switch (ri.opcode) { case Opcode::Add: { Add(ri); } break; case Opcode::And: { And(ri); } break; case Opcode::Bisz: { Bisz(ri); } break; case Opcode::Bsh: { Bsh(ri); } break; case Opcode::Div: { Div(ri); } break; case Opcode::Jcc: { Jcc(ri); } break; case Opcode::Ldm: { Ldm(ri); } break; case Opcode::Mod: { Mod(ri); } break; case Opcode::Mul: { Mul(ri); } break; case Opcode::Nop: { Nop(ri); } break; case Opcode::Or: { Or(ri); } break; case Opcode::Stm: { Stm(ri); } break; case Opcode::Str: { Str(ri); } break; case Opcode::Sub: { Sub(ri); } break; case Opcode::Undef: { Undef(ri); } break; case Opcode::Unkn: { Unkn(ri); } break; case Opcode::Xor: { Xor(ri); } break; case Opcode::Bisnz: { Bisnz(ri); } break; case Opcode::Equ: { Equ(ri); } break; case Opcode::Lshl: { Lshl(ri); } break; case Opcode::Lshr: { Lshr(ri); } break; case Opcode::Ashr: { Ashr(ri); } break; case Opcode::Sex: { Sex(ri); } break; case Opcode::Sys: { Sys(ri); } break; case Opcode::Ite: { Ite(ri); } } return offset_; } uint64_t Interpreter::Execute(NativeInstruction ni) { Start(ni); while (offset_ < instructions_.size()) { SingleStep(); } if (offset_ != 0xffff) { pc_ = ni.address + ni.size; } return pc_; } Immediate Interpreter::GetRegister(uint32_t index) const { return registers_.at(index); } void Interpreter::SetRegister(uint32_t index, Immediate value) { registers_[index] = value; } std::vector<uint8_t> Interpreter::GetMemory(uint64_t address, size_t size) { std::vector<uint8_t> bytes; for (size_t i = 0; i < size; ++i) { bytes.push_back(memory_[address + i]); } return bytes; } void Interpreter::SetMemory(uint64_t address, const std::vector<uint8_t> &bytes) { SetMemory(address, bytes.data(), bytes.size()); } void Interpreter::SetMemory(uint64_t address, const uint8_t *bytes, size_t bytes_len) { for (size_t i = 0; i < bytes_len; ++i) { memory_[address + i] = bytes[i]; } } } // namespace reil <commit_msg>Whoops, : instead of ; ran tests this time...<commit_after>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "interpreter.h" #include <cassert> #include <stdexcept> namespace reil { Interpreter::Interpreter() {} Interpreter::~Interpreter() {} Immediate Interpreter::GetOperand(const Operand &op) const { if (absl::holds_alternative<Immediate>(op)) { return absl::get<Immediate>(op); } else if (absl::holds_alternative<Register>(op)) { return registers_.at(absl::get<Register>(op).index); } else if (absl::holds_alternative<Temporary>(op)) { return temporaries_.at(absl::get<Temporary>(op).index); } else { // unreachable abort(); } } void Interpreter::SetOperand(const Operand &op, Immediate value) { if (absl::holds_alternative<Register>(op)) { registers_[absl::get<Register>(op).index] = value; } else if (absl::holds_alternative<Temporary>(op)) { temporaries_[absl::get<Temporary>(op).index] = value; } else { // unreachable abort(); } } void Interpreter::Add(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a + b); } void Interpreter::And(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a & b); } void Interpreter::Bisz(const Instruction &ri) { Immediate a = GetOperand(ri.input0); SetOperand(ri.output, Immediate(Size(ri.output), a ? 0 : 1)); } void Interpreter::Bsh(const Instruction &ri) {} void Interpreter::Div(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a / b); } void Interpreter::Jcc(const Instruction &ri) { Immediate a = GetOperand(ri.input0); if (a) { if (ri.output.index() == kOffset) { Offset target = absl::get<Offset>(ri.output); offset_ = target.offset; } else { Immediate target = GetOperand(ri.output); pc_ = static_cast<uint64_t>(target); offset_ = 0xffff; } } } void Interpreter::Ldm(const Instruction &ri) { Immediate a = GetOperand(ri.input0); uint64_t address = static_cast<uint64_t>(a); std::vector<uint8_t> bytes = GetMemory(address, Size(ri.output) / 8); SetOperand(ri.output, Immediate(bytes)); } void Interpreter::Mod(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a % b); } void Interpreter::Mul(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a * b); } void Interpreter::Nop(const Instruction &ri) {} void Interpreter::Or(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a | b); } void Interpreter::Stm(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.output); uint64_t address = static_cast<uint64_t>(b); std::vector<uint8_t> bytes = a.bytes(); SetMemory(address, bytes); } void Interpreter::Str(const Instruction &ri) { Immediate a = GetOperand(ri.input0); uint16_t result_size = Size(ri.output); if (result_size < a.size()) { SetOperand(ri.output, a.Extract(result_size)); } else if (a.size() < result_size) { SetOperand(ri.output, a.ZeroExtend(Size(ri.output))); } else { SetOperand(ri.output, a); } } void Interpreter::Sub(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a - b); } void Interpreter::Undef(const Instruction &ri) { if (absl::holds_alternative<Register>(ri.output)) { // TODO: } else if (absl::holds_alternative<Temporary>(ri.output)) { // TODO: } } void Interpreter::Unkn(const Instruction &ri) {} void Interpreter::Xor(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a ^ b); } void Interpreter::Bisnz(const Instruction &ri) { Immediate a = GetOperand(ri.input0); SetOperand(ri.output, Immediate(Size(ri.output), a ? 1 : 0)); } void Interpreter::Equ(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, Immediate(Size(ri.output), a == b ? 1 : 0)); } void Interpreter::Lshl(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a << b); } void Interpreter::Lshr(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); SetOperand(ri.output, a >> b); } void Interpreter::Ashr(const Instruction &ri) { Immediate a = GetOperand(ri.input0); Immediate b = GetOperand(ri.input1); uint16_t size = a.size(); if (Immediate::SignBit(size, size) & a) { a >>= b; a |= Immediate::Mask(size, size) << (size - (uint64_t)b); } else { a >>= b; } SetOperand(ri.output, a); } void Interpreter::Sex(const Instruction &ri) { Immediate a = GetOperand(ri.input0); uint16_t result_size = Size(ri.output); if (result_size < a.size()) { SetOperand(ri.output, a.Extract(result_size)); } else if (a.size() < result_size) { SetOperand(ri.output, a.SignExtend(Size(ri.output))); } else { SetOperand(ri.output, a); } } void Interpreter::Sys(const Instruction &ri) {} void Interpreter::Ite(const Instruction &ri) { Immediate cond = GetOperand(ri.input0); Immediate if_value = GetOperand(ri.input1); Immediate else_value = GetOperand(ri.input2); if (cond) { SetOperand(ri.output, if_value); } else { SetOperand(ri.output, else_value); } } void Interpreter::Start(NativeInstruction ni) { assert(ni.reil.size() < 0xffff); instructions_ = ni.reil; offset_ = 0; pc_ = ni.address; temporaries_.clear(); } uint16_t Interpreter::SingleStep() { const Instruction &ri = instructions_[offset_++]; switch (ri.opcode) { case Opcode::Add: { Add(ri); } break; case Opcode::And: { And(ri); } break; case Opcode::Bisz: { Bisz(ri); } break; case Opcode::Bsh: { Bsh(ri); } break; case Opcode::Div: { Div(ri); } break; case Opcode::Jcc: { Jcc(ri); } break; case Opcode::Ldm: { Ldm(ri); } break; case Opcode::Mod: { Mod(ri); } break; case Opcode::Mul: { Mul(ri); } break; case Opcode::Nop: { Nop(ri); } break; case Opcode::Or: { Or(ri); } break; case Opcode::Stm: { Stm(ri); } break; case Opcode::Str: { Str(ri); } break; case Opcode::Sub: { Sub(ri); } break; case Opcode::Undef: { Undef(ri); } break; case Opcode::Unkn: { Unkn(ri); } break; case Opcode::Xor: { Xor(ri); } break; case Opcode::Bisnz: { Bisnz(ri); } break; case Opcode::Equ: { Equ(ri); } break; case Opcode::Lshl: { Lshl(ri); } break; case Opcode::Lshr: { Lshr(ri); } break; case Opcode::Ashr: { Ashr(ri); } break; case Opcode::Sex: { Sex(ri); } break; case Opcode::Sys: { Sys(ri); } break; case Opcode::Ite: { Ite(ri); } } return offset_; } uint64_t Interpreter::Execute(NativeInstruction ni) { Start(ni); while (offset_ < instructions_.size()) { SingleStep(); } if (offset_ != 0xffff) { pc_ = ni.address + ni.size; } return pc_; } Immediate Interpreter::GetRegister(uint32_t index) const { return registers_.at(index); } void Interpreter::SetRegister(uint32_t index, Immediate value) { registers_[index] = value; } std::vector<uint8_t> Interpreter::GetMemory(uint64_t address, size_t size) { std::vector<uint8_t> bytes; for (size_t i = 0; i < size; ++i) { bytes.push_back(memory_[address + i]); } return bytes; } void Interpreter::SetMemory(uint64_t address, const std::vector<uint8_t> &bytes) { SetMemory(address, bytes.data(), bytes.size()); } void Interpreter::SetMemory(uint64_t address, const uint8_t *bytes, size_t bytes_len) { for (size_t i = 0; i < bytes_len; ++i) { memory_[address + i] = bytes[i]; } } } // namespace reil <|endoftext|>
<commit_before><commit_msg>linux: make NSS version check non-fatal<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Windows Timer Primer // // A good article: http://www.ddj.com/windows/184416651 // A good mozilla bug: http://bugzilla.mozilla.org/show_bug.cgi?id=363258 // // The default windows timer, GetSystemTimeAsFileTime is not very precise. // It is only good to ~15.5ms. // // QueryPerformanceCounter is the logical choice for a high-precision timer. // However, it is known to be buggy on some hardware. Specifically, it can // sometimes "jump". On laptops, QPC can also be very expensive to call. // It's 3-4x slower than timeGetTime() on desktops, but can be 10x slower // on laptops. A unittest exists which will show the relative cost of various // timers on any system. // // The next logical choice is timeGetTime(). timeGetTime has a precision of // 1ms, but only if you call APIs (timeBeginPeriod()) which affect all other // applications on the system. By default, precision is only 15.5ms. // Unfortunately, we don't want to call timeBeginPeriod because we don't // want to affect other applications. Further, on mobile platforms, use of // faster multimedia timers can hurt battery life. See the intel // article about this here: // http://softwarecommunity.intel.com/articles/eng/1086.htm // // To work around all this, we're going to generally use timeGetTime(). We // will only increase the system-wide timer if we're not running on battery // power. Using timeBeginPeriod(1) is a requirement in order to make our // message loop waits have the same resolution that our time measurements // do. Otherwise, WaitForSingleObject(..., 1) will no less than 15ms when // there is nothing else to waken the Wait. #include "base/time.h" #pragma comment(lib, "winmm.lib") #include <windows.h> #include <mmsystem.h> #include "base/basictypes.h" #include "base/lock.h" #include "base/logging.h" #include "base/cpu.h" #include "base/singleton.h" using base::Time; using base::TimeDelta; using base::TimeTicks; namespace { // From MSDN, FILETIME "Contains a 64-bit value representing the number of // 100-nanosecond intervals since January 1, 1601 (UTC)." int64 FileTimeToMicroseconds(const FILETIME& ft) { // Need to bit_cast to fix alignment, then divide by 10 to convert // 100-nanoseconds to milliseconds. This only works on little-endian // machines. return bit_cast<int64, FILETIME>(ft) / 10; } void MicrosecondsToFileTime(int64 us, FILETIME* ft) { DCHECK(us >= 0) << "Time is less than 0, negative values are not " "representable in FILETIME"; // Multiply by 10 to convert milliseconds to 100-nanoseconds. Bit_cast will // handle alignment problems. This only works on little-endian machines. *ft = bit_cast<FILETIME, int64>(us * 10); } int64 CurrentWallclockMicroseconds() { FILETIME ft; ::GetSystemTimeAsFileTime(&ft); return FileTimeToMicroseconds(ft); } // Time between resampling the un-granular clock for this API. 60 seconds. const int kMaxMillisecondsToAvoidDrift = 60 * Time::kMillisecondsPerSecond; int64 initial_time = 0; TimeTicks initial_ticks; void InitializeClock() { initial_ticks = TimeTicks::Now(); initial_time = CurrentWallclockMicroseconds(); } } // namespace // Time ----------------------------------------------------------------------- // The internal representation of Time uses FILETIME, whose epoch is 1601-01-01 // 00:00:00 UTC. ((1970-1601)*365+89)*24*60*60*1000*1000, where 89 is the // number of leap year days between 1601 and 1970: (1970-1601)/4 excluding // 1700, 1800, and 1900. // static const int64 Time::kTimeTToMicrosecondsOffset = GG_INT64_C(11644473600000000); bool Time::high_resolution_timer_enabled_ = false; // static Time Time::Now() { if (initial_time == 0) InitializeClock(); // We implement time using the high-resolution timers so that we can get // timeouts which are smaller than 10-15ms. If we just used // CurrentWallclockMicroseconds(), we'd have the less-granular timer. // // To make this work, we initialize the clock (initial_time) and the // counter (initial_ctr). To compute the initial time, we can check // the number of ticks that have elapsed, and compute the delta. // // To avoid any drift, we periodically resync the counters to the system // clock. while (true) { TimeTicks ticks = TimeTicks::Now(); // Calculate the time elapsed since we started our timer TimeDelta elapsed = ticks - initial_ticks; // Check if enough time has elapsed that we need to resync the clock. if (elapsed.InMilliseconds() > kMaxMillisecondsToAvoidDrift) { InitializeClock(); continue; } return Time(elapsed + Time(initial_time)); } } // static Time Time::NowFromSystemTime() { // Force resync. InitializeClock(); return Time(initial_time); } // static Time Time::FromFileTime(FILETIME ft) { return Time(FileTimeToMicroseconds(ft)); } FILETIME Time::ToFileTime() const { FILETIME utc_ft; MicrosecondsToFileTime(us_, &utc_ft); return utc_ft; } // static void Time::EnableHighResolutionTimer(bool enable) { // Test for single-threaded access. static PlatformThreadId my_thread = PlatformThread::CurrentId(); DCHECK(PlatformThread::CurrentId() == my_thread); if (high_resolution_timer_enabled_ == enable) return; high_resolution_timer_enabled_ = enable; } // static bool Time::ActivateHighResolutionTimer(bool activate) { if (!high_resolution_timer_enabled_) return false; // Using anything other than 1ms makes timers granular // to that interval. const int kMinTimerIntervalMs = 1; MMRESULT result; if (activate) result = timeBeginPeriod(kMinTimerIntervalMs); else result = timeEndPeriod(kMinTimerIntervalMs); return result == TIMERR_NOERROR; } // static Time Time::FromExploded(bool is_local, const Exploded& exploded) { // Create the system struct representing our exploded time. It will either be // in local time or UTC. SYSTEMTIME st; st.wYear = exploded.year; st.wMonth = exploded.month; st.wDayOfWeek = exploded.day_of_week; st.wDay = exploded.day_of_month; st.wHour = exploded.hour; st.wMinute = exploded.minute; st.wSecond = exploded.second; st.wMilliseconds = exploded.millisecond; // Convert to FILETIME. FILETIME ft; if (!SystemTimeToFileTime(&st, &ft)) { NOTREACHED() << "Unable to convert time"; return Time(0); } // Ensure that it's in UTC. if (is_local) { FILETIME utc_ft; LocalFileTimeToFileTime(&ft, &utc_ft); return Time(FileTimeToMicroseconds(utc_ft)); } return Time(FileTimeToMicroseconds(ft)); } void Time::Explode(bool is_local, Exploded* exploded) const { // FILETIME in UTC. FILETIME utc_ft; MicrosecondsToFileTime(us_, &utc_ft); // FILETIME in local time if necessary. BOOL success = TRUE; FILETIME ft; if (is_local) success = FileTimeToLocalFileTime(&utc_ft, &ft); else ft = utc_ft; // FILETIME in SYSTEMTIME (exploded). SYSTEMTIME st; if (!success || !FileTimeToSystemTime(&ft, &st)) { NOTREACHED() << "Unable to convert time, don't know why"; ZeroMemory(exploded, sizeof(exploded)); return; } exploded->year = st.wYear; exploded->month = st.wMonth; exploded->day_of_week = st.wDayOfWeek; exploded->day_of_month = st.wDay; exploded->hour = st.wHour; exploded->minute = st.wMinute; exploded->second = st.wSecond; exploded->millisecond = st.wMilliseconds; } // TimeTicks ------------------------------------------------------------------ namespace { // We define a wrapper to adapt between the __stdcall and __cdecl call of the // mock function, and to avoid a static constructor. Assigning an import to a // function pointer directly would require setup code to fetch from the IAT. DWORD timeGetTimeWrapper() { return timeGetTime(); } DWORD (*tick_function)(void) = &timeGetTimeWrapper; // Accumulation of time lost due to rollover (in milliseconds). int64 rollover_ms = 0; // The last timeGetTime value we saw, to detect rollover. DWORD last_seen_now = 0; // Lock protecting rollover_ms and last_seen_now. // Note: this is a global object, and we usually avoid these. However, the time // code is low-level, and we don't want to use Singletons here (it would be too // easy to use a Singleton without even knowing it, and that may lead to many // gotchas). Its impact on startup time should be negligible due to low-level // nature of time code. Lock rollover_lock; // We use timeGetTime() to implement TimeTicks::Now(). This can be problematic // because it returns the number of milliseconds since Windows has started, // which will roll over the 32-bit value every ~49 days. We try to track // rollover ourselves, which works if TimeTicks::Now() is called at least every // 49 days. TimeDelta RolloverProtectedNow() { AutoLock locked(rollover_lock); // We should hold the lock while calling tick_function to make sure that // we keep last_seen_now stay correctly in sync. DWORD now = tick_function(); if (now < last_seen_now) rollover_ms += 0x100000000I64; // ~49.7 days. last_seen_now = now; return TimeDelta::FromMilliseconds(now + rollover_ms); } // Overview of time counters: // (1) CPU cycle counter. (Retrieved via RDTSC) // The CPU counter provides the highest resolution time stamp and is the least // expensive to retrieve. However, the CPU counter is unreliable and should not // be used in production. Its biggest issue is that it is per processor and it // is not synchronized between processors. Also, on some computers, the counters // will change frequency due to thermal and power changes, and stop in some // states. // // (2) QueryPerformanceCounter (QPC). The QPC counter provides a high- // resolution (100 nanoseconds) time stamp but is comparatively more expensive // to retrieve. What QueryPerformanceCounter actually does is up to the HAL. // (with some help from ACPI). // According to http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx // in the worst case, it gets the counter from the rollover interrupt on the // programmable interrupt timer. In best cases, the HAL may conclude that the // RDTSC counter runs at a constant frequency, then it uses that instead. On // multiprocessor machines, it will try to verify the values returned from // RDTSC on each processor are consistent with each other, and apply a handful // of workarounds for known buggy hardware. In other words, QPC is supposed to // give consistent result on a multiprocessor computer, but it is unreliable in // reality due to bugs in BIOS or HAL on some, especially old computers. // With recent updates on HAL and newer BIOS, QPC is getting more reliable but // it should be used with caution. // // (3) System time. The system time provides a low-resolution (typically 10ms // to 55 milliseconds) time stamp but is comparatively less expensive to // retrieve and more reliable. class HighResNowSingleton { public: HighResNowSingleton() : ticks_per_microsecond_(0.0), skew_(0) { InitializeClock(); // On Athlon X2 CPUs (e.g. model 15) QueryPerformanceCounter is // unreliable. Fallback to low-res clock. base::CPU cpu; if (cpu.vendor_name() == "AuthenticAMD" && cpu.family() == 15) DisableHighResClock(); } bool IsUsingHighResClock() { return ticks_per_microsecond_ != 0.0; } void DisableHighResClock() { ticks_per_microsecond_ = 0.0; } TimeDelta Now() { // Our maximum tolerance for QPC drifting. const int kMaxTimeDrift = 50 * Time::kMicrosecondsPerMillisecond; if (IsUsingHighResClock()) { int64 now = UnreliableNow(); // Verify that QPC does not seem to drift. DCHECK(now - ReliableNow() - skew_ < kMaxTimeDrift); return TimeDelta::FromMicroseconds(now); } // Just fallback to the slower clock. return RolloverProtectedNow(); } private: // Synchronize the QPC clock with GetSystemTimeAsFileTime. void InitializeClock() { LARGE_INTEGER ticks_per_sec = {0}; if (!QueryPerformanceFrequency(&ticks_per_sec)) return; // Broken, we don't guarantee this function works. ticks_per_microsecond_ = static_cast<float>(ticks_per_sec.QuadPart) / static_cast<float>(Time::kMicrosecondsPerSecond); skew_ = UnreliableNow() - ReliableNow(); } // Get the number of microseconds since boot in an unreliable fashion. int64 UnreliableNow() { LARGE_INTEGER now; QueryPerformanceCounter(&now); return static_cast<int64>(now.QuadPart / ticks_per_microsecond_); } // Get the number of microseconds since boot in a reliable fashion. int64 ReliableNow() { return RolloverProtectedNow().InMicroseconds(); } // Cached clock frequency -> microseconds. This assumes that the clock // frequency is faster than one microsecond (which is 1MHz, should be OK). float ticks_per_microsecond_; // 0 indicates QPF failed and we're broken. int64 skew_; // Skew between lo-res and hi-res clocks (for debugging). DISALLOW_COPY_AND_ASSIGN(HighResNowSingleton); }; } // namespace // static TimeTicks::TickFunctionType TimeTicks::SetMockTickFunction( TickFunctionType ticker) { TickFunctionType old = tick_function; tick_function = ticker; return old; } // static TimeTicks TimeTicks::Now() { return TimeTicks() + RolloverProtectedNow(); } // static TimeTicks TimeTicks::HighResNow() { return TimeTicks() + Singleton<HighResNowSingleton>::get()->Now(); } <commit_msg>Change a DCHECK to a DCHECK_LT so we can see the failing values.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Windows Timer Primer // // A good article: http://www.ddj.com/windows/184416651 // A good mozilla bug: http://bugzilla.mozilla.org/show_bug.cgi?id=363258 // // The default windows timer, GetSystemTimeAsFileTime is not very precise. // It is only good to ~15.5ms. // // QueryPerformanceCounter is the logical choice for a high-precision timer. // However, it is known to be buggy on some hardware. Specifically, it can // sometimes "jump". On laptops, QPC can also be very expensive to call. // It's 3-4x slower than timeGetTime() on desktops, but can be 10x slower // on laptops. A unittest exists which will show the relative cost of various // timers on any system. // // The next logical choice is timeGetTime(). timeGetTime has a precision of // 1ms, but only if you call APIs (timeBeginPeriod()) which affect all other // applications on the system. By default, precision is only 15.5ms. // Unfortunately, we don't want to call timeBeginPeriod because we don't // want to affect other applications. Further, on mobile platforms, use of // faster multimedia timers can hurt battery life. See the intel // article about this here: // http://softwarecommunity.intel.com/articles/eng/1086.htm // // To work around all this, we're going to generally use timeGetTime(). We // will only increase the system-wide timer if we're not running on battery // power. Using timeBeginPeriod(1) is a requirement in order to make our // message loop waits have the same resolution that our time measurements // do. Otherwise, WaitForSingleObject(..., 1) will no less than 15ms when // there is nothing else to waken the Wait. #include "base/time.h" #pragma comment(lib, "winmm.lib") #include <windows.h> #include <mmsystem.h> #include "base/basictypes.h" #include "base/lock.h" #include "base/logging.h" #include "base/cpu.h" #include "base/singleton.h" using base::Time; using base::TimeDelta; using base::TimeTicks; namespace { // From MSDN, FILETIME "Contains a 64-bit value representing the number of // 100-nanosecond intervals since January 1, 1601 (UTC)." int64 FileTimeToMicroseconds(const FILETIME& ft) { // Need to bit_cast to fix alignment, then divide by 10 to convert // 100-nanoseconds to milliseconds. This only works on little-endian // machines. return bit_cast<int64, FILETIME>(ft) / 10; } void MicrosecondsToFileTime(int64 us, FILETIME* ft) { DCHECK(us >= 0) << "Time is less than 0, negative values are not " "representable in FILETIME"; // Multiply by 10 to convert milliseconds to 100-nanoseconds. Bit_cast will // handle alignment problems. This only works on little-endian machines. *ft = bit_cast<FILETIME, int64>(us * 10); } int64 CurrentWallclockMicroseconds() { FILETIME ft; ::GetSystemTimeAsFileTime(&ft); return FileTimeToMicroseconds(ft); } // Time between resampling the un-granular clock for this API. 60 seconds. const int kMaxMillisecondsToAvoidDrift = 60 * Time::kMillisecondsPerSecond; int64 initial_time = 0; TimeTicks initial_ticks; void InitializeClock() { initial_ticks = TimeTicks::Now(); initial_time = CurrentWallclockMicroseconds(); } } // namespace // Time ----------------------------------------------------------------------- // The internal representation of Time uses FILETIME, whose epoch is 1601-01-01 // 00:00:00 UTC. ((1970-1601)*365+89)*24*60*60*1000*1000, where 89 is the // number of leap year days between 1601 and 1970: (1970-1601)/4 excluding // 1700, 1800, and 1900. // static const int64 Time::kTimeTToMicrosecondsOffset = GG_INT64_C(11644473600000000); bool Time::high_resolution_timer_enabled_ = false; // static Time Time::Now() { if (initial_time == 0) InitializeClock(); // We implement time using the high-resolution timers so that we can get // timeouts which are smaller than 10-15ms. If we just used // CurrentWallclockMicroseconds(), we'd have the less-granular timer. // // To make this work, we initialize the clock (initial_time) and the // counter (initial_ctr). To compute the initial time, we can check // the number of ticks that have elapsed, and compute the delta. // // To avoid any drift, we periodically resync the counters to the system // clock. while (true) { TimeTicks ticks = TimeTicks::Now(); // Calculate the time elapsed since we started our timer TimeDelta elapsed = ticks - initial_ticks; // Check if enough time has elapsed that we need to resync the clock. if (elapsed.InMilliseconds() > kMaxMillisecondsToAvoidDrift) { InitializeClock(); continue; } return Time(elapsed + Time(initial_time)); } } // static Time Time::NowFromSystemTime() { // Force resync. InitializeClock(); return Time(initial_time); } // static Time Time::FromFileTime(FILETIME ft) { return Time(FileTimeToMicroseconds(ft)); } FILETIME Time::ToFileTime() const { FILETIME utc_ft; MicrosecondsToFileTime(us_, &utc_ft); return utc_ft; } // static void Time::EnableHighResolutionTimer(bool enable) { // Test for single-threaded access. static PlatformThreadId my_thread = PlatformThread::CurrentId(); DCHECK(PlatformThread::CurrentId() == my_thread); if (high_resolution_timer_enabled_ == enable) return; high_resolution_timer_enabled_ = enable; } // static bool Time::ActivateHighResolutionTimer(bool activate) { if (!high_resolution_timer_enabled_) return false; // Using anything other than 1ms makes timers granular // to that interval. const int kMinTimerIntervalMs = 1; MMRESULT result; if (activate) result = timeBeginPeriod(kMinTimerIntervalMs); else result = timeEndPeriod(kMinTimerIntervalMs); return result == TIMERR_NOERROR; } // static Time Time::FromExploded(bool is_local, const Exploded& exploded) { // Create the system struct representing our exploded time. It will either be // in local time or UTC. SYSTEMTIME st; st.wYear = exploded.year; st.wMonth = exploded.month; st.wDayOfWeek = exploded.day_of_week; st.wDay = exploded.day_of_month; st.wHour = exploded.hour; st.wMinute = exploded.minute; st.wSecond = exploded.second; st.wMilliseconds = exploded.millisecond; // Convert to FILETIME. FILETIME ft; if (!SystemTimeToFileTime(&st, &ft)) { NOTREACHED() << "Unable to convert time"; return Time(0); } // Ensure that it's in UTC. if (is_local) { FILETIME utc_ft; LocalFileTimeToFileTime(&ft, &utc_ft); return Time(FileTimeToMicroseconds(utc_ft)); } return Time(FileTimeToMicroseconds(ft)); } void Time::Explode(bool is_local, Exploded* exploded) const { // FILETIME in UTC. FILETIME utc_ft; MicrosecondsToFileTime(us_, &utc_ft); // FILETIME in local time if necessary. BOOL success = TRUE; FILETIME ft; if (is_local) success = FileTimeToLocalFileTime(&utc_ft, &ft); else ft = utc_ft; // FILETIME in SYSTEMTIME (exploded). SYSTEMTIME st; if (!success || !FileTimeToSystemTime(&ft, &st)) { NOTREACHED() << "Unable to convert time, don't know why"; ZeroMemory(exploded, sizeof(exploded)); return; } exploded->year = st.wYear; exploded->month = st.wMonth; exploded->day_of_week = st.wDayOfWeek; exploded->day_of_month = st.wDay; exploded->hour = st.wHour; exploded->minute = st.wMinute; exploded->second = st.wSecond; exploded->millisecond = st.wMilliseconds; } // TimeTicks ------------------------------------------------------------------ namespace { // We define a wrapper to adapt between the __stdcall and __cdecl call of the // mock function, and to avoid a static constructor. Assigning an import to a // function pointer directly would require setup code to fetch from the IAT. DWORD timeGetTimeWrapper() { return timeGetTime(); } DWORD (*tick_function)(void) = &timeGetTimeWrapper; // Accumulation of time lost due to rollover (in milliseconds). int64 rollover_ms = 0; // The last timeGetTime value we saw, to detect rollover. DWORD last_seen_now = 0; // Lock protecting rollover_ms and last_seen_now. // Note: this is a global object, and we usually avoid these. However, the time // code is low-level, and we don't want to use Singletons here (it would be too // easy to use a Singleton without even knowing it, and that may lead to many // gotchas). Its impact on startup time should be negligible due to low-level // nature of time code. Lock rollover_lock; // We use timeGetTime() to implement TimeTicks::Now(). This can be problematic // because it returns the number of milliseconds since Windows has started, // which will roll over the 32-bit value every ~49 days. We try to track // rollover ourselves, which works if TimeTicks::Now() is called at least every // 49 days. TimeDelta RolloverProtectedNow() { AutoLock locked(rollover_lock); // We should hold the lock while calling tick_function to make sure that // we keep last_seen_now stay correctly in sync. DWORD now = tick_function(); if (now < last_seen_now) rollover_ms += 0x100000000I64; // ~49.7 days. last_seen_now = now; return TimeDelta::FromMilliseconds(now + rollover_ms); } // Overview of time counters: // (1) CPU cycle counter. (Retrieved via RDTSC) // The CPU counter provides the highest resolution time stamp and is the least // expensive to retrieve. However, the CPU counter is unreliable and should not // be used in production. Its biggest issue is that it is per processor and it // is not synchronized between processors. Also, on some computers, the counters // will change frequency due to thermal and power changes, and stop in some // states. // // (2) QueryPerformanceCounter (QPC). The QPC counter provides a high- // resolution (100 nanoseconds) time stamp but is comparatively more expensive // to retrieve. What QueryPerformanceCounter actually does is up to the HAL. // (with some help from ACPI). // According to http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx // in the worst case, it gets the counter from the rollover interrupt on the // programmable interrupt timer. In best cases, the HAL may conclude that the // RDTSC counter runs at a constant frequency, then it uses that instead. On // multiprocessor machines, it will try to verify the values returned from // RDTSC on each processor are consistent with each other, and apply a handful // of workarounds for known buggy hardware. In other words, QPC is supposed to // give consistent result on a multiprocessor computer, but it is unreliable in // reality due to bugs in BIOS or HAL on some, especially old computers. // With recent updates on HAL and newer BIOS, QPC is getting more reliable but // it should be used with caution. // // (3) System time. The system time provides a low-resolution (typically 10ms // to 55 milliseconds) time stamp but is comparatively less expensive to // retrieve and more reliable. class HighResNowSingleton { public: HighResNowSingleton() : ticks_per_microsecond_(0.0), skew_(0) { InitializeClock(); // On Athlon X2 CPUs (e.g. model 15) QueryPerformanceCounter is // unreliable. Fallback to low-res clock. base::CPU cpu; if (cpu.vendor_name() == "AuthenticAMD" && cpu.family() == 15) DisableHighResClock(); } bool IsUsingHighResClock() { return ticks_per_microsecond_ != 0.0; } void DisableHighResClock() { ticks_per_microsecond_ = 0.0; } TimeDelta Now() { // Our maximum tolerance for QPC drifting. const int kMaxTimeDrift = 50 * Time::kMicrosecondsPerMillisecond; if (IsUsingHighResClock()) { int64 now = UnreliableNow(); // Verify that QPC does not seem to drift. DCHECK_LT(now - ReliableNow() - skew_, kMaxTimeDrift); return TimeDelta::FromMicroseconds(now); } // Just fallback to the slower clock. return RolloverProtectedNow(); } private: // Synchronize the QPC clock with GetSystemTimeAsFileTime. void InitializeClock() { LARGE_INTEGER ticks_per_sec = {0}; if (!QueryPerformanceFrequency(&ticks_per_sec)) return; // Broken, we don't guarantee this function works. ticks_per_microsecond_ = static_cast<float>(ticks_per_sec.QuadPart) / static_cast<float>(Time::kMicrosecondsPerSecond); skew_ = UnreliableNow() - ReliableNow(); } // Get the number of microseconds since boot in an unreliable fashion. int64 UnreliableNow() { LARGE_INTEGER now; QueryPerformanceCounter(&now); return static_cast<int64>(now.QuadPart / ticks_per_microsecond_); } // Get the number of microseconds since boot in a reliable fashion. int64 ReliableNow() { return RolloverProtectedNow().InMicroseconds(); } // Cached clock frequency -> microseconds. This assumes that the clock // frequency is faster than one microsecond (which is 1MHz, should be OK). float ticks_per_microsecond_; // 0 indicates QPF failed and we're broken. int64 skew_; // Skew between lo-res and hi-res clocks (for debugging). DISALLOW_COPY_AND_ASSIGN(HighResNowSingleton); }; } // namespace // static TimeTicks::TickFunctionType TimeTicks::SetMockTickFunction( TickFunctionType ticker) { TickFunctionType old = tick_function; tick_function = ticker; return old; } // static TimeTicks TimeTicks::Now() { return TimeTicks() + RolloverProtectedNow(); } // static TimeTicks TimeTicks::HighResNow() { return TimeTicks() + Singleton<HighResNowSingleton>::get()->Now(); } <|endoftext|>
<commit_before>#ifndef MS_RTC_RTP_STREAM_HPP #define MS_RTC_RTP_STREAM_HPP #include "common.hpp" #include "json.hpp" #include "RTC/RTCP/FeedbackPsFir.hpp" #include "RTC/RTCP/FeedbackPsPli.hpp" #include "RTC/RTCP/FeedbackRtp.hpp" #include "RTC/RTCP/FeedbackRtpNack.hpp" #include "RTC/RTCP/Packet.hpp" #include "RTC/RTCP/ReceiverReport.hpp" #include "RTC/RTCP/Sdes.hpp" #include "RTC/RTCP/SenderReport.hpp" #include "RTC/RtpDictionaries.hpp" #include "RTC/RtpPacket.hpp" #include <string> #include <vector> using json = nlohmann::json; namespace RTC { class RtpStream { protected: class Listener { public: virtual void OnRtpStreamScore(RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) = 0; }; public: struct Params { void FillJson(json& jsonObject) const; uint32_t ssrc{ 0 }; uint8_t payloadType{ 0 }; RTC::RtpCodecMimeType mimeType; uint32_t clockRate{ 0 }; std::string rid; std::string cname; uint32_t rtxSsrc{ 0 }; uint8_t rtxPayloadType{ 0 }; bool useNack{ false }; bool usePli{ false }; bool useFir{ false }; bool useInBandFec{ false }; bool useDtx{ false }; uint8_t spatialLayers{ 0 }; uint8_t temporalLayers{ 0 }; }; public: RtpStream(RTC::RtpStream::Listener* listener, RTC::RtpStream::Params& params, uint8_t initialScore); virtual ~RtpStream(); void FillJson(json& jsonObject) const; virtual void FillJsonStats(json& jsonObject); uint32_t GetSsrc() const; uint8_t GetPayloadType() const; const RTC::RtpCodecMimeType& GetMimeType() const; uint32_t GetClockRate() const; const std::string& GetRid() const; const std::string& GetCname() const; bool HasRtx() const; virtual void SetRtx(uint8_t payloadType, uint32_t ssrc); uint32_t GetRtxSsrc() const; uint8_t GetRtxPayloadType() const; uint8_t GetSpatialLayers() const; uint8_t GetTemporalLayers() const; virtual bool ReceivePacket(RTC::RtpPacket* packet); virtual void Pause() = 0; virtual void Resume() = 0; virtual uint32_t GetBitrate(uint64_t now) = 0; virtual uint32_t GetBitrate(uint64_t now, uint8_t spatialLayer, uint8_t temporalLayer) = 0; virtual uint32_t GetLayerBitrate(uint64_t now, uint8_t spatialLayer, uint8_t temporalLayer) = 0; void ResetScore(uint8_t score, bool notify); uint8_t GetFractionLost() const; float GetLossPercentage() const; uint64_t GetMaxPacketMs() const; uint8_t GetScore() const; protected: bool UpdateSeq(RTC::RtpPacket* packet); void UpdateScore(uint8_t score); void PacketRetransmitted(RTC::RtpPacket* packet); void PacketRepaired(RTC::RtpPacket* packet); uint32_t GetExpectedPackets(); private: void InitSeq(uint16_t seq); protected: // Given as argument. RTC::RtpStream::Listener* listener{ nullptr }; Params params; // Others. // https://tools.ietf.org/html/rfc3550#appendix-A.1 stuff. uint16_t maxSeq{ 0 }; // Highest seq. number seen. uint32_t cycles{ 0 }; // Shifted count of seq. number cycles. uint32_t baseSeq{ 0 }; // Base seq number. uint32_t badSeq{ 0 }; // Last 'bad' seq number + 1. uint32_t maxPacketTs{ 0 }; // Highest timestamp seen. uint64_t maxPacketMs{ 0 }; // When the packet with highest timestammp was seen. uint32_t packetsLost{ 0 }; uint8_t fractionLost{ 0 }; size_t packetsDiscarded{ 0 }; size_t packetsRetransmitted{ 0 }; size_t packetsRepaired{ 0 }; size_t nackCount{ 0 }; size_t nackPacketCount{ 0 }; size_t pliCount{ 0 }; size_t firCount{ 0 }; size_t repairedPrior{ 0 }; // Packets repaired at last interval. size_t retransmittedPrior{ 0 }; // Packets retransmitted at last interval. uint32_t expectedPrior{ 0 }; // Packets expected at last interval. private: // Score related. uint8_t score{ 0 }; std::vector<uint8_t> scores; // RTP stream data information for score calculation. int32_t totalSourceLoss{ 0 }; int32_t totalReportedLoss{ 0 }; size_t totalSentPackets{ 0 }; // Whether at least a RTP packet has been received. bool started{ false }; }; // namespace RTC /* Inline instance methods. */ inline uint32_t RtpStream::GetSsrc() const { return this->params.ssrc; } inline uint8_t RtpStream::GetPayloadType() const { return this->params.payloadType; } inline const RTC::RtpCodecMimeType& RtpStream::GetMimeType() const { return this->params.mimeType; } inline uint32_t RtpStream::GetClockRate() const { return this->params.clockRate; } inline const std::string& RtpStream::GetRid() const { return this->params.rid; } inline const std::string& RtpStream::GetCname() const { return this->params.cname; } inline bool RtpStream::HasRtx() const { return this->params.rtxSsrc != 0; } inline void RtpStream::SetRtx(uint8_t payloadType, uint32_t ssrc) { this->params.rtxPayloadType = payloadType; this->params.rtxSsrc = ssrc; } inline uint32_t RtpStream::GetRtxSsrc() const { return this->params.rtxSsrc; } inline uint8_t RtpStream::GetRtxPayloadType() const { return this->params.rtxPayloadType; } inline uint8_t RtpStream::GetSpatialLayers() const { return this->params.spatialLayers; } inline uint8_t RtpStream::GetTemporalLayers() const { return this->params.temporalLayers; } inline uint8_t RtpStream::GetFractionLost() const { return this->fractionLost; } inline float RtpStream::GetLossPercentage() const { return static_cast<float>(this->fractionLost) * 100 / 256; } inline uint64_t RtpStream::GetMaxPacketMs() const { return this->maxPacketMs; } inline uint32_t RtpStream::GetExpectedPackets() { return (this->cycles + this->maxSeq) - this->baseSeq + 1; } inline uint8_t RtpStream::GetScore() const { return this->score; } } // namespace RTC #endif <commit_msg>RtpStream: by default assume spatialLayers and temporalLayers are 1 instead of 0<commit_after>#ifndef MS_RTC_RTP_STREAM_HPP #define MS_RTC_RTP_STREAM_HPP #include "common.hpp" #include "json.hpp" #include "RTC/RTCP/FeedbackPsFir.hpp" #include "RTC/RTCP/FeedbackPsPli.hpp" #include "RTC/RTCP/FeedbackRtp.hpp" #include "RTC/RTCP/FeedbackRtpNack.hpp" #include "RTC/RTCP/Packet.hpp" #include "RTC/RTCP/ReceiverReport.hpp" #include "RTC/RTCP/Sdes.hpp" #include "RTC/RTCP/SenderReport.hpp" #include "RTC/RtpDictionaries.hpp" #include "RTC/RtpPacket.hpp" #include <string> #include <vector> using json = nlohmann::json; namespace RTC { class RtpStream { protected: class Listener { public: virtual void OnRtpStreamScore(RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) = 0; }; public: struct Params { void FillJson(json& jsonObject) const; uint32_t ssrc{ 0 }; uint8_t payloadType{ 0 }; RTC::RtpCodecMimeType mimeType; uint32_t clockRate{ 0 }; std::string rid; std::string cname; uint32_t rtxSsrc{ 0 }; uint8_t rtxPayloadType{ 0 }; bool useNack{ false }; bool usePli{ false }; bool useFir{ false }; bool useInBandFec{ false }; bool useDtx{ false }; uint8_t spatialLayers{ 1 }; uint8_t temporalLayers{ 1 }; }; public: RtpStream(RTC::RtpStream::Listener* listener, RTC::RtpStream::Params& params, uint8_t initialScore); virtual ~RtpStream(); void FillJson(json& jsonObject) const; virtual void FillJsonStats(json& jsonObject); uint32_t GetSsrc() const; uint8_t GetPayloadType() const; const RTC::RtpCodecMimeType& GetMimeType() const; uint32_t GetClockRate() const; const std::string& GetRid() const; const std::string& GetCname() const; bool HasRtx() const; virtual void SetRtx(uint8_t payloadType, uint32_t ssrc); uint32_t GetRtxSsrc() const; uint8_t GetRtxPayloadType() const; uint8_t GetSpatialLayers() const; uint8_t GetTemporalLayers() const; virtual bool ReceivePacket(RTC::RtpPacket* packet); virtual void Pause() = 0; virtual void Resume() = 0; virtual uint32_t GetBitrate(uint64_t now) = 0; virtual uint32_t GetBitrate(uint64_t now, uint8_t spatialLayer, uint8_t temporalLayer) = 0; virtual uint32_t GetLayerBitrate(uint64_t now, uint8_t spatialLayer, uint8_t temporalLayer) = 0; void ResetScore(uint8_t score, bool notify); uint8_t GetFractionLost() const; float GetLossPercentage() const; uint64_t GetMaxPacketMs() const; uint8_t GetScore() const; protected: bool UpdateSeq(RTC::RtpPacket* packet); void UpdateScore(uint8_t score); void PacketRetransmitted(RTC::RtpPacket* packet); void PacketRepaired(RTC::RtpPacket* packet); uint32_t GetExpectedPackets(); private: void InitSeq(uint16_t seq); protected: // Given as argument. RTC::RtpStream::Listener* listener{ nullptr }; Params params; // Others. // https://tools.ietf.org/html/rfc3550#appendix-A.1 stuff. uint16_t maxSeq{ 0 }; // Highest seq. number seen. uint32_t cycles{ 0 }; // Shifted count of seq. number cycles. uint32_t baseSeq{ 0 }; // Base seq number. uint32_t badSeq{ 0 }; // Last 'bad' seq number + 1. uint32_t maxPacketTs{ 0 }; // Highest timestamp seen. uint64_t maxPacketMs{ 0 }; // When the packet with highest timestammp was seen. uint32_t packetsLost{ 0 }; uint8_t fractionLost{ 0 }; size_t packetsDiscarded{ 0 }; size_t packetsRetransmitted{ 0 }; size_t packetsRepaired{ 0 }; size_t nackCount{ 0 }; size_t nackPacketCount{ 0 }; size_t pliCount{ 0 }; size_t firCount{ 0 }; size_t repairedPrior{ 0 }; // Packets repaired at last interval. size_t retransmittedPrior{ 0 }; // Packets retransmitted at last interval. uint32_t expectedPrior{ 0 }; // Packets expected at last interval. private: // Score related. uint8_t score{ 0 }; std::vector<uint8_t> scores; // RTP stream data information for score calculation. int32_t totalSourceLoss{ 0 }; int32_t totalReportedLoss{ 0 }; size_t totalSentPackets{ 0 }; // Whether at least a RTP packet has been received. bool started{ false }; }; // namespace RTC /* Inline instance methods. */ inline uint32_t RtpStream::GetSsrc() const { return this->params.ssrc; } inline uint8_t RtpStream::GetPayloadType() const { return this->params.payloadType; } inline const RTC::RtpCodecMimeType& RtpStream::GetMimeType() const { return this->params.mimeType; } inline uint32_t RtpStream::GetClockRate() const { return this->params.clockRate; } inline const std::string& RtpStream::GetRid() const { return this->params.rid; } inline const std::string& RtpStream::GetCname() const { return this->params.cname; } inline bool RtpStream::HasRtx() const { return this->params.rtxSsrc != 0; } inline void RtpStream::SetRtx(uint8_t payloadType, uint32_t ssrc) { this->params.rtxPayloadType = payloadType; this->params.rtxSsrc = ssrc; } inline uint32_t RtpStream::GetRtxSsrc() const { return this->params.rtxSsrc; } inline uint8_t RtpStream::GetRtxPayloadType() const { return this->params.rtxPayloadType; } inline uint8_t RtpStream::GetSpatialLayers() const { return this->params.spatialLayers; } inline uint8_t RtpStream::GetTemporalLayers() const { return this->params.temporalLayers; } inline uint8_t RtpStream::GetFractionLost() const { return this->fractionLost; } inline float RtpStream::GetLossPercentage() const { return static_cast<float>(this->fractionLost) * 100 / 256; } inline uint64_t RtpStream::GetMaxPacketMs() const { return this->maxPacketMs; } inline uint32_t RtpStream::GetExpectedPackets() { return (this->cycles + this->maxSeq) - this->baseSeq + 1; } inline uint8_t RtpStream::GetScore() const { return this->score; } } // namespace RTC #endif <|endoftext|>
<commit_before>#include "rudp/rudp_send_buffer.h" #include "revolver/base_timer_value.h" #include "rudp/rudp_log_macro.h" #include "rudp/rudp_ccc.h" #include <math.h> BASE_NAMESPACE_BEGIN_DECL #define DEFAULT_RUDP_SEND_BUFFSIZE 4096 #define NAGLE_DELAY 100 RUDPSendBuffer::RUDPSendBuffer() : net_channel_(NULL) , buffer_seq_(0) , dest_max_seq_(0) , cwnd_max_seq_(0) , max_loss_seq_(0) , buffer_size_(DEFAULT_RUDP_SEND_BUFFSIZE) , buffer_data_size_(0) , nagle_(false) , send_ts_(0) , ccc_(NULL) { reset(); } RUDPSendBuffer::~RUDPSendBuffer() { reset(); } void RUDPSendBuffer::reset() { buffer_seq_ = rand() + 1; dest_max_seq_ = buffer_seq_ - 1; cwnd_max_seq_ = buffer_seq_; max_loss_seq_ = buffer_seq_; buffer_data_size_ = 0; buffer_size_ = DEFAULT_RUDP_SEND_BUFFSIZE; nagle_ = false; send_ts_ = CBaseTimeValue::get_time_value().msec(); loss_set_.clear(); for(SendWindowMap::iterator it = send_window_.begin(); it != send_window_.end(); ++ it) RETURN_SEND_SEG(it->second); send_window_.clear(); for(SendDataList::iterator it = send_data_.begin(); it != send_data_.end(); ++ it) RETURN_SEND_SEG(*it); send_data_.clear(); bandwidth_ = 0; bandwidth_ts_ = CBaseTimeValue::get_time_value().msec(); } int32_t RUDPSendBuffer::send(const uint8_t* data, int32_t data_size) { int32_t copy_pos = 0; int32_t copy_size = 0; uint8_t* pos = (uint8_t *)data; uint64_t now_timer = CBaseTimeValue::get_time_value().msec(); if(!send_data_.empty()) //ճ { RUDPSendSegment* last_seg = send_data_.back(); if(last_seg != NULL && last_seg->data_size_ < MAX_SEGMENT_SIZE) { copy_size = MAX_SEGMENT_SIZE - last_seg->data_size_; if( copy_size > data_size) copy_size = data_size; memcpy(last_seg->data_ + last_seg->data_size_, pos, copy_size); copy_pos += copy_size; pos += copy_size; last_seg->data_size_ += copy_size; } } //Ƭ while(copy_pos < data_size) { GAIN_SEND_SEG(last_seg); //óʼĵʱ last_seg->push_ts_ = now_timer; last_seg->seq_ = buffer_seq_; buffer_seq_ ++; //RUDP_SEND_DEBUG("put packet, seq = " << buffer_seq_); //ȷĿ鳤 copy_size = (data_size - copy_pos); if(copy_size > MAX_SEGMENT_SIZE) copy_size = MAX_SEGMENT_SIZE; memcpy(last_seg->data_, pos, copy_size); copy_pos += copy_size; pos += copy_size; last_seg->data_size_ = copy_size; send_data_.push_back(last_seg); if (buffer_data_size_ + copy_pos > buffer_size_) break; } buffer_data_size_ += copy_pos; //Է, //if(!nagle_) attempt_send(now_timer); return copy_pos; } void RUDPSendBuffer::on_ack(uint64_t seq) { //ID if(cwnd_max_seq_ < seq) return; if(!send_window_.empty()) { //ɾڵƬ SendWindowMap::iterator it = send_window_.begin(); while(it != send_window_.end() && it->first <= seq) { //ݻĴС if(buffer_data_size_ > it->second->data_size_) buffer_data_size_ = buffer_data_size_ - it->second->data_size_; else buffer_data_size_ = 0; bandwidth_ += it->second->data_size_; RETURN_SEND_SEG(it->second); send_window_.erase(it); it = send_window_.begin(); ccc_->add_recv(1); } if(send_window_.size() == 1){ it = send_window_.begin(); net_channel_->send_data(0, it->second->seq_, it->second->data_, it->second->data_size_, now_timer); it->second->last_send_ts_ = now_timer; it->second->send_count_++; ccc_->add_resend(); } } if (dest_max_seq_ < seq) dest_max_seq_ = seq; check_buffer(); //Է /*attempt_send(CBaseTimeValue::get_time_value().msec());*/ } void RUDPSendBuffer::on_nack(uint64_t base_seq, const LossIDArray& loss_ids) { uint64_t now_timer = CBaseTimeValue::get_time_value().msec(); SendWindowMap::iterator it; uint64_t seq = base_seq; uint32_t sz = loss_ids.size(); for (size_t i = 0; i < sz; ++i){ /*óط*/ seq = loss_ids[i] + base_seq; it = send_window_.find(seq); if (it != send_window_.end()){ net_channel_->send_data(0, it->second->seq_, it->second->data_, it->second->data_size_, now_timer); it->second->last_send_ts_ = now_timer; it->second->send_count_++; ccc_->add_resend(); } } if (loss_ids.size() > 0) ccc_->on_loss(base_seq, loss_ids); on_ack(base_seq); } void RUDPSendBuffer::on_timer(uint64_t now_timer) { attempt_send(now_timer); check_buffer(); } void RUDPSendBuffer::check_buffer() { buffer_size_ = core_max(buffer_size_, (ccc_->get_send_window_size() * MAX_SEGMENT_SIZE)); //Ƿд if(buffer_data_size_ < buffer_size_ && net_channel_ != NULL) net_channel_->on_write(); } //CCCӿ void RUDPSendBuffer::clear_loss() { loss_set_.clear(); } uint32_t RUDPSendBuffer::get_threshold(uint32_t rtt) { uint32_t rtt_threshold = 10; uint32_t var_rtt = core_max(ccc_->get_rtt_var(), rtt / 16); if (rtt < 10) rtt_threshold = 10; else rtt_threshold = rtt + var_rtt; if(rtt < 80) rtt_threshold = rtt + var_rtt + 3; else if (rtt < 100) rtt_threshold = rtt + var_rtt + 10; else rtt_threshold = rtt + var_rtt; return rtt_threshold; } uint32_t RUDPSendBuffer::calculate_snd_size(uint64_t now_timer) { uint32_t ret; uint32_t timer; if (now_timer < send_ts_ + 10) ret = 0; timer = now_timer - send_ts_; ret = ccc_->get_send_window_size() * timer / get_threshold(ccc_->get_rtt()); send_ts_ = now_timer; return core_min(ret, ccc_->get_send_window_size()); } void RUDPSendBuffer::attempt_send(uint64_t now_timer) { uint32_t cwnd_size; uint32_t ccc_cwnd_size = ccc_->get_send_window_size(); RUDPSendSegment* seg = NULL; SendWindowMap::iterator map_it; cwnd_size = 0; //жǷԷµı while (!send_data_.empty() && send_window_.size() < ccc_cwnd_size) { RUDPSendSegment* seg = send_data_.front(); //жNAGLE㷨,NAGLEҪ100MS1024ֽڱ if(nagle_ && seg->push_ts_ + NAGLE_DELAY > now_timer && seg->data_size_ < MAX_SEGMENT_SIZE - 256) break; //жϷʹ send_data_.pop_front(); send_window_.insert(SendWindowMap::value_type(seg->seq_, seg)); cwnd_size += seg->data_size_; now_timer = CBaseTimeValue::get_time_value().msec(); seg->push_ts_ = now_timer; seg->last_send_ts_ = now_timer; seg->send_count_ = 1; net_channel_->send_data(0, seg->seq_, seg->data_, seg->data_size_, now_timer); if(cwnd_max_seq_ < seg->seq_) cwnd_max_seq_ = seg->seq_; } } uint32_t RUDPSendBuffer::get_bandwidth() { uint32_t ret = 0; uint64_t cur_ts = CBaseTimeValue::get_time_value().msec(); if(cur_ts > bandwidth_ts_) ret = static_cast<uint32_t>(bandwidth_ * 1000 / (cur_ts - bandwidth_ts_)); else ret = bandwidth_ * 1000; bandwidth_ts_ = cur_ts; bandwidth_ = 0; return ret; } BASE_NAMESPACE_END_DECL <commit_msg>修改编译错误<commit_after>#include "rudp/rudp_send_buffer.h" #include "revolver/base_timer_value.h" #include "rudp/rudp_log_macro.h" #include "rudp/rudp_ccc.h" #include <math.h> BASE_NAMESPACE_BEGIN_DECL #define DEFAULT_RUDP_SEND_BUFFSIZE 4096 #define NAGLE_DELAY 100 RUDPSendBuffer::RUDPSendBuffer() : net_channel_(NULL) , buffer_seq_(0) , dest_max_seq_(0) , cwnd_max_seq_(0) , max_loss_seq_(0) , buffer_size_(DEFAULT_RUDP_SEND_BUFFSIZE) , buffer_data_size_(0) , nagle_(false) , send_ts_(0) , ccc_(NULL) { reset(); } RUDPSendBuffer::~RUDPSendBuffer() { reset(); } void RUDPSendBuffer::reset() { buffer_seq_ = rand() + 1; dest_max_seq_ = buffer_seq_ - 1; cwnd_max_seq_ = buffer_seq_; max_loss_seq_ = buffer_seq_; buffer_data_size_ = 0; buffer_size_ = DEFAULT_RUDP_SEND_BUFFSIZE; nagle_ = false; send_ts_ = CBaseTimeValue::get_time_value().msec(); loss_set_.clear(); for(SendWindowMap::iterator it = send_window_.begin(); it != send_window_.end(); ++ it) RETURN_SEND_SEG(it->second); send_window_.clear(); for(SendDataList::iterator it = send_data_.begin(); it != send_data_.end(); ++ it) RETURN_SEND_SEG(*it); send_data_.clear(); bandwidth_ = 0; bandwidth_ts_ = CBaseTimeValue::get_time_value().msec(); } int32_t RUDPSendBuffer::send(const uint8_t* data, int32_t data_size) { int32_t copy_pos = 0; int32_t copy_size = 0; uint8_t* pos = (uint8_t *)data; uint64_t now_timer = CBaseTimeValue::get_time_value().msec(); if(!send_data_.empty()) //ճ { RUDPSendSegment* last_seg = send_data_.back(); if(last_seg != NULL && last_seg->data_size_ < MAX_SEGMENT_SIZE) { copy_size = MAX_SEGMENT_SIZE - last_seg->data_size_; if( copy_size > data_size) copy_size = data_size; memcpy(last_seg->data_ + last_seg->data_size_, pos, copy_size); copy_pos += copy_size; pos += copy_size; last_seg->data_size_ += copy_size; } } //Ƭ while(copy_pos < data_size) { GAIN_SEND_SEG(last_seg); //óʼĵʱ last_seg->push_ts_ = now_timer; last_seg->seq_ = buffer_seq_; buffer_seq_ ++; //RUDP_SEND_DEBUG("put packet, seq = " << buffer_seq_); //ȷĿ鳤 copy_size = (data_size - copy_pos); if(copy_size > MAX_SEGMENT_SIZE) copy_size = MAX_SEGMENT_SIZE; memcpy(last_seg->data_, pos, copy_size); copy_pos += copy_size; pos += copy_size; last_seg->data_size_ = copy_size; send_data_.push_back(last_seg); if (buffer_data_size_ + copy_pos > buffer_size_) break; } buffer_data_size_ += copy_pos; //Է, //if(!nagle_) attempt_send(now_timer); return copy_pos; } void RUDPSendBuffer::on_ack(uint64_t seq) { //ID if(cwnd_max_seq_ < seq) return; uint64_t now_timer = CBaseTimeValue::get_time_value().msec(); if(!send_window_.empty()) { //ɾڵƬ SendWindowMap::iterator it = send_window_.begin(); while(it != send_window_.end() && it->first <= seq) { //ݻĴС if(buffer_data_size_ > it->second->data_size_) buffer_data_size_ = buffer_data_size_ - it->second->data_size_; else buffer_data_size_ = 0; bandwidth_ += it->second->data_size_; RETURN_SEND_SEG(it->second); send_window_.erase(it); it = send_window_.begin(); ccc_->add_recv(1); } if(send_window_.size() == 1){ it = send_window_.begin(); net_channel_->send_data(0, it->second->seq_, it->second->data_, it->second->data_size_, now_timer); it->second->last_send_ts_ = now_timer; it->second->send_count_++; ccc_->add_resend(); } } if (dest_max_seq_ < seq) dest_max_seq_ = seq; check_buffer(); //Է /*attempt_send(CBaseTimeValue::get_time_value().msec());*/ } void RUDPSendBuffer::on_nack(uint64_t base_seq, const LossIDArray& loss_ids) { uint64_t now_timer = CBaseTimeValue::get_time_value().msec(); SendWindowMap::iterator it; uint64_t seq = base_seq; uint32_t sz = loss_ids.size(); for (size_t i = 0; i < sz; ++i){ /*óط*/ seq = loss_ids[i] + base_seq; it = send_window_.find(seq); if (it != send_window_.end()){ net_channel_->send_data(0, it->second->seq_, it->second->data_, it->second->data_size_, now_timer); it->second->last_send_ts_ = now_timer; it->second->send_count_++; ccc_->add_resend(); } } if (loss_ids.size() > 0) ccc_->on_loss(base_seq, loss_ids); on_ack(base_seq); } void RUDPSendBuffer::on_timer(uint64_t now_timer) { attempt_send(now_timer); check_buffer(); } void RUDPSendBuffer::check_buffer() { buffer_size_ = core_max(buffer_size_, (ccc_->get_send_window_size() * MAX_SEGMENT_SIZE)); //Ƿд if(buffer_data_size_ < buffer_size_ && net_channel_ != NULL) net_channel_->on_write(); } //CCCӿ void RUDPSendBuffer::clear_loss() { loss_set_.clear(); } uint32_t RUDPSendBuffer::get_threshold(uint32_t rtt) { uint32_t rtt_threshold = 10; uint32_t var_rtt = core_max(ccc_->get_rtt_var(), rtt / 16); if (rtt < 10) rtt_threshold = 10; else rtt_threshold = rtt + var_rtt; if(rtt < 80) rtt_threshold = rtt + var_rtt + 3; else if (rtt < 100) rtt_threshold = rtt + var_rtt + 10; else rtt_threshold = rtt + var_rtt; return rtt_threshold; } uint32_t RUDPSendBuffer::calculate_snd_size(uint64_t now_timer) { uint32_t ret; uint32_t timer; if (now_timer < send_ts_ + 10) ret = 0; timer = now_timer - send_ts_; ret = ccc_->get_send_window_size() * timer / get_threshold(ccc_->get_rtt()); send_ts_ = now_timer; return core_min(ret, ccc_->get_send_window_size()); } void RUDPSendBuffer::attempt_send(uint64_t now_timer) { uint32_t cwnd_size; uint32_t ccc_cwnd_size = ccc_->get_send_window_size(); RUDPSendSegment* seg = NULL; SendWindowMap::iterator map_it; cwnd_size = 0; //жǷԷµı while (!send_data_.empty() && send_window_.size() < ccc_cwnd_size) { RUDPSendSegment* seg = send_data_.front(); //жNAGLE㷨,NAGLEҪ100MS1024ֽڱ if(nagle_ && seg->push_ts_ + NAGLE_DELAY > now_timer && seg->data_size_ < MAX_SEGMENT_SIZE - 256) break; //жϷʹ send_data_.pop_front(); send_window_.insert(SendWindowMap::value_type(seg->seq_, seg)); cwnd_size += seg->data_size_; now_timer = CBaseTimeValue::get_time_value().msec(); seg->push_ts_ = now_timer; seg->last_send_ts_ = now_timer; seg->send_count_ = 1; net_channel_->send_data(0, seg->seq_, seg->data_, seg->data_size_, now_timer); if(cwnd_max_seq_ < seg->seq_) cwnd_max_seq_ = seg->seq_; } } uint32_t RUDPSendBuffer::get_bandwidth() { uint32_t ret = 0; uint64_t cur_ts = CBaseTimeValue::get_time_value().msec(); if(cur_ts > bandwidth_ts_) ret = static_cast<uint32_t>(bandwidth_ * 1000 / (cur_ts - bandwidth_ts_)); else ret = bandwidth_ * 1000; bandwidth_ts_ = cur_ts; bandwidth_ = 0; return ret; } BASE_NAMESPACE_END_DECL <|endoftext|>
<commit_before>#include "SymbianDTMFPrivate.h" #include "SymbianCallInitiator.h" SymbianDTMFPrivate::SymbianDTMFPrivate(SymbianCallInitiator *p) : CActive(EPriorityNormal) , parent (p) { }//SymbianDTMFPrivate::SymbianDTMFPrivate SymbianDTMFPrivate::~SymbianDTMFPrivate () { Cancel(); parent = NULL; }//SymbianDTMFPrivate::~SymbianDTMFPrivate void SymbianDTMFPrivate::RunL () { qDebug("RunL"); bool bSuccess = (iStatus == KErrNone); if (NULL != parent) { qDebug("RunL about to call onDtmfSent"); parent->onDtmfSent (this, bSuccess); } qDebug("RunL called onDtmfSent"); }//SymbianDTMFPrivate::RunL void SymbianDTMFPrivate::DoCancel () { parent->iTelephony->CancelAsync(CTelephony::ESendDTMFTonesCancel); }//SymbianDTMFPrivate::DoCancel void SymbianDTMFPrivate::sendDTMF (const QString &strTones) { #define SIZE_LIMIT 40 if (strTones.length () > SIZE_LIMIT) { qDebug ("Too many DTMF characters"); return; } TBuf<SIZE_LIMIT>aNumber; #undef SIZE_LIMIT TPtrC8 ptr(reinterpret_cast<const TUint8*>(strTones.toLatin1().constData())); aNumber.Copy(ptr); parent->iTelephony->SendDTMFTones(iStatus, aNumber); SetActive (); }//SymbianDTMFPrivate::sendDTMF <commit_msg>Use the utf8 representation<commit_after>#include "SymbianDTMFPrivate.h" #include "SymbianCallInitiator.h" SymbianDTMFPrivate::SymbianDTMFPrivate(SymbianCallInitiator *p) : CActive(EPriorityNormal) , parent (p) { }//SymbianDTMFPrivate::SymbianDTMFPrivate SymbianDTMFPrivate::~SymbianDTMFPrivate () { Cancel(); parent = NULL; }//SymbianDTMFPrivate::~SymbianDTMFPrivate void SymbianDTMFPrivate::RunL () { qDebug("RunL"); bool bSuccess = (iStatus == KErrNone); if (NULL != parent) { qDebug("RunL about to call onDtmfSent"); parent->onDtmfSent (this, bSuccess); } qDebug("RunL called onDtmfSent"); }//SymbianDTMFPrivate::RunL void SymbianDTMFPrivate::DoCancel () { parent->iTelephony->CancelAsync(CTelephony::ESendDTMFTonesCancel); }//SymbianDTMFPrivate::DoCancel void SymbianDTMFPrivate::sendDTMF (const QString &strTones) { #define SIZE_LIMIT 40 if (strTones.length () > SIZE_LIMIT) { qDebug ("Too many DTMF characters"); return; } TBuf<SIZE_LIMIT>aNumber; #undef SIZE_LIMIT TPtrC8 ptr(reinterpret_cast<const TUint8*>(strTones.toUtf8().constData())); aNumber.Copy(ptr); parent->iTelephony->SendDTMFTones(iStatus, aNumber); SetActive (); }//SymbianDTMFPrivate::sendDTMF <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: AccessibleShapeTreeInfo.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: af $ $Date: 2002-05-22 08:19:30 $ * * 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): _______________________________________ * * ************************************************************************/ #include "AccessibleShapeTreeInfo.hxx" using namespace ::com::sun::star; using namespace ::drafts::com::sun::star::accessibility; using ::com::sun::star::uno::Reference; namespace accessibility { AccessibleShapeTreeInfo::AccessibleShapeTreeInfo ( const Reference<XAccessibleComponent>& rxDocumentWindow, const Reference<document::XEventBroadcaster>& rxModelBroadcaster) : mxDocumentWindow (rxDocumentWindow), mxModelBroadcaster (rxModelBroadcaster), mpView (NULL), mpWindow (NULL), mpViewForwarder (NULL) { // Empty. } AccessibleShapeTreeInfo::AccessibleShapeTreeInfo (void) : mpView (NULL), mpWindow (NULL), mpViewForwarder (NULL) { // Empty. } AccessibleShapeTreeInfo::AccessibleShapeTreeInfo (const AccessibleShapeTreeInfo& rInfo) : mxDocumentWindow (rInfo.mxDocumentWindow), mxModelBroadcaster (rInfo.mxModelBroadcaster), mpView (rInfo.mpView), mxController (rInfo.mxController), mpWindow (rInfo.mpWindow), mpViewForwarder (rInfo.mpViewForwarder) { // Empty. } AccessibleShapeTreeInfo& AccessibleShapeTreeInfo::operator= (const AccessibleShapeTreeInfo& rInfo) { mxDocumentWindow = rInfo.mxDocumentWindow; mxModelBroadcaster = rInfo.mxModelBroadcaster; mpView = rInfo.mpView; mxController = rInfo.mxController, mpWindow = rInfo.mpWindow; mpViewForwarder = rInfo.mpViewForwarder; return *this; } AccessibleShapeTreeInfo::~AccessibleShapeTreeInfo (void) { //empty } void AccessibleShapeTreeInfo::SetDocumentWindow ( const Reference<XAccessibleComponent>& rxDocumentWindow) { if (mxDocumentWindow != rxDocumentWindow) mxDocumentWindow = rxDocumentWindow; } uno::Reference<XAccessibleComponent> AccessibleShapeTreeInfo::GetDocumentWindow (void) const { return mxDocumentWindow; } void AccessibleShapeTreeInfo::SetControllerBroadcaster ( const uno::Reference<document::XEventBroadcaster>& rxControllerBroadcaster) { mxModelBroadcaster = rxControllerBroadcaster; } uno::Reference<document::XEventBroadcaster> AccessibleShapeTreeInfo::GetControllerBroadcaster (void) const { return mxModelBroadcaster; } void AccessibleShapeTreeInfo::SetModelBroadcaster ( const Reference<document::XEventBroadcaster>& rxModelBroadcaster) { mxModelBroadcaster = rxModelBroadcaster; } Reference<document::XEventBroadcaster> AccessibleShapeTreeInfo::GetModelBroadcaster (void) const { return mxModelBroadcaster; } void AccessibleShapeTreeInfo::SetSdrView (SdrView* pView) { mpView = pView; } SdrView* AccessibleShapeTreeInfo::GetSdrView (void) const { return mpView; } void AccessibleShapeTreeInfo::SetController ( const Reference<frame::XController>& rxController) { mxController = rxController; } Reference<frame::XController> AccessibleShapeTreeInfo::GetController (void) const { return mxController; } void AccessibleShapeTreeInfo::SetWindow (Window* pWindow) { mpWindow = pWindow; } const Window* AccessibleShapeTreeInfo::GetWindow (void) const { return mpWindow; } void AccessibleShapeTreeInfo::SetViewForwarder (const IAccessibleViewForwarder* pViewForwarder) { mpViewForwarder = pViewForwarder; } const IAccessibleViewForwarder* AccessibleShapeTreeInfo::GetViewForwarder (void) const { return mpViewForwarder; } } // end of namespace accessibility <commit_msg>#99875# Removed constness of returned window.<commit_after>/************************************************************************* * * $RCSfile: AccessibleShapeTreeInfo.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: af $ $Date: 2002-06-07 14:51:14 $ * * 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): _______________________________________ * * ************************************************************************/ #include "AccessibleShapeTreeInfo.hxx" using namespace ::com::sun::star; using namespace ::drafts::com::sun::star::accessibility; using ::com::sun::star::uno::Reference; namespace accessibility { AccessibleShapeTreeInfo::AccessibleShapeTreeInfo ( const Reference<XAccessibleComponent>& rxDocumentWindow, const Reference<document::XEventBroadcaster>& rxModelBroadcaster) : mxDocumentWindow (rxDocumentWindow), mxModelBroadcaster (rxModelBroadcaster), mpView (NULL), mpWindow (NULL), mpViewForwarder (NULL) { // Empty. } AccessibleShapeTreeInfo::AccessibleShapeTreeInfo (void) : mpView (NULL), mpWindow (NULL), mpViewForwarder (NULL) { // Empty. } AccessibleShapeTreeInfo::AccessibleShapeTreeInfo (const AccessibleShapeTreeInfo& rInfo) : mxDocumentWindow (rInfo.mxDocumentWindow), mxModelBroadcaster (rInfo.mxModelBroadcaster), mpView (rInfo.mpView), mxController (rInfo.mxController), mpWindow (rInfo.mpWindow), mpViewForwarder (rInfo.mpViewForwarder) { // Empty. } AccessibleShapeTreeInfo& AccessibleShapeTreeInfo::operator= (const AccessibleShapeTreeInfo& rInfo) { mxDocumentWindow = rInfo.mxDocumentWindow; mxModelBroadcaster = rInfo.mxModelBroadcaster; mpView = rInfo.mpView; mxController = rInfo.mxController, mpWindow = rInfo.mpWindow; mpViewForwarder = rInfo.mpViewForwarder; return *this; } AccessibleShapeTreeInfo::~AccessibleShapeTreeInfo (void) { //empty } void AccessibleShapeTreeInfo::SetDocumentWindow ( const Reference<XAccessibleComponent>& rxDocumentWindow) { if (mxDocumentWindow != rxDocumentWindow) mxDocumentWindow = rxDocumentWindow; } uno::Reference<XAccessibleComponent> AccessibleShapeTreeInfo::GetDocumentWindow (void) const { return mxDocumentWindow; } void AccessibleShapeTreeInfo::SetControllerBroadcaster ( const uno::Reference<document::XEventBroadcaster>& rxControllerBroadcaster) { mxModelBroadcaster = rxControllerBroadcaster; } uno::Reference<document::XEventBroadcaster> AccessibleShapeTreeInfo::GetControllerBroadcaster (void) const { return mxModelBroadcaster; } void AccessibleShapeTreeInfo::SetModelBroadcaster ( const Reference<document::XEventBroadcaster>& rxModelBroadcaster) { mxModelBroadcaster = rxModelBroadcaster; } Reference<document::XEventBroadcaster> AccessibleShapeTreeInfo::GetModelBroadcaster (void) const { return mxModelBroadcaster; } void AccessibleShapeTreeInfo::SetSdrView (SdrView* pView) { mpView = pView; } SdrView* AccessibleShapeTreeInfo::GetSdrView (void) const { return mpView; } void AccessibleShapeTreeInfo::SetController ( const Reference<frame::XController>& rxController) { mxController = rxController; } Reference<frame::XController> AccessibleShapeTreeInfo::GetController (void) const { return mxController; } void AccessibleShapeTreeInfo::SetWindow (Window* pWindow) { mpWindow = pWindow; } Window* AccessibleShapeTreeInfo::GetWindow (void) const { return mpWindow; } void AccessibleShapeTreeInfo::SetViewForwarder (const IAccessibleViewForwarder* pViewForwarder) { mpViewForwarder = pViewForwarder; } const IAccessibleViewForwarder* AccessibleShapeTreeInfo::GetViewForwarder (void) const { return mpViewForwarder; } } // end of namespace accessibility <|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 "sk_tool_utils.h" #include "SkShader.h" #include "SkTraceEvent.h" using namespace skiagm; GM::GM() { fMode = kGM_Mode; fBGColor = SK_ColorWHITE; fCanvasIsDeferred = false; fHaveCalledOnceBeforeDraw = false; } GM::~GM() {} void GM::draw(SkCanvas* canvas) { TRACE_EVENT1("GM", TRACE_FUNC, "name", TRACE_STR_COPY(this->getName())); this->drawBackground(canvas); this->drawContent(canvas); } void GM::drawContent(SkCanvas* canvas) { TRACE_EVENT0("GM", TRACE_FUNC); if (!fHaveCalledOnceBeforeDraw) { fHaveCalledOnceBeforeDraw = true; this->onOnceBeforeDraw(); } this->onDraw(canvas); } void GM::drawBackground(SkCanvas* canvas) { TRACE_EVENT0("GM", TRACE_FUNC); if (!fHaveCalledOnceBeforeDraw) { fHaveCalledOnceBeforeDraw = true; this->onOnceBeforeDraw(); } this->onDrawBackground(canvas); } const char* GM::getName() { if (fShortName.size() == 0) { fShortName = this->onShortName(); } return fShortName.c_str(); } void GM::setBGColor(SkColor color) { fBGColor = color; } bool GM::animate(const SkAnimTimer& timer) { return this->onAnimate(timer); } ///////////////////////////////////////////////////////////////////////////////////////////// void GM::onDrawBackground(SkCanvas* canvas) { canvas->drawColor(fBGColor, SkBlendMode::kSrc); } void GM::drawSizeBounds(SkCanvas* canvas, SkColor color) { SkISize size = this->getISize(); SkRect r = SkRect::MakeWH(SkIntToScalar(size.width()), SkIntToScalar(size.height())); SkPaint paint; paint.setColor(color); canvas->drawRect(r, paint); } void GM::DrawGpuOnlyMessage(SkCanvas* canvas) { SkBitmap bmp; bmp.allocN32Pixels(128, 64); SkCanvas bmpCanvas(bmp); bmpCanvas.drawColor(SK_ColorWHITE); SkPaint paint; paint.setAntiAlias(true); paint.setTextSize(20); paint.setColor(SK_ColorRED); sk_tool_utils::set_portable_typeface(&paint); constexpr char kTxt[] = "GPU Only"; bmpCanvas.drawString(kTxt, 20, 40, paint); SkMatrix localM; localM.setRotate(35.f); localM.postTranslate(10.f, 0.f); paint.setShader(SkShader::MakeBitmapShader(bmp, SkShader::kMirror_TileMode, SkShader::kMirror_TileMode, &localM)); paint.setFilterQuality(kMedium_SkFilterQuality); canvas->drawPaint(paint); return; } // need to explicitly declare this, or we get some weird infinite loop llist template GMRegistry* GMRegistry::gHead; void skiagm::SimpleGM::onDraw(SkCanvas* canvas) { fDrawProc(canvas); } SkISize skiagm::SimpleGM::onISize() { return fSize; } SkString skiagm::SimpleGM::onShortName() { return fName; } template <typename Fn> static void mark(SkCanvas* canvas, SkScalar x, SkScalar y, Fn&& fn) { SkPaint alpha; alpha.setAlpha(0x50); canvas->saveLayer(nullptr, &alpha); canvas->translate(x,y); canvas->scale(2,2); fn(); canvas->restore(); } void MarkGMGood(SkCanvas* canvas, SkScalar x, SkScalar y) { mark(canvas, x,y, [&]{ SkPaint paint; // A green circle. paint.setColor(SkColorSetRGB(27, 158, 119)); canvas->drawCircle(0,0, 12, paint); // Cut out a check mark. paint.setBlendMode(SkBlendMode::kSrc); paint.setColor(0x00000000); paint.setStrokeWidth(2); paint.setStyle(SkPaint::kStroke_Style); canvas->drawLine(-6, 0, -1, 5, paint); canvas->drawLine(-1, +5, +7, -5, paint); }); } void MarkGMBad(SkCanvas* canvas, SkScalar x, SkScalar y) { mark(canvas, x,y, [&] { SkPaint paint; // A red circle. paint.setColor(SkColorSetRGB(231, 41, 138)); canvas->drawCircle(0,0, 12, paint); // Cut out an 'X'. paint.setBlendMode(SkBlendMode::kSrc); paint.setColor(0x00000000); paint.setStrokeWidth(2); paint.setStyle(SkPaint::kStroke_Style); canvas->drawLine(-5,-5, +5,+5, paint); canvas->drawLine(+5,-5, -5,+5, paint); }); } <commit_msg>force balanced save/restore after calling a GM<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 "sk_tool_utils.h" #include "SkShader.h" #include "SkTraceEvent.h" using namespace skiagm; GM::GM() { fMode = kGM_Mode; fBGColor = SK_ColorWHITE; fCanvasIsDeferred = false; fHaveCalledOnceBeforeDraw = false; } GM::~GM() {} void GM::draw(SkCanvas* canvas) { TRACE_EVENT1("GM", TRACE_FUNC, "name", TRACE_STR_COPY(this->getName())); this->drawBackground(canvas); this->drawContent(canvas); } void GM::drawContent(SkCanvas* canvas) { TRACE_EVENT0("GM", TRACE_FUNC); if (!fHaveCalledOnceBeforeDraw) { fHaveCalledOnceBeforeDraw = true; this->onOnceBeforeDraw(); } SkAutoCanvasRestore acr(canvas, true); this->onDraw(canvas); } void GM::drawBackground(SkCanvas* canvas) { TRACE_EVENT0("GM", TRACE_FUNC); if (!fHaveCalledOnceBeforeDraw) { fHaveCalledOnceBeforeDraw = true; this->onOnceBeforeDraw(); } SkAutoCanvasRestore acr(canvas, true); this->onDrawBackground(canvas); } const char* GM::getName() { if (fShortName.size() == 0) { fShortName = this->onShortName(); } return fShortName.c_str(); } void GM::setBGColor(SkColor color) { fBGColor = color; } bool GM::animate(const SkAnimTimer& timer) { return this->onAnimate(timer); } ///////////////////////////////////////////////////////////////////////////////////////////// void GM::onDrawBackground(SkCanvas* canvas) { canvas->drawColor(fBGColor, SkBlendMode::kSrc); } void GM::drawSizeBounds(SkCanvas* canvas, SkColor color) { SkISize size = this->getISize(); SkRect r = SkRect::MakeWH(SkIntToScalar(size.width()), SkIntToScalar(size.height())); SkPaint paint; paint.setColor(color); canvas->drawRect(r, paint); } void GM::DrawGpuOnlyMessage(SkCanvas* canvas) { SkBitmap bmp; bmp.allocN32Pixels(128, 64); SkCanvas bmpCanvas(bmp); bmpCanvas.drawColor(SK_ColorWHITE); SkPaint paint; paint.setAntiAlias(true); paint.setTextSize(20); paint.setColor(SK_ColorRED); sk_tool_utils::set_portable_typeface(&paint); constexpr char kTxt[] = "GPU Only"; bmpCanvas.drawString(kTxt, 20, 40, paint); SkMatrix localM; localM.setRotate(35.f); localM.postTranslate(10.f, 0.f); paint.setShader(SkShader::MakeBitmapShader(bmp, SkShader::kMirror_TileMode, SkShader::kMirror_TileMode, &localM)); paint.setFilterQuality(kMedium_SkFilterQuality); canvas->drawPaint(paint); return; } // need to explicitly declare this, or we get some weird infinite loop llist template GMRegistry* GMRegistry::gHead; void skiagm::SimpleGM::onDraw(SkCanvas* canvas) { fDrawProc(canvas); } SkISize skiagm::SimpleGM::onISize() { return fSize; } SkString skiagm::SimpleGM::onShortName() { return fName; } template <typename Fn> static void mark(SkCanvas* canvas, SkScalar x, SkScalar y, Fn&& fn) { SkPaint alpha; alpha.setAlpha(0x50); canvas->saveLayer(nullptr, &alpha); canvas->translate(x,y); canvas->scale(2,2); fn(); canvas->restore(); } void MarkGMGood(SkCanvas* canvas, SkScalar x, SkScalar y) { mark(canvas, x,y, [&]{ SkPaint paint; // A green circle. paint.setColor(SkColorSetRGB(27, 158, 119)); canvas->drawCircle(0,0, 12, paint); // Cut out a check mark. paint.setBlendMode(SkBlendMode::kSrc); paint.setColor(0x00000000); paint.setStrokeWidth(2); paint.setStyle(SkPaint::kStroke_Style); canvas->drawLine(-6, 0, -1, 5, paint); canvas->drawLine(-1, +5, +7, -5, paint); }); } void MarkGMBad(SkCanvas* canvas, SkScalar x, SkScalar y) { mark(canvas, x,y, [&] { SkPaint paint; // A red circle. paint.setColor(SkColorSetRGB(231, 41, 138)); canvas->drawCircle(0,0, 12, paint); // Cut out an 'X'. paint.setBlendMode(SkBlendMode::kSrc); paint.setColor(0x00000000); paint.setStrokeWidth(2); paint.setStyle(SkPaint::kStroke_Style); canvas->drawLine(-5,-5, +5,+5, paint); canvas->drawLine(+5,-5, -5,+5, paint); }); } <|endoftext|>
<commit_before>//===- PDB.cpp ------------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "PDB.h" #include "Chunks.h" #include "Config.h" #include "Error.h" #include "SymbolTable.h" #include "Symbols.h" #include "llvm/DebugInfo/CodeView/CVDebugRecord.h" #include "llvm/DebugInfo/CodeView/CVTypeDumper.h" #include "llvm/DebugInfo/CodeView/SymbolDumper.h" #include "llvm/DebugInfo/CodeView/TypeDatabase.h" #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h" #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h" #include "llvm/DebugInfo/CodeView/TypeTableBuilder.h" #include "llvm/DebugInfo/MSF/BinaryByteStream.h" #include "llvm/DebugInfo/MSF/MSFBuilder.h" #include "llvm/DebugInfo/MSF/MSFCommon.h" #include "llvm/DebugInfo/PDB/Native/DbiStream.h" #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h" #include "llvm/DebugInfo/PDB/Native/InfoStream.h" #include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h" #include "llvm/DebugInfo/PDB/Native/PDBFile.h" #include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h" #include "llvm/DebugInfo/PDB/Native/PDBTypeServerHandler.h" #include "llvm/DebugInfo/PDB/Native/StringTableBuilder.h" #include "llvm/DebugInfo/PDB/Native/TpiStream.h" #include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h" #include "llvm/Object/COFF.h" #include "llvm/Support/Endian.h" #include "llvm/Support/FileOutputBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/ScopedPrinter.h" #include <memory> using namespace lld; using namespace lld::coff; using namespace llvm; using namespace llvm::codeview; using namespace llvm::support; using namespace llvm::support::endian; using llvm::object::coff_section; static ExitOnError ExitOnErr; // Returns a list of all SectionChunks. static std::vector<coff_section> getInputSections(SymbolTable *Symtab) { std::vector<coff_section> V; for (Chunk *C : Symtab->getChunks()) if (auto *SC = dyn_cast<SectionChunk>(C)) V.push_back(*SC->Header); return V; } static SectionChunk *findByName(std::vector<SectionChunk *> &Sections, StringRef Name) { for (SectionChunk *C : Sections) if (C->getSectionName() == Name) return C; return nullptr; } static ArrayRef<uint8_t> getDebugSection(ObjectFile *File, StringRef SecName) { SectionChunk *Sec = findByName(File->getDebugChunks(), SecName); if (!Sec) return {}; // First 4 bytes are section magic. ArrayRef<uint8_t> Data = Sec->getContents(); if (Data.size() < 4) fatal(SecName + " too short"); if (read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC) fatal(SecName + " has an invalid magic"); return Data.slice(4); } // Merge .debug$T sections and returns it. static std::vector<uint8_t> mergeDebugT(SymbolTable *Symtab) { ScopedPrinter W(outs()); // Visit all .debug$T sections to add them to Builder. codeview::TypeTableBuilder Builder(BAlloc); for (ObjectFile *File : Symtab->ObjectFiles) { ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T"); if (Data.empty()) continue; BinaryByteStream Stream(Data); codeview::CVTypeArray Types; BinaryStreamReader Reader(Stream); // Follow type servers. If the same type server is encountered more than // once for this instance of `PDBTypeServerHandler` (for example if many // object files reference the same TypeServer), the types from the // TypeServer will only be visited once. pdb::PDBTypeServerHandler Handler; Handler.addSearchPath(llvm::sys::path::parent_path(File->getName())); if (auto EC = Reader.readArray(Types, Reader.getLength())) fatal(EC, "Reader::readArray failed"); if (auto Err = codeview::mergeTypeStreams(Builder, &Handler, Types)) fatal(Err, "codeview::mergeTypeStreams failed"); } // Construct section contents. std::vector<uint8_t> V; Builder.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) { V.insert(V.end(), Rec.begin(), Rec.end()); }); return V; } static void dumpDebugT(ScopedPrinter &W, ObjectFile *File) { ListScope LS(W, "DebugT"); ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T"); if (Data.empty()) return; TypeDatabase TDB; TypeDumpVisitor TDV(TDB, &W, false); // Use a default implementation that does not follow type servers and instead // just dumps the contents of the TypeServer2 record. CVTypeDumper TypeDumper(TDB); if (auto EC = TypeDumper.dump(Data, TDV)) fatal(EC, "CVTypeDumper::dump failed"); } static void dumpDebugS(ScopedPrinter &W, ObjectFile *File) { ListScope LS(W, "DebugS"); ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$S"); if (Data.empty()) return; BinaryByteStream Stream(Data); CVSymbolArray Symbols; BinaryStreamReader Reader(Stream); if (auto EC = Reader.readArray(Symbols, Reader.getLength())) fatal(EC, "StreamReader.readArray<CVSymbolArray> failed"); TypeDatabase TDB; CVSymbolDumper SymbolDumper(W, TDB, nullptr, false); if (auto EC = SymbolDumper.dump(Symbols)) fatal(EC, "CVSymbolDumper::dump failed"); } // Dump CodeView debug info. This is for debugging. static void dumpCodeView(SymbolTable *Symtab) { ScopedPrinter W(outs()); for (ObjectFile *File : Symtab->ObjectFiles) { dumpDebugT(W, File); dumpDebugS(W, File); } } static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder, ArrayRef<uint8_t> Data) { BinaryByteStream Stream(Data); codeview::CVTypeArray Records; BinaryStreamReader Reader(Stream); if (auto EC = Reader.readArray(Records, Reader.getLength())) fatal(EC, "Reader.readArray failed"); for (const codeview::CVType &Rec : Records) TpiBuilder.addTypeRecord(Rec); } // Creates a PDB file. void coff::createPDB(StringRef Path, SymbolTable *Symtab, ArrayRef<uint8_t> SectionTable, const llvm::codeview::DebugInfo *DI) { if (Config->DumpPdb) dumpCodeView(Symtab); BumpPtrAllocator Alloc; pdb::PDBFileBuilder Builder(Alloc); ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize // Create streams in MSF for predefined streams, namely // PDB, TPI, DBI and IPI. for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I) ExitOnErr(Builder.getMsfBuilder().addStream(0)); // Add an Info stream. auto &InfoBuilder = Builder.getInfoBuilder(); InfoBuilder.setAge(DI ? DI->PDB70.Age : 0); pdb::PDB_UniqueId uuid{}; if (DI) memcpy(&uuid, &DI->PDB70.Signature, sizeof(uuid)); InfoBuilder.setGuid(uuid); // Should be the current time, but set 0 for reproducibilty. InfoBuilder.setSignature(0); InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70); // Add an empty DPI stream. auto &DbiBuilder = Builder.getDbiBuilder(); DbiBuilder.setVersionHeader(pdb::PdbDbiV110); // Add an empty TPI stream. auto &TpiBuilder = Builder.getTpiBuilder(); TpiBuilder.setVersionHeader(pdb::PdbTpiV80); std::vector<uint8_t> TpiData; if (Config->DebugPdb) { TpiData = mergeDebugT(Symtab); addTypeInfo(TpiBuilder, TpiData); } // Add an empty IPI stream. auto &IpiBuilder = Builder.getIpiBuilder(); IpiBuilder.setVersionHeader(pdb::PdbTpiV80); // Add Section Contributions. std::vector<pdb::SectionContrib> Contribs = pdb::DbiStreamBuilder::createSectionContribs(getInputSections(Symtab)); DbiBuilder.setSectionContribs(Contribs); // Add Section Map stream. ArrayRef<object::coff_section> Sections = { (const object::coff_section *)SectionTable.data(), SectionTable.size() / sizeof(object::coff_section)}; std::vector<pdb::SecMapEntry> SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections); DbiBuilder.setSectionMap(SectionMap); ExitOnErr(DbiBuilder.addModuleInfo("", "* Linker *")); // Add COFF section header stream. ExitOnErr( DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable)); // Write to a file. ExitOnErr(Builder.commit(Path)); } <commit_msg>[PDB] Make streams carry their own endianness.<commit_after>//===- PDB.cpp ------------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "PDB.h" #include "Chunks.h" #include "Config.h" #include "Error.h" #include "SymbolTable.h" #include "Symbols.h" #include "llvm/DebugInfo/CodeView/CVDebugRecord.h" #include "llvm/DebugInfo/CodeView/CVTypeDumper.h" #include "llvm/DebugInfo/CodeView/SymbolDumper.h" #include "llvm/DebugInfo/CodeView/TypeDatabase.h" #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h" #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h" #include "llvm/DebugInfo/CodeView/TypeTableBuilder.h" #include "llvm/DebugInfo/MSF/BinaryByteStream.h" #include "llvm/DebugInfo/MSF/MSFBuilder.h" #include "llvm/DebugInfo/MSF/MSFCommon.h" #include "llvm/DebugInfo/PDB/Native/DbiStream.h" #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h" #include "llvm/DebugInfo/PDB/Native/InfoStream.h" #include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h" #include "llvm/DebugInfo/PDB/Native/PDBFile.h" #include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h" #include "llvm/DebugInfo/PDB/Native/PDBTypeServerHandler.h" #include "llvm/DebugInfo/PDB/Native/StringTableBuilder.h" #include "llvm/DebugInfo/PDB/Native/TpiStream.h" #include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h" #include "llvm/Object/COFF.h" #include "llvm/Support/Endian.h" #include "llvm/Support/FileOutputBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/ScopedPrinter.h" #include <memory> using namespace lld; using namespace lld::coff; using namespace llvm; using namespace llvm::codeview; using namespace llvm::support; using namespace llvm::support::endian; using llvm::object::coff_section; static ExitOnError ExitOnErr; // Returns a list of all SectionChunks. static std::vector<coff_section> getInputSections(SymbolTable *Symtab) { std::vector<coff_section> V; for (Chunk *C : Symtab->getChunks()) if (auto *SC = dyn_cast<SectionChunk>(C)) V.push_back(*SC->Header); return V; } static SectionChunk *findByName(std::vector<SectionChunk *> &Sections, StringRef Name) { for (SectionChunk *C : Sections) if (C->getSectionName() == Name) return C; return nullptr; } static ArrayRef<uint8_t> getDebugSection(ObjectFile *File, StringRef SecName) { SectionChunk *Sec = findByName(File->getDebugChunks(), SecName); if (!Sec) return {}; // First 4 bytes are section magic. ArrayRef<uint8_t> Data = Sec->getContents(); if (Data.size() < 4) fatal(SecName + " too short"); if (read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC) fatal(SecName + " has an invalid magic"); return Data.slice(4); } // Merge .debug$T sections and returns it. static std::vector<uint8_t> mergeDebugT(SymbolTable *Symtab) { ScopedPrinter W(outs()); // Visit all .debug$T sections to add them to Builder. codeview::TypeTableBuilder Builder(BAlloc); for (ObjectFile *File : Symtab->ObjectFiles) { ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T"); if (Data.empty()) continue; BinaryByteStream Stream(Data, llvm::support::little); codeview::CVTypeArray Types; BinaryStreamReader Reader(Stream); // Follow type servers. If the same type server is encountered more than // once for this instance of `PDBTypeServerHandler` (for example if many // object files reference the same TypeServer), the types from the // TypeServer will only be visited once. pdb::PDBTypeServerHandler Handler; Handler.addSearchPath(llvm::sys::path::parent_path(File->getName())); if (auto EC = Reader.readArray(Types, Reader.getLength())) fatal(EC, "Reader::readArray failed"); if (auto Err = codeview::mergeTypeStreams(Builder, &Handler, Types)) fatal(Err, "codeview::mergeTypeStreams failed"); } // Construct section contents. std::vector<uint8_t> V; Builder.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) { V.insert(V.end(), Rec.begin(), Rec.end()); }); return V; } static void dumpDebugT(ScopedPrinter &W, ObjectFile *File) { ListScope LS(W, "DebugT"); ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T"); if (Data.empty()) return; TypeDatabase TDB; TypeDumpVisitor TDV(TDB, &W, false); // Use a default implementation that does not follow type servers and instead // just dumps the contents of the TypeServer2 record. CVTypeDumper TypeDumper(TDB); if (auto EC = TypeDumper.dump(Data, TDV)) fatal(EC, "CVTypeDumper::dump failed"); } static void dumpDebugS(ScopedPrinter &W, ObjectFile *File) { ListScope LS(W, "DebugS"); ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$S"); if (Data.empty()) return; BinaryByteStream Stream(Data, llvm::support::little); CVSymbolArray Symbols; BinaryStreamReader Reader(Stream); if (auto EC = Reader.readArray(Symbols, Reader.getLength())) fatal(EC, "StreamReader.readArray<CVSymbolArray> failed"); TypeDatabase TDB; CVSymbolDumper SymbolDumper(W, TDB, nullptr, false); if (auto EC = SymbolDumper.dump(Symbols)) fatal(EC, "CVSymbolDumper::dump failed"); } // Dump CodeView debug info. This is for debugging. static void dumpCodeView(SymbolTable *Symtab) { ScopedPrinter W(outs()); for (ObjectFile *File : Symtab->ObjectFiles) { dumpDebugT(W, File); dumpDebugS(W, File); } } static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder, ArrayRef<uint8_t> Data) { BinaryByteStream Stream(Data, llvm::support::little); codeview::CVTypeArray Records; BinaryStreamReader Reader(Stream); if (auto EC = Reader.readArray(Records, Reader.getLength())) fatal(EC, "Reader.readArray failed"); for (const codeview::CVType &Rec : Records) TpiBuilder.addTypeRecord(Rec); } // Creates a PDB file. void coff::createPDB(StringRef Path, SymbolTable *Symtab, ArrayRef<uint8_t> SectionTable, const llvm::codeview::DebugInfo *DI) { if (Config->DumpPdb) dumpCodeView(Symtab); BumpPtrAllocator Alloc; pdb::PDBFileBuilder Builder(Alloc); ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize // Create streams in MSF for predefined streams, namely // PDB, TPI, DBI and IPI. for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I) ExitOnErr(Builder.getMsfBuilder().addStream(0)); // Add an Info stream. auto &InfoBuilder = Builder.getInfoBuilder(); InfoBuilder.setAge(DI ? DI->PDB70.Age : 0); pdb::PDB_UniqueId uuid{}; if (DI) memcpy(&uuid, &DI->PDB70.Signature, sizeof(uuid)); InfoBuilder.setGuid(uuid); // Should be the current time, but set 0 for reproducibilty. InfoBuilder.setSignature(0); InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70); // Add an empty DPI stream. auto &DbiBuilder = Builder.getDbiBuilder(); DbiBuilder.setVersionHeader(pdb::PdbDbiV110); // Add an empty TPI stream. auto &TpiBuilder = Builder.getTpiBuilder(); TpiBuilder.setVersionHeader(pdb::PdbTpiV80); std::vector<uint8_t> TpiData; if (Config->DebugPdb) { TpiData = mergeDebugT(Symtab); addTypeInfo(TpiBuilder, TpiData); } // Add an empty IPI stream. auto &IpiBuilder = Builder.getIpiBuilder(); IpiBuilder.setVersionHeader(pdb::PdbTpiV80); // Add Section Contributions. std::vector<pdb::SectionContrib> Contribs = pdb::DbiStreamBuilder::createSectionContribs(getInputSections(Symtab)); DbiBuilder.setSectionContribs(Contribs); // Add Section Map stream. ArrayRef<object::coff_section> Sections = { (const object::coff_section *)SectionTable.data(), SectionTable.size() / sizeof(object::coff_section)}; std::vector<pdb::SecMapEntry> SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections); DbiBuilder.setSectionMap(SectionMap); ExitOnErr(DbiBuilder.addModuleInfo("", "* Linker *")); // Add COFF section header stream. ExitOnErr( DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable)); // Write to a file. ExitOnErr(Builder.commit(Path)); } <|endoftext|>
<commit_before>/** * Provides the TicTacToe GameState example in the GQE library. * * @file examples/demo/GameState.cpp * @author Ryan Lindeman * @date 20110704 - Initial Release * @date 20110721 - Remove * from GetAsset() calls since it now returns TYPE& * @date 20110831 - Support new SFML2 snapshot changes */ #include "GameState.hpp" #include <GQE/Core/assets/ImageAsset.hpp> #include <GQE/Core/classes/App.hpp> GameState::GameState(GQE::App* theApp) : GQE::IState("Game",theApp), mBackground(NULL), mPlayer1(NULL), mPlayer2(NULL), mEmpty(NULL), mCurrentPlayer(0) { } GameState::~GameState(void) { } void GameState::DoInit(void) { // First call our base class implementation IState::DoInit(); // Check our App pointer assert(NULL != mApp && "GameState::DoInit() bad app pointer"); // Load our Background image which will show the TicTacToe game board mBackground = mApp->mAssetManager.AddImage("Board", "resources/Board.png", GQE::AssetLoadStyleImmediate); if(NULL != mBackground) { #if (SFML_VERSION_MAJOR < 2) mBackgroundSprite.SetImage(mBackground->GetAsset()); #else mBackgroundSprite.SetTexture(mBackground->GetAsset()); #endif } // Load our Player 1 and Player 2 images which will show an X and O pieces mPlayer1 = mApp->mAssetManager.AddImage("Player1", "resources/Player1.png", GQE::AssetLoadStyleImmediate); mPlayer2 = mApp->mAssetManager.AddImage("Player2", "resources/Player2.png", GQE::AssetLoadStyleImmediate); // Load our Empty square image which will be used when there is nothing to show mEmpty = mApp->mAssetManager.AddImage("Empty", "resources/Empty.png", GQE::AssetLoadStyleImmediate); // Setup winner text color as White mWinnerText.SetColor(sf::Color::White); // Call ReInit to reset the board ReInit(); // Make sure our update loop is only called 30 times per second mApp->SetUpdateRate(30.0f); } void GameState::ReInit(void) { // Reset our board for(GQE::Uint8 row = 0; row < 3; row++) { for(GQE::Uint8 col = 0; col < 3; col++) { // Reset the sprite for this square to empty #if (SFML_VERSION_MAJOR < 2) mBoardSprite[row][col].SetImage(mEmpty->GetAsset()); #else mBoardSprite[row][col].SetTexture(mEmpty->GetAsset()); #endif mBoardSprite[row][col].SetPosition((col*270.0f), (row*202.0f)); // Set this squares owner to no player mBoardPlayer[row][col] = 0; } } // Set Cursor to Player 1 image #if (SFML_VERSION_MAJOR < 2) mCursor.SetImage(mPlayer1->GetAsset()); #else mCursor.SetTexture(mPlayer1->GetAsset()); #endif // Set Cursor scale to be 25% of original image mCursor.SetScale(0.25f, 0.25f); // Set current player to player 1 mCurrentPlayer = 1; // Reset our winner text #if (SFML_VERSION_MAJOR < 2) mWinnerText.SetText(""); #else mWinnerText.SetString(""); #endif } void GameState::HandleEvents(sf::Event theEvent) { // Exit program if Escape key is pressed #if (SFML_VERSION_MAJOR < 2) if((theEvent.Type == sf::Event::KeyReleased) && (theEvent.Key.Code == sf::Key::Escape)) #else if((theEvent.Type == sf::Event::KeyReleased) && (theEvent.Key.Code == sf::Keyboard::Escape)) #endif { // Signal the application to exit mApp->Quit(GQE::StatusAppOK); } if(theEvent.Type == sf::Event::MouseButtonReleased) { // Determine which square they clicked on GQE::Uint8 col = (theEvent.MouseButton.X / 270); GQE::Uint8 row = (theEvent.MouseButton.Y / 202); if(3 > col && 3 > row && mBoardPlayer[row][col] == 0) { // Set ownership of this square to the current player mBoardPlayer[row][col] = mCurrentPlayer; // Determine which Sprite to use for this square switch(mCurrentPlayer) { case 1: // Set Player 1 image for this square #if (SFML_VERSION_MAJOR < 2) mBoardSprite[row][col].SetImage(mPlayer1->GetAsset()); #else mBoardSprite[row][col].SetTexture(mPlayer1->GetAsset()); #endif // Set Cursor to Player 2 image #if (SFML_VERSION_MAJOR < 2) mCursor.SetImage(mPlayer2->GetAsset()); #else mCursor.SetTexture(mPlayer2->GetAsset()); #endif // Switch to Player 2 mCurrentPlayer = 2; break; case 2: // Set Player 2 image for this square #if (SFML_VERSION_MAJOR < 2) mBoardSprite[row][col].SetImage(mPlayer2->GetAsset()); #else mBoardSprite[row][col].SetTexture(mPlayer2->GetAsset()); #endif // Set Cursor to Player 1 image #if (SFML_VERSION_MAJOR < 2) mCursor.SetImage(mPlayer1->GetAsset()); #else mCursor.SetTexture(mPlayer1->GetAsset()); #endif // Switch to Player 1 mCurrentPlayer = 1; break; default: // Leave as empty, we shouldn't even be here! break; } } // If current player is 0 then the last game ended, start a new game if(0 == mCurrentPlayer) { // Reinitialize the board and start a new game ReInit(); } } } void GameState::UpdateFixed(void) { // Check our App pointer assert(NULL != mApp && "GameState::UpdateFixed() bad app pointer, init must be called first"); // Start with a tie game GQE::Uint8 anWinner = 3; // Check each row to see if some player has won! for(GQE::Uint8 row = 0; row < 3; row++) { // Make sure each column matches and that its not the Empty player (0) if(mBoardPlayer[row][0] != 0 && mBoardPlayer[row][0] == mBoardPlayer[row][1] && mBoardPlayer[row][0] == mBoardPlayer[row][2]) { // Make a note of which player is the winner! anWinner = mBoardPlayer[row][0]; break; } // Check for empty columns on each row if(mBoardPlayer[row][0] == 0 || mBoardPlayer[row][1] == 0 || mBoardPlayer[row][2] == 0 && anWinner == 3) { // No tie game, there are still empty spaces anWinner = 0; } } // Check each column to see if some player has won! for(GQE::Uint8 col = 0; col < 3; col++) { // Make sure each column matches and that its not the Empty player (0) if(mBoardPlayer[0][col] != 0 && mBoardPlayer[0][col] == mBoardPlayer[1][col] && mBoardPlayer[0][col] == mBoardPlayer[2][col]) { // Make a note of which player is the winner! anWinner = mBoardPlayer[0][col]; break; } } // Check diagonals if(mBoardPlayer[1][1] != 0 && ((mBoardPlayer[1][1] == mBoardPlayer[0][0] && mBoardPlayer[1][1] == mBoardPlayer[2][2]) || (mBoardPlayer[1][1] == mBoardPlayer[0][2] && mBoardPlayer[1][1] == mBoardPlayer[2][0]))) { anWinner = mBoardPlayer[1][1]; } // Did we find a winner? if(anWinner == 1) { #if (SFML_VERSION_MAJOR < 2) mWinnerText.SetText("Player 1 Wins!"); #else mWinnerText.SetString("Player 1 Wins!"); #endif // Setup winner text in middle of screen mWinnerText.SetPosition(300.0f,280.0f); } else if(anWinner == 2) { #if (SFML_VERSION_MAJOR < 2) mWinnerText.SetText("Player 2 Wins!"); #else mWinnerText.SetString("Player 2 Wins!"); #endif // Setup winner text in middle of screen mWinnerText.SetPosition(300.0f,280.0f); } else if(anWinner == 3) { #if (SFML_VERSION_MAJOR < 2) mWinnerText.SetText("Tie Game"); #else mWinnerText.SetString("Tie Game"); #endif // Setup winner text in middle of screen mWinnerText.SetPosition(340.0f,280.0f); } // Set current player and cursor to empty if a winner was declared if(anWinner != 0) { // Set Cursor to Player 1 image #if (SFML_VERSION_MAJOR < 2) mCursor.SetImage(mEmpty->GetAsset()); #else mCursor.SetTexture(mEmpty->GetAsset()); #endif // Switch to empty (no player) mCurrentPlayer = 0; } } void GameState::UpdateVariable(float theElapsedTime) { // Check our App pointer assert(NULL != mApp && "GameState::UpdateVariable() bad app pointer, init must be called first"); // Draw the current player image at the mouse position #if (SFML_VERSION_MAJOR < 2) mCursor.SetPosition(mApp->mInput.GetMouseX()-32.0f, mApp->mInput.GetMouseY()-25.25f); #else mCursor.SetPosition(sf::Mouse::GetPosition().x-32.0f, sf::Mouse::GetPosition().y-25.25f); #endif } void GameState::Draw(void) { // Check our App pointer assert(NULL != mApp && "GameState::Draw() bad app pointer, init must be called first"); // Draw our Board sprite mApp->mWindow.Draw(mBackgroundSprite); for(GQE::Uint8 row = 0; row < 3; row++) { for(GQE::Uint8 col = 0; col < 3; col++) { // Draw our Board mApp->mWindow.Draw(mBoardSprite[row][col]); } } // Draw winner text mApp->mWindow.Draw(mWinnerText); // Draw our cursor mApp->mWindow.Draw(mCursor); } void GameState::Cleanup(void) { // Unload our images since we don't need them anymore mApp->mAssetManager.UnloadImage("Board"); mApp->mAssetManager.UnloadImage("Player1"); mApp->mAssetManager.UnloadImage("Player2"); mApp->mAssetManager.UnloadImage("Empty"); // Last of all, call our base class implementation IState::Cleanup(); } /** * Copyright (c) 2010-2011 Ryan Lindeman * 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. */ <commit_msg>SFML2 snapshot changes<commit_after>/** * Provides the TicTacToe GameState example in the GQE library. * * @file examples/demo/GameState.cpp * @author Ryan Lindeman * @date 20110704 - Initial Release * @date 20110721 - Remove * from GetAsset() calls since it now returns TYPE& * @date 20110831 - Support new SFML2 snapshot changes */ #include "GameState.hpp" #include <GQE/Core/assets/ImageAsset.hpp> #include <GQE/Core/classes/App.hpp> #include <SFML/Graphics/Color.hpp> GameState::GameState(GQE::App* theApp) : GQE::IState("Game",theApp), mBackground(NULL), mPlayer1(NULL), mPlayer2(NULL), mEmpty(NULL), mCurrentPlayer(0) { } GameState::~GameState(void) { } void GameState::DoInit(void) { // First call our base class implementation IState::DoInit(); // Check our App pointer assert(NULL != mApp && "GameState::DoInit() bad app pointer"); // Load our Background image which will show the TicTacToe game board mBackground = mApp->mAssetManager.AddImage("Board", "resources/Board.png", GQE::AssetLoadStyleImmediate); if(NULL != mBackground) { #if (SFML_VERSION_MAJOR < 2) mBackgroundSprite.SetImage(mBackground->GetAsset()); #else mBackgroundSprite.setTexture(mBackground->GetAsset()); #endif } // Load our Player 1 and Player 2 images which will show an X and O pieces mPlayer1 = mApp->mAssetManager.AddImage("Player1", "resources/Player1.png", GQE::AssetLoadStyleImmediate); mPlayer2 = mApp->mAssetManager.AddImage("Player2", "resources/Player2.png", GQE::AssetLoadStyleImmediate); // Load our Empty square image which will be used when there is nothing to show mEmpty = mApp->mAssetManager.AddImage("Empty", "resources/Empty.png", GQE::AssetLoadStyleImmediate); #if (SFML_VERSION_MAJOR < 2) // Setup winner text color as White mWinnerText.SetColor(sf::Color::White); #else // Setup winner text color as White mWinnerText.setColor(sf::Color::White); #endif // Call ReInit to reset the board ReInit(); // Make sure our update loop is only called 30 times per second mApp->SetUpdateRate(30.0f); } void GameState::ReInit(void) { // Reset our board for(GQE::Uint8 row = 0; row < 3; row++) { for(GQE::Uint8 col = 0; col < 3; col++) { // Reset the sprite for this square to empty #if (SFML_VERSION_MAJOR < 2) mBoardSprite[row][col].SetImage(mEmpty->GetAsset()); mBoardSprite[row][col].SetPosition((col*270.0f), (row*202.0f)); #else mBoardSprite[row][col].setTexture(mEmpty->GetAsset()); mBoardSprite[row][col].setPosition((col*270.0f), (row*202.0f)); #endif // Set this squares owner to no player mBoardPlayer[row][col] = 0; } } // Set Cursor to Player 1 image #if (SFML_VERSION_MAJOR < 2) mCursor.SetImage(mPlayer1->GetAsset()); // Set Cursor scale to be 25% of original image mCursor.SetScale(0.25f, 0.25f); #else mCursor.setTexture(mPlayer1->GetAsset()); // Set Cursor scale to be 25% of original image mCursor.setScale(0.25f, 0.25f); #endif // Set current player to player 1 mCurrentPlayer = 1; // Reset our winner text #if (SFML_VERSION_MAJOR < 2) mWinnerText.SetText(""); #else mWinnerText.setString(""); #endif } void GameState::HandleEvents(sf::Event theEvent) { // Exit program if Escape key is pressed #if (SFML_VERSION_MAJOR < 2) if((theEvent.Type == sf::Event::KeyReleased) && (theEvent.Key.Code == sf::Key::Escape)) #else if((theEvent.type == sf::Event::KeyReleased) && (theEvent.key.code == sf::Keyboard::Escape)) #endif { // Signal the application to exit mApp->Quit(GQE::StatusAppOK); } #if (SFML_VERSION_MAJOR < 2) if(theEvent.Type == sf::Event::MouseButtonReleased) #else if(theEvent.type == sf::Event::MouseButtonReleased) #endif { #if (SFML_VERSION_MAJOR < 2) // Determine which square they clicked on GQE::Uint8 col = (theEvent.MouseButton.X / 270); GQE::Uint8 row = (theEvent.MouseButton.Y / 202); #else // Determine which square they clicked on GQE::Uint8 col = (theEvent.mouseButton.x / 270); GQE::Uint8 row = (theEvent.mouseButton.y / 202); #endif if(3 > col && 3 > row && mBoardPlayer[row][col] == 0) { // Set ownership of this square to the current player mBoardPlayer[row][col] = mCurrentPlayer; // Determine which Sprite to use for this square switch(mCurrentPlayer) { case 1: // Set Player 1 image for this square #if (SFML_VERSION_MAJOR < 2) mBoardSprite[row][col].SetImage(mPlayer1->GetAsset()); #else mBoardSprite[row][col].setTexture(mPlayer1->GetAsset()); #endif // Set Cursor to Player 2 image #if (SFML_VERSION_MAJOR < 2) mCursor.SetImage(mPlayer2->GetAsset()); #else mCursor.setTexture(mPlayer2->GetAsset()); #endif // Switch to Player 2 mCurrentPlayer = 2; break; case 2: // Set Player 2 image for this square #if (SFML_VERSION_MAJOR < 2) mBoardSprite[row][col].SetImage(mPlayer2->GetAsset()); #else mBoardSprite[row][col].setTexture(mPlayer2->GetAsset()); #endif // Set Cursor to Player 1 image #if (SFML_VERSION_MAJOR < 2) mCursor.SetImage(mPlayer1->GetAsset()); #else mCursor.setTexture(mPlayer1->GetAsset()); #endif // Switch to Player 1 mCurrentPlayer = 1; break; default: // Leave as empty, we shouldn't even be here! break; } } // If current player is 0 then the last game ended, start a new game if(0 == mCurrentPlayer) { // Reinitialize the board and start a new game ReInit(); } } } void GameState::UpdateFixed(void) { // Check our App pointer assert(NULL != mApp && "GameState::UpdateFixed() bad app pointer, init must be called first"); // Start with a tie game GQE::Uint8 anWinner = 3; // Check each row to see if some player has won! for(GQE::Uint8 row = 0; row < 3; row++) { // Make sure each column matches and that its not the Empty player (0) if(mBoardPlayer[row][0] != 0 && mBoardPlayer[row][0] == mBoardPlayer[row][1] && mBoardPlayer[row][0] == mBoardPlayer[row][2]) { // Make a note of which player is the winner! anWinner = mBoardPlayer[row][0]; break; } // Check for empty columns on each row if(mBoardPlayer[row][0] == 0 || mBoardPlayer[row][1] == 0 || mBoardPlayer[row][2] == 0 && anWinner == 3) { // No tie game, there are still empty spaces anWinner = 0; } } // Check each column to see if some player has won! for(GQE::Uint8 col = 0; col < 3; col++) { // Make sure each column matches and that its not the Empty player (0) if(mBoardPlayer[0][col] != 0 && mBoardPlayer[0][col] == mBoardPlayer[1][col] && mBoardPlayer[0][col] == mBoardPlayer[2][col]) { // Make a note of which player is the winner! anWinner = mBoardPlayer[0][col]; break; } } // Check diagonals if(mBoardPlayer[1][1] != 0 && ((mBoardPlayer[1][1] == mBoardPlayer[0][0] && mBoardPlayer[1][1] == mBoardPlayer[2][2]) || (mBoardPlayer[1][1] == mBoardPlayer[0][2] && mBoardPlayer[1][1] == mBoardPlayer[2][0]))) { anWinner = mBoardPlayer[1][1]; } // Did we find a winner? if(anWinner == 1) { #if (SFML_VERSION_MAJOR < 2) mWinnerText.SetText("Player 1 Wins!"); // Setup winner text in middle of screen mWinnerText.SetPosition(300.0f,280.0f); #else mWinnerText.setString("Player 1 Wins!"); // Setup winner text in middle of screen mWinnerText.setPosition(300.0f,280.0f); #endif } else if(anWinner == 2) { #if (SFML_VERSION_MAJOR < 2) mWinnerText.SetText("Player 2 Wins!"); // Setup winner text in middle of screen mWinnerText.SetPosition(300.0f,280.0f); #else mWinnerText.setString("Player 2 Wins!"); // Setup winner text in middle of screen mWinnerText.setPosition(300.0f,280.0f); #endif } else if(anWinner == 3) { #if (SFML_VERSION_MAJOR < 2) mWinnerText.SetText("Tie Game"); // Setup winner text in middle of screen mWinnerText.SetPosition(340.0f,280.0f); #else mWinnerText.setString("Tie Game"); // Setup winner text in middle of screen mWinnerText.setPosition(340.0f,280.0f); #endif } // Set current player and cursor to empty if a winner was declared if(anWinner != 0) { // Set Cursor to Player 1 image #if (SFML_VERSION_MAJOR < 2) mCursor.SetImage(mEmpty->GetAsset()); #else mCursor.setTexture(mEmpty->GetAsset()); #endif // Switch to empty (no player) mCurrentPlayer = 0; } } void GameState::UpdateVariable(float theElapsedTime) { // Check our App pointer assert(NULL != mApp && "GameState::UpdateVariable() bad app pointer, init must be called first"); // Draw the current player image at the mouse position #if (SFML_VERSION_MAJOR < 2) mCursor.SetPosition(mApp->mInput.GetMouseX()-32.0f, mApp->mInput.GetMouseY()-25.25f); #else mCursor.setPosition(sf::Mouse::getPosition().x-32.0f, sf::Mouse::getPosition().y-25.25f); #endif } void GameState::Draw(void) { // Check our App pointer assert(NULL != mApp && "GameState::Draw() bad app pointer, init must be called first"); #if (SFML_VERSION_MAJOR < 2) // Draw our Board sprite mApp->mWindow.Draw(mBackgroundSprite); #else // Draw our Board sprite mApp->mWindow.draw(mBackgroundSprite); #endif for(GQE::Uint8 row = 0; row < 3; row++) { for(GQE::Uint8 col = 0; col < 3; col++) { #if (SFML_VERSION_MAJOR < 2) // Draw our Board mApp->mWindow.Draw(mBoardSprite[row][col]); #else // Draw our Board mApp->mWindow.draw(mBoardSprite[row][col]); #endif } } #if (SFML_VERSION_MAJOR < 2) // Draw winner text mApp->mWindow.Draw(mWinnerText); // Draw our cursor mApp->mWindow.Draw(mCursor); #else // Draw winner text mApp->mWindow.draw(mWinnerText); // Draw our cursor mApp->mWindow.draw(mCursor); #endif } void GameState::Cleanup(void) { // Unload our images since we don't need them anymore mApp->mAssetManager.UnloadImage("Board"); mApp->mAssetManager.UnloadImage("Player1"); mApp->mAssetManager.UnloadImage("Player2"); mApp->mAssetManager.UnloadImage("Empty"); // Last of all, call our base class implementation IState::Cleanup(); } /** * Copyright (c) 2010-2011 Ryan Lindeman * 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. */ <|endoftext|>