text
stringlengths
54
60.6k
<commit_before> #ifndef AT_GLOBALS_HPP #define AT_GLOBALS_HPP #include <math.h> enum { AT_X = 0, AT_Y = 1, AT_Z = 2, AT_W = 3, AT_H = 0, AT_P = 1, AT_R = 2, AT_RED = 0, AT_GREEN = 1, AT_BLUE = 2, AT_ALPHA = 3 }; #define AT_PI (3.14159265358979) #define AT_DEFAULT_TOLERANCE (1E-12) // Various useful macros #define AT_SQR(x) ( (x) * (x) ) // Convert from degrees to radians #define AT_DEG2RAD(x) ( (x) * AT_PI / 180.0 ) // Convert from radians to degrees #define AT_RAD2DEG(x) ( (x) * 180.0 / AT_PI ) // Determine if two floating-point values are close enough to be equal #define AT_EQUAL(x,y) ( fabs((x) - (y)) < AT_DEFAULT_TOLERANCE ) // Constants for use in conversion to/from Euler rotations // The three axes of rotation are specified in left to right order // i.e. XYZ means rotate around the X-axis, then the Y-axis, finally the Z-axis // The last letter ('S' or 'R') indicates static or relative rotation axes. // With static axes, the coordinate axes stay fixed during rotations; each // rotation around a particular axis rotates points the same way, regardless // of what other rotations have been done. Relative coordinate axes move with // each rotation; two X-axis rotations will move in different directions // if there is an intervening Y or Z-axis rotation. The two types are opposites // of each other: XYZ static produces the same effect as ZYX relative. enum atMathEulerAxisOrder { AT_EULER_ANGLES_XYZ_S, AT_EULER_ANGLES_XZY_S, AT_EULER_ANGLES_YXZ_S, AT_EULER_ANGLES_YZX_S, AT_EULER_ANGLES_ZXY_S, AT_EULER_ANGLES_ZYX_S, AT_EULER_ANGLES_XYX_S, AT_EULER_ANGLES_XZX_S, AT_EULER_ANGLES_YXY_S, AT_EULER_ANGLES_YZY_S, AT_EULER_ANGLES_ZXZ_S, AT_EULER_ANGLES_ZYZ_S, AT_EULER_ANGLES_XYZ_R, AT_EULER_ANGLES_XZY_R, AT_EULER_ANGLES_YXZ_R, AT_EULER_ANGLES_YZX_R, AT_EULER_ANGLES_ZXY_R, AT_EULER_ANGLES_ZYX_R, AT_EULER_ANGLES_XYX_R, AT_EULER_ANGLES_XZX_R, AT_EULER_ANGLES_YXY_R, AT_EULER_ANGLES_YZY_R, AT_EULER_ANGLES_ZXZ_R, AT_EULER_ANGLES_ZYZ_R }; // Windows-specific DLL linkage directives. Windows requires explicit export // and import instructions for its shared libraries (DLL's). The following // sections define a token AT_*_DLL for the ATLAS library that specifies // the linkage. The token is defined conditionally. If the library itself // is being compiled the token expands into an export directive. If a module // that is using the library is being compiled, the token expands into an // import directive. On platforms other than Windows, the tokens expand to // nothing. // #ifdef WIN32 // Atlas library #ifdef ATLAS_EXPORTS #define ATLAS_DLL __declspec(dllexport) #else #define ATLAS_DLL __declspec(dllimport) #endif #else // Define all tokens to be nothing #define ATLAS_DLL #endif // Under Windows, define the sleep() and usleep() functions as macros of // the Windows Sleep() function #ifdef _MSC_VER #include <windows.h> #include <wingdi.h> // Sleep() takes milliseconds so multiply x by 1000 for sleep() #define sleep(x) Sleep((x) * 1000) // Sleep() takes milliseconds, so divide x by 1000 for usleep() // if the result of (x/1000) is zero, the thread will still sleep // (give up the processor). #define usleep(x) Sleep((x) / 1000) #endif #endif <commit_msg>Added AT_MAX and AT_MIN macros.<commit_after> #ifndef AT_GLOBALS_HPP #define AT_GLOBALS_HPP #include <math.h> enum { AT_X = 0, AT_Y = 1, AT_Z = 2, AT_W = 3, AT_H = 0, AT_P = 1, AT_R = 2, AT_RED = 0, AT_GREEN = 1, AT_BLUE = 2, AT_ALPHA = 3 }; #define AT_PI (3.14159265358979) #define AT_DEFAULT_TOLERANCE (1E-12) // Various useful macros #define AT_SQR(x) ( (x) * (x) ) // Convert from degrees to radians #define AT_DEG2RAD(x) ( (x) * AT_PI / 180.0 ) // Convert from radians to degrees #define AT_RAD2DEG(x) ( (x) * 180.0 / AT_PI ) // Determine if two floating-point values are close enough to be equal #define AT_EQUAL(x,y) ( fabs((x) - (y)) < AT_DEFAULT_TOLERANCE ) // Find the maximum (or minimum) of any two values #define AT_MAX(x,y) ({typeof (x) _x = x; typeof (y) _y = y; \ _x > _y ? _x : _y; }) #define AT_MIN(x,y) ({typeof (x) _x = x; typeof (y) _y = y; \ _x < _y ? _x : _y; }) // Constants for use in conversion to/from Euler rotations // The three axes of rotation are specified in left to right order // i.e. XYZ means rotate around the X-axis, then the Y-axis, finally the Z-axis // The last letter ('S' or 'R') indicates static or relative rotation axes. // With static axes, the coordinate axes stay fixed during rotations; each // rotation around a particular axis rotates points the same way, regardless // of what other rotations have been done. Relative coordinate axes move with // each rotation; two X-axis rotations will move in different directions // if there is an intervening Y or Z-axis rotation. The two types are opposites // of each other: XYZ static produces the same effect as ZYX relative. enum atMathEulerAxisOrder { AT_EULER_ANGLES_XYZ_S, AT_EULER_ANGLES_XZY_S, AT_EULER_ANGLES_YXZ_S, AT_EULER_ANGLES_YZX_S, AT_EULER_ANGLES_ZXY_S, AT_EULER_ANGLES_ZYX_S, AT_EULER_ANGLES_XYX_S, AT_EULER_ANGLES_XZX_S, AT_EULER_ANGLES_YXY_S, AT_EULER_ANGLES_YZY_S, AT_EULER_ANGLES_ZXZ_S, AT_EULER_ANGLES_ZYZ_S, AT_EULER_ANGLES_XYZ_R, AT_EULER_ANGLES_XZY_R, AT_EULER_ANGLES_YXZ_R, AT_EULER_ANGLES_YZX_R, AT_EULER_ANGLES_ZXY_R, AT_EULER_ANGLES_ZYX_R, AT_EULER_ANGLES_XYX_R, AT_EULER_ANGLES_XZX_R, AT_EULER_ANGLES_YXY_R, AT_EULER_ANGLES_YZY_R, AT_EULER_ANGLES_ZXZ_R, AT_EULER_ANGLES_ZYZ_R }; // Windows-specific DLL linkage directives. Windows requires explicit export // and import instructions for its shared libraries (DLL's). The following // sections define a token AT_*_DLL for the ATLAS library that specifies // the linkage. The token is defined conditionally. If the library itself // is being compiled the token expands into an export directive. If a module // that is using the library is being compiled, the token expands into an // import directive. On platforms other than Windows, the tokens expand to // nothing. // #ifdef WIN32 // Atlas library #ifdef ATLAS_EXPORTS #define ATLAS_DLL __declspec(dllexport) #else #define ATLAS_DLL __declspec(dllimport) #endif #else // Define all tokens to be nothing #define ATLAS_DLL #endif // Under Windows, define the sleep() and usleep() functions as macros of // the Windows Sleep() function #ifdef _MSC_VER #include <windows.h> #include <wingdi.h> // Sleep() takes milliseconds so multiply x by 1000 for sleep() #define sleep(x) Sleep((x) * 1000) // Sleep() takes milliseconds, so divide x by 1000 for usleep() // if the result of (x/1000) is zero, the thread will still sleep // (give up the processor). #define usleep(x) Sleep((x) / 1000) #endif #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2003-2005 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tnt/job.h" #include "tnt/tcpjob.h" #include "tnt/tntnet.h" #include <tnt/httpreply.h> #include <tnt/ssl.h> #include <cxxtools/log.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <config.h> #include <fcntl.h> log_define("tntnet.job") namespace tnt { Job::Job(Tntnet& app_, const SocketIf* socketIf_) : keepAliveCounter(TntConfig::it().keepAliveMax), request(app_, socketIf_), parser(request), lastAccessTime(0) { } Job::~Job() { } void Job::clear() { parser.reset(); request.clear(); } int Job::msecToTimeout(time_t currentTime) const { return (lastAccessTime - currentTime + 1) * 1000 + TntConfig::it().keepAliveTimeout - TntConfig::it().socketReadTimeout; } //////////////////////////////////////////////////////////////////////// // Tcpjob // std::string Tcpjob::getPeerIp() const { return socket.getPeerAddr(); } std::string Tcpjob::getServerIp() const { return socket.getSockAddr(); } bool Tcpjob::isSsl() const { return false; } void Tcpjob::accept() { socket.accept(listener); log_debug("connection accepted from " << getPeerIp()); } void Tcpjob::regenerateJob() { if (Tntnet::shouldStop()) queue.put(this); else queue.put(new Tcpjob(getRequest().getApplication(), listener, queue)); } std::iostream& Tcpjob::getStream() { if (!socket.isConnected()) { try { accept(); touch(); } catch (const std::exception& e) { regenerateJob(); log_debug("exception occured in accept: " << e.what()); throw; } regenerateJob(); } return socket; } int Tcpjob::getFd() const { return socket.getFd(); } void Tcpjob::setRead() { socket.setTimeout(TntConfig::it().socketReadTimeout); } void Tcpjob::setWrite() { socket.setTimeout(TntConfig::it().socketWriteTimeout); } #ifdef USE_SSL //////////////////////////////////////////////////////////////////////// // SslTcpjob // std::string SslTcpjob::getPeerIp() const { return socket.getPeerAddr(); } std::string SslTcpjob::getServerIp() const { return socket.getSockAddr(); } bool SslTcpjob::isSsl() const { return true; } void SslTcpjob::accept() { socket.accept(listener, cxxtools::net::TcpSocket::DEFER_ACCEPT); } void SslTcpjob::handshake() { socket.handshake(listener); fcntl(socket.getFd(), F_SETFD, FD_CLOEXEC); setRead(); } void SslTcpjob::regenerateJob() { if (Tntnet::shouldStop()) queue.put(this); else queue.put(new SslTcpjob(getRequest().getApplication(), listener, queue)); } std::iostream& SslTcpjob::getStream() { if (!socket.isConnected()) { try { accept(); touch(); } catch (const std::exception& e) { log_debug("exception occured in accept (ssl): " << e.what()); regenerateJob(); throw; } regenerateJob(); if (!Tntnet::shouldStop()) handshake(); } return socket; } int SslTcpjob::getFd() const { return socket.getFd(); } void SslTcpjob::setRead() { socket.setTimeout(TntConfig::it().socketReadTimeout); } void SslTcpjob::setWrite() { socket.setTimeout(TntConfig::it().socketWriteTimeout); } #endif // USE_SSL ////////////////////////////////////////////////////////////////////// // Jobqueue // void Jobqueue::put(JobPtr j, bool force) { j->touch(); cxxtools::MutexLock lock(mutex); if (!force && capacity > 0) { while (jobs.size() >= capacity) { log_warn("Jobqueue full"); notFull.wait(lock); } } jobs.push_back(j); if (waitThreads == 0) noWaitThreads.signal(); notEmpty.signal(); } Jobqueue::JobPtr Jobqueue::get() { cxxtools::MutexLock lock(mutex); // wait, until a job is available ++waitThreads; while (jobs.empty()) notEmpty.wait(lock); --waitThreads; // take next job (queue is locked) JobPtr j = jobs.front(); jobs.pop_front(); // if there are threads waiting, wake another if (!jobs.empty() && waitThreads > 0) notEmpty.signal(); notFull.signal(); return j; } } <commit_msg>fix racing condition: releasing request may result in a pthread unlock error<commit_after>/* * Copyright (C) 2003-2005 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tnt/job.h" #include "tnt/tcpjob.h" #include "tnt/tntnet.h" #include <tnt/httpreply.h> #include <tnt/ssl.h> #include <cxxtools/log.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <config.h> #include <fcntl.h> log_define("tntnet.job") namespace tnt { Job::Job(Tntnet& app_, const SocketIf* socketIf_) : keepAliveCounter(TntConfig::it().keepAliveMax), request(app_, socketIf_), parser(request), lastAccessTime(0) { } Job::~Job() { } void Job::clear() { parser.reset(); request.clear(); } int Job::msecToTimeout(time_t currentTime) const { return (lastAccessTime - currentTime + 1) * 1000 + TntConfig::it().keepAliveTimeout - TntConfig::it().socketReadTimeout; } //////////////////////////////////////////////////////////////////////// // Tcpjob // std::string Tcpjob::getPeerIp() const { return socket.getPeerAddr(); } std::string Tcpjob::getServerIp() const { return socket.getSockAddr(); } bool Tcpjob::isSsl() const { return false; } void Tcpjob::accept() { socket.accept(listener); log_debug("connection accepted from " << getPeerIp()); } void Tcpjob::regenerateJob() { if (Tntnet::shouldStop()) queue.put(this); else queue.put(new Tcpjob(getRequest().getApplication(), listener, queue)); } std::iostream& Tcpjob::getStream() { if (!socket.isConnected()) { try { accept(); touch(); } catch (const std::exception& e) { regenerateJob(); log_debug("exception occured in accept: " << e.what()); throw; } regenerateJob(); } return socket; } int Tcpjob::getFd() const { return socket.getFd(); } void Tcpjob::setRead() { socket.setTimeout(TntConfig::it().socketReadTimeout); } void Tcpjob::setWrite() { socket.setTimeout(TntConfig::it().socketWriteTimeout); } #ifdef USE_SSL //////////////////////////////////////////////////////////////////////// // SslTcpjob // std::string SslTcpjob::getPeerIp() const { return socket.getPeerAddr(); } std::string SslTcpjob::getServerIp() const { return socket.getSockAddr(); } bool SslTcpjob::isSsl() const { return true; } void SslTcpjob::accept() { socket.accept(listener, cxxtools::net::TcpSocket::DEFER_ACCEPT); } void SslTcpjob::handshake() { socket.handshake(listener); fcntl(socket.getFd(), F_SETFD, FD_CLOEXEC); setRead(); } void SslTcpjob::regenerateJob() { if (Tntnet::shouldStop()) queue.put(this); else queue.put(new SslTcpjob(getRequest().getApplication(), listener, queue)); } std::iostream& SslTcpjob::getStream() { if (!socket.isConnected()) { try { accept(); touch(); } catch (const std::exception& e) { log_debug("exception occured in accept (ssl): " << e.what()); regenerateJob(); throw; } regenerateJob(); if (!Tntnet::shouldStop()) handshake(); } return socket; } int SslTcpjob::getFd() const { return socket.getFd(); } void SslTcpjob::setRead() { socket.setTimeout(TntConfig::it().socketReadTimeout); } void SslTcpjob::setWrite() { socket.setTimeout(TntConfig::it().socketWriteTimeout); } #endif // USE_SSL ////////////////////////////////////////////////////////////////////// // Jobqueue // void Jobqueue::put(JobPtr j, bool force) { j->touch(); cxxtools::MutexLock lock(mutex); if (!force && capacity > 0) { while (jobs.size() >= capacity) { log_warn("Jobqueue full"); notFull.wait(lock); } } jobs.push_back(j); // We have to drop ownership before releasing the lock of the queue. // Therefore we set the smart pointer to 0. j = 0; if (waitThreads == 0) noWaitThreads.signal(); notEmpty.signal(); } Jobqueue::JobPtr Jobqueue::get() { cxxtools::MutexLock lock(mutex); // wait, until a job is available ++waitThreads; while (jobs.empty()) notEmpty.wait(lock); --waitThreads; // take next job (queue is locked) JobPtr j = jobs.front(); jobs.pop_front(); // if there are threads waiting, wake another if (!jobs.empty() && waitThreads > 0) notEmpty.signal(); notFull.signal(); return j; } } <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <fstream> #include <string> // Loriano: let's try Armadillo quick code #include <armadillo> #define ENTDIM 8 #define COORDIM (ENTDIM-2) #define PARAMDIM 5 namespace { int numofline (const char * fname) { int number_of_lines = 0; std::string line; std::ifstream myfile(fname); while (std::getline(myfile, line)) ++number_of_lines; myfile.close(); return number_of_lines; } void writetofile (const char * fname, int cidx, const arma::mat & mat) { if (cidx < (int) mat.n_cols) { std::ofstream myfile(fname); for (int i=0; i<(int)mat.n_rows; i++) myfile << i << " " << mat(i,cidx) << std::endl; myfile.close(); } } } int main (int argc, char ** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl; return 1; } int num_of_line = numofline(argv[1]); std::cout << "file has " << num_of_line << " line " << std::endl; int num_of_ent = (num_of_line-1)/ENTDIM; std::cout << " " << num_of_ent << " entries " << std::endl; // non perfomante ma easy to go arma::mat paraminp = arma::zeros<arma::mat>(num_of_ent,PARAMDIM); arma::mat coordinp = arma::zeros<arma::mat>(num_of_ent,3*COORDIM); arma::mat layer, ladder, module; layer.set_size(num_of_ent,COORDIM); ladder.set_size(num_of_ent,COORDIM); module.set_size(num_of_ent,COORDIM); // leggere file coordinate tracce simulate plus parametri std::string line; std::ifstream mytfp; mytfp.open (argv[1], std::ios::in); std::getline (mytfp, line); //std::cout << line << std::endl; for (int i = 0; i < num_of_ent; ++i) { int fake1, fake2; mytfp >> fake1 >> fake2 ; #ifdef DEBUG std::cout << fake1 << " " << fake2 << std::endl; #endif for (int j = 0; j < COORDIM; ++j) { int a, b, c; mytfp >> coordinp(i, j*3) >> coordinp(i, j*3+1) >> coordinp(i, j*3+2) >> a >> b >> c; layer(i, j) = a; ladder(i, j) = b; module(i, j) = c; } mytfp >> paraminp(i,0) >> paraminp(i,1) >> paraminp(i,2) >> paraminp(i,3) >> paraminp(i,4); } mytfp.close(); for (int i = 0; i < PARAMDIM; ++i) { switch (i) { case 0: std::cout << i+1 << " q * pt" << std::endl; break; case 1: std::cout << i+1 << " phi" << std::endl; break; case 2: std::cout << i+1 << " d0" << std::endl; break; case 3: std::cout << i+1 << " eta" << std::endl; break; case 4: std::cout << i+1 << " z0" << std::endl; break; }; std::ostringstream fname; fname << "p" << i+1 << ".txt"; writetofile(fname.str().c_str(), i, paraminp); } #ifdef DEBUG for (int i = 0; i < num_of_ent; ++i) { for (int j = 0; j < COORDIM; ++j) { std::cout << coordinp(i, j*3) << " " << coordinp(i, j*3+1) << " " << coordinp(i, j*3+2) << " " << ladder(i, j) << std::endl; } std::cout << paraminp(i,0) << " " << paraminp(i,1) << " " << paraminp(i,2) << " " << paraminp(i,3) << " " << paraminp(i,4) << std::endl; } #endif arma::mat param; arma::mat coord; int k = 0; // to be used to select inly a ladder .... for (int i = 0; i < num_of_ent; ++i) { bool todo = false; //if ((ladder(i, 0) == 0) && (ladder(i, 1) == 1) && // (ladder(i, 2) == 2)) if (paraminp(i,0) > 0.0) todo = true; if (todo) k++; } param.set_size(k,PARAMDIM); coord.set_size(k,3*COORDIM); k = 0; // to be used to select inly a ladder .... for (int i = 0; i < num_of_ent; ++i) { bool todo = false; //if ((ladder(i, 0) == 0) && (ladder(i, 1) == 1) && // (ladder(i, 2) == 2)) if (paraminp(i,0) > 0.0) todo = true; if (todo) { for (int j = 0; j < 3*COORDIM; ++j) coord(k,j) = coordinp(i,j); for (int j = 0; j < PARAMDIM; ++j) param(k,j) = paraminp(i,j); k++; } } num_of_ent = k; std::cout << "We got " << num_of_ent << " tracks " << std::endl; // projection arma::mat score; // ordered arma::vec eigval; // by row or by column ? arma::mat eigvec; arma::princomp(eigvec, score, eigval, coord); //std::cout << score.n_rows << " " << score.n_cols << std::endl; std::ofstream myfilesc("scoreplot.txt"); for (int i=0; i<(int)score.n_rows; ++i) { myfilesc << score(i,0) << " " << score(i,1) << " " << score(i,2) << std::endl; double mainr = 0.0e0; for (int j=1; j<5; ++j) mainr += score(i,j) * score(i,j); double residue = 0.0; for (int j=5; j<3*COORDIM; ++j) residue += score(i,j) * score(i,j); std::cout << "Track " << i+1 << " residue " << residue << " mainr " << mainr << std::endl; } myfilesc.close(); double totval = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) totval += eigval(i); std::cout << "Eigenvalues: " << std::endl; double totvar = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) { if (i < PARAMDIM) totvar += 100.0e0*(eigval(i)/totval); std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << "% value: " << eigval(i) << std::endl; } std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl; arma::mat v = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); v = arma::cov(coord); #ifdef DEBUG /* correlation matrix ricorda su dati standardizzati coincide con la matrice * di covarianza : * z = x -<x> / sigma */ arma::mat corr = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) corr(i,j) = v(i,j) / sqrt(v(i,i)*v(j,j)); std::cout << "Correlation matrix: " << std::endl; std::cout << corr; #endif arma::mat vi = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); vi = v.i(); #ifdef DEBUG std::cout << "inverse by cov matrix: " << std::endl; std::cout << v * vi ; #endif // and so on ... arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM); arma::mat paramm = arma::zeros<arma::mat>(PARAMDIM); arma::mat coordm = arma::zeros<arma::mat>(3*COORDIM); double sum = 1.0e0; for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm(i) += (coord(l,i)-coordm(i))/sum; for (int i=0; i<PARAMDIM; ++i) paramm(i) += (param(l,i)-paramm(i))/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<PARAMDIM; ++j) { hcap(i,j) += ((coord(l,i) - coordm(i))* (param(l,j) - paramm(j))- (sum-1.0e0)*hcap(i,j)/sum)/(sum-1.0e0); } } } arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM); for (int i=0; i<PARAMDIM; ++i) for (int l=0; l<(3*COORDIM); ++l) for (int m=0; m<(3*COORDIM); ++m) cmtx(i,l) += vi(l,m) * hcap (m,i); #ifdef DEBUG std::cout << "C matrix: " << std::endl; std::cout << cmtx; #endif arma::mat q = arma::zeros<arma::mat>(PARAMDIM); for (int i=0; i<PARAMDIM; ++i) { q(i) = paramm(i); for (int l=0; l<(3*COORDIM); ++l) q(i) -= cmtx(i,l)*coordm[l]; } #ifdef DEBUG std::cout << "Q vector: " << std::endl; for (int i=0; i<PARAMDIM; ++i) std::cout << q(i) << std::endl; #endif //test back arma::running_stat<double> chi2stats; arma::running_stat<double> pc[PARAMDIM]; for (int l=0; l<num_of_ent; ++l) { std::cout << "Track: " << l+1 << std::endl; for (int i=0; i<PARAMDIM; ++i) { double p = q(i); for (int k=0; k<(3*COORDIM); ++k) p += cmtx(i,k)*coord(l,k); std::cout << " computed " << p << " real " << param(l,i) << std::endl; pc[i](fabs(p - param(l,i))/(fabs(p + param(l,i))/2.0)); } /* chi**2 */ double chi2 = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) chi2 += (coord(l,i) - coordm(i)) * vi(i, j) * (coord(l,j) - coordm(j)); std::cout << " chi2: " << chi2 << std::endl; chi2stats(chi2); } std::cout << "chi2 mean = " << chi2stats.mean() << std::endl; std::cout << "chi2 stdev = " << chi2stats.stddev() << std::endl; std::cout << "chi2 min = " << chi2stats.min() << std::endl; std::cout << "chi2 max = " << chi2stats.max() << std::endl; for (int i=0; i<PARAMDIM; ++i) { std::cout << 100.0*pc[i].mean() << " " << 100.0*pc[i].stddev() << std::endl; arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(param(l,i)); std::cout << " mean = " << stats.mean() << std::endl; std::cout << " stdev = " << stats.stddev() << std::endl; std::cout << " min = " << stats.min() << std::endl; std::cout << " max = " << stats.max() << std::endl; } return 0; } <commit_msg>count subsectors<commit_after>#include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <string> #include <string> #include <set> // Loriano: let's try Armadillo quick code #include <armadillo> #define ENTDIM 8 #define COORDIM (ENTDIM-2) #define PARAMDIM 5 namespace { int numofline (const char * fname) { int number_of_lines = 0; std::string line; std::ifstream myfile(fname); while (std::getline(myfile, line)) ++number_of_lines; myfile.close(); return number_of_lines; } void writetofile (const char * fname, int cidx, const arma::mat & mat) { if (cidx < (int) mat.n_cols) { std::ofstream myfile(fname); for (int i=0; i<(int)mat.n_rows; i++) myfile << i << " " << mat(i,cidx) << std::endl; myfile.close(); } } } int main (int argc, char ** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl; return 1; } int num_of_line = numofline(argv[1]); std::cout << "file has " << num_of_line << " line " << std::endl; int num_of_ent = (num_of_line-1)/ENTDIM; std::cout << " " << num_of_ent << " entries " << std::endl; // non perfomante ma easy to go arma::mat paraminp = arma::zeros<arma::mat>(num_of_ent,PARAMDIM); arma::mat coordinp = arma::zeros<arma::mat>(num_of_ent,3*COORDIM); arma::mat layer, ladder, module; layer.set_size(num_of_ent,COORDIM); ladder.set_size(num_of_ent,COORDIM); module.set_size(num_of_ent,COORDIM); // leggere file coordinate tracce simulate plus parametri std::string line; std::ifstream mytfp; mytfp.open (argv[1], std::ios::in); std::getline (mytfp, line); //std::cout << line << std::endl; std::set<std::string> subsectors; for (int i = 0; i < num_of_ent; ++i) { int fake1, fake2; mytfp >> fake1 >> fake2 ; #ifdef DEBUG std::cout << fake1 << " " << fake2 << std::endl; #endif std::ostringstream oss; oss << std::setfill('0'); for (int j = 0; j < COORDIM; ++j) { int a, b, c; mytfp >> coordinp(i, j*3) >> coordinp(i, j*3+1) >> coordinp(i, j*3+2) >> a >> b >> c; layer(i, j) = a; ladder(i, j) = b; module(i, j) = c; oss << std::setw(2) << layer(i, j); oss << std::setw(2) << ladder(i, j); if (j != COORDIM-1) oss<<"-"; subsectors.insert(oss.str()); } mytfp >> paraminp(i,0) >> paraminp(i,1) >> paraminp(i,2) >> paraminp(i,3) >> paraminp(i,4); } mytfp.close(); std::cout << "We found " << subsectors.size() << " subsector " << std::endl; for (int i = 0; i < PARAMDIM; ++i) { switch (i) { case 0: std::cout << i+1 << " q * pt" << std::endl; break; case 1: std::cout << i+1 << " phi" << std::endl; break; case 2: std::cout << i+1 << " d0" << std::endl; break; case 3: std::cout << i+1 << " eta" << std::endl; break; case 4: std::cout << i+1 << " z0" << std::endl; break; }; std::ostringstream fname; fname << "p" << i+1 << ".txt"; writetofile(fname.str().c_str(), i, paraminp); } #ifdef DEBUG for (int i = 0; i < num_of_ent; ++i) { for (int j = 0; j < COORDIM; ++j) { std::cout << coordinp(i, j*3) << " " << coordinp(i, j*3+1) << " " << coordinp(i, j*3+2) << " " << ladder(i, j) << std::endl; } std::cout << paraminp(i,0) << " " << paraminp(i,1) << " " << paraminp(i,2) << " " << paraminp(i,3) << " " << paraminp(i,4) << std::endl; } #endif arma::mat param; arma::mat coord; int k = 0; // to be used to select inly a ladder .... for (int i = 0; i < num_of_ent; ++i) { bool todo = false; //if ((ladder(i, 0) == 0) && (ladder(i, 1) == 1) && // (ladder(i, 2) == 2)) if (paraminp(i,0) > 0.0) todo = true; if (todo) k++; } param.set_size(k,PARAMDIM); coord.set_size(k,3*COORDIM); k = 0; // to be used to select inly a ladder .... for (int i = 0; i < num_of_ent; ++i) { bool todo = false; //if ((ladder(i, 0) == 0) && (ladder(i, 1) == 1) && // (ladder(i, 2) == 2)) if (paraminp(i,0) > 0.0) todo = true; if (todo) { for (int j = 0; j < 3*COORDIM; ++j) coord(k,j) = coordinp(i,j); for (int j = 0; j < PARAMDIM; ++j) param(k,j) = paraminp(i,j); k++; } } num_of_ent = k; std::cout << "We got " << num_of_ent << " tracks " << std::endl; // projection arma::mat score; // ordered arma::vec eigval; // by row or by column ? arma::mat eigvec; arma::princomp(eigvec, score, eigval, coord); //std::cout << score.n_rows << " " << score.n_cols << std::endl; std::ofstream myfilesc("scoreplot.txt"); for (int i=0; i<(int)score.n_rows; ++i) { myfilesc << score(i,0) << " " << score(i,1) << " " << score(i,2) << std::endl; double mainr = 0.0e0; for (int j=1; j<5; ++j) mainr += score(i,j) * score(i,j); double residue = 0.0; for (int j=5; j<3*COORDIM; ++j) residue += score(i,j) * score(i,j); std::cout << "Track " << i+1 << " residue " << residue << " mainr " << mainr << std::endl; } myfilesc.close(); double totval = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) totval += eigval(i); std::cout << "Eigenvalues: " << std::endl; double totvar = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) { if (i < PARAMDIM) totvar += 100.0e0*(eigval(i)/totval); std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << "% value: " << eigval(i) << std::endl; } std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl; arma::mat v = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); v = arma::cov(coord); #ifdef DEBUG /* correlation matrix ricorda su dati standardizzati coincide con la matrice * di covarianza : * z = x -<x> / sigma */ arma::mat corr = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) corr(i,j) = v(i,j) / sqrt(v(i,i)*v(j,j)); std::cout << "Correlation matrix: " << std::endl; std::cout << corr; #endif arma::mat vi = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); vi = v.i(); #ifdef DEBUG std::cout << "inverse by cov matrix: " << std::endl; std::cout << v * vi ; #endif // and so on ... arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM); arma::mat paramm = arma::zeros<arma::mat>(PARAMDIM); arma::mat coordm = arma::zeros<arma::mat>(3*COORDIM); double sum = 1.0e0; for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm(i) += (coord(l,i)-coordm(i))/sum; for (int i=0; i<PARAMDIM; ++i) paramm(i) += (param(l,i)-paramm(i))/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<PARAMDIM; ++j) { hcap(i,j) += ((coord(l,i) - coordm(i))* (param(l,j) - paramm(j))- (sum-1.0e0)*hcap(i,j)/sum)/(sum-1.0e0); } } } arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM); for (int i=0; i<PARAMDIM; ++i) for (int l=0; l<(3*COORDIM); ++l) for (int m=0; m<(3*COORDIM); ++m) cmtx(i,l) += vi(l,m) * hcap (m,i); #ifdef DEBUG std::cout << "C matrix: " << std::endl; std::cout << cmtx; #endif arma::mat q = arma::zeros<arma::mat>(PARAMDIM); for (int i=0; i<PARAMDIM; ++i) { q(i) = paramm(i); for (int l=0; l<(3*COORDIM); ++l) q(i) -= cmtx(i,l)*coordm[l]; } #ifdef DEBUG std::cout << "Q vector: " << std::endl; for (int i=0; i<PARAMDIM; ++i) std::cout << q(i) << std::endl; #endif //test back arma::running_stat<double> chi2stats; arma::running_stat<double> pc[PARAMDIM]; for (int l=0; l<num_of_ent; ++l) { std::cout << "Track: " << l+1 << std::endl; for (int i=0; i<PARAMDIM; ++i) { double p = q(i); for (int k=0; k<(3*COORDIM); ++k) p += cmtx(i,k)*coord(l,k); std::cout << " computed " << p << " real " << param(l,i) << std::endl; pc[i](fabs(p - param(l,i))/(fabs(p + param(l,i))/2.0)); } /* chi**2 */ double chi2 = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) chi2 += (coord(l,i) - coordm(i)) * vi(i, j) * (coord(l,j) - coordm(j)); std::cout << " chi2: " << chi2 << std::endl; chi2stats(chi2); } std::cout << "chi2 mean = " << chi2stats.mean() << std::endl; std::cout << "chi2 stdev = " << chi2stats.stddev() << std::endl; std::cout << "chi2 min = " << chi2stats.min() << std::endl; std::cout << "chi2 max = " << chi2stats.max() << std::endl; for (int i=0; i<PARAMDIM; ++i) { std::cout << 100.0*pc[i].mean() << " " << 100.0*pc[i].stddev() << std::endl; arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(param(l,i)); std::cout << " mean = " << stats.mean() << std::endl; std::cout << " stdev = " << stats.stddev() << std::endl; std::cout << " min = " << stats.min() << std::endl; std::cout << " max = " << stats.max() << std::endl; } return 0; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "com4j.h" void error( JNIEnv* env, const char* file, int line, HRESULT hr, const char* msg ... ) { // format the message char w[1024]; va_list va; va_start(va,msg); vsprintf(w,msg,va); env->ExceptionClear(); env->Throw( (jthrowable)comexception_new_hr( env, env->NewStringUTF(w), hr, file, line ) ); } void error( JNIEnv* env, const char* file, int line, const char* msg ... ) { // format the message char w[1024]; va_list va; va_start(va,msg); vsprintf(w,msg,va); env->ExceptionClear(); env->Throw( (jthrowable)comexception_new( env, env->NewStringUTF(w), file, line ) ); } <commit_msg>fixed issue #8.<commit_after>#include "stdafx.h" #include "com4j.h" void error( JNIEnv* env, const char* file, int line, HRESULT hr, const char* msg ... ) { // format the message char w[1024]; va_list va; va_start(va,msg); vsprintf(w,msg,va); env->ExceptionClear(); env->Throw( (jthrowable)comexception_new_hr( env, env->NewStringUTF(w), hr, env->NewStringUTF(file), line ) ); } void error( JNIEnv* env, const char* file, int line, const char* msg ... ) { // format the message char w[1024]; va_list va; va_start(va,msg); vsprintf(w,msg,va); env->ExceptionClear(); env->Throw( (jthrowable)comexception_new( env, env->NewStringUTF(w), env->NewStringUTF(file), line ) ); } <|endoftext|>
<commit_before>#include "Client.h" #include "Common.h" #include "SchemeHandlerFactory.h" #include "PrintHandler.h" #include "RenderHandler.h" #include "RenderProcessHandler.h" #include "RequestHandler.h" #include "include/base/cef_logging.h" #include "include/wrapper/cef_helpers.h" #include "include/base/cef_bind.h" #include "include/wrapper/cef_closure_task.h" #include "include/wrapper/cef_message_router.h" namespace cefpdf { Client::Client() : m_jobManager(new job::Manager()), m_pendingBrowsersCount(0), m_browsersCount(0), m_initialized(false), m_contextInitialized(false), m_running(false), m_stopAfterLastJob(false), m_printHandler(new PrintHandler), m_renderHandler(new RenderHandler), m_renderProcessHandler(new RenderProcessHandler), m_requestHandler(new RequestHandler) { m_settings.no_sandbox = true; m_settings.windowless_rendering_enabled = true; m_settings.command_line_args_disabled = true; m_windowInfo.windowless_rendering_enabled = true; m_browserSettings.windowless_frame_rate = 1; CefString(&m_browserSettings.default_encoding).FromString(constants::encoding); m_browserSettings.plugins = STATE_DISABLED; m_browserSettings.javascript_close_windows = STATE_DISABLED; } int Client::ExecuteSubProcess(const CefMainArgs& mainArgs) { return CefExecuteProcess(mainArgs, this, NULL); } void Client::Initialize(const CefMainArgs& mainArgs) { DCHECK(!m_initialized); m_initialized = true; CefInitialize(mainArgs, m_settings, this, NULL); } void Client::Shutdown() { DCHECK(m_initialized); CefShutdown(); m_contextInitialized = false; m_initialized = false; } void Client::Run() { DCHECK(m_initialized); DCHECK(!m_running); m_running = true; CefRunMessageLoop(); m_running = false; Shutdown(); } void Client::Stop() { DCHECK(m_initialized); if (m_running) { m_pendingBrowsersCount = 0; m_jobManager->StopAll(); CefQuitMessageLoop(); } } void Client::AddJob(CefRefPtr<job::Job> job) { m_jobManager->Queue(job); CreateBrowsers(1); } void Client::CreateBrowsers(unsigned int browserCount) { m_pendingBrowsersCount += browserCount; if (!m_contextInitialized) { return; } while (m_pendingBrowsersCount > 0 && m_browsersCount <= constants::maxProcesses) { --m_pendingBrowsersCount; ++m_browsersCount; CefBrowserHost::CreateBrowser(m_windowInfo, this, "", m_browserSettings, NULL); } } void Client::SetRemoteTrigger(bool flag) { m_remoteTrigger = flag; } // CefApp methods: // ----------------------------------------------------------------------------- CefRefPtr<CefBrowserProcessHandler> Client::GetBrowserProcessHandler() { return this; } void Client::OnRegisterCustomSchemes(CefRawPtr<CefSchemeRegistrar> registrar) { registrar->AddCustomScheme(constants::scheme, true, false, false, false, true, false); } void Client::OnBeforeCommandLineProcessing(const CefString& process_type, CefRefPtr<CefCommandLine> command_line) { DLOG(INFO) << "Client::OnBeforeCommandLineProcessing" << " with process_type: " << process_type.ToString() << ", command_line: " << command_line->GetCommandLineString().ToString(); command_line->AppendSwitch("disable-gpu"); command_line->AppendSwitch("disable-gpu-compositing"); command_line->AppendSwitch("disable-extensions"); command_line->AppendSwitch("disable-pinch"); }; CefRefPtr<CefRenderProcessHandler> Client::GetRenderProcessHandler() { return m_renderProcessHandler; } // CefBrowserProcessHandler methods: // ----------------------------------------------------------------------------- CefRefPtr<CefPrintHandler> Client::GetPrintHandler() { return m_printHandler; } void Client::OnBeforeChildProcessLaunch(CefRefPtr<CefCommandLine> command_line) { DLOG(INFO) << "Client::OnBeforeChildProcessLaunch" << " with command_line: " << command_line->GetCommandLineString().ToString(); } void Client::OnContextInitialized() { DLOG(INFO) << "Client::OnContextInitialized"; CEF_REQUIRE_UI_THREAD(); m_contextInitialized = true; CefRegisterSchemeHandlerFactory(constants::scheme, "", new SchemeHandlerFactory(m_jobManager)); CreateBrowsers(); if (!m_requestHandler->m_messageRouterBrowserSide) { CefMessageRouterConfig config; config.js_query_function = constants::jsQueryFunction; config.js_cancel_function = constants::jsCancelFunction; m_requestHandler->m_messageRouterBrowserSide = CefMessageRouterBrowserSide::Create(config); m_requestHandler->m_messageRouterBrowserSide->AddHandler(this, true); } } // CefClient methods: // ----------------------------------------------------------------------------- CefRefPtr<CefLifeSpanHandler> Client::GetLifeSpanHandler() { return this; } CefRefPtr<CefLoadHandler> Client::GetLoadHandler() { return this; } CefRefPtr<CefRenderHandler> Client::GetRenderHandler() { return m_renderHandler; } CefRefPtr<CefRequestHandler> Client::GetRequestHandler() { return m_requestHandler; } bool Client::OnProcessMessageReceived( CefRefPtr<CefBrowser> browser, CefProcessId source_process, CefRefPtr<CefProcessMessage> message ) { DLOG(INFO) << "Client::OnProcessMessageReceived"; CEF_REQUIRE_UI_THREAD(); m_requestHandler->m_messageRouterBrowserSide->OnProcessMessageReceived(browser, source_process, message); return true; } // CefLifeSpanHandler methods: // ----------------------------------------------------------------------------- void Client::OnAfterCreated(CefRefPtr<CefBrowser> browser) { DLOG(INFO) << "Client::OnAfterCreated"; CEF_REQUIRE_UI_THREAD(); CefRefPtr<CefFrame> frame = browser->GetMainFrame(); frame->ExecuteJavaScript( "window.triggerCefPdf = function () { window." + constants::jsQueryFunction + "({request: "", onSuccess: function () {}, onFailure: function () {}}); };" , frame->GetURL() , 0 ); // Assign this browser to the next job. JobsManager will // check if there is any queued job m_jobManager->Assign(browser); } bool Client::DoClose(CefRefPtr<CefBrowser> browser) { DLOG(INFO) << "Client::DoClose"; CEF_REQUIRE_UI_THREAD(); // Allow the close. For windowed browsers this will result in the OS close // event being sent. return false; } void Client::OnBeforeClose(CefRefPtr<CefBrowser> browser) { DLOG(INFO) << "Client::OnBeforeClose"; CEF_REQUIRE_UI_THREAD(); --m_browsersCount; m_requestHandler->m_messageRouterBrowserSide->OnBeforeClose(browser); if (0 == m_browsersCount && m_stopAfterLastJob) { CefPostDelayedTask(TID_UI, base::Bind(&Client::Stop, this), 50); } else { CreateBrowsers(); } } // CefLoadHandler methods: // ----------------------------------------------------------------------------- void Client::OnLoadStart(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, TransitionType transition_type) { DLOG(INFO) << "Client::OnLoadStart" << " with url: " << frame->GetURL().ToString(); CEF_REQUIRE_UI_THREAD(); } void Client::OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) { DLOG(INFO) << "Client::OnLoadEnd" << " with url: " << frame->GetURL().ToString() << ", httpStatusCode: " << httpStatusCode; CEF_REQUIRE_UI_THREAD(); if (frame->IsMain() && !m_remoteTrigger) { m_jobManager->Process(browser, httpStatusCode); } } void Client::OnLoadError( CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, ErrorCode errorCode, const CefString& errorText, const CefString& failedUrl ) { DLOG(INFO) << "Client::OnLoadError" << " with errorCode: " << errorCode << ", failedUrl: " << failedUrl.ToString(); CEF_REQUIRE_UI_THREAD(); if (frame->IsMain()) { m_jobManager->Abort(browser, errorCode); } } // CefMessageRouterBrowserSide::Handler methods: bool Client::OnQuery( CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int64 query_id, const CefString& request, bool persistent, CefRefPtr<Callback> callback ) { DLOG(INFO) << "Client::OnQuery"; CEF_REQUIRE_UI_THREAD(); if (frame->IsMain() && m_remoteTrigger) { m_jobManager->Process(browser, 200); callback->Success("OK"); return true; } return false; } } // namespace cefpdf <commit_msg>Only add triggerCefPdf to window if remote trigger flag is provided<commit_after>#include "Client.h" #include "Common.h" #include "SchemeHandlerFactory.h" #include "PrintHandler.h" #include "RenderHandler.h" #include "RenderProcessHandler.h" #include "RequestHandler.h" #include "include/base/cef_logging.h" #include "include/wrapper/cef_helpers.h" #include "include/base/cef_bind.h" #include "include/wrapper/cef_closure_task.h" #include "include/wrapper/cef_message_router.h" namespace cefpdf { Client::Client() : m_jobManager(new job::Manager()), m_pendingBrowsersCount(0), m_browsersCount(0), m_initialized(false), m_contextInitialized(false), m_running(false), m_stopAfterLastJob(false), m_printHandler(new PrintHandler), m_renderHandler(new RenderHandler), m_renderProcessHandler(new RenderProcessHandler), m_requestHandler(new RequestHandler) { m_settings.no_sandbox = true; m_settings.windowless_rendering_enabled = true; m_settings.command_line_args_disabled = true; m_windowInfo.windowless_rendering_enabled = true; m_browserSettings.windowless_frame_rate = 1; CefString(&m_browserSettings.default_encoding).FromString(constants::encoding); m_browserSettings.plugins = STATE_DISABLED; m_browserSettings.javascript_close_windows = STATE_DISABLED; } int Client::ExecuteSubProcess(const CefMainArgs& mainArgs) { return CefExecuteProcess(mainArgs, this, NULL); } void Client::Initialize(const CefMainArgs& mainArgs) { DCHECK(!m_initialized); m_initialized = true; CefInitialize(mainArgs, m_settings, this, NULL); } void Client::Shutdown() { DCHECK(m_initialized); CefShutdown(); m_contextInitialized = false; m_initialized = false; } void Client::Run() { DCHECK(m_initialized); DCHECK(!m_running); m_running = true; CefRunMessageLoop(); m_running = false; Shutdown(); } void Client::Stop() { DCHECK(m_initialized); if (m_running) { m_pendingBrowsersCount = 0; m_jobManager->StopAll(); CefQuitMessageLoop(); } } void Client::AddJob(CefRefPtr<job::Job> job) { m_jobManager->Queue(job); CreateBrowsers(1); } void Client::CreateBrowsers(unsigned int browserCount) { m_pendingBrowsersCount += browserCount; if (!m_contextInitialized) { return; } while (m_pendingBrowsersCount > 0 && m_browsersCount <= constants::maxProcesses) { --m_pendingBrowsersCount; ++m_browsersCount; CefBrowserHost::CreateBrowser(m_windowInfo, this, "", m_browserSettings, NULL); } } void Client::SetRemoteTrigger(bool flag) { m_remoteTrigger = flag; } // CefApp methods: // ----------------------------------------------------------------------------- CefRefPtr<CefBrowserProcessHandler> Client::GetBrowserProcessHandler() { return this; } void Client::OnRegisterCustomSchemes(CefRawPtr<CefSchemeRegistrar> registrar) { registrar->AddCustomScheme(constants::scheme, true, false, false, false, true, false); } void Client::OnBeforeCommandLineProcessing(const CefString& process_type, CefRefPtr<CefCommandLine> command_line) { DLOG(INFO) << "Client::OnBeforeCommandLineProcessing" << " with process_type: " << process_type.ToString() << ", command_line: " << command_line->GetCommandLineString().ToString(); command_line->AppendSwitch("disable-gpu"); command_line->AppendSwitch("disable-gpu-compositing"); command_line->AppendSwitch("disable-extensions"); command_line->AppendSwitch("disable-pinch"); }; CefRefPtr<CefRenderProcessHandler> Client::GetRenderProcessHandler() { return m_renderProcessHandler; } // CefBrowserProcessHandler methods: // ----------------------------------------------------------------------------- CefRefPtr<CefPrintHandler> Client::GetPrintHandler() { return m_printHandler; } void Client::OnBeforeChildProcessLaunch(CefRefPtr<CefCommandLine> command_line) { DLOG(INFO) << "Client::OnBeforeChildProcessLaunch" << " with command_line: " << command_line->GetCommandLineString().ToString(); } void Client::OnContextInitialized() { DLOG(INFO) << "Client::OnContextInitialized"; CEF_REQUIRE_UI_THREAD(); m_contextInitialized = true; CefRegisterSchemeHandlerFactory(constants::scheme, "", new SchemeHandlerFactory(m_jobManager)); CreateBrowsers(); if (!m_requestHandler->m_messageRouterBrowserSide) { CefMessageRouterConfig config; config.js_query_function = constants::jsQueryFunction; config.js_cancel_function = constants::jsCancelFunction; m_requestHandler->m_messageRouterBrowserSide = CefMessageRouterBrowserSide::Create(config); m_requestHandler->m_messageRouterBrowserSide->AddHandler(this, true); } } // CefClient methods: // ----------------------------------------------------------------------------- CefRefPtr<CefLifeSpanHandler> Client::GetLifeSpanHandler() { return this; } CefRefPtr<CefLoadHandler> Client::GetLoadHandler() { return this; } CefRefPtr<CefRenderHandler> Client::GetRenderHandler() { return m_renderHandler; } CefRefPtr<CefRequestHandler> Client::GetRequestHandler() { return m_requestHandler; } bool Client::OnProcessMessageReceived( CefRefPtr<CefBrowser> browser, CefProcessId source_process, CefRefPtr<CefProcessMessage> message ) { DLOG(INFO) << "Client::OnProcessMessageReceived"; CEF_REQUIRE_UI_THREAD(); m_requestHandler->m_messageRouterBrowserSide->OnProcessMessageReceived(browser, source_process, message); return true; } // CefLifeSpanHandler methods: // ----------------------------------------------------------------------------- void Client::OnAfterCreated(CefRefPtr<CefBrowser> browser) { DLOG(INFO) << "Client::OnAfterCreated"; CEF_REQUIRE_UI_THREAD(); if (m_remoteTrigger) { CefRefPtr<CefFrame> frame = browser->GetMainFrame(); frame->ExecuteJavaScript( "window.triggerCefPdf = function () { window." + constants::jsQueryFunction + "({request: "", onSuccess: function () {}, onFailure: function () {}}); };" , frame->GetURL() , 0 ); } // Assign this browser to the next job. JobsManager will // check if there is any queued job m_jobManager->Assign(browser); } bool Client::DoClose(CefRefPtr<CefBrowser> browser) { DLOG(INFO) << "Client::DoClose"; CEF_REQUIRE_UI_THREAD(); // Allow the close. For windowed browsers this will result in the OS close // event being sent. return false; } void Client::OnBeforeClose(CefRefPtr<CefBrowser> browser) { DLOG(INFO) << "Client::OnBeforeClose"; CEF_REQUIRE_UI_THREAD(); --m_browsersCount; m_requestHandler->m_messageRouterBrowserSide->OnBeforeClose(browser); if (0 == m_browsersCount && m_stopAfterLastJob) { CefPostDelayedTask(TID_UI, base::Bind(&Client::Stop, this), 50); } else { CreateBrowsers(); } } // CefLoadHandler methods: // ----------------------------------------------------------------------------- void Client::OnLoadStart(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, TransitionType transition_type) { DLOG(INFO) << "Client::OnLoadStart" << " with url: " << frame->GetURL().ToString(); CEF_REQUIRE_UI_THREAD(); } void Client::OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) { DLOG(INFO) << "Client::OnLoadEnd" << " with url: " << frame->GetURL().ToString() << ", httpStatusCode: " << httpStatusCode; CEF_REQUIRE_UI_THREAD(); if (frame->IsMain() && !m_remoteTrigger) { m_jobManager->Process(browser, httpStatusCode); } } void Client::OnLoadError( CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, ErrorCode errorCode, const CefString& errorText, const CefString& failedUrl ) { DLOG(INFO) << "Client::OnLoadError" << " with errorCode: " << errorCode << ", failedUrl: " << failedUrl.ToString(); CEF_REQUIRE_UI_THREAD(); if (frame->IsMain()) { m_jobManager->Abort(browser, errorCode); } } // CefMessageRouterBrowserSide::Handler methods: bool Client::OnQuery( CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int64 query_id, const CefString& request, bool persistent, CefRefPtr<Callback> callback ) { DLOG(INFO) << "Client::OnQuery"; CEF_REQUIRE_UI_THREAD(); if (frame->IsMain() && m_remoteTrigger) { m_jobManager->Process(browser, 200); callback->Success("OK"); return true; } return false; } } // namespace cefpdf <|endoftext|>
<commit_before><commit_msg>fix memory leak for python record reader<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "cefclient/cefclient.h" #include <stdio.h> #include <cstdlib> #include <sstream> #include <string> #include "include/cef_app.h" #include "include/cef_browser.h" #include "include/cef_command_line.h" #include "include/cef_frame.h" #include "include/cef_runnable.h" #include "include/cef_web_plugin.h" #include "cefclient/client_handler.h" #include "cefclient/client_switches.h" #include "cefclient/string_util.h" #include "cefclient/util.h" CefRefPtr<ClientHandler> g_handler; CefRefPtr<CefCommandLine> g_command_line; CefRefPtr<CefBrowser> AppGetBrowser() { if (!g_handler.get()) return NULL; return g_handler->GetBrowser(); } CefWindowHandle AppGetMainHwnd() { if (!g_handler.get()) return NULL; return g_handler->GetMainHwnd(); } void AppInitCommandLine(int argc, const char* const* argv) { g_command_line = CefCommandLine::CreateCommandLine(); #if defined(OS_WIN) g_command_line->InitFromString(::GetCommandLineW()); #else g_command_line->InitFromArgv(argc, argv); #endif } // Returns the application command line object. CefRefPtr<CefCommandLine> AppGetCommandLine() { return g_command_line; } // Returns the application settings based on command line arguments. void AppGetSettings(CefSettings& settings) { ASSERT(g_command_line.get()); if (!g_command_line.get()) return; CefString str; #if defined(OS_WIN) settings.multi_threaded_message_loop = g_command_line->HasSwitch(cefclient::kMultiThreadedMessageLoop); #endif CefString(&settings.cache_path) = g_command_line->GetSwitchValue(cefclient::kCachePath); } bool AppIsOffScreenRenderingEnabled() { ASSERT(g_command_line.get()); if (!g_command_line.get()) return false; return g_command_line->HasSwitch(cefclient::kOffScreenRenderingEnabled); } void RunGetSourceTest(CefRefPtr<CefBrowser> browser) { class Visitor : public CefStringVisitor { public: explicit Visitor(CefRefPtr<CefBrowser> browser) : browser_(browser) {} virtual void Visit(const CefString& string) OVERRIDE { std::string source = StringReplace(string, "<", "&lt;"); source = StringReplace(source, ">", "&gt;"); std::stringstream ss; ss << "<html><body>Source:<pre>" << source << "</pre></body></html>"; browser_->GetMainFrame()->LoadString(ss.str(), "http://tests/getsource"); } private: CefRefPtr<CefBrowser> browser_; IMPLEMENT_REFCOUNTING(Visitor); }; browser->GetMainFrame()->GetSource(new Visitor(browser)); } void RunGetTextTest(CefRefPtr<CefBrowser> browser) { class Visitor : public CefStringVisitor { public: explicit Visitor(CefRefPtr<CefBrowser> browser) : browser_(browser) {} virtual void Visit(const CefString& string) OVERRIDE { std::string text = StringReplace(string, "<", "&lt;"); text = StringReplace(text, ">", "&gt;"); std::stringstream ss; ss << "<html><body>Text:<pre>" << text << "</pre></body></html>"; browser_->GetMainFrame()->LoadString(ss.str(), "http://tests/gettext"); } private: CefRefPtr<CefBrowser> browser_; IMPLEMENT_REFCOUNTING(Visitor); }; browser->GetMainFrame()->GetText(new Visitor(browser)); } void RunRequestTest(CefRefPtr<CefBrowser> browser) { // Create a new request CefRefPtr<CefRequest> request(CefRequest::Create()); // Set the request URL request->SetURL("http://tests/request"); // Add post data to the request. The correct method and content- // type headers will be set by CEF. CefRefPtr<CefPostDataElement> postDataElement(CefPostDataElement::Create()); std::string data = "arg1=val1&arg2=val2"; postDataElement->SetToBytes(data.length(), data.c_str()); CefRefPtr<CefPostData> postData(CefPostData::Create()); postData->AddElement(postDataElement); request->SetPostData(postData); // Add a custom header CefRequest::HeaderMap headerMap; headerMap.insert( std::make_pair("X-My-Header", "My Header Value")); request->SetHeaderMap(headerMap); // Load the request browser->GetMainFrame()->LoadRequest(request); } void RunPopupTest(CefRefPtr<CefBrowser> browser) { browser->GetMainFrame()->ExecuteJavaScript( "window.open('http://www.google.com');", "about:blank", 0); } void RunPluginInfoTest(CefRefPtr<CefBrowser> browser) { class Visitor : public CefWebPluginInfoVisitor { public: explicit Visitor(CefRefPtr<CefBrowser> browser) : browser_(browser) { html_ = "<html><head><title>Plugin Info Test</title></head><body>" "\n<b>Installed plugins:</b>"; } ~Visitor() { html_ += "\n</body></html>"; // Load the html in the browser. browser_->GetMainFrame()->LoadString(html_, "http://tests/plugin_info"); } virtual bool Visit(CefRefPtr<CefWebPluginInfo> info, int count, int total) OVERRIDE { html_ += "\n<br/><br/>Name: " + info->GetName().ToString() + "\n<br/>Description: " + info->GetDescription().ToString() + "\n<br/>Version: " + info->GetVersion().ToString() + "\n<br/>Path: " + info->GetPath().ToString(); return true; } private: std::string html_; CefRefPtr<CefBrowser> browser_; IMPLEMENT_REFCOUNTING(Visitor); }; CefVisitWebPluginInfo(new Visitor(browser)); } void RunOtherTests(CefRefPtr<CefBrowser> browser) { browser->GetMainFrame()->LoadURL("http://tests/other_tests"); } <commit_msg>cefclient: Enable DevTools by default.<commit_after>// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "cefclient/cefclient.h" #include <stdio.h> #include <cstdlib> #include <sstream> #include <string> #include "include/cef_app.h" #include "include/cef_browser.h" #include "include/cef_command_line.h" #include "include/cef_frame.h" #include "include/cef_runnable.h" #include "include/cef_web_plugin.h" #include "cefclient/client_handler.h" #include "cefclient/client_switches.h" #include "cefclient/string_util.h" #include "cefclient/util.h" CefRefPtr<ClientHandler> g_handler; CefRefPtr<CefCommandLine> g_command_line; CefRefPtr<CefBrowser> AppGetBrowser() { if (!g_handler.get()) return NULL; return g_handler->GetBrowser(); } CefWindowHandle AppGetMainHwnd() { if (!g_handler.get()) return NULL; return g_handler->GetMainHwnd(); } void AppInitCommandLine(int argc, const char* const* argv) { g_command_line = CefCommandLine::CreateCommandLine(); #if defined(OS_WIN) g_command_line->InitFromString(::GetCommandLineW()); #else g_command_line->InitFromArgv(argc, argv); #endif } // Returns the application command line object. CefRefPtr<CefCommandLine> AppGetCommandLine() { return g_command_line; } // Returns the application settings based on command line arguments. void AppGetSettings(CefSettings& settings) { ASSERT(g_command_line.get()); if (!g_command_line.get()) return; CefString str; #if defined(OS_WIN) settings.multi_threaded_message_loop = g_command_line->HasSwitch(cefclient::kMultiThreadedMessageLoop); #endif CefString(&settings.cache_path) = g_command_line->GetSwitchValue(cefclient::kCachePath); // Specify a port to enable DevTools if one isn't already specified. if (!g_command_line->HasSwitch("remote-debugging-port")) settings.remote_debugging_port = 8088; } bool AppIsOffScreenRenderingEnabled() { ASSERT(g_command_line.get()); if (!g_command_line.get()) return false; return g_command_line->HasSwitch(cefclient::kOffScreenRenderingEnabled); } void RunGetSourceTest(CefRefPtr<CefBrowser> browser) { class Visitor : public CefStringVisitor { public: explicit Visitor(CefRefPtr<CefBrowser> browser) : browser_(browser) {} virtual void Visit(const CefString& string) OVERRIDE { std::string source = StringReplace(string, "<", "&lt;"); source = StringReplace(source, ">", "&gt;"); std::stringstream ss; ss << "<html><body>Source:<pre>" << source << "</pre></body></html>"; browser_->GetMainFrame()->LoadString(ss.str(), "http://tests/getsource"); } private: CefRefPtr<CefBrowser> browser_; IMPLEMENT_REFCOUNTING(Visitor); }; browser->GetMainFrame()->GetSource(new Visitor(browser)); } void RunGetTextTest(CefRefPtr<CefBrowser> browser) { class Visitor : public CefStringVisitor { public: explicit Visitor(CefRefPtr<CefBrowser> browser) : browser_(browser) {} virtual void Visit(const CefString& string) OVERRIDE { std::string text = StringReplace(string, "<", "&lt;"); text = StringReplace(text, ">", "&gt;"); std::stringstream ss; ss << "<html><body>Text:<pre>" << text << "</pre></body></html>"; browser_->GetMainFrame()->LoadString(ss.str(), "http://tests/gettext"); } private: CefRefPtr<CefBrowser> browser_; IMPLEMENT_REFCOUNTING(Visitor); }; browser->GetMainFrame()->GetText(new Visitor(browser)); } void RunRequestTest(CefRefPtr<CefBrowser> browser) { // Create a new request CefRefPtr<CefRequest> request(CefRequest::Create()); // Set the request URL request->SetURL("http://tests/request"); // Add post data to the request. The correct method and content- // type headers will be set by CEF. CefRefPtr<CefPostDataElement> postDataElement(CefPostDataElement::Create()); std::string data = "arg1=val1&arg2=val2"; postDataElement->SetToBytes(data.length(), data.c_str()); CefRefPtr<CefPostData> postData(CefPostData::Create()); postData->AddElement(postDataElement); request->SetPostData(postData); // Add a custom header CefRequest::HeaderMap headerMap; headerMap.insert( std::make_pair("X-My-Header", "My Header Value")); request->SetHeaderMap(headerMap); // Load the request browser->GetMainFrame()->LoadRequest(request); } void RunPopupTest(CefRefPtr<CefBrowser> browser) { browser->GetMainFrame()->ExecuteJavaScript( "window.open('http://www.google.com');", "about:blank", 0); } void RunPluginInfoTest(CefRefPtr<CefBrowser> browser) { class Visitor : public CefWebPluginInfoVisitor { public: explicit Visitor(CefRefPtr<CefBrowser> browser) : browser_(browser) { html_ = "<html><head><title>Plugin Info Test</title></head><body>" "\n<b>Installed plugins:</b>"; } ~Visitor() { html_ += "\n</body></html>"; // Load the html in the browser. browser_->GetMainFrame()->LoadString(html_, "http://tests/plugin_info"); } virtual bool Visit(CefRefPtr<CefWebPluginInfo> info, int count, int total) OVERRIDE { html_ += "\n<br/><br/>Name: " + info->GetName().ToString() + "\n<br/>Description: " + info->GetDescription().ToString() + "\n<br/>Version: " + info->GetVersion().ToString() + "\n<br/>Path: " + info->GetPath().ToString(); return true; } private: std::string html_; CefRefPtr<CefBrowser> browser_; IMPLEMENT_REFCOUNTING(Visitor); }; CefVisitWebPluginInfo(new Visitor(browser)); } void RunOtherTests(CefRefPtr<CefBrowser> browser) { browser->GetMainFrame()->LoadURL("http://tests/other_tests"); } <|endoftext|>
<commit_before>#include "Debug.h" #include "Editor.h" #include "Renderer.h" #include "Color.h" #include <cstdio> #define MODAL_BORDER 2 Editor::Editor(EditorState& editorState, bool wantsFocus) : mEditorState(editorState), mFocus(NULL), mModal(NULL), mIsDirty(true), mRedraw(true), mParent(NULL), mWantsFocus(wantsFocus), mPopupMessageId(-1), mMounted(false) { mThisArea.x = 0; mThisArea.y = 0; } Editor::~Editor() {} void Editor::onRendererMount(const Renderer& renderer) { } Editor * Editor::getFocus() { if (mParent) return mParent->getFocus(); return mFocus; } void Editor::setFocus(Editor *editor) { if (mParent) mParent->setFocus(editor); else { if (mFocus) mFocus->setDirty(true); mFocus = editor; if (editor) editor->setDirty(true); } } bool Editor::onEvent(SDL_Event& event) { return false; } void Editor::setDirty(bool dirty) { mIsDirty = dirty; if (!dirty) mRedraw = false; if (dirty && mParent != NULL) mParent->setDirty(true); } bool Editor::shouldRedrawBackground() const { return mRedraw; } bool Editor::isDirty() const { return mIsDirty || hasDirty(); } void Editor::addChild(Editor *child, int x, int y, int w, int h) { child->mParent = this; SDL_Rect area = { x, y, w, h }; mChildren.push_back(EditorChild(child, area)); SDL_Rect absArea = {area.x + mThisArea.x, area.y + mThisArea.y, area.w, area.h}; child->setArea(absArea); } void Editor::setArea(const SDL_Rect& area) { mThisArea.x = area.x; mThisArea.y = area.y; mThisArea.w = area.w; mThisArea.h = area.h; if (mParent) mParent->childAreaChanged(this); onAreaChanged(mThisArea); } const SDL_Rect& Editor::getArea() const { return mThisArea; } void Editor::onAreaChanged(const SDL_Rect& area) { } bool Editor::hasDirty() const { for (auto child : mChildren) if (child.editor->isDirty()) return true; return false; } bool Editor::hasFocus() { return getFocus() == this; } bool Editor::isFocusable() const { return mWantsFocus; } void Editor::onListenableChange(Listenable *listenable) { setDirty(true); } void Editor::drawCoveredChildren(Renderer& renderer, const SDL_Rect& area, const SDL_Rect& childArea, int maxIndex) { renderer.renderBackground(childArea); int index = 0; for (auto child : mChildren) { if (index > maxIndex) break; SDL_Rect thisChildArea = child.area; thisChildArea.x += area.x; thisChildArea.y += area.y; SDL_Rect intersection; if (intersectRect(childArea, thisChildArea, intersection)) { renderer.setClip(intersection); child.editor->draw(renderer, thisChildArea); } ++index; } } void Editor::drawChildren(Renderer& renderer, const SDL_Rect& area) { int index = 0; for (auto child : mChildren) { if (child.editor->isDirty()) { SDL_Rect childArea = child.area; childArea.x += area.x; childArea.y += area.y; drawCoveredChildren(renderer, area, childArea, index - 1); renderer.setClip(childArea); child.editor->draw(renderer, childArea); } index++; } } void Editor::drawModal(Renderer& renderer) { if (mModal != NULL) { renderer.unsetClip(); if (mModal->shouldRedrawBackground()) { // Draw plain black background with white border SDL_Rect modalBorder = mModal->getArea(); modalBorder.x -= MODAL_BORDER; modalBorder.y -= MODAL_BORDER; modalBorder.w += MODAL_BORDER * 2; modalBorder.h += MODAL_BORDER * 2; renderer.clearRect(modalBorder, Theme::ColorType::ModalBackground); renderer.drawRect(modalBorder, Theme::ColorType::ModalBorder); } mModal->draw(renderer, mModal->getArea()); } } void Editor::setModal(Editor *modal) { if (mModal != NULL) { mModal->onModalStatusChange(false); mModal->mParent = NULL; } mModal = modal; if (mModal != NULL) { mModal->mParent = this; SDL_Rect modalArea = { mThisArea.x + modalMargin, mThisArea.y + modalMargin, mThisArea.w - modalMargin * 2, mThisArea.h - modalMargin * 2 }; mModal->setArea(modalArea); mModal->onModalStatusChange(true); } invalidateAll(); } void Editor::onFileSelectorEvent(const Editor& fileSelector, bool accept) { } void Editor::invalidateAll() { setDirty(true); mRedraw = true; for (auto child : mChildren) { child.editor->invalidateAll(); } if (mModal) mModal->invalidateAll(); } void Editor::onMessageBoxEvent(const Editor& messageBox, int code) { } void Editor::draw(Renderer& renderer, const SDL_Rect& area) { // This should fix problems with modal backgrounds not being updated // and perhaps also other child Editors. invalidateAll(); // First time rendered if (!mMounted) { this->onRendererMount(renderer); mMounted = true; } this->onDraw(renderer, area); drawChildren(renderer, area); if (mModal != NULL) { drawModal(renderer); } setDirty(false); } void Editor::invalidateParent() { if (mParent) mParent->invalidateAll(); } bool Editor::pointInRect(const SDL_Point& point, const SDL_Rect& rect) { #ifdef SDL_PointInRect return SDL_PointInRect(&point, &rect); #else // In case we are using SDL <2.0.4 (of whatever the version is // where the rect built-in functions are introduced. E.g. my // PocketCHIP only goes up to 2.0.2 by default. return point.x >= rect.x && point.x < rect.x + rect.w && point.y >= rect.y && point.y < rect.y + rect.h; #endif } bool Editor::intersectRect(const SDL_Rect& a, const SDL_Rect& b, SDL_Rect& result) { #ifdef SDL_IntersectRect return SDL_IntersectRect(&point, &rect, &result); #else // In case we are using SDL <2.0.4 (of whatever the version is // where the rect built-in functions are introduced. E.g. my // PocketCHIP only goes up to 2.0.2 by default. int aRight = a.x + a.w; int aBottom = a.y + a.h; int bRight = b.x + b.w; int bBottom = b.y + b.h; if (!(a.x < bRight && aRight > b.x && a.y < bBottom && aBottom > b.y)) return false; result.x = std::max(a.x, b.x); result.y = std::max(a.y, b.y); result.w = std::min(aRight, bRight) - result.x; result.h = std::min(aBottom, bBottom) - result.y; return true; #endif } void Editor::showTooltipV(const SDL_Rect& area, const char* message, ...) { char dest[1024]; va_list argptr; va_start(argptr, message); vsnprintf(dest, sizeof(dest), message, argptr); va_end(argptr); showTooltip(area, dest); } void Editor::showTooltip(const SDL_Rect& area, const char* message) { if (mParent != NULL) mParent->showTooltip(area, message); } int Editor::showMessageV(MessageClass messageClass, int messageId, const char* message, ...) { char dest[1024]; va_list argptr; va_start(argptr, message); vsnprintf(dest, sizeof(dest), message, argptr); va_end(argptr); return showMessage(messageClass, messageId, dest); } int Editor::showMessageV(MessageClass messageClass, const char* message, ...) { char dest[1024]; va_list argptr; va_start(argptr, message); vsnprintf(dest, sizeof(dest), message, argptr); va_end(argptr); return showMessage(messageClass, dest); } int Editor::showMessageInner(MessageClass messageClass, int messageId, const char* message) { debug("[%s] %s", messageClass == MessageInfo ? "INFO" : "ERROR", message); return 0; } int Editor::showMessage(MessageClass messageClass, int messageId, const char* message) { if (mParent != NULL) return mParent->showMessage(messageClass, messageId, message); else { int finalId = messageId; // If useSingleMessage was given as ID use the stored per Editor ID if (messageId == replacePreviousMessage) finalId = mPopupMessageId; return mPopupMessageId = showMessageInner(messageClass, finalId, message); } } int Editor::showMessage(MessageClass messageClass, const char* message) { return showMessage(messageClass, -1, message); } void Editor::onUpdate(int ms) { } void Editor::update(int ms) { onUpdate(ms); for (auto child : mChildren) { child.editor->update(ms); } } void Editor::onLoaded() { for (auto child : mChildren) { child.editor->onLoaded(); } } void Editor::childAreaChanged(Editor* changedChild) { for (auto& child : mChildren) { if (child.editor == changedChild) child.area = changedChild->getArea(); } } void Editor::onModalStatusChange(bool isNowModal) { } Editor::EditorChild::EditorChild(Editor *_editor, const SDL_Rect& _area) : editor(_editor), area(_area) { } <commit_msg>Messages always replaced the earlier message<commit_after>#include "Debug.h" #include "Editor.h" #include "Renderer.h" #include "Color.h" #include <cstdio> #define MODAL_BORDER 2 Editor::Editor(EditorState& editorState, bool wantsFocus) : mEditorState(editorState), mFocus(NULL), mModal(NULL), mIsDirty(true), mRedraw(true), mParent(NULL), mWantsFocus(wantsFocus), mPopupMessageId(-1), mMounted(false) { mThisArea.x = 0; mThisArea.y = 0; } Editor::~Editor() {} void Editor::onRendererMount(const Renderer& renderer) { } Editor * Editor::getFocus() { if (mParent) return mParent->getFocus(); return mFocus; } void Editor::setFocus(Editor *editor) { if (mParent) mParent->setFocus(editor); else { if (mFocus) mFocus->setDirty(true); mFocus = editor; if (editor) editor->setDirty(true); } } bool Editor::onEvent(SDL_Event& event) { return false; } void Editor::setDirty(bool dirty) { mIsDirty = dirty; if (!dirty) mRedraw = false; if (dirty && mParent != NULL) mParent->setDirty(true); } bool Editor::shouldRedrawBackground() const { return mRedraw; } bool Editor::isDirty() const { return mIsDirty || hasDirty(); } void Editor::addChild(Editor *child, int x, int y, int w, int h) { child->mParent = this; SDL_Rect area = { x, y, w, h }; mChildren.push_back(EditorChild(child, area)); SDL_Rect absArea = {area.x + mThisArea.x, area.y + mThisArea.y, area.w, area.h}; child->setArea(absArea); } void Editor::setArea(const SDL_Rect& area) { mThisArea.x = area.x; mThisArea.y = area.y; mThisArea.w = area.w; mThisArea.h = area.h; if (mParent) mParent->childAreaChanged(this); onAreaChanged(mThisArea); } const SDL_Rect& Editor::getArea() const { return mThisArea; } void Editor::onAreaChanged(const SDL_Rect& area) { } bool Editor::hasDirty() const { for (auto child : mChildren) if (child.editor->isDirty()) return true; return false; } bool Editor::hasFocus() { return getFocus() == this; } bool Editor::isFocusable() const { return mWantsFocus; } void Editor::onListenableChange(Listenable *listenable) { setDirty(true); } void Editor::drawCoveredChildren(Renderer& renderer, const SDL_Rect& area, const SDL_Rect& childArea, int maxIndex) { renderer.renderBackground(childArea); int index = 0; for (auto child : mChildren) { if (index > maxIndex) break; SDL_Rect thisChildArea = child.area; thisChildArea.x += area.x; thisChildArea.y += area.y; SDL_Rect intersection; if (intersectRect(childArea, thisChildArea, intersection)) { renderer.setClip(intersection); child.editor->draw(renderer, thisChildArea); } ++index; } } void Editor::drawChildren(Renderer& renderer, const SDL_Rect& area) { int index = 0; for (auto child : mChildren) { if (child.editor->isDirty()) { SDL_Rect childArea = child.area; childArea.x += area.x; childArea.y += area.y; drawCoveredChildren(renderer, area, childArea, index - 1); renderer.setClip(childArea); child.editor->draw(renderer, childArea); } index++; } } void Editor::drawModal(Renderer& renderer) { if (mModal != NULL) { renderer.unsetClip(); if (mModal->shouldRedrawBackground()) { // Draw plain black background with white border SDL_Rect modalBorder = mModal->getArea(); modalBorder.x -= MODAL_BORDER; modalBorder.y -= MODAL_BORDER; modalBorder.w += MODAL_BORDER * 2; modalBorder.h += MODAL_BORDER * 2; renderer.clearRect(modalBorder, Theme::ColorType::ModalBackground); renderer.drawRect(modalBorder, Theme::ColorType::ModalBorder); } mModal->draw(renderer, mModal->getArea()); } } void Editor::setModal(Editor *modal) { if (mModal != NULL) { mModal->onModalStatusChange(false); mModal->mParent = NULL; } mModal = modal; if (mModal != NULL) { mModal->mParent = this; SDL_Rect modalArea = { mThisArea.x + modalMargin, mThisArea.y + modalMargin, mThisArea.w - modalMargin * 2, mThisArea.h - modalMargin * 2 }; mModal->setArea(modalArea); mModal->onModalStatusChange(true); } invalidateAll(); } void Editor::onFileSelectorEvent(const Editor& fileSelector, bool accept) { } void Editor::invalidateAll() { setDirty(true); mRedraw = true; for (auto child : mChildren) { child.editor->invalidateAll(); } if (mModal) mModal->invalidateAll(); } void Editor::onMessageBoxEvent(const Editor& messageBox, int code) { } void Editor::draw(Renderer& renderer, const SDL_Rect& area) { // This should fix problems with modal backgrounds not being updated // and perhaps also other child Editors. invalidateAll(); // First time rendered if (!mMounted) { this->onRendererMount(renderer); mMounted = true; } this->onDraw(renderer, area); drawChildren(renderer, area); if (mModal != NULL) { drawModal(renderer); } setDirty(false); } void Editor::invalidateParent() { if (mParent) mParent->invalidateAll(); } bool Editor::pointInRect(const SDL_Point& point, const SDL_Rect& rect) { #ifdef SDL_PointInRect return SDL_PointInRect(&point, &rect); #else // In case we are using SDL <2.0.4 (of whatever the version is // where the rect built-in functions are introduced. E.g. my // PocketCHIP only goes up to 2.0.2 by default. return point.x >= rect.x && point.x < rect.x + rect.w && point.y >= rect.y && point.y < rect.y + rect.h; #endif } bool Editor::intersectRect(const SDL_Rect& a, const SDL_Rect& b, SDL_Rect& result) { #ifdef SDL_IntersectRect return SDL_IntersectRect(&point, &rect, &result); #else // In case we are using SDL <2.0.4 (of whatever the version is // where the rect built-in functions are introduced. E.g. my // PocketCHIP only goes up to 2.0.2 by default. int aRight = a.x + a.w; int aBottom = a.y + a.h; int bRight = b.x + b.w; int bBottom = b.y + b.h; if (!(a.x < bRight && aRight > b.x && a.y < bBottom && aBottom > b.y)) return false; result.x = std::max(a.x, b.x); result.y = std::max(a.y, b.y); result.w = std::min(aRight, bRight) - result.x; result.h = std::min(aBottom, bBottom) - result.y; return true; #endif } void Editor::showTooltipV(const SDL_Rect& area, const char* message, ...) { char dest[1024]; va_list argptr; va_start(argptr, message); vsnprintf(dest, sizeof(dest), message, argptr); va_end(argptr); showTooltip(area, dest); } void Editor::showTooltip(const SDL_Rect& area, const char* message) { if (mParent != NULL) mParent->showTooltip(area, message); } int Editor::showMessageV(MessageClass messageClass, int messageId, const char* message, ...) { char dest[1024]; va_list argptr; va_start(argptr, message); vsnprintf(dest, sizeof(dest), message, argptr); va_end(argptr); return showMessage(messageClass, messageId, dest); } int Editor::showMessageV(MessageClass messageClass, const char* message, ...) { char dest[1024]; va_list argptr; va_start(argptr, message); vsnprintf(dest, sizeof(dest), message, argptr); va_end(argptr); return showMessage(messageClass, dest); } int Editor::showMessageInner(MessageClass messageClass, int messageId, const char* message) { debug("[%s] %s", messageClass == MessageInfo ? "INFO" : "ERROR", message); return 0; } int Editor::showMessage(MessageClass messageClass, int messageId, const char* message) { if (mParent != NULL) return mParent->showMessage(messageClass, messageId, message); else { int finalId = messageId; // If useSingleMessage was given as ID use the stored per Editor ID if (messageId == replacePreviousMessage) finalId = mPopupMessageId; return mPopupMessageId = showMessageInner(messageClass, finalId, message); } } int Editor::showMessage(MessageClass messageClass, const char* message) { return showMessage(messageClass, -2, message); } void Editor::onUpdate(int ms) { } void Editor::update(int ms) { onUpdate(ms); for (auto child : mChildren) { child.editor->update(ms); } } void Editor::onLoaded() { for (auto child : mChildren) { child.editor->onLoaded(); } } void Editor::childAreaChanged(Editor* changedChild) { for (auto& child : mChildren) { if (child.editor == changedChild) child.area = changedChild->getArea(); } } void Editor::onModalStatusChange(bool isNowModal) { } Editor::EditorChild::EditorChild(Editor *_editor, const SDL_Rect& _area) : editor(_editor), area(_area) { } <|endoftext|>
<commit_before>// $Id$ // Category: event // // See the class description in the header file. #include "AliStackingAction.h" #include "AliStackingActionMessenger.h" #include "AliTrackingAction.h" #include "AliGlobals.h" #include <G4Track.hh> #include <G4TrackStack.hh> #include <G4StackedTrack.hh> #include <G4StackManager.hh> #include <G4NeutrinoE.hh> #include <G4NeutrinoMu.hh> #include <G4NeutrinoTau.hh> #include <G4AntiNeutrinoE.hh> #include <G4AntiNeutrinoMu.hh> #include <G4AntiNeutrinoTau.hh> AliStackingAction::AliStackingAction() : fStage(0), fVerboseLevel(0), fSavePrimaries(true), fTrackingAction(0) { // fPrimaryStack = new G4TrackStack(); fMessenger = new AliStackingActionMessenger(this); } AliStackingAction::AliStackingAction(const AliStackingAction& right) { // AliGlobals::Exception("AliStackingAction is protected from copying."); } AliStackingAction::~AliStackingAction() { // delete fPrimaryStack; delete fMessenger; } // operators AliStackingAction& AliStackingAction::operator=(const AliStackingAction &right) { // check assignement to self if (this == &right) return *this; AliGlobals::Exception("AliStackingAction is protected from assigning."); return *this; } // public methods G4ClassificationOfNewTrack AliStackingAction::ClassifyNewTrack(const G4Track* track) { // Classifies the new track. // --- G4ClassificationOfNewTrack classification; if (fStage == 0) { // move all primaries to PrimaryStack G4Track* nonconstTrack = (G4Track*)track; G4StackedTrack* newTrack = new G4StackedTrack(nonconstTrack); fPrimaryStack->PushToStack(newTrack); classification = fPostpone; // save primary particle info // (secondary particles are stored // by AlTrackingAction::PreUserTrackingAction() method) if (fSavePrimaries) fTrackingAction->SaveParticle(track, "primary"); } else { // exclude neutrinos G4ParticleDefinition* particle = track->GetDefinition(); if( particle == G4NeutrinoE::NeutrinoEDefinition() || particle == G4NeutrinoMu::NeutrinoMuDefinition() || particle == G4NeutrinoTau::NeutrinoTauDefinition() || particle == G4AntiNeutrinoE::AntiNeutrinoEDefinition() || particle == G4AntiNeutrinoMu::AntiNeutrinoMuDefinition() || particle == G4AntiNeutrinoTau::AntiNeutrinoTauDefinition()) { return fKill; } G4int parentID = track->GetParentID(); if (parentID ==0) { return fUrgent; } else { return fWaiting; } } return classification; } void AliStackingAction::NewStage() { // Called by G4 kernel at the new stage of stacking. // --- fStage++; if (fVerboseLevel>0) { G4cout << "AliStackingAction::NewStage " << fStage << " has been started." << G4endl; } G4int nofUrgent = stackManager->GetNUrgentTrack(); if (nofUrgent == 0) { G4int nofPrimary = fPrimaryStack->GetNTrack(); if (nofPrimary>0) { G4StackedTrack* stackedTrack = fPrimaryStack->PopFromStack(); G4Track* primaryTrack = stackedTrack->GetTrack(); delete stackedTrack; stackManager->PushOneTrack(primaryTrack); } } } void AliStackingAction::ClearPrimaryStack() { // Clears the primary stack. // --- stackManager->ClearPostponeStack(); } void AliStackingAction::PrepareNewEvent() { // Called by G4 kernel at the beginning of event. // --- fStage = 0; ClearPrimaryStack(); fTrackingAction = AliTrackingAction::Instance(); fSavePrimaries = fTrackingAction->GetSavePrimaries(); } <commit_msg>updated for AliTrackingAction change<commit_after>// $Id$ // Category: event // // See the class description in the header file. #include "AliStackingAction.h" #include "AliStackingActionMessenger.h" #include "AliTrackingAction.h" #include "AliGlobals.h" #include <G4Track.hh> #include <G4TrackStack.hh> #include <G4StackedTrack.hh> #include <G4StackManager.hh> #include <G4NeutrinoE.hh> #include <G4NeutrinoMu.hh> #include <G4NeutrinoTau.hh> #include <G4AntiNeutrinoE.hh> #include <G4AntiNeutrinoMu.hh> #include <G4AntiNeutrinoTau.hh> AliStackingAction::AliStackingAction() : fStage(0), fVerboseLevel(0), fSavePrimaries(true), fTrackingAction(0) { // fPrimaryStack = new G4TrackStack(); fMessenger = new AliStackingActionMessenger(this); } AliStackingAction::AliStackingAction(const AliStackingAction& right) { // AliGlobals::Exception("AliStackingAction is protected from copying."); } AliStackingAction::~AliStackingAction() { // delete fPrimaryStack; delete fMessenger; } // operators AliStackingAction& AliStackingAction::operator=(const AliStackingAction &right) { // check assignement to self if (this == &right) return *this; AliGlobals::Exception("AliStackingAction is protected from assigning."); return *this; } // public methods G4ClassificationOfNewTrack AliStackingAction::ClassifyNewTrack(const G4Track* track) { // Classifies the new track. // --- G4ClassificationOfNewTrack classification; if (fStage == 0) { // move all primaries to PrimaryStack G4Track* nonconstTrack = (G4Track*)track; G4StackedTrack* newTrack = new G4StackedTrack(nonconstTrack); fPrimaryStack->PushToStack(newTrack); classification = fPostpone; // save primary particle info // (secondary particles are stored // by AlTrackingAction::PreUserTrackingAction() method) if (fSavePrimaries) fTrackingAction->SaveParticle(track); } else { // exclude neutrinos G4ParticleDefinition* particle = track->GetDefinition(); if( particle == G4NeutrinoE::NeutrinoEDefinition() || particle == G4NeutrinoMu::NeutrinoMuDefinition() || particle == G4NeutrinoTau::NeutrinoTauDefinition() || particle == G4AntiNeutrinoE::AntiNeutrinoEDefinition() || particle == G4AntiNeutrinoMu::AntiNeutrinoMuDefinition() || particle == G4AntiNeutrinoTau::AntiNeutrinoTauDefinition()) { return fKill; } G4int parentID = track->GetParentID(); if (parentID ==0) { return fUrgent; } else { return fWaiting; } } return classification; } void AliStackingAction::NewStage() { // Called by G4 kernel at the new stage of stacking. // --- fStage++; if (fVerboseLevel>0) { G4cout << "AliStackingAction::NewStage " << fStage << " has been started." << G4endl; } G4int nofUrgent = stackManager->GetNUrgentTrack(); if (nofUrgent == 0) { G4int nofPrimary = fPrimaryStack->GetNTrack(); if (nofPrimary>0) { G4StackedTrack* stackedTrack = fPrimaryStack->PopFromStack(); G4Track* primaryTrack = stackedTrack->GetTrack(); delete stackedTrack; stackManager->PushOneTrack(primaryTrack); } } } void AliStackingAction::ClearPrimaryStack() { // Clears the primary stack. // --- stackManager->ClearPostponeStack(); } void AliStackingAction::PrepareNewEvent() { // Called by G4 kernel at the beginning of event. // --- fStage = 0; ClearPrimaryStack(); fTrackingAction = AliTrackingAction::Instance(); fSavePrimaries = fTrackingAction->GetSavePrimaries(); } <|endoftext|>
<commit_before>#include <QtCore/QEventLoop> #include <QtTest/QtTest> #include <TelepathyQt4/Debug> #include <TelepathyQt4/Types> #include <TelepathyQt4/Client/AccountManager> #include <TelepathyQt4/Client/PendingOperation> using namespace Telepathy; using namespace Telepathy::Client; class TestAccountBasics : public QObject { Q_OBJECT public: TestAccountBasics(QObject *parent = 0); ~TestAccountBasics(); protected Q_SLOTS: void expectSuccessfulCall(Telepathy::Client::PendingOperation *); private Q_SLOTS: void init(); void testBasics(); void cleanup(); private: QEventLoop *mLoop; AccountManager *mAccount; }; TestAccountBasics::TestAccountBasics(QObject *parent) : QObject(parent), mLoop(new QEventLoop(this)), mAccount(0) { } TestAccountBasics::~TestAccountBasics() { delete mLoop; } void TestAccountBasics::expectSuccessfulCall(PendingOperation *operation) { if (operation->isError()) { qWarning().nospace() << operation->errorName() << ": " << operation->errorMessage(); mLoop->exit(1); return; } mLoop->exit(0); } void TestAccountBasics::init() { Telepathy::registerTypes(); Telepathy::enableDebug(true); Telepathy::enableWarnings(true); } void TestAccountBasics::testBasics() { mAccount = new AccountManager(); QCOMPARE(mAccount->isReady(), false); connect(mAccount->becomeReady(), SIGNAL(finished(Telepathy::Client::PendingOperation *)), this, SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *))); qDebug() << "enter main loop"; QCOMPARE(mLoop->exec(), 0); QCOMPARE(mAccount->isReady(), true); QCOMPARE(mAccount->interfaces(), QStringList()); QCOMPARE(mAccount->validAccountPaths(), ObjectPathList()); QCOMPARE(mAccount->invalidAccountPaths(), ObjectPathList()); QCOMPARE(mAccount->allAccountPaths(), ObjectPathList()); } void TestAccountBasics::cleanup() { if (mAccount) { delete mAccount; mAccount = 0; } } QTEST_MAIN(TestAccountBasics) #include "_gen/account-basics.cpp.moc.hpp" <commit_msg>Added tests for account creation.<commit_after>#include <QtCore/QEventLoop> #include <QtTest/QtTest> #include <QtDBus/QDBusObjectPath> #include <TelepathyQt4/Debug> #include <TelepathyQt4/Types> #include <TelepathyQt4/Client/Account> #include <TelepathyQt4/Client/AccountManager> #include <TelepathyQt4/Client/PendingAccount> #include <TelepathyQt4/Client/PendingOperation> using namespace Telepathy; using namespace Telepathy::Client; static QStringList objectPathListToStringList(const ObjectPathList &paths) { QStringList result; Q_FOREACH (const QDBusObjectPath &path, paths) { result << path.path(); } return result; } class TestAccountBasics : public QObject { Q_OBJECT public: TestAccountBasics(QObject *parent = 0); ~TestAccountBasics(); protected Q_SLOTS: void expectSuccessfulCall(Telepathy::Client::PendingOperation *); void onAccountCreated(Telepathy::Client::PendingOperation *); void onAccountReady(Telepathy::Client::PendingOperation *); private Q_SLOTS: void init(); void testBasics(); void cleanup(); private: QEventLoop *mLoop; AccountManager *mAM; }; TestAccountBasics::TestAccountBasics(QObject *parent) : QObject(parent), mLoop(new QEventLoop(this)), mAM(0) { } TestAccountBasics::~TestAccountBasics() { delete mLoop; } void TestAccountBasics::expectSuccessfulCall(PendingOperation *operation) { if (operation->isError()) { qWarning().nospace() << operation->errorName() << ": " << operation->errorMessage(); mLoop->exit(1); return; } mLoop->exit(0); } void TestAccountBasics::onAccountCreated(Telepathy::Client::PendingOperation *operation) { if (operation->isError()) { qWarning().nospace() << operation->errorName() << ": " << operation->errorMessage(); mLoop->exit(1); return; } mLoop->exit(0); } void TestAccountBasics::onAccountReady(Telepathy::Client::PendingOperation *operation) { if (operation->isError()) { qWarning().nospace() << operation->errorName() << ": " << operation->errorMessage(); mLoop->exit(1); return; } mLoop->exit(0); } void TestAccountBasics::init() { Telepathy::registerTypes(); Telepathy::enableDebug(true); Telepathy::enableWarnings(true); } void TestAccountBasics::testBasics() { mAM = new AccountManager(); QCOMPARE(mAM->isReady(), false); connect(mAM->becomeReady(), SIGNAL(finished(Telepathy::Client::PendingOperation *)), this, SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *))); qDebug() << "enter main loop"; QCOMPARE(mLoop->exec(), 0); QCOMPARE(mAM->isReady(), true); QVariantMap parameters; parameters["account"] = "foobar"; PendingAccount *pacc = mAM->createAccount("foo", "bar", "foobar", parameters); connect(pacc, SIGNAL(finished(Telepathy::Client::PendingOperation *)), this, SLOT(onAccountCreated(Telepathy::Client::PendingOperation *))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mAM->interfaces(), QStringList()); QCOMPARE(objectPathListToStringList(mAM->validAccountPaths()), QStringList() << "/org/freedesktop/Telepathy/Account/foo/bar/Account0"); QCOMPARE(objectPathListToStringList(mAM->invalidAccountPaths()), QStringList()); QCOMPARE(objectPathListToStringList(mAM->allAccountPaths()), QStringList() << "/org/freedesktop/Telepathy/Account/foo/bar/Account0"); Account *acc = mAM->accountForPath( QDBusObjectPath("/org/freedesktop/Telepathy/Account/foo/bar/Account0")); connect(acc->becomeReady(), SIGNAL(finished(Telepathy::Client::PendingOperation *)), this, SLOT(onAccountReady(Telepathy::Client::PendingOperation *))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->displayName(), QString("foobar (account 0)")); } void TestAccountBasics::cleanup() { if (mAM) { delete mAM; mAM = 0; } } QTEST_MAIN(TestAccountBasics) #include "_gen/account-basics.cpp.moc.hpp" <|endoftext|>
<commit_before>/* * ty, a collection of GUI and command-line tools to manage Teensy devices * * Distributed under the MIT license (see LICENSE.txt or http://opensource.org/licenses/MIT) * Copyright (c) 2015 Niels Martignène <niels.martignene@gmail.com> */ #ifndef BOARD_HH #define BOARD_HH #include <QMutex> #include <QTextDocument> #include <QThread> #include <QTimer> #include <functional> #include <memory> #include <vector> #include "ty/board.h" #include "descriptor_notifier.hh" #include "firmware.hh" #include "ty/monitor.h" #include "task.hh" struct BoardInterfaceInfo { QString name; QString path; uint16_t capabilities; uint8_t number; bool open; }; class Board : public QObject, public std::enable_shared_from_this<Board> { Q_OBJECT Q_PROPERTY(QString tag READ tag WRITE setTag) Q_PROPERTY(QString firmware READ firmware WRITE setFirmware STORED false) Q_PROPERTY(bool resetAfter READ resetAfter WRITE setResetAfter) Q_PROPERTY(bool clearOnReset READ clearOnReset WRITE setClearOnReset) tyb_board *board_; bool serial_attach_ = true; tyb_board_interface *serial_iface_ = nullptr; DescriptorNotifier serial_notifier_; QMutex serial_lock_; char serial_buf_[262144]; size_t serial_buf_len_ = 0; QTextDocument serial_document_; QTimer error_timer_; QString firmware_; bool reset_after_ = true; bool clear_on_reset_ = false; QString firmware_name_; TaskInterface running_task_; TaskWatcher task_watcher_; std::function<void(bool success, std::shared_ptr<void> result)> task_finish_; public: static std::shared_ptr<Board> createBoard(tyb_board *board); virtual ~Board(); tyb_board *board() const; bool matchesTag(const QString &id); tyb_board_state state() const; uint16_t capabilities() const; const tyb_board_model *model() const; QString modelName() const; QString id() const; QString location() const; uint64_t serialNumber() const; std::vector<BoardInterfaceInfo> interfaces() const; bool isRunning() const; bool isUploadAvailable() const; bool isResetAvailable() const; bool isRebootAvailable() const; bool isSerialAvailable() const; bool errorOccured() const; QString statusIconFileName() const; QString firmwareName() const; void setTag(const QString &tag); QString tag() const { return tyb_board_get_tag(board_); } void setFirmware(const QString &firmware); QString firmware() const { return firmware_; } void setResetAfter(bool reset_after); bool resetAfter() const { return reset_after_; } void setClearOnReset(bool clear_on_reset); bool clearOnReset() const { return clear_on_reset_; } QTextDocument &serialDocument(); void appendToSerialDocument(const QString& s); static QStringList makeCapabilityList(uint16_t capabilities); static QString makeCapabilityString(uint16_t capabilities, QString empty_str = QString()); TaskInterface upload(const std::vector<std::shared_ptr<Firmware>> &fws); TaskInterface upload(const std::vector<std::shared_ptr<Firmware>> &fws, bool reset_after); TaskInterface reset(); TaskInterface reboot(); bool attachMonitor(); void detachMonitor(); bool isMonitorAttached() const { return serial_iface_; } bool autoAttachMonitor() const { return serial_attach_; } bool sendSerial(const QByteArray &buf); TaskInterface runningTask() const; signals: void boardChanged(); void boardDropped(); void taskChanged(); void settingChanged(const QString &name, const QVariant &value); public slots: void notifyLog(ty_log_level level, const QString &msg); private slots: void serialReceived(ty_descriptor desc); void updateSerialDocument(); void notifyFinished(bool success, std::shared_ptr<void> result); void notifyProgress(const QString &action, unsigned int value, unsigned int max); private: Board(tyb_board *board, QObject *parent = nullptr); void refreshBoard(); bool openSerialInterface(); void closeSerialInterface(); TaskInterface wrapBoardTask(ty_task *task, std::function<void(bool success, std::shared_ptr<void> result)> finish = nullptr); friend class Monitor; }; #endif <commit_msg>cosmetic: White lines between board properties<commit_after>/* * ty, a collection of GUI and command-line tools to manage Teensy devices * * Distributed under the MIT license (see LICENSE.txt or http://opensource.org/licenses/MIT) * Copyright (c) 2015 Niels Martignène <niels.martignene@gmail.com> */ #ifndef BOARD_HH #define BOARD_HH #include <QMutex> #include <QTextDocument> #include <QThread> #include <QTimer> #include <functional> #include <memory> #include <vector> #include "ty/board.h" #include "descriptor_notifier.hh" #include "firmware.hh" #include "ty/monitor.h" #include "task.hh" struct BoardInterfaceInfo { QString name; QString path; uint16_t capabilities; uint8_t number; bool open; }; class Board : public QObject, public std::enable_shared_from_this<Board> { Q_OBJECT Q_PROPERTY(QString tag READ tag WRITE setTag) Q_PROPERTY(QString firmware READ firmware WRITE setFirmware STORED false) Q_PROPERTY(bool resetAfter READ resetAfter WRITE setResetAfter) Q_PROPERTY(bool clearOnReset READ clearOnReset WRITE setClearOnReset) tyb_board *board_; bool serial_attach_ = true; tyb_board_interface *serial_iface_ = nullptr; DescriptorNotifier serial_notifier_; QMutex serial_lock_; char serial_buf_[262144]; size_t serial_buf_len_ = 0; QTextDocument serial_document_; QTimer error_timer_; QString firmware_; bool reset_after_ = true; bool clear_on_reset_ = false; QString firmware_name_; TaskInterface running_task_; TaskWatcher task_watcher_; std::function<void(bool success, std::shared_ptr<void> result)> task_finish_; public: static std::shared_ptr<Board> createBoard(tyb_board *board); virtual ~Board(); tyb_board *board() const; bool matchesTag(const QString &id); tyb_board_state state() const; uint16_t capabilities() const; const tyb_board_model *model() const; QString modelName() const; QString id() const; QString location() const; uint64_t serialNumber() const; std::vector<BoardInterfaceInfo> interfaces() const; bool isRunning() const; bool isUploadAvailable() const; bool isResetAvailable() const; bool isRebootAvailable() const; bool isSerialAvailable() const; bool errorOccured() const; QString statusIconFileName() const; QString firmwareName() const; void setTag(const QString &tag); QString tag() const { return tyb_board_get_tag(board_); } void setFirmware(const QString &firmware); QString firmware() const { return firmware_; } void setResetAfter(bool reset_after); bool resetAfter() const { return reset_after_; } void setClearOnReset(bool clear_on_reset); bool clearOnReset() const { return clear_on_reset_; } QTextDocument &serialDocument(); void appendToSerialDocument(const QString& s); static QStringList makeCapabilityList(uint16_t capabilities); static QString makeCapabilityString(uint16_t capabilities, QString empty_str = QString()); TaskInterface upload(const std::vector<std::shared_ptr<Firmware>> &fws); TaskInterface upload(const std::vector<std::shared_ptr<Firmware>> &fws, bool reset_after); TaskInterface reset(); TaskInterface reboot(); bool attachMonitor(); void detachMonitor(); bool isMonitorAttached() const { return serial_iface_; } bool autoAttachMonitor() const { return serial_attach_; } bool sendSerial(const QByteArray &buf); TaskInterface runningTask() const; signals: void boardChanged(); void boardDropped(); void taskChanged(); void settingChanged(const QString &name, const QVariant &value); public slots: void notifyLog(ty_log_level level, const QString &msg); private slots: void serialReceived(ty_descriptor desc); void updateSerialDocument(); void notifyFinished(bool success, std::shared_ptr<void> result); void notifyProgress(const QString &action, unsigned int value, unsigned int max); private: Board(tyb_board *board, QObject *parent = nullptr); void refreshBoard(); bool openSerialInterface(); void closeSerialInterface(); TaskInterface wrapBoardTask(ty_task *task, std::function<void(bool success, std::shared_ptr<void> result)> finish = nullptr); friend class Monitor; }; #endif <|endoftext|>
<commit_before>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QIMESSAGING_DETAILS_TYPE_HXX_ #define _QIMESSAGING_DETAILS_TYPE_HXX_ #include <qi/types.hpp> #include <cstring> #include <map> #include <vector> #include <list> #include <boost/mpl/for_each.hpp> #include <boost/mpl/transform_view.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/type_traits/add_pointer.hpp> #include <boost/function_types/parameter_types.hpp> #include <boost/function_types/result_type.hpp> #include <boost/function_types/function_type.hpp> #include <boost/function_types/is_member_pointer.hpp> #include <qimessaging/typespecialized.hpp> /* This file contains the default-provided Type specialisations * */ namespace qi { // void template<> class TypeImpl<void>: public Type { public: const TypeInfo& info() { static TypeInfo result = TypeInfo(typeid(void)); return result; } void* initializeStorage(void*) { return 0;} void* ptrFromStorage(void** ) { return 0;} void* clone(void*) { return 0;} void destroy(void* ptr) {} Kind kind() const { return Void;} }; //reference template<typename T> class TypeImpl<T&> : public TypeImpl<T> {}; } namespace qi { namespace detail { template<typename T> inline Type* typeOfBackend() { Type* result = getType(typeid(T)); if (!result) { static Type* defaultResult = 0; // Is this realy a problem? if (!defaultResult) qiLogVerbose("qi.meta") << "typeOf request for unregistered type " << typeid(T).name(); if (!defaultResult) defaultResult = new TypeImpl<T>(); result = defaultResult; } if (typeid(T).name() != result->infoString() && typeid(T)!= typeid(bool)) qiLogWarning("qi.meta") << "typeOfBackend: type mismatch " << typeid(T).name() << " " << result <<" " << result->infoString(); return result; } template<typename T> struct TypeOfAdapter { typedef T type; }; template<typename T> struct TypeOfAdapter<T&> { typedef typename TypeOfAdapter<T>::type type; }; template<typename T> struct TypeOfAdapter<const T> { typedef typename TypeOfAdapter<T>::type type; }; template<typename T> struct TypeOfAdapter<T*> { typedef typename boost::add_pointer<typename boost::remove_const<typename TypeOfAdapter<T>::type>::type>::type type; }; } template<typename T> Type* typeOf() { return detail::typeOfBackend<typename detail::TypeOfAdapter<T>::type>(); } inline Type::Kind Type::kind() const { return Unknown; } namespace detail { struct signature_function_arg_apply { signature_function_arg_apply(std::string* val) : val(*val) {} template<typename T> void operator()(T *x) { val += qi::typeOf<T>()->signature(); } std::string &val; }; template<typename T> struct RawFunctionSignature { static std::string makeSigreturn() { typedef typename boost::function_types::result_type<T>::type ResultType; return typeOf<ResultType>()->signature(); } static std::string makeSignature() { std::string signature; signature += '('; typedef typename boost::function_types::parameter_types<T>::type ArgsType; boost::mpl::for_each< boost::mpl::transform_view<ArgsType, boost::add_pointer< boost::remove_const< boost::remove_reference<boost::mpl::_1> > > > > (qi::detail::signature_function_arg_apply(&signature)); signature += ')'; return signature; } }; template<typename T> struct MemberFunctionSignature { static std::string makeSigreturn() { typedef typename boost::function_types::result_type<T>::type ResultType; return typeOf<ResultType>()->signature(); } static std::string makeSignature() { // Reconstruct the boost::bind(instance, _1, _2...) signature typedef typename boost::function_types::result_type<T>::type RetType; typedef typename boost::function_types::parameter_types<T>::type MemArgsType; typedef typename boost::mpl::pop_front< MemArgsType >::type ArgsType; typedef typename boost::mpl::push_front<ArgsType, RetType>::type EffectiveType; typedef typename boost::function_types::function_type<EffectiveType>::type type; return RawFunctionSignature<type>::makeSignature(); } }; template<typename T> struct FunctionSignature { typedef typename boost::mpl::if_< typename boost::function_types::is_member_pointer<T>, MemberFunctionSignature<T>, RawFunctionSignature<T> >::type Backend; static std::string signature() { static std::string result = Backend::makeSignature(); return result; } static std::string sigreturn() { static std::string result = Backend::makeSigreturn(); return result; } }; template<typename T> struct FunctionSignature<boost::function<T> > : public FunctionSignature<T> {}; template<typename T> inline std::string functionArgumentsSignature() { static bool done = false; static std::string sigs; if (!done) { sigs += '('; typedef typename boost::function_types::parameter_types<T>::type ArgsType; boost::mpl::for_each< boost::mpl::transform_view<ArgsType, boost::add_pointer< boost::remove_const< boost::remove_reference<boost::mpl::_1> > > > > (qi::detail::signature_function_arg_apply(&sigs)); sigs += ')'; done = true; } return sigs; } // Bouncer to DefaultAccess or DirectAccess based on type size template<typename T> class TypeImplMethodsBySize { public: typedef typename boost::mpl::if_c< sizeof(T) <= sizeof(void*), DefaultTypeImplMethods<T, TypeByValue<T> >, DefaultTypeImplMethods<T, TypeByPointer<T> > >::type type; }; } } #include <qimessaging/details/typestring.hxx> #include <qimessaging/details/typetuple.hxx> #endif // _QIMESSAGING_DETAILS_TYPE_HXX_ <commit_msg>Fix suprious warning under win32.<commit_after>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QIMESSAGING_DETAILS_TYPE_HXX_ #define _QIMESSAGING_DETAILS_TYPE_HXX_ #include <qi/types.hpp> #include <cstring> #include <map> #include <vector> #include <list> #include <boost/mpl/for_each.hpp> #include <boost/mpl/transform_view.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/type_traits/add_pointer.hpp> #include <boost/function_types/parameter_types.hpp> #include <boost/function_types/result_type.hpp> #include <boost/function_types/function_type.hpp> #include <boost/function_types/is_member_pointer.hpp> #include <qimessaging/typespecialized.hpp> /* This file contains the default-provided Type specialisations * */ namespace qi { // void template<> class TypeImpl<void>: public Type { public: const TypeInfo& info() { static TypeInfo result = TypeInfo(typeid(void)); return result; } void* initializeStorage(void*) { return 0;} void* ptrFromStorage(void** ) { return 0;} void* clone(void*) { return 0;} void destroy(void* ptr) {} Kind kind() const { return Void;} }; //reference template<typename T> class TypeImpl<T&> : public TypeImpl<T> {}; } namespace qi { namespace detail { template<typename T> inline Type* typeOfBackend() { Type* result = getType(typeid(T)); if (!result) { static Type* defaultResult = 0; // Is this realy a problem? if (!defaultResult) qiLogVerbose("qi.meta") << "typeOf request for unregistered type " << typeid(T).name(); if (!defaultResult) defaultResult = new TypeImpl<T>(); result = defaultResult; } if (strcmp(typeid(T).name(), result->infoString()) && typeid(T)!= typeid(bool)) qiLogWarning("qi.meta") << "typeOfBackend: type mismatch " << typeid(T).name() << " " << result <<" " << result->infoString(); return result; } template<typename T> struct TypeOfAdapter { typedef T type; }; template<typename T> struct TypeOfAdapter<T&> { typedef typename TypeOfAdapter<T>::type type; }; template<typename T> struct TypeOfAdapter<const T> { typedef typename TypeOfAdapter<T>::type type; }; template<typename T> struct TypeOfAdapter<T*> { typedef typename boost::add_pointer<typename boost::remove_const<typename TypeOfAdapter<T>::type>::type>::type type; }; } template<typename T> Type* typeOf() { return detail::typeOfBackend<typename detail::TypeOfAdapter<T>::type>(); } inline Type::Kind Type::kind() const { return Unknown; } namespace detail { struct signature_function_arg_apply { signature_function_arg_apply(std::string* val) : val(*val) {} template<typename T> void operator()(T *x) { val += qi::typeOf<T>()->signature(); } std::string &val; }; template<typename T> struct RawFunctionSignature { static std::string makeSigreturn() { typedef typename boost::function_types::result_type<T>::type ResultType; return typeOf<ResultType>()->signature(); } static std::string makeSignature() { std::string signature; signature += '('; typedef typename boost::function_types::parameter_types<T>::type ArgsType; boost::mpl::for_each< boost::mpl::transform_view<ArgsType, boost::add_pointer< boost::remove_const< boost::remove_reference<boost::mpl::_1> > > > > (qi::detail::signature_function_arg_apply(&signature)); signature += ')'; return signature; } }; template<typename T> struct MemberFunctionSignature { static std::string makeSigreturn() { typedef typename boost::function_types::result_type<T>::type ResultType; return typeOf<ResultType>()->signature(); } static std::string makeSignature() { // Reconstruct the boost::bind(instance, _1, _2...) signature typedef typename boost::function_types::result_type<T>::type RetType; typedef typename boost::function_types::parameter_types<T>::type MemArgsType; typedef typename boost::mpl::pop_front< MemArgsType >::type ArgsType; typedef typename boost::mpl::push_front<ArgsType, RetType>::type EffectiveType; typedef typename boost::function_types::function_type<EffectiveType>::type type; return RawFunctionSignature<type>::makeSignature(); } }; template<typename T> struct FunctionSignature { typedef typename boost::mpl::if_< typename boost::function_types::is_member_pointer<T>, MemberFunctionSignature<T>, RawFunctionSignature<T> >::type Backend; static std::string signature() { static std::string result = Backend::makeSignature(); return result; } static std::string sigreturn() { static std::string result = Backend::makeSigreturn(); return result; } }; template<typename T> struct FunctionSignature<boost::function<T> > : public FunctionSignature<T> {}; template<typename T> inline std::string functionArgumentsSignature() { static bool done = false; static std::string sigs; if (!done) { sigs += '('; typedef typename boost::function_types::parameter_types<T>::type ArgsType; boost::mpl::for_each< boost::mpl::transform_view<ArgsType, boost::add_pointer< boost::remove_const< boost::remove_reference<boost::mpl::_1> > > > > (qi::detail::signature_function_arg_apply(&sigs)); sigs += ')'; done = true; } return sigs; } // Bouncer to DefaultAccess or DirectAccess based on type size template<typename T> class TypeImplMethodsBySize { public: typedef typename boost::mpl::if_c< sizeof(T) <= sizeof(void*), DefaultTypeImplMethods<T, TypeByValue<T> >, DefaultTypeImplMethods<T, TypeByPointer<T> > >::type type; }; } } #include <qimessaging/details/typestring.hxx> #include <qimessaging/details/typetuple.hxx> #endif // _QIMESSAGING_DETAILS_TYPE_HXX_ <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/binary_deserializer.hpp" #include <iomanip> #include <sstream> #include <type_traits> #include "caf/detail/ieee_754.hpp" #include "caf/detail/network_order.hpp" namespace caf { namespace { template <class T> error apply_int(binary_deserializer& bs, T& x) { typename std::make_unsigned<T>::type tmp; if (auto err = bs.apply_raw(sizeof(T), &tmp)) return err; x = static_cast<T>(detail::from_network_order(tmp)); return none; } template <class T> error apply_float(binary_deserializer& bs, T& x) { typename detail::ieee_754_trait<T>::packed_type tmp; if (auto err = apply_int(bs, tmp)) return err; x = detail::unpack754(tmp); return none; } } // namespace <anonmyous> binary_deserializer::binary_deserializer(actor_system& sys, const char* buf, size_t buf_size) : super(sys), pos_(buf), end_(buf + buf_size) { // nop } binary_deserializer::binary_deserializer(execution_unit* ctx, const char* buf, size_t buf_size) : super(ctx), pos_(buf), end_(buf + buf_size) { // nop } binary_deserializer::binary_deserializer(actor_system& sys, const buffer& buf) : binary_deserializer(sys, buf.data(), buf.size()) { // nop } binary_deserializer::binary_deserializer(execution_unit* ctx, const buffer& buf) : binary_deserializer(ctx, buf.data(), buf.size()) { // nop } error binary_deserializer::begin_object(uint16_t& nr, std::string& name) { if (auto err = apply(nr)) return err; if (nr != 0) return none; return apply(name); } error binary_deserializer::end_object() { return none; } error binary_deserializer::begin_sequence(size_t& list_size) { auto s = static_cast<uint32_t>(list_size); if (auto err = apply(s)) return err; list_size = s; return none; } error binary_deserializer::end_sequence() { return none; } error binary_deserializer::apply_raw(size_t num_bytes, void* storage) { if (!range_check(num_bytes)) return sec::end_of_stream; memcpy(storage, pos_, num_bytes); pos_ += num_bytes; return none; } error binary_deserializer::apply_impl(int8_t& x) { return apply_raw(sizeof(int8_t), &x); } error binary_deserializer::apply_impl(uint8_t& x) { return apply_raw(sizeof(uint8_t), &x); } error binary_deserializer::apply_impl(int16_t& x) { return apply_int(*this, x); } error binary_deserializer::apply_impl(uint16_t& x) { return apply_int(*this, x); } error binary_deserializer::apply_impl(int32_t& x) { return apply_int(*this, x); } error binary_deserializer::apply_impl(uint32_t& x) { return apply_int(*this, x); } error binary_deserializer::apply_impl(int64_t& x) { return apply_int(*this, x); } error binary_deserializer::apply_impl(uint64_t& x) { return apply_int(*this, x); } error binary_deserializer::apply_impl(float& x) { return apply_float(*this, x); } error binary_deserializer::apply_impl(double& x) { return apply_float(*this, x); } error binary_deserializer::apply_impl(long double& x) { // The IEEE-754 conversion does not work for long double // => fall back to string serialization (even though it sucks). std::string tmp; if (auto err = apply(tmp)) return err; std::istringstream iss{std::move(tmp)}; iss >> x; return none; } error binary_deserializer::apply_impl(std::string& x) { size_t str_size; if (auto err = begin_sequence(str_size)) return err; if (!range_check(str_size)) return sec::end_of_stream; x.assign(pos_, pos_ + str_size); pos_ += str_size; return end_sequence(); } error binary_deserializer::apply_impl(std::u16string& x) { auto str_size = x.size(); if (auto err = begin_sequence(str_size)) return err; for (size_t i = 0; i < str_size; ++i) { // The standard does not guarantee that char16_t is exactly 16 bits. uint16_t tmp; if (auto err = apply_int(*this, tmp)) return err; x.push_back(static_cast<char16_t>(tmp)); } return none; } error binary_deserializer::apply_impl(std::u32string& x) { auto str_size = x.size(); if (auto err = begin_sequence(str_size)) return err; for (size_t i = 0; i < str_size; ++i) { // The standard does not guarantee that char32_t is exactly 32 bits. uint32_t tmp; if (auto err = apply_int(*this, tmp)) return err; x.push_back(static_cast<char32_t>(tmp)); } return none; } } // namespace caf <commit_msg>Add missing include<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/binary_deserializer.hpp" #include <iomanip> #include <sstream> #include <type_traits> #include "caf/detail/ieee_754.hpp" #include "caf/detail/network_order.hpp" #include "caf/sec.hpp" namespace caf { namespace { template <class T> error apply_int(binary_deserializer& bs, T& x) { typename std::make_unsigned<T>::type tmp; if (auto err = bs.apply_raw(sizeof(T), &tmp)) return err; x = static_cast<T>(detail::from_network_order(tmp)); return none; } template <class T> error apply_float(binary_deserializer& bs, T& x) { typename detail::ieee_754_trait<T>::packed_type tmp; if (auto err = apply_int(bs, tmp)) return err; x = detail::unpack754(tmp); return none; } } // namespace <anonmyous> binary_deserializer::binary_deserializer(actor_system& sys, const char* buf, size_t buf_size) : super(sys), pos_(buf), end_(buf + buf_size) { // nop } binary_deserializer::binary_deserializer(execution_unit* ctx, const char* buf, size_t buf_size) : super(ctx), pos_(buf), end_(buf + buf_size) { // nop } binary_deserializer::binary_deserializer(actor_system& sys, const buffer& buf) : binary_deserializer(sys, buf.data(), buf.size()) { // nop } binary_deserializer::binary_deserializer(execution_unit* ctx, const buffer& buf) : binary_deserializer(ctx, buf.data(), buf.size()) { // nop } error binary_deserializer::begin_object(uint16_t& nr, std::string& name) { if (auto err = apply(nr)) return err; if (nr != 0) return none; return apply(name); } error binary_deserializer::end_object() { return none; } error binary_deserializer::begin_sequence(size_t& list_size) { auto s = static_cast<uint32_t>(list_size); if (auto err = apply(s)) return err; list_size = s; return none; } error binary_deserializer::end_sequence() { return none; } error binary_deserializer::apply_raw(size_t num_bytes, void* storage) { if (!range_check(num_bytes)) return sec::end_of_stream; memcpy(storage, pos_, num_bytes); pos_ += num_bytes; return none; } error binary_deserializer::apply_impl(int8_t& x) { return apply_raw(sizeof(int8_t), &x); } error binary_deserializer::apply_impl(uint8_t& x) { return apply_raw(sizeof(uint8_t), &x); } error binary_deserializer::apply_impl(int16_t& x) { return apply_int(*this, x); } error binary_deserializer::apply_impl(uint16_t& x) { return apply_int(*this, x); } error binary_deserializer::apply_impl(int32_t& x) { return apply_int(*this, x); } error binary_deserializer::apply_impl(uint32_t& x) { return apply_int(*this, x); } error binary_deserializer::apply_impl(int64_t& x) { return apply_int(*this, x); } error binary_deserializer::apply_impl(uint64_t& x) { return apply_int(*this, x); } error binary_deserializer::apply_impl(float& x) { return apply_float(*this, x); } error binary_deserializer::apply_impl(double& x) { return apply_float(*this, x); } error binary_deserializer::apply_impl(long double& x) { // The IEEE-754 conversion does not work for long double // => fall back to string serialization (even though it sucks). std::string tmp; if (auto err = apply(tmp)) return err; std::istringstream iss{std::move(tmp)}; iss >> x; return none; } error binary_deserializer::apply_impl(std::string& x) { size_t str_size; if (auto err = begin_sequence(str_size)) return err; if (!range_check(str_size)) return sec::end_of_stream; x.assign(pos_, pos_ + str_size); pos_ += str_size; return end_sequence(); } error binary_deserializer::apply_impl(std::u16string& x) { auto str_size = x.size(); if (auto err = begin_sequence(str_size)) return err; for (size_t i = 0; i < str_size; ++i) { // The standard does not guarantee that char16_t is exactly 16 bits. uint16_t tmp; if (auto err = apply_int(*this, tmp)) return err; x.push_back(static_cast<char16_t>(tmp)); } return none; } error binary_deserializer::apply_impl(std::u32string& x) { auto str_size = x.size(); if (auto err = begin_sequence(str_size)) return err; for (size_t i = 0; i < str_size; ++i) { // The standard does not guarantee that char32_t is exactly 32 bits. uint32_t tmp; if (auto err = apply_int(*this, tmp)) return err; x.push_back(static_cast<char32_t>(tmp)); } return none; } } // namespace caf <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #if defined(WNT) #include <windows.h> #endif #include <osl/thread.h> #include <osl/file.hxx> #include <tools/debug.hxx> #include <tools/urlobj.hxx> #include <i18npool/mslangid.hxx> #include <unotools/lingucfg.hxx> #include <unotools/pathoptions.hxx> #include <rtl/ustring.hxx> #include <rtl/string.hxx> #include <rtl/tencinfo.h> #include <linguistic/misc.hxx> #include <set> #include <vector> #include <string.h> #include <lingutil.hxx> #include <dictmgr.hxx> #include <sal/macros.h> using ::com::sun::star::lang::Locale; using namespace ::com::sun::star; #if 0 ////////////////////////////////////////////////////////////////////// String GetDirectoryPathFromFileURL( const String &rFileURL ) { // get file URL INetURLObject aURLObj; aURLObj.SetSmartProtocol( INET_PROT_FILE ); aURLObj.SetSmartURL( rFileURL ); aURLObj.removeSegment(); DBG_ASSERT( !aURLObj.HasError(), "invalid URL" ); String aRes = aURLObj.GetMainURL( INetURLObject::DECODE_TO_IURI ); return aRes; } #endif #if defined(WNT) rtl::OString Win_GetShortPathName( const rtl::OUString &rLongPathName ) { rtl::OString aRes; sal_Unicode aShortBuffer[1024] = {0}; sal_Int32 nShortBufSize = SAL_N_ELEMENTS( aShortBuffer ); // use the version of 'GetShortPathName' that can deal with Unicode... sal_Int32 nShortLen = GetShortPathNameW( reinterpret_cast<LPCWSTR>( rLongPathName.getStr() ), reinterpret_cast<LPWSTR>( aShortBuffer ), nShortBufSize ); if (nShortLen < nShortBufSize) // conversion successful? aRes = rtl::OString( OU2ENC( rtl::OUString( aShortBuffer, nShortLen ), osl_getThreadTextEncoding()) ); else OSL_FAIL( "Win_GetShortPathName: buffer to short" ); return aRes; } #endif //defined(WNT) ////////////////////////////////////////////////////////////////////// // build list of old style diuctionaries (not as extensions) to use. // User installed dictionaries (the ones residing in the user paths) // will get precedence over system installed ones for the same language. std::vector< SvtLinguConfigDictionaryEntry > GetOldStyleDics( const char *pDicType ) { std::vector< SvtLinguConfigDictionaryEntry > aRes; if (!pDicType) return aRes; rtl::OUString aFormatName; String aDicExtension; #ifdef SYSTEM_DICTS rtl::OUString aSystemDir; rtl::OUString aSystemPrefix; rtl::OUString aSystemSuffix; #endif if (strcmp( pDicType, "DICT" ) == 0) { aFormatName = A2OU("DICT_SPELL"); aDicExtension = rtl::OUString( ".dic" ); #ifdef SYSTEM_DICTS aSystemDir = A2OU( DICT_SYSTEM_DIR ); aSystemSuffix = aDicExtension; #endif } else if (strcmp( pDicType, "HYPH" ) == 0) { aFormatName = A2OU("DICT_HYPH"); aDicExtension = rtl::OUString( ".dic" ); #ifdef SYSTEM_DICTS aSystemDir = A2OU( HYPH_SYSTEM_DIR ); aSystemPrefix = A2OU( "hyph_" ); aSystemSuffix = aDicExtension; #endif } else if (strcmp( pDicType, "THES" ) == 0) { aFormatName = A2OU("DICT_THES"); aDicExtension = rtl::OUString( ".dat" ); #ifdef SYSTEM_DICTS aSystemDir = A2OU( THES_SYSTEM_DIR ); aSystemPrefix = A2OU( "th_" ); aSystemSuffix = A2OU( "_v2.dat" ); #endif } if (aFormatName.isEmpty() || aDicExtension.Len() == 0) return aRes; // set of languages to remember the language where it is already // decided to make use of the dictionary. std::set< LanguageType > aDicLangInUse; #ifdef SYSTEM_DICTS osl::Directory aSystemDicts(aSystemDir); if (aSystemDicts.open() == osl::FileBase::E_None) { osl::DirectoryItem aItem; osl::FileStatus aFileStatus(osl_FileStatus_Mask_FileURL); while (aSystemDicts.getNextItem(aItem) == osl::FileBase::E_None) { aItem.getFileStatus(aFileStatus); rtl::OUString sPath = aFileStatus.getFileURL(); if (sPath.lastIndexOf(aSystemSuffix) == sPath.getLength()-aSystemSuffix.getLength()) { sal_Int32 nStartIndex = sPath.lastIndexOf(sal_Unicode('/')) + 1; if (!sPath.match(aSystemPrefix, nStartIndex)) continue; rtl::OUString sChunk = sPath.copy(0, sPath.getLength() - aSystemSuffix.getLength()); sal_Int32 nIndex = nStartIndex + aSystemPrefix.getLength(); rtl::OUString sLang = sChunk.getToken( 0, '_', nIndex ); if (!sLang.getLength()) continue; rtl::OUString sRegion; if (nIndex != -1) sRegion = sChunk.copy( nIndex, sChunk.getLength() - nIndex ); // Thus we first get the language of the dictionary LanguageType nLang = MsLangId::convertIsoNamesToLanguage( sLang, sRegion ); if (aDicLangInUse.count( nLang ) == 0) { // remember the new language in use aDicLangInUse.insert( nLang ); // add the dictionary to the resulting vector SvtLinguConfigDictionaryEntry aDicEntry; aDicEntry.aLocations.realloc(1); aDicEntry.aLocaleNames.realloc(1); rtl::OUString aLocaleName( MsLangId::convertLanguageToIsoString( nLang ) ); aDicEntry.aLocations[0] = sPath; aDicEntry.aFormatName = aFormatName; aDicEntry.aLocaleNames[0] = aLocaleName; aRes.push_back( aDicEntry ); } } } } #endif return aRes; } void MergeNewStyleDicsAndOldStyleDics( std::list< SvtLinguConfigDictionaryEntry > &rNewStyleDics, const std::vector< SvtLinguConfigDictionaryEntry > &rOldStyleDics ) { // get list of languages supported by new style dictionaries std::set< LanguageType > aNewStyleLanguages; std::list< SvtLinguConfigDictionaryEntry >::const_iterator aIt; for (aIt = rNewStyleDics.begin() ; aIt != rNewStyleDics.end(); ++aIt) { const uno::Sequence< rtl::OUString > aLocaleNames( aIt->aLocaleNames ); sal_Int32 nLocaleNames = aLocaleNames.getLength(); for (sal_Int32 k = 0; k < nLocaleNames; ++k) { LanguageType nLang = MsLangId::convertIsoStringToLanguage( aLocaleNames[k] ); aNewStyleLanguages.insert( nLang ); } } // now check all old style dictionaries if they will add a not yet // added language. If so add them to the resulting vector std::vector< SvtLinguConfigDictionaryEntry >::const_iterator aIt2; for (aIt2 = rOldStyleDics.begin(); aIt2 != rOldStyleDics.end(); ++aIt2) { sal_Int32 nOldStyleDics = aIt2->aLocaleNames.getLength(); // old style dics should only have one language listed... DBG_ASSERT( nOldStyleDics, "old style dictionary with more then one language found!"); if (nOldStyleDics > 0) { LanguageType nLang = MsLangId::convertIsoStringToLanguage( aIt2->aLocaleNames[0] ); if (nLang == LANGUAGE_DONTKNOW || nLang == LANGUAGE_NONE) { OSL_FAIL( "old style dictionary with invalid language found!" ); continue; } // language not yet added? if (aNewStyleLanguages.count( nLang ) == 0) rNewStyleDics.push_back( *aIt2 ); } else { OSL_FAIL( "old style dictionary with no language found!" ); } } } rtl_TextEncoding getTextEncodingFromCharset(const sal_Char* pCharset) { // default result: used to indicate that we failed to get the proper encoding rtl_TextEncoding eRet = RTL_TEXTENCODING_DONTKNOW; if (pCharset) { eRet = rtl_getTextEncodingFromMimeCharset(pCharset); if (eRet == RTL_TEXTENCODING_DONTKNOW) eRet = rtl_getTextEncodingFromUnixCharset(pCharset); if (eRet == RTL_TEXTENCODING_DONTKNOW) { if (strcmp("ISCII-DEVANAGARI", pCharset) == 0) eRet = RTL_TEXTENCODING_ISCII_DEVANAGARI; } } return eRet; } ////////////////////////////////////////////////////////////////////// /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>support system dicts named using bcp47 scheme<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #if defined(WNT) #include <windows.h> #endif #include <osl/thread.h> #include <osl/file.hxx> #include <tools/debug.hxx> #include <tools/urlobj.hxx> #include <i18npool/languagetag.hxx> #include <i18npool/mslangid.hxx> #include <unotools/lingucfg.hxx> #include <unotools/pathoptions.hxx> #include <rtl/ustring.hxx> #include <rtl/string.hxx> #include <rtl/tencinfo.h> #include <linguistic/misc.hxx> #include <set> #include <vector> #include <string.h> #include <lingutil.hxx> #include <dictmgr.hxx> #include <sal/macros.h> using ::com::sun::star::lang::Locale; using namespace ::com::sun::star; #if 0 ////////////////////////////////////////////////////////////////////// String GetDirectoryPathFromFileURL( const String &rFileURL ) { // get file URL INetURLObject aURLObj; aURLObj.SetSmartProtocol( INET_PROT_FILE ); aURLObj.SetSmartURL( rFileURL ); aURLObj.removeSegment(); DBG_ASSERT( !aURLObj.HasError(), "invalid URL" ); String aRes = aURLObj.GetMainURL( INetURLObject::DECODE_TO_IURI ); return aRes; } #endif #if defined(WNT) rtl::OString Win_GetShortPathName( const rtl::OUString &rLongPathName ) { rtl::OString aRes; sal_Unicode aShortBuffer[1024] = {0}; sal_Int32 nShortBufSize = SAL_N_ELEMENTS( aShortBuffer ); // use the version of 'GetShortPathName' that can deal with Unicode... sal_Int32 nShortLen = GetShortPathNameW( reinterpret_cast<LPCWSTR>( rLongPathName.getStr() ), reinterpret_cast<LPWSTR>( aShortBuffer ), nShortBufSize ); if (nShortLen < nShortBufSize) // conversion successful? aRes = rtl::OString( OU2ENC( rtl::OUString( aShortBuffer, nShortLen ), osl_getThreadTextEncoding()) ); else OSL_FAIL( "Win_GetShortPathName: buffer to short" ); return aRes; } #endif //defined(WNT) ////////////////////////////////////////////////////////////////////// // build list of old style diuctionaries (not as extensions) to use. // User installed dictionaries (the ones residing in the user paths) // will get precedence over system installed ones for the same language. std::vector< SvtLinguConfigDictionaryEntry > GetOldStyleDics( const char *pDicType ) { std::vector< SvtLinguConfigDictionaryEntry > aRes; if (!pDicType) return aRes; rtl::OUString aFormatName; String aDicExtension; #ifdef SYSTEM_DICTS rtl::OUString aSystemDir; rtl::OUString aSystemPrefix; rtl::OUString aSystemSuffix; #endif if (strcmp( pDicType, "DICT" ) == 0) { aFormatName = A2OU("DICT_SPELL"); aDicExtension = rtl::OUString( ".dic" ); #ifdef SYSTEM_DICTS aSystemDir = A2OU( DICT_SYSTEM_DIR ); aSystemSuffix = aDicExtension; #endif } else if (strcmp( pDicType, "HYPH" ) == 0) { aFormatName = A2OU("DICT_HYPH"); aDicExtension = rtl::OUString( ".dic" ); #ifdef SYSTEM_DICTS aSystemDir = A2OU( HYPH_SYSTEM_DIR ); aSystemPrefix = A2OU( "hyph_" ); aSystemSuffix = aDicExtension; #endif } else if (strcmp( pDicType, "THES" ) == 0) { aFormatName = A2OU("DICT_THES"); aDicExtension = rtl::OUString( ".dat" ); #ifdef SYSTEM_DICTS aSystemDir = A2OU( THES_SYSTEM_DIR ); aSystemPrefix = A2OU( "th_" ); aSystemSuffix = A2OU( "_v2.dat" ); #endif } if (aFormatName.isEmpty() || aDicExtension.Len() == 0) return aRes; // set of languages to remember the language where it is already // decided to make use of the dictionary. std::set< OUString > aDicLangInUse; #ifdef SYSTEM_DICTS osl::Directory aSystemDicts(aSystemDir); if (aSystemDicts.open() == osl::FileBase::E_None) { osl::DirectoryItem aItem; osl::FileStatus aFileStatus(osl_FileStatus_Mask_FileURL); while (aSystemDicts.getNextItem(aItem) == osl::FileBase::E_None) { aItem.getFileStatus(aFileStatus); OUString sPath = aFileStatus.getFileURL(); if (sPath.lastIndexOf(aSystemSuffix) == sPath.getLength()-aSystemSuffix.getLength()) { sal_Int32 nStartIndex = sPath.lastIndexOf(sal_Unicode('/')) + 1; if (!sPath.match(aSystemPrefix, nStartIndex)) continue; OUString sChunk = sPath.copy(nStartIndex + aSystemPrefix.getLength(), sPath.getLength() - aSystemSuffix.getLength() - nStartIndex - aSystemPrefix.getLength()); if (sChunk.isEmpty()) continue; //We prefer (now) to use language tags LanguageTag aLangTag(sChunk, true); //On failure try older basic LANG_REGION scheme if (!aLangTag.isValidBcp47()) { sal_Int32 nIndex = 0; OUString sLang = sChunk.getToken(0, '_', nIndex); if (!sLang.getLength()) continue; OUString sRegion; if (nIndex != -1) sRegion = sChunk.copy(nIndex); aLangTag = LanguageTag(sLang, sRegion); } if (!aLangTag.isValidBcp47()) continue; // Thus we first get the language of the dictionary OUString aLocaleName(aLangTag.getBcp47()); if (aDicLangInUse.count(aLocaleName) == 0) { // remember the new language in use aDicLangInUse.insert(aLocaleName); // add the dictionary to the resulting vector SvtLinguConfigDictionaryEntry aDicEntry; aDicEntry.aLocations.realloc(1); aDicEntry.aLocaleNames.realloc(1); aDicEntry.aLocations[0] = sPath; aDicEntry.aFormatName = aFormatName; aDicEntry.aLocaleNames[0] = aLocaleName; aRes.push_back( aDicEntry ); } } } } #endif return aRes; } void MergeNewStyleDicsAndOldStyleDics( std::list< SvtLinguConfigDictionaryEntry > &rNewStyleDics, const std::vector< SvtLinguConfigDictionaryEntry > &rOldStyleDics ) { // get list of languages supported by new style dictionaries std::set< LanguageType > aNewStyleLanguages; std::list< SvtLinguConfigDictionaryEntry >::const_iterator aIt; for (aIt = rNewStyleDics.begin() ; aIt != rNewStyleDics.end(); ++aIt) { const uno::Sequence< rtl::OUString > aLocaleNames( aIt->aLocaleNames ); sal_Int32 nLocaleNames = aLocaleNames.getLength(); for (sal_Int32 k = 0; k < nLocaleNames; ++k) { LanguageType nLang = MsLangId::convertIsoStringToLanguage( aLocaleNames[k] ); aNewStyleLanguages.insert( nLang ); } } // now check all old style dictionaries if they will add a not yet // added language. If so add them to the resulting vector std::vector< SvtLinguConfigDictionaryEntry >::const_iterator aIt2; for (aIt2 = rOldStyleDics.begin(); aIt2 != rOldStyleDics.end(); ++aIt2) { sal_Int32 nOldStyleDics = aIt2->aLocaleNames.getLength(); // old style dics should only have one language listed... DBG_ASSERT( nOldStyleDics, "old style dictionary with more then one language found!"); if (nOldStyleDics > 0) { LanguageType nLang = MsLangId::convertIsoStringToLanguage( aIt2->aLocaleNames[0] ); if (nLang == LANGUAGE_DONTKNOW || nLang == LANGUAGE_NONE) { OSL_FAIL( "old style dictionary with invalid language found!" ); continue; } // language not yet added? if (aNewStyleLanguages.count( nLang ) == 0) rNewStyleDics.push_back( *aIt2 ); } else { OSL_FAIL( "old style dictionary with no language found!" ); } } } rtl_TextEncoding getTextEncodingFromCharset(const sal_Char* pCharset) { // default result: used to indicate that we failed to get the proper encoding rtl_TextEncoding eRet = RTL_TEXTENCODING_DONTKNOW; if (pCharset) { eRet = rtl_getTextEncodingFromMimeCharset(pCharset); if (eRet == RTL_TEXTENCODING_DONTKNOW) eRet = rtl_getTextEncodingFromUnixCharset(pCharset); if (eRet == RTL_TEXTENCODING_DONTKNOW) { if (strcmp("ISCII-DEVANAGARI", pCharset) == 0) eRet = RTL_TEXTENCODING_ISCII_DEVANAGARI; } } return eRet; } ////////////////////////////////////////////////////////////////////// /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* * lookup-atomese.cc * * Implement the word-lookup callbacks * * Copyright (c) 2022 Linas Vepstas <linasvepstas@gmail.com> */ #ifdef HAVE_ATOMESE #include <cstdlib> #include <opencog/atomspace/AtomSpace.h> #include <opencog/persist/api/StorageNode.h> #include <opencog/persist/cog-storage/CogStorage.h> #include <opencog/nlp/types/atom_types.h> #undef STRINGIFY extern "C" { #include "../link-includes.h" // For Dictionary #include "../dict-common/dict-common.h" // for Dictionary_s #include "lookup-atomese.h" }; using namespace opencog; class Local { public: AtomSpacePtr asp; StorageNodePtr stnp; }; void as_open(Dictionary dict, const char* url) { Local* local = new Local; local->asp = createAtomSpace(); /* The cast below forces the shared lib constructor to run. */ /* That's needed to force the factory to get installed. */ Handle hsn = local->asp->add_node(COG_STORAGE_NODE, url); local->stnp = CogStorageNodeCast(hsn); local->stnp->open(); // XXX FIXME -- if we cannot connect, then should hard-fail. if (local->stnp->connected()) printf("Connected to %s\n", url); else printf("Failed to connect to %s\n", url); dict->as_server = (void*) local; } void as_close(Dictionary dict) { if (nullptr == dict->as_server) return; Local* local = (Local*) (dict->as_server); local->stnp->close(); delete local; dict->as_server = nullptr; } bool as_lookup(Dictionary dict, const char *s) { Local* local = (Local*) (dict->as_server); printf("duuude called as_lookup for >>%s<<\n", s); Handle wrd = local->asp->get_node(WORD_NODE, s); if (nullptr == wrd) wrd = local->asp->add_node(WORD_NODE, s); // Are there any Sections in the local atomspace? size_t nsects = wrd->getIncomingSetSizeByType(SECTION); if (0 == nsects) local->stnp->fetch_incoming_by_type(wrd, SECTION); nsects = wrd->getIncomingSetSizeByType(SECTION); printf("duuude as_lookup for >>%s<< sects=%lu\n", s, nsects); return 0 != nsects; } Dict_node * as_lookup_list(Dictionary dict, const char *s) { printf("duuude called as_lookup_list for %s\n", s); return NULL; } Dict_node * as_lookup_wild(Dictionary dict, const char *s) { printf("duuude called as_lookup_wild for %s\n", s); return NULL; } void as_free_llist(Dictionary dict, Dict_node *llist) { Dict_node * dn; while (llist != NULL) { dn = llist->right; free(llist); llist = dn; } } #endif /* HAVE_ATOMSPACE */ <commit_msg>Flush barrier is needed.<commit_after>/* * lookup-atomese.cc * * Implement the word-lookup callbacks * * Copyright (c) 2022 Linas Vepstas <linasvepstas@gmail.com> */ #ifdef HAVE_ATOMESE #include <cstdlib> #include <opencog/atomspace/AtomSpace.h> #include <opencog/persist/api/StorageNode.h> #include <opencog/persist/cog-storage/CogStorage.h> #include <opencog/nlp/types/atom_types.h> #undef STRINGIFY extern "C" { #include "../link-includes.h" // For Dictionary #include "../dict-common/dict-common.h" // for Dictionary_s #include "lookup-atomese.h" }; using namespace opencog; class Local { public: AtomSpacePtr asp; StorageNodePtr stnp; }; void as_open(Dictionary dict, const char* url) { Local* local = new Local; local->asp = createAtomSpace(); /* The cast below forces the shared lib constructor to run. */ /* That's needed to force the factory to get installed. */ Handle hsn = local->asp->add_node(COG_STORAGE_NODE, url); local->stnp = CogStorageNodeCast(hsn); local->stnp->open(); // XXX FIXME -- if we cannot connect, then should hard-fail. if (local->stnp->connected()) printf("Connected to %s\n", url); else printf("Failed to connect to %s\n", url); dict->as_server = (void*) local; } void as_close(Dictionary dict) { if (nullptr == dict->as_server) return; Local* local = (Local*) (dict->as_server); local->stnp->close(); delete local; dict->as_server = nullptr; } bool as_lookup(Dictionary dict, const char *s) { Local* local = (Local*) (dict->as_server); printf("duuude called as_lookup for >>%s<<\n", s); Handle wrd = local->asp->get_node(WORD_NODE, s); if (nullptr == wrd) wrd = local->asp->add_node(WORD_NODE, s); // Are there any Sections in the local atomspace? size_t nsects = wrd->getIncomingSetSizeByType(SECTION); if (0 == nsects) { local->stnp->fetch_incoming_by_type(wrd, SECTION); local->stnp->barrier(); } nsects = wrd->getIncomingSetSizeByType(SECTION); printf("duuude as_lookup for >>%s<< sects=%lu\n", s, nsects); return 0 != nsects; } Dict_node * as_lookup_list(Dictionary dict, const char *s) { printf("duuude called as_lookup_list for %s\n", s); return NULL; } Dict_node * as_lookup_wild(Dictionary dict, const char *s) { printf("duuude called as_lookup_wild for %s\n", s); return NULL; } void as_free_llist(Dictionary dict, Dict_node *llist) { Dict_node * dn; while (llist != NULL) { dn = llist->right; free(llist); llist = dn; } } #endif /* HAVE_ATOMSPACE */ <|endoftext|>
<commit_before>#include <Refal2.h> namespace Refal2 { //----------------------------------------------------------------------------- // CError void CError::Reset() { ResetSeverity(); ResetFileName(); ResetToken(); ResetMessage(); } bool CError::IsSet() const { return ( Severity() != ES_None && !Message().empty() ); } void CError::ResetSeverity() { severity = ES_None; resetCache(); } void CError::SetSeverity( TErrorSeverity _severity ) { assert( _severity != ES_None ); severity = _severity; resetCache(); } void CError::ResetFileName() { fileName.clear(); resetCache(); } void CError::SetFileName( const std::string& _fileName ) { assert( !_fileName.empty() ); fileName = _fileName; resetCache(); } void CError::ResetToken() { token.type = TT_None; resetCache(); } void CError::SetTokenData( int line, int position, const std::string& wrongText ) { token.type = TT_Word; token.line = line; token.position = position; token.word = wrongText; } void CError::SetToken( const CToken& _token ) { assert( !_token.IsNone() ); token = _token; resetCache(); } void CError::ResetMessage() { message.clear(); resetCache(); } void CError::SetMessage( const std::string& _message ) { assert( !_message.empty() ); message = _message; resetCache(); } const std::string& CError::UserMessage() const { if( userMessage.empty() ) { std::ostringstream userMessageStream; if( !fileName.empty() ) { userMessageStream << fileName << ":"; if( !token.IsNone() ) { assert( token.type == TT_Word ); userMessageStream << token.line << ":" << token.position << ":"; } std::cout << " "; } else { assert( token.IsNone() ); } switch( Severity() ) { case ES_Warning: userMessageStream << "warning"; break; case ES_Error: userMessageStream << "error"; break; case ES_LinkError: userMessageStream << "link error"; break; case ES_FatalError: userMessageStream << "fatal error"; break; case ES_None: default: assert( false ); break; } assert( !message.empty() ); userMessageStream << ": " << message << "."; userMessage = userMessageStream.str(); } return userMessage; } //----------------------------------------------------------------------------- CErrorsHelper::CErrorsHelper( IErrorHandler* errorHandler ) { CError::Reset(); Reset(); SetErrorHandler( errorHandler ); } void CErrorsHelper::Reset() { errorHandler = nullptr; errorSeverity = ES_None; } void CErrorsHelper::SetErrorHandler( IErrorHandler* _errorHandler ) { errorHandler = _errorHandler; } bool CErrorsHelper::HasErrors() const { switch( ErrorSeverity() ) { case ES_None: case ES_Warning: return false; case ES_Error: case ES_LinkError: case ES_FatalError: return true; } assert( false ); return false; } void CErrorsHelper::RaiseError( TErrorSeverity severity, const std::string& message ) { CError::SetSeverity( severity ); CError::SetMessage( message ); raiseError(); CError::ResetSeverity(); CError::ResetMessage(); } void CErrorsHelper::RaiseError( TErrorSeverity severity, const std::string& message, const CToken& token ) { CError::SetToken( token ); RaiseError( severity, message ); CError::ResetToken(); } void CErrorsHelper::raiseError() { assert( errorHandler != nullptr ); assert( CError::IsSet() ); const TErrorSeverity severities[] = { ES_FatalError, ES_LinkError, ES_Error, ES_Warning, ES_None }; for( int i = 0; i < sizeof( severities ) / sizeof( TErrorSeverity ); i++ ) { if( severities[i] == CError::Severity() || severities[i] == errorSeverity ) { errorSeverity = severities[i]; } } errorHandler->Error( *this ); } //----------------------------------------------------------------------------- } // end of namespace Refal2 <commit_msg>remove bad assert<commit_after>#include <Refal2.h> namespace Refal2 { //----------------------------------------------------------------------------- // CError void CError::Reset() { ResetSeverity(); ResetFileName(); ResetToken(); ResetMessage(); } bool CError::IsSet() const { return ( Severity() != ES_None && !Message().empty() ); } void CError::ResetSeverity() { severity = ES_None; resetCache(); } void CError::SetSeverity( TErrorSeverity _severity ) { assert( _severity != ES_None ); severity = _severity; resetCache(); } void CError::ResetFileName() { fileName.clear(); resetCache(); } void CError::SetFileName( const std::string& _fileName ) { assert( !_fileName.empty() ); fileName = _fileName; resetCache(); } void CError::ResetToken() { token.type = TT_None; resetCache(); } void CError::SetTokenData( int line, int position, const std::string& wrongText ) { token.type = TT_Word; token.line = line; token.position = position; token.word = wrongText; } void CError::SetToken( const CToken& _token ) { assert( !_token.IsNone() ); token = _token; resetCache(); } void CError::ResetMessage() { message.clear(); resetCache(); } void CError::SetMessage( const std::string& _message ) { assert( !_message.empty() ); message = _message; resetCache(); } const std::string& CError::UserMessage() const { if( userMessage.empty() ) { std::ostringstream userMessageStream; if( !fileName.empty() ) { userMessageStream << fileName << ":"; if( !token.IsNone() ) { userMessageStream << token.line << ":" << token.position << ":"; } std::cout << " "; } else { assert( token.IsNone() ); } switch( Severity() ) { case ES_Warning: userMessageStream << "warning"; break; case ES_Error: userMessageStream << "error"; break; case ES_LinkError: userMessageStream << "link error"; break; case ES_FatalError: userMessageStream << "fatal error"; break; case ES_None: default: assert( false ); break; } assert( !message.empty() ); userMessageStream << ": " << message << "."; userMessage = userMessageStream.str(); } return userMessage; } //----------------------------------------------------------------------------- CErrorsHelper::CErrorsHelper( IErrorHandler* errorHandler ) { CError::Reset(); Reset(); SetErrorHandler( errorHandler ); } void CErrorsHelper::Reset() { errorHandler = nullptr; errorSeverity = ES_None; } void CErrorsHelper::SetErrorHandler( IErrorHandler* _errorHandler ) { errorHandler = _errorHandler; } bool CErrorsHelper::HasErrors() const { switch( ErrorSeverity() ) { case ES_None: case ES_Warning: return false; case ES_Error: case ES_LinkError: case ES_FatalError: return true; } assert( false ); return false; } void CErrorsHelper::RaiseError( TErrorSeverity severity, const std::string& message ) { CError::SetSeverity( severity ); CError::SetMessage( message ); raiseError(); CError::ResetSeverity(); CError::ResetMessage(); } void CErrorsHelper::RaiseError( TErrorSeverity severity, const std::string& message, const CToken& token ) { CError::SetToken( token ); RaiseError( severity, message ); CError::ResetToken(); } void CErrorsHelper::raiseError() { assert( errorHandler != nullptr ); assert( CError::IsSet() ); const TErrorSeverity severities[] = { ES_FatalError, ES_LinkError, ES_Error, ES_Warning, ES_None }; for( int i = 0; i < sizeof( severities ) / sizeof( TErrorSeverity ); i++ ) { if( severities[i] == CError::Severity() || severities[i] == errorSeverity ) { errorSeverity = severities[i]; } } errorHandler->Error( *this ); } //----------------------------------------------------------------------------- } // end of namespace Refal2 <|endoftext|>
<commit_before>#include "FTSize.h" #include "FTGL.h" FTSize::FTSize() : ftFace(0), size(0), err(0) {} FTSize::~FTSize() {} bool FTSize::CharSize( FT_Face* face, unsigned int point_size, unsigned int x_resolution, unsigned int y_resolution ) { ftFace = face; size = point_size; err = FT_Set_Char_Size( *ftFace, 0L, point_size * 64, x_resolution, y_resolution); ftSize = (*ftFace)->size; return !err; } int FTSize::Ascender() const { return ftSize->metrics.ascender >> 6; } int FTSize::Descender() const { return ftSize->metrics.descender >> 6; } int FTSize::Height() const { if( FT_IS_SCALABLE((*ftFace))) { float height; if( FT_IS_SFNT((*ftFace))) // Don't think this is correct { height = (*ftFace)->bbox.yMax - (*ftFace)->bbox.yMin; // bbox.yMax-bbox.yMin } else { height = (*ftFace)->bbox.yMax - (*ftFace)->bbox.yMin >> 16; // bbox.yMax-bbox.yMin } height = height * ( (float)ftSize->metrics.y_ppem / (float)(*ftFace)->units_per_EM); return static_cast<int>(height); } else { return ftSize->metrics.height >> 6; } } int FTSize::Width() const { if( FT_IS_SCALABLE((*ftFace))) { float width; if( FT_IS_SFNT((*ftFace))) // Don't think this is correct { width = ((*ftFace)->bbox.xMax - (*ftFace)->bbox.xMin); // bbox.xMax-bbox.xMin } else { width = ((*ftFace)->bbox.xMax - (*ftFace)->bbox.xMin) >> 16; // bbox.xMax-bbox.xMin } width = width * ( (float)ftSize->metrics.x_ppem / (float)(*ftFace)->units_per_EM); return static_cast<int>(width); } else { return ftSize->metrics.max_advance >> 6; } } int FTSize::Underline() const { return 0; } <commit_msg>Added brackets to clear Win32 warning<commit_after>#include "FTSize.h" #include "FTGL.h" FTSize::FTSize() : ftFace(0), size(0), err(0) {} FTSize::~FTSize() {} bool FTSize::CharSize( FT_Face* face, unsigned int point_size, unsigned int x_resolution, unsigned int y_resolution ) { ftFace = face; size = point_size; err = FT_Set_Char_Size( *ftFace, 0L, point_size * 64, x_resolution, y_resolution); ftSize = (*ftFace)->size; return !err; } int FTSize::Ascender() const { return ftSize->metrics.ascender >> 6; } int FTSize::Descender() const { return ftSize->metrics.descender >> 6; } int FTSize::Height() const { if( FT_IS_SCALABLE((*ftFace))) { float height; if( FT_IS_SFNT((*ftFace))) // Don't think this is correct { height = ((*ftFace)->bbox.yMax - (*ftFace)->bbox.yMin); // bbox.yMax-bbox.yMin } else { height = ((*ftFace)->bbox.yMax - (*ftFace)->bbox.yMin) >> 16; // bbox.yMax-bbox.yMin } height = height * ( (float)ftSize->metrics.y_ppem / (float)(*ftFace)->units_per_EM); return static_cast<int>(height); } else { return ftSize->metrics.height >> 6; } } int FTSize::Width() const { if( FT_IS_SCALABLE((*ftFace))) { float width; if( FT_IS_SFNT((*ftFace))) // Don't think this is correct { width = ((*ftFace)->bbox.xMax - (*ftFace)->bbox.xMin); // bbox.xMax-bbox.xMin } else { width = ((*ftFace)->bbox.xMax - (*ftFace)->bbox.xMin) >> 16; // bbox.xMax-bbox.xMin } width = width * ( (float)ftSize->metrics.x_ppem / (float)(*ftFace)->units_per_EM); return static_cast<int>(width); } else { return ftSize->metrics.max_advance >> 6; } } int FTSize::Underline() const { return 0; } <|endoftext|>
<commit_before>#include "Common.h" #include "Folder.h" #if !WINDOWS #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #endif VINYL_NS_BEGIN; FolderIndex::FolderIndex(const char* path, bool recursive) { s::String pathname = path; if (!pathname.EndsWith("/")) { pathname += "/"; } m_path = pathname; #if WINDOWS ReadDir(nullptr, pathname, recursive); #else ReadDir(opendir(pathname), pathname, recursive); #endif } FolderIndex::~FolderIndex() { } const char* FolderIndex::GetPath() { return m_path; } void FolderIndex::ReadDir(void* impl, const char* dirname, bool recursive) { #if WINDOWS WIN32_FIND_DATA findData; s::String fnmDir = dirname; fnmDir += "*"; HANDLE findHandle = FindFirstFile(fnmDir, &findData); if (findHandle == INVALID_HANDLE_VALUE) { return; } do { if (!strcmp(findData.cFileName, ".") || !strcmp(findData.cFileName, "..")) { continue; } s::String path = dirname; path += findData.cFileName; if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { m_dirs.Push() = path; if (recursive) { ReadDir(nullptr, path, true); } } else { m_files.Push() = path; } } while (FindNextFile(findHandle, &findData)); #else DIR* d = (DIR*)impl; if (!d) { return; } struct dirent* dir; while ((dir = readdir(d)) != nullptr) { if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, "..")) { continue; } s::String path = dirname; path += dir->d_name; struct stat fst; stat(path, &fst); if (S_ISREG(fst.st_mode)) { m_files.Push() = path; } else { path += "/"; m_dirs.Push() = path; if (recursive) { ReadDir(opendir(path), path, true); } } } #endif } int FolderIndex::GetFileCount() { return m_files.Count(); } const char* FolderIndex::GetFilePath(int i) { return m_files[i]; } int FolderIndex::GetDirCount() { return m_dirs.Count(); } const char* FolderIndex::GetDirPath(int i) { return m_dirs[i]; } Folder::Folder(const char* path) { m_path = path; } Folder::~Folder() { } const char* Folder::GetPath() { return m_path; } FolderIndex Folder::GetIndex(bool recursive) { return FolderIndex(m_path, recursive); } VINYL_NS_END; <commit_msg>Consistency<commit_after>#include "Common.h" #include "Folder.h" #if !WINDOWS #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #endif VINYL_NS_BEGIN; FolderIndex::FolderIndex(const char* path, bool recursive) { s::String pathname = path; if (!pathname.EndsWith("/")) { pathname += "/"; } m_path = pathname; #if WINDOWS ReadDir(nullptr, pathname, recursive); #else ReadDir(opendir(pathname), pathname, recursive); #endif } FolderIndex::~FolderIndex() { } const char* FolderIndex::GetPath() { return m_path; } void FolderIndex::ReadDir(void* impl, const char* dirname, bool recursive) { #if WINDOWS WIN32_FIND_DATA findData; s::String fnmDir = dirname; fnmDir += "*"; HANDLE findHandle = FindFirstFile(fnmDir, &findData); if (findHandle == INVALID_HANDLE_VALUE) { return; } do { if (!strcmp(findData.cFileName, ".") || !strcmp(findData.cFileName, "..")) { continue; } s::String path = dirname; path += findData.cFileName; if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { path += "/"; m_dirs.Push() = path; if (recursive) { ReadDir(nullptr, path, true); } } else { m_files.Push() = path; } } while (FindNextFile(findHandle, &findData)); #else DIR* d = (DIR*)impl; if (!d) { return; } struct dirent* dir; while ((dir = readdir(d)) != nullptr) { if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, "..")) { continue; } s::String path = dirname; path += dir->d_name; struct stat fst; stat(path, &fst); if (S_ISREG(fst.st_mode)) { m_files.Push() = path; } else { path += "/"; m_dirs.Push() = path; if (recursive) { ReadDir(opendir(path), path, true); } } } #endif } int FolderIndex::GetFileCount() { return m_files.Count(); } const char* FolderIndex::GetFilePath(int i) { return m_files[i]; } int FolderIndex::GetDirCount() { return m_dirs.Count(); } const char* FolderIndex::GetDirPath(int i) { return m_dirs[i]; } Folder::Folder(const char* path) { m_path = path; } Folder::~Folder() { } const char* Folder::GetPath() { return m_path; } FolderIndex Folder::GetIndex(bool recursive) { return FolderIndex(m_path, recursive); } VINYL_NS_END; <|endoftext|>
<commit_before>#pragma once #include <iostream> #include <functional> #include <vector> #include <mutex> #include <boost/format.hpp> #include <crossbow/singleton.hpp> #include <crossbow/string.hpp> namespace crossbow { namespace logger { enum class LogLevel : unsigned char { TRACE = 0, DEBUG, INFO, WARN, ERROR, FATAL }; LogLevel logLevelFromString(const crossbow::string& s); template<class... Args> struct LogFormatter; template<class Head, class... Tail> struct LogFormatter<Head, Tail...> { LogFormatter<Tail...> base; void format(boost::format& f, Head h, Tail... tail) const { f % h; base.format(f, tail...); } }; template<> struct LogFormatter<> { void format(boost::format&) const { return; } }; struct LoggerConfig { using DestructFunction = std::function<void()>; std::vector<DestructFunction> destructFunctions; LogLevel level; std::ostream* traceOut = &std::cout; std::ostream* debugOut = &std::cout; std::ostream* infoOut = &std::cout; std::ostream* warnOut = &std::clog; std::ostream* errorOut = &std::cerr; std::ostream* fatalOut = &std::cerr; }; class LoggerT { std::mutex mTraceMutex; std::mutex mDebugMutex; std::mutex mInfoMutex; std::mutex mWarnMutex; std::mutex mErrorMutex; std::mutex mFatalMutex; template<class...Args> void log( LogLevel level, std::ostream& stream, std::mutex& mutex, const char* file, unsigned line, const char* function, const crossbow::string& str, Args... args) { if (config.level > level) return; boost::format formatter(str.c_str()); LogFormatter<Args...> fmt; fmt.format(formatter, args...); std::lock_guard<std::mutex> _(mutex); stream << formatter.str(); stream << " (in " << function << " at " << file << ':' << line << ')' << std::endl; } public: LoggerConfig config; ~LoggerT(); template<class...Args> void trace(const char* file, unsigned line, const char* function, const crossbow::string& str, Args... args) { log(LogLevel::TRACE, *(config.traceOut), mTraceMutex, file, line, function, str, args...); } template<class...Args> void debug(const char* file, unsigned line, const char* function, const crossbow::string& str, Args... args) { log(LogLevel::DEBUG, *(config.debugOut), mDebugMutex, file, line, function, str, args...); } template<class...Args> void info(const char* file, unsigned line, const char* function, const crossbow::string& str, Args... args) { log(LogLevel::INFO, *(config.infoOut), mInfoMutex, file, line, function, str, args...); } template<class...Args> void warn(const char* file, unsigned line, const char* function, const crossbow::string& str, Args... args) { log(LogLevel::WARN, *(config.warnOut), mWarnMutex, file, line, function, str, args...); } template<class...Args> void error(const char* file, unsigned line, const char* function, const crossbow::string& str, Args... args) { log(LogLevel::ERROR, *(config.errorOut), mInfoMutex, file, line, function, str, args...); } template<class...Args> void fatal(const char* file, unsigned line, const char* function, const crossbow::string& str, Args... args) { log(LogLevel::FATAL, *(config.fatalOut), mInfoMutex, file, line, function, str, args...); } }; using Logger = crossbow::singleton<LoggerT>; extern Logger logger; #define LOG_TRACE(...) crossbow::logger::logger->trace(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__) #define LOG_DEBUG(...) crossbow::logger::logger->debug(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__) #define LOG_INFO(...) crossbow::logger::logger->info(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__) #define LOG_WARN(...) crossbow::logger::logger->warn(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__) #define LOG_ERROR(...) crossbow::logger::logger->error(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__) #define LOG_FATAL(...) crossbow::logger::logger->fatal(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__) #ifdef NDEBUG # define LOG_ASSERT(...) #else # define LOG_ASSERT(Cond, ...) if (!(Cond)) {\ std::cerr << "Assertion Failed: " #Cond ":" << std::endl;\ LOG_FATAL(__VA_ARGS__);\ std::terminate();\ } #endif // NDEBUG } // namespace logger } // namespace crossbow <commit_msg>Forward arguments in Logger to print objects that are not copyable<commit_after>#pragma once #include <iostream> #include <functional> #include <vector> #include <mutex> #include <boost/format.hpp> #include <crossbow/singleton.hpp> #include <crossbow/string.hpp> namespace crossbow { namespace logger { enum class LogLevel : unsigned char { TRACE = 0, DEBUG, INFO, WARN, ERROR, FATAL }; LogLevel logLevelFromString(const crossbow::string& s); template<class... Args> struct LogFormatter; template<class Head, class... Tail> struct LogFormatter<Head, Tail...> { LogFormatter<Tail...> base; void format(boost::format& f, Head h, Tail&&... tail) const { f % h; base.format(f, std::forward<Tail>(tail)...); } }; template<> struct LogFormatter<> { void format(boost::format&) const { return; } }; struct LoggerConfig { using DestructFunction = std::function<void()>; std::vector<DestructFunction> destructFunctions; LogLevel level; std::ostream* traceOut = &std::cout; std::ostream* debugOut = &std::cout; std::ostream* infoOut = &std::cout; std::ostream* warnOut = &std::clog; std::ostream* errorOut = &std::cerr; std::ostream* fatalOut = &std::cerr; }; class LoggerT { std::mutex mTraceMutex; std::mutex mDebugMutex; std::mutex mInfoMutex; std::mutex mWarnMutex; std::mutex mErrorMutex; std::mutex mFatalMutex; template<class...Args> void log( LogLevel level, std::ostream& stream, std::mutex& mutex, const char* file, unsigned line, const char* function, const crossbow::string& str, Args&&... args) { if (config.level > level) return; boost::format formatter(str.c_str()); LogFormatter<Args...> fmt; fmt.format(formatter, std::forward<Args>(args)...); std::lock_guard<std::mutex> _(mutex); stream << formatter.str(); stream << " (in " << function << " at " << file << ':' << line << ')' << std::endl; } public: LoggerConfig config; ~LoggerT(); template<class...Args> void trace(const char* file, unsigned line, const char* function, const crossbow::string& str, Args&&... args) { log(LogLevel::TRACE, *(config.traceOut), mTraceMutex, file, line, function, str, std::forward<Args>(args)...); } template<class...Args> void debug(const char* file, unsigned line, const char* function, const crossbow::string& str, Args&&... args) { log(LogLevel::DEBUG, *(config.debugOut), mDebugMutex, file, line, function, str, std::forward<Args>(args)...); } template<class...Args> void info(const char* file, unsigned line, const char* function, const crossbow::string& str, Args&&... args) { log(LogLevel::INFO, *(config.infoOut), mInfoMutex, file, line, function, str, std::forward<Args>(args)...); } template<class...Args> void warn(const char* file, unsigned line, const char* function, const crossbow::string& str, Args&&... args) { log(LogLevel::WARN, *(config.warnOut), mWarnMutex, file, line, function, str, std::forward<Args>(args)...); } template<class...Args> void error(const char* file, unsigned line, const char* function, const crossbow::string& str, Args&&... args) { log(LogLevel::ERROR, *(config.errorOut), mInfoMutex, file, line, function, str, std::forward<Args>(args)...); } template<class...Args> void fatal(const char* file, unsigned line, const char* function, const crossbow::string& str, Args&&... args) { log(LogLevel::FATAL, *(config.fatalOut), mInfoMutex, file, line, function, str, std::forward<Args>(args)...); } }; using Logger = crossbow::singleton<LoggerT>; extern Logger logger; #define LOG_TRACE(...) crossbow::logger::logger->trace(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__) #define LOG_DEBUG(...) crossbow::logger::logger->debug(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__) #define LOG_INFO(...) crossbow::logger::logger->info(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__) #define LOG_WARN(...) crossbow::logger::logger->warn(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__) #define LOG_ERROR(...) crossbow::logger::logger->error(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__) #define LOG_FATAL(...) crossbow::logger::logger->fatal(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__) #ifdef NDEBUG # define LOG_ASSERT(...) #else # define LOG_ASSERT(Cond, ...) if (!(Cond)) {\ std::cerr << "Assertion Failed: " #Cond ":" << std::endl;\ LOG_FATAL(__VA_ARGS__);\ std::terminate();\ } #endif // NDEBUG } // namespace logger } // namespace crossbow <|endoftext|>
<commit_before>/** * @file descriptors_type.hpp * @brief Visual image search supported descriptors. * @author Paolo D'Apice */ #ifndef VIS_DESCRIPTORS_TYPE_HPP #define VIS_DESCRIPTORS_TYPE_HPP #include <string> namespace vis { /// Available descriptors types. enum DescriptorsType { HOG, ///< HOG descriptors. HSV, ///< HSV color histograms. HOG_HSV, ///< Both HOG descriptors and HSV color histograms. }; /// Return a textual representation of the enum value. inline std::string toString(DescriptorsType type) { switch(type) { case vis::HSV: return "HSV"; case vis::HOG: return "HOG"; case vis::HOG_HSV: return "HOG_HSV"; } } /// Return enum value from string. inline DescriptorsType toDescriptorsType(const std::string& type) { if (type == "HSV") return vis::HSV; else if (type == "HOG") return vis::HOG; else if (type == "HOG_HSV") return vis::HOG_HSV; } /// Returs \c true if the given type requires a vocabulary. inline bool requiresVocabulary(DescriptorsType type) { return (type == HOG or type == HOG_HSV); } } /* namespace vis */ #endif /* VIS_DESCRIPTORS_TYPE_HPP */ <commit_msg>Added missing else branch<commit_after>/** * @file descriptors_type.hpp * @brief Visual image search supported descriptors. * @author Paolo D'Apice */ #ifndef VIS_DESCRIPTORS_TYPE_HPP #define VIS_DESCRIPTORS_TYPE_HPP #include <string> namespace vis { /// Available descriptors types. enum DescriptorsType { HOG, ///< HOG descriptors. HSV, ///< HSV color histograms. HOG_HSV, ///< Both HOG descriptors and HSV color histograms. }; /// Return a textual representation of the enum value. inline std::string toString(DescriptorsType type) { switch(type) { case vis::HSV: return "HSV"; case vis::HOG: return "HOG"; case vis::HOG_HSV: return "HOG_HSV"; } } /// Return enum value from string. inline DescriptorsType toDescriptorsType(const std::string& type) { if (type == "HSV") return vis::HSV; else if (type == "HOG") return vis::HOG; else if (type == "HOG_HSV") return vis::HOG_HSV; else throw "invalid type"; } /// Returs \c true if the given type requires a vocabulary. inline bool requiresVocabulary(DescriptorsType type) { return (type == HOG or type == HOG_HSV); } } /* namespace vis */ #endif /* VIS_DESCRIPTORS_TYPE_HPP */ <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexLua.cxx ** Lexer for Lua language. ** ** Written by Paul Winwood. ** Folder by Alexey Yutkin. ** Modified by Marcos E. Wurzius & Philippe Lhoste **/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.'); } static inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } static inline bool IsANumberChar(const int ch) { // Not exactly following number definition (several dots are seen as OK, etc.) // but probably enough in most cases. return (ch < 0x80) && (isdigit(ch) || toupper(ch) == 'E' || ch == '.' || ch == '-' || ch == '+'); } static inline bool IsLuaOperator(int ch) { if (ch >= 0x80 || isalnum(ch)) { return false; } // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '{' || ch == '}' || ch == '~' || ch == '[' || ch == ']' || ch == ';' || ch == '<' || ch == '>' || ch == ',' || ch == '.' || ch == '^' || ch == '%' || ch == ':') { return true; } return false; } static void ColouriseLuaDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; WordList &keywords6 = *keywordlists[5]; WordList &keywords7 = *keywordlists[6]; WordList &keywords8 = *keywordlists[7]; int currentLine = styler.GetLine(startPos); // Initialize the literal string [[ ... ]] nesting level, if we are inside such a string. int literalStringLevel = 0; if (initStyle == SCE_LUA_LITERALSTRING) { literalStringLevel = styler.GetLineState(currentLine - 1); } // Initialize the block comment --[[ ... ]] nesting level, if we are inside such a comment int blockCommentLevel = 0; if (initStyle == SCE_LUA_COMMENT) { blockCommentLevel = styler.GetLineState(currentLine - 1); } // Do not leak onto next line if (initStyle == SCE_LUA_STRINGEOL) { initStyle = SCE_LUA_DEFAULT; } StyleContext sc(startPos, length, initStyle, styler); if (startPos == 0 && sc.ch == '#') { // shbang line: # is a comment only if first char of the script sc.SetState(SCE_LUA_COMMENTLINE); } for (; sc.More(); sc.Forward()) { if (sc.atLineEnd) { // Update the line state, so it can be seen by next line currentLine = styler.GetLine(sc.currentPos); switch (sc.state) { case SCE_LUA_LITERALSTRING: // Inside a literal string, we set the line state styler.SetLineState(currentLine, literalStringLevel); break; case SCE_LUA_COMMENT: // Block comment // Inside a block comment, we set the line state styler.SetLineState(currentLine, blockCommentLevel); break; default: // Reset the line state styler.SetLineState(currentLine, 0); break; } } if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) { // Prevent SCE_LUA_STRINGEOL from leaking back to previous line sc.SetState(SCE_LUA_STRING); } // Handle string line continuation if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) && sc.ch == '\\') { if (sc.chNext == '\n' || sc.chNext == '\r') { sc.Forward(); if (sc.ch == '\r' && sc.chNext == '\n') { sc.Forward(); } continue; } } // Determine if the current state should terminate. if (sc.state == SCE_LUA_OPERATOR) { sc.SetState(SCE_LUA_DEFAULT); } else if (sc.state == SCE_LUA_NUMBER) { // We stop the number definition on non-numerical non-dot non-eE non-sign char if (!IsANumberChar(sc.ch)) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_IDENTIFIER) { if (!IsAWordChar(sc.ch) || sc.Match('.', '.')) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (keywords.InList(s)) { sc.ChangeState(SCE_LUA_WORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_LUA_WORD2); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_LUA_WORD3); } else if (keywords4.InList(s)) { sc.ChangeState(SCE_LUA_WORD4); } else if (keywords5.InList(s)) { sc.ChangeState(SCE_LUA_WORD5); } else if (keywords6.InList(s)) { sc.ChangeState(SCE_LUA_WORD6); } else if (keywords6.InList(s)) { sc.ChangeState(SCE_LUA_WORD6); } else if (keywords7.InList(s)) { sc.ChangeState(SCE_LUA_WORD7); } else if (keywords8.InList(s)) { sc.ChangeState(SCE_LUA_WORD8); } sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_COMMENTLINE ) { if (sc.atLineEnd) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_PREPROCESSOR ) { if (sc.atLineEnd) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_STRING) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_CHARACTER) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_LITERALSTRING) { if (sc.Match('[', '[')) { literalStringLevel++; sc.Forward(); sc.SetState(SCE_LUA_LITERALSTRING); } else if (sc.Match(']', ']') && literalStringLevel > 0) { literalStringLevel--; sc.Forward(); if (literalStringLevel == 0) { sc.ForwardSetState(SCE_LUA_DEFAULT); } } } else if (sc.state == SCE_LUA_COMMENT) { // Lua 5.0's block comment if (sc.Match('[', '[')) { blockCommentLevel++; sc.Forward(); } else if (sc.Match(']', ']') && blockCommentLevel > 0) { blockCommentLevel--; sc.Forward(); if (blockCommentLevel == 0) { sc.ForwardSetState(SCE_LUA_DEFAULT); } } } // Determine if a new state should be entered. if (sc.state == SCE_LUA_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_LUA_NUMBER); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_LUA_IDENTIFIER); } else if (sc.Match('\"')) { sc.SetState(SCE_LUA_STRING); } else if (sc.Match('\'')) { sc.SetState(SCE_LUA_CHARACTER); } else if (sc.Match('[', '[')) { literalStringLevel = 1; sc.SetState(SCE_LUA_LITERALSTRING); sc.Forward(); } else if (sc.Match("--[[")) { // Lua 5.0's block comment blockCommentLevel = 1; sc.SetState(SCE_LUA_COMMENT); sc.Forward(3); } else if (sc.Match('-', '-')) { sc.SetState(SCE_LUA_COMMENTLINE); sc.Forward(); } else if (sc.atLineStart && sc.Match('$')) { sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code } else if (IsLuaOperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_LUA_OPERATOR); } } } sc.Complete(); } static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[], Accessor &styler) { unsigned int lengthDoc = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; int styleNext = styler.StyleAt(startPos); char s[10]; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_LUA_WORD) { if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e') { for (unsigned int j = 0; j < 8; j++) { if (!iswordchar(styler[i + j])) { break; } s[j] = styler[i + j]; s[j + 1] = '\0'; } if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0)) { levelCurrent++; } if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0)) { levelCurrent--; } } } else if (style == SCE_LUA_OPERATOR) { if (ch == '{' || ch == '(') { levelCurrent++; } else if (ch == '}' || ch == ')') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) { lev |= SC_FOLDLEVELWHITEFLAG; } if ((levelCurrent > levelPrev) && (visibleChars > 0)) { lev |= SC_FOLDLEVELHEADERFLAG; } if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) { visibleChars++; } } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } static const char * const luaWordListDesc[] = { "Keywords", "Basic functions", "String, (table) & math functions", "(coroutines), I/O & system facilities", "XXX", "XXX", 0 }; LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc); <commit_msg>Comment line and preprocessor lines style the end of line characters so they can have the eolfilled dtyle applied to them.<commit_after>// Scintilla source code edit control /** @file LexLua.cxx ** Lexer for Lua language. ** ** Written by Paul Winwood. ** Folder by Alexey Yutkin. ** Modified by Marcos E. Wurzius & Philippe Lhoste **/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.'); } static inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } static inline bool IsANumberChar(const int ch) { // Not exactly following number definition (several dots are seen as OK, etc.) // but probably enough in most cases. return (ch < 0x80) && (isdigit(ch) || toupper(ch) == 'E' || ch == '.' || ch == '-' || ch == '+'); } static inline bool IsLuaOperator(int ch) { if (ch >= 0x80 || isalnum(ch)) { return false; } // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '{' || ch == '}' || ch == '~' || ch == '[' || ch == ']' || ch == ';' || ch == '<' || ch == '>' || ch == ',' || ch == '.' || ch == '^' || ch == '%' || ch == ':') { return true; } return false; } static void ColouriseLuaDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; WordList &keywords6 = *keywordlists[5]; WordList &keywords7 = *keywordlists[6]; WordList &keywords8 = *keywordlists[7]; int currentLine = styler.GetLine(startPos); // Initialize the literal string [[ ... ]] nesting level, if we are inside such a string. int literalStringLevel = 0; if (initStyle == SCE_LUA_LITERALSTRING) { literalStringLevel = styler.GetLineState(currentLine - 1); } // Initialize the block comment --[[ ... ]] nesting level, if we are inside such a comment int blockCommentLevel = 0; if (initStyle == SCE_LUA_COMMENT) { blockCommentLevel = styler.GetLineState(currentLine - 1); } // Do not leak onto next line if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE) { initStyle = SCE_LUA_DEFAULT; } StyleContext sc(startPos, length, initStyle, styler); if (startPos == 0 && sc.ch == '#') { // shbang line: # is a comment only if first char of the script sc.SetState(SCE_LUA_COMMENTLINE); } for (; sc.More(); sc.Forward()) { if (sc.atLineEnd) { // Update the line state, so it can be seen by next line currentLine = styler.GetLine(sc.currentPos); switch (sc.state) { case SCE_LUA_LITERALSTRING: // Inside a literal string, we set the line state styler.SetLineState(currentLine, literalStringLevel); break; case SCE_LUA_COMMENT: // Block comment // Inside a block comment, we set the line state styler.SetLineState(currentLine, blockCommentLevel); break; default: // Reset the line state styler.SetLineState(currentLine, 0); break; } } if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) { // Prevent SCE_LUA_STRINGEOL from leaking back to previous line sc.SetState(SCE_LUA_STRING); } // Handle string line continuation if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) && sc.ch == '\\') { if (sc.chNext == '\n' || sc.chNext == '\r') { sc.Forward(); if (sc.ch == '\r' && sc.chNext == '\n') { sc.Forward(); } continue; } } // Determine if the current state should terminate. if (sc.state == SCE_LUA_OPERATOR) { sc.SetState(SCE_LUA_DEFAULT); } else if (sc.state == SCE_LUA_NUMBER) { // We stop the number definition on non-numerical non-dot non-eE non-sign char if (!IsANumberChar(sc.ch)) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_IDENTIFIER) { if (!IsAWordChar(sc.ch) || sc.Match('.', '.')) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (keywords.InList(s)) { sc.ChangeState(SCE_LUA_WORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_LUA_WORD2); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_LUA_WORD3); } else if (keywords4.InList(s)) { sc.ChangeState(SCE_LUA_WORD4); } else if (keywords5.InList(s)) { sc.ChangeState(SCE_LUA_WORD5); } else if (keywords6.InList(s)) { sc.ChangeState(SCE_LUA_WORD6); } else if (keywords6.InList(s)) { sc.ChangeState(SCE_LUA_WORD6); } else if (keywords7.InList(s)) { sc.ChangeState(SCE_LUA_WORD7); } else if (keywords8.InList(s)) { sc.ChangeState(SCE_LUA_WORD8); } sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_COMMENTLINE ) { if (sc.atLineEnd) { sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_PREPROCESSOR ) { if (sc.atLineEnd) { sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_STRING) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_CHARACTER) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_LITERALSTRING) { if (sc.Match('[', '[')) { literalStringLevel++; sc.Forward(); sc.SetState(SCE_LUA_LITERALSTRING); } else if (sc.Match(']', ']') && literalStringLevel > 0) { literalStringLevel--; sc.Forward(); if (literalStringLevel == 0) { sc.ForwardSetState(SCE_LUA_DEFAULT); } } } else if (sc.state == SCE_LUA_COMMENT) { // Lua 5.0's block comment if (sc.Match('[', '[')) { blockCommentLevel++; sc.Forward(); } else if (sc.Match(']', ']') && blockCommentLevel > 0) { blockCommentLevel--; sc.Forward(); if (blockCommentLevel == 0) { sc.ForwardSetState(SCE_LUA_DEFAULT); } } } // Determine if a new state should be entered. if (sc.state == SCE_LUA_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_LUA_NUMBER); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_LUA_IDENTIFIER); } else if (sc.Match('\"')) { sc.SetState(SCE_LUA_STRING); } else if (sc.Match('\'')) { sc.SetState(SCE_LUA_CHARACTER); } else if (sc.Match('[', '[')) { literalStringLevel = 1; sc.SetState(SCE_LUA_LITERALSTRING); sc.Forward(); } else if (sc.Match("--[[")) { // Lua 5.0's block comment blockCommentLevel = 1; sc.SetState(SCE_LUA_COMMENT); sc.Forward(3); } else if (sc.Match('-', '-')) { sc.SetState(SCE_LUA_COMMENTLINE); sc.Forward(); } else if (sc.atLineStart && sc.Match('$')) { sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code } else if (IsLuaOperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_LUA_OPERATOR); } } } sc.Complete(); } static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[], Accessor &styler) { unsigned int lengthDoc = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; int styleNext = styler.StyleAt(startPos); char s[10]; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_LUA_WORD) { if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e') { for (unsigned int j = 0; j < 8; j++) { if (!iswordchar(styler[i + j])) { break; } s[j] = styler[i + j]; s[j + 1] = '\0'; } if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0)) { levelCurrent++; } if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0)) { levelCurrent--; } } } else if (style == SCE_LUA_OPERATOR) { if (ch == '{' || ch == '(') { levelCurrent++; } else if (ch == '}' || ch == ')') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) { lev |= SC_FOLDLEVELWHITEFLAG; } if ((levelCurrent > levelPrev) && (visibleChars > 0)) { lev |= SC_FOLDLEVELHEADERFLAG; } if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) { visibleChars++; } } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } static const char * const luaWordListDesc[] = { "Keywords", "Basic functions", "String, (table) & math functions", "(coroutines), I/O & system facilities", "XXX", "XXX", 0 }; LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc); <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexPOV.cxx ** Lexer for POV-Ray SDL (Persistance of Vision Raytracer, Scene Description Language). ** Written by Philippe Lhoste but this is mostly a derivative of LexCPP... **/ // Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. // Some points that distinguish from a simple C lexer: // Identifiers start only by a character. // No line continuation character. // Strings are limited to 256 characters. // Directives are similar to preprocessor commands, // but we match directive keywords and colorize incorrect ones. // Block comments can be nested (code stolen from my code in LexLua). #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsAWordChar(const int ch) { return ch < 0x80 && (isalnum(ch) || ch == '_'); } static inline bool IsAWordStart(const int ch) { return ch < 0x80 && isalpha(ch); } static inline bool IsANumberChar(const int ch) { // Not exactly following number definition (several dots are seen as OK, etc.) // but probably enough in most cases. return (ch < 0x80) && (isdigit(ch) || toupper(ch) == 'E' || ch == '.' || ch == '-' || ch == '+'); } static void ColourisePovDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords1 = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; WordList &keywords6 = *keywordlists[5]; WordList &keywords7 = *keywordlists[6]; WordList &keywords8 = *keywordlists[7]; int currentLine = styler.GetLine(startPos); // Initialize the block comment /* */ nesting level, if we are inside such a comment. int blockCommentLevel = 0; if (initStyle == SCE_POV_COMMENT) { blockCommentLevel = styler.GetLineState(currentLine - 1); } // Do not leak onto next line if (initStyle == SCE_POV_STRINGEOL) { initStyle = SCE_POV_DEFAULT; } StyleContext sc(startPos, length, initStyle, styler); short stringLen = 0; for (; sc.More(); sc.Forward()) { if (sc.atLineEnd) { // Update the line state, so it can be seen by next line currentLine = styler.GetLine(sc.currentPos); if (sc.state == SCE_POV_COMMENT) { // Inside a block comment, we set the line state styler.SetLineState(currentLine, blockCommentLevel); } else { // Reset the line state styler.SetLineState(currentLine, 0); } } if (sc.atLineStart && (sc.state == SCE_POV_STRING)) { // Prevent SCE_POV_STRINGEOL from leaking back to previous line sc.SetState(SCE_POV_STRING); } // Determine if the current state should terminate. if (sc.state == SCE_POV_OPERATOR) { sc.SetState(SCE_POV_DEFAULT); } else if (sc.state == SCE_POV_NUMBER) { // We stop the number definition on non-numerical non-dot non-eE non-sign char if (!IsANumberChar(sc.ch)) { sc.SetState(SCE_POV_DEFAULT); } } else if (sc.state == SCE_POV_IDENTIFIER) { if (!IsAWordChar(sc.ch)) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (keywords2.InList(s)) { sc.ChangeState(SCE_POV_WORD2); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_POV_WORD3); } else if (keywords4.InList(s)) { sc.ChangeState(SCE_POV_WORD4); } else if (keywords5.InList(s)) { sc.ChangeState(SCE_POV_WORD5); } else if (keywords6.InList(s)) { sc.ChangeState(SCE_POV_WORD6); } else if (keywords7.InList(s)) { sc.ChangeState(SCE_POV_WORD7); } else if (keywords8.InList(s)) { sc.ChangeState(SCE_POV_WORD8); } sc.SetState(SCE_POV_DEFAULT); } } else if (sc.state == SCE_POV_DIRECTIVE) { if (!IsAWordChar(sc.ch)) { char s[100]; char *p; sc.GetCurrent(s, sizeof(s)); p = s; // Skip # and whitespace between # and directive word do { p++; } while ((*p == ' ' || *p == '\t') && *p != '\0'); if (!keywords1.InList(p)) { sc.ChangeState(SCE_POV_BADDIRECTIVE); } sc.SetState(SCE_POV_DEFAULT); } } else if (sc.state == SCE_POV_COMMENT) { if (sc.Match('/', '*')) { blockCommentLevel++; sc.Forward(); } else if (sc.Match('*', '/') && blockCommentLevel > 0) { blockCommentLevel--; sc.Forward(); if (blockCommentLevel == 0) { sc.ForwardSetState(SCE_POV_DEFAULT); } } } else if (sc.state == SCE_POV_COMMENTLINE) { if (sc.atLineEnd) { sc.SetState(SCE_POV_DEFAULT); } } else if (sc.state == SCE_POV_STRING) { if (sc.ch == '\\') { stringLen++; if (strchr("abfnrtuv0'\"", sc.chNext)) { // Compound characters are counted as one. // Note: for Unicode chars \u, we shouldn't count the next 4 digits... sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_POV_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_POV_STRINGEOL); sc.ForwardSetState(SCE_POV_DEFAULT); } else { stringLen++; } if (stringLen > 256) { // Strings are limited to 256 chars sc.SetState(SCE_POV_STRINGEOL); } } else if (sc.state == SCE_POV_STRINGEOL) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_C_DEFAULT); } else if (sc.atLineEnd) { sc.ForwardSetState(SCE_POV_DEFAULT); } } // Determine if a new state should be entered. if (sc.state == SCE_POV_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_POV_NUMBER); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_POV_IDENTIFIER); } else if (sc.Match('/', '*')) { blockCommentLevel = 1; sc.SetState(SCE_POV_COMMENT); sc.Forward(); // Eat the * so it isn't used for the end of the comment } else if (sc.Match('/', '/')) { sc.SetState(SCE_POV_COMMENTLINE); } else if (sc.ch == '\"') { sc.SetState(SCE_POV_STRING); stringLen = 0; } else if (sc.ch == '#') { sc.SetState(SCE_POV_DIRECTIVE); // Skip whitespace between # and directive word do { sc.Forward(); } while ((sc.ch == ' ' || sc.ch == '\t') && sc.More()); if (sc.atLineEnd) { sc.SetState(SCE_POV_DEFAULT); } } else if (isoperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_POV_OPERATOR); } } } sc.Complete(); } static void FoldPovDoc( unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { bool foldComment = styler.GetPropertyInt("fold.comment") != 0; bool foldDirective = styler.GetPropertyInt("fold.directive") != 0; bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style = initStyle; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int stylePrev = style; style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (foldComment && (style == SCE_POV_COMMENT)) { if (stylePrev != SCE_POV_COMMENT) { levelCurrent++; } else if ((styleNext != SCE_POV_COMMENT) && !atEOL) { // Comments don't end at end of line and the next character may be unstyled. levelCurrent--; } } if (foldComment && (style == SCE_POV_COMMENTLINE)) { if ((ch == '/') && (chNext == '/')) { char chNext2 = styler.SafeGetCharAt(i + 2); if (chNext2 == '{') { levelCurrent++; } else if (chNext2 == '}') { levelCurrent--; } } } if (foldDirective && (style == SCE_POV_DIRECTIVE)) { if (ch == '#') { unsigned int j=i+1; while ((j<endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) { j++; } } } if (style == SCE_POV_OPERATOR) { if (ch == '{') { levelCurrent++; } else if (ch == '}') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } static const char * const povWordLists[] = { "Language directives", "Objects & CSG & Appearance", "Types & Modifiers & Items", "Predefined Identifiers", "Predefined Functions", "User defined 1", "User defined 2", "User defined 3", 0, }; LexerModule lmPOV(SCLEX_POV, ColourisePovDoc, "pov", FoldPovDoc, povWordLists); <commit_msg>Patch from Philippe that improves lexing of comment lines.<commit_after>// Scintilla source code edit control /** @file LexPOV.cxx ** Lexer for POV-Ray SDL (Persistance of Vision Raytracer, Scene Description Language). ** Written by Philippe Lhoste but this is mostly a derivative of LexCPP... **/ // Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. // Some points that distinguish from a simple C lexer: // Identifiers start only by a character. // No line continuation character. // Strings are limited to 256 characters. // Directives are similar to preprocessor commands, // but we match directive keywords and colorize incorrect ones. // Block comments can be nested (code stolen from my code in LexLua). #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsAWordChar(int ch) { return ch < 0x80 && (isalnum(ch) || ch == '_'); } static inline bool IsAWordStart(int ch) { return ch < 0x80 && isalpha(ch); } static inline bool IsANumberChar(int ch) { // Not exactly following number definition (several dots are seen as OK, etc.) // but probably enough in most cases. return (ch < 0x80) && (isdigit(ch) || toupper(ch) == 'E' || ch == '.' || ch == '-' || ch == '+'); } static void ColourisePovDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords1 = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; WordList &keywords6 = *keywordlists[5]; WordList &keywords7 = *keywordlists[6]; WordList &keywords8 = *keywordlists[7]; int currentLine = styler.GetLine(startPos); // Initialize the block comment /* */ nesting level, if we are inside such a comment. int blockCommentLevel = 0; if (initStyle == SCE_POV_COMMENT) { blockCommentLevel = styler.GetLineState(currentLine - 1); } // Do not leak onto next line if (initStyle == SCE_POV_STRINGEOL || initStyle == SCE_POV_COMMENTLINE) { initStyle = SCE_POV_DEFAULT; } short stringLen = 0; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { if (sc.atLineEnd) { // Update the line state, so it can be seen by next line currentLine = styler.GetLine(sc.currentPos); if (sc.state == SCE_POV_COMMENT) { // Inside a block comment, we set the line state styler.SetLineState(currentLine, blockCommentLevel); } else { // Reset the line state styler.SetLineState(currentLine, 0); } } if (sc.atLineStart && (sc.state == SCE_POV_STRING)) { // Prevent SCE_POV_STRINGEOL from leaking back to previous line sc.SetState(SCE_POV_STRING); } // Determine if the current state should terminate. if (sc.state == SCE_POV_OPERATOR) { sc.SetState(SCE_POV_DEFAULT); } else if (sc.state == SCE_POV_NUMBER) { // We stop the number definition on non-numerical non-dot non-eE non-sign char if (!IsANumberChar(sc.ch)) { sc.SetState(SCE_POV_DEFAULT); } } else if (sc.state == SCE_POV_IDENTIFIER) { if (!IsAWordChar(sc.ch)) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (keywords2.InList(s)) { sc.ChangeState(SCE_POV_WORD2); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_POV_WORD3); } else if (keywords4.InList(s)) { sc.ChangeState(SCE_POV_WORD4); } else if (keywords5.InList(s)) { sc.ChangeState(SCE_POV_WORD5); } else if (keywords6.InList(s)) { sc.ChangeState(SCE_POV_WORD6); } else if (keywords7.InList(s)) { sc.ChangeState(SCE_POV_WORD7); } else if (keywords8.InList(s)) { sc.ChangeState(SCE_POV_WORD8); } sc.SetState(SCE_POV_DEFAULT); } } else if (sc.state == SCE_POV_DIRECTIVE) { if (!IsAWordChar(sc.ch)) { char s[100]; char *p; sc.GetCurrent(s, sizeof(s)); p = s; // Skip # and whitespace between # and directive word do { p++; } while ((*p == ' ' || *p == '\t') && *p != '\0'); if (!keywords1.InList(p)) { sc.ChangeState(SCE_POV_BADDIRECTIVE); } sc.SetState(SCE_POV_DEFAULT); } } else if (sc.state == SCE_POV_COMMENT) { if (sc.Match('/', '*')) { blockCommentLevel++; sc.Forward(); } else if (sc.Match('*', '/') && blockCommentLevel > 0) { blockCommentLevel--; sc.Forward(); if (blockCommentLevel == 0) { sc.ForwardSetState(SCE_POV_DEFAULT); } } } else if (sc.state == SCE_POV_COMMENTLINE) { if (sc.atLineEnd) { sc.ForwardSetState(SCE_POV_DEFAULT); } } else if (sc.state == SCE_POV_STRING) { if (sc.ch == '\\') { stringLen++; if (strchr("abfnrtuv0'\"", sc.chNext)) { // Compound characters are counted as one. // Note: for Unicode chars \u, we shouldn't count the next 4 digits... sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_POV_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_POV_STRINGEOL); sc.ForwardSetState(SCE_POV_DEFAULT); } else { stringLen++; } if (stringLen > 256) { // Strings are limited to 256 chars sc.SetState(SCE_POV_STRINGEOL); } } else if (sc.state == SCE_POV_STRINGEOL) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_C_DEFAULT); } else if (sc.atLineEnd) { sc.ForwardSetState(SCE_POV_DEFAULT); } } // Determine if a new state should be entered. if (sc.state == SCE_POV_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_POV_NUMBER); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_POV_IDENTIFIER); } else if (sc.Match('/', '*')) { blockCommentLevel = 1; sc.SetState(SCE_POV_COMMENT); sc.Forward(); // Eat the * so it isn't used for the end of the comment } else if (sc.Match('/', '/')) { sc.SetState(SCE_POV_COMMENTLINE); } else if (sc.ch == '\"') { sc.SetState(SCE_POV_STRING); stringLen = 0; } else if (sc.ch == '#') { sc.SetState(SCE_POV_DIRECTIVE); // Skip whitespace between # and directive word do { sc.Forward(); } while ((sc.ch == ' ' || sc.ch == '\t') && sc.More()); if (sc.atLineEnd) { sc.SetState(SCE_POV_DEFAULT); } } else if (isoperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_POV_OPERATOR); } } } sc.Complete(); } static void FoldPovDoc( unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { bool foldComment = styler.GetPropertyInt("fold.comment") != 0; bool foldDirective = styler.GetPropertyInt("fold.directive") != 0; bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style = initStyle; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int stylePrev = style; style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (foldComment && (style == SCE_POV_COMMENT)) { if (stylePrev != SCE_POV_COMMENT) { levelCurrent++; } else if ((styleNext != SCE_POV_COMMENT) && !atEOL) { // Comments don't end at end of line and the next character may be unstyled. levelCurrent--; } } if (foldComment && (style == SCE_POV_COMMENTLINE)) { if ((ch == '/') && (chNext == '/')) { char chNext2 = styler.SafeGetCharAt(i + 2); if (chNext2 == '{') { levelCurrent++; } else if (chNext2 == '}') { levelCurrent--; } } } if (foldDirective && (style == SCE_POV_DIRECTIVE)) { if (ch == '#') { unsigned int j=i+1; while ((j<endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) { j++; } } } if (style == SCE_POV_OPERATOR) { if (ch == '{') { levelCurrent++; } else if (ch == '}') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } static const char * const povWordLists[] = { "Language directives", "Objects & CSG & Appearance", "Types & Modifiers & Items", "Predefined Identifiers", "Predefined Functions", "User defined 1", "User defined 2", "User defined 3", 0, }; LexerModule lmPOV(SCLEX_POV, ColourisePovDoc, "pov", FoldPovDoc, povWordLists); <|endoftext|>
<commit_before>/* * Object.cpp * * Created on: Mar 7, 2016 * Author: mad */ #include <vnl/Object.h> #include <vnl/Pipe.h> #include <vnl/Sample.h> #include <vnl/Announce.hxx> #include <vnl/LogMsg.hxx> #include <vnl/Topic.hxx> #include <vnl/Shutdown.hxx> #include <vnl/Heartbeat.hxx> #include <vnl/Exit.hxx> #include <vnl/NoSuchMethodException.hxx> namespace vnl { void Object::exit() { vnl_dorun = false; } StringWriter Object::log(int level) { StringOutput* out = 0; if(level <= vnl_log_level) { vnl_log_writer.level = level; out = &vnl_log_writer; } return StringWriter(out); } Timer* Object::set_timeout(int64_t micros, const std::function<void()>& func, int type) { Timer& timer = *vnl_timers.push_back(); timer.interval = micros; timer.func = func; timer.type = type; if(type != VNL_TIMER_MANUAL) { timer.reset(); } return &timer; } void Object::add_client(Client& client, Router* target) { assert(vnl_dorun); client.connect(vnl_engine, target); vnl_output_channels[client.get_mac()] = "Client"; } void Object::add_input(Stream& stream, Router* target) { assert(vnl_dorun); stream.connect(vnl_engine, target); stream.listen(this); vnl_output_channels[stream.get_mac()] = "Stream"; } void Object::add_input(InputPin& pin) { assert(vnl_dorun); pin.enable(vnl_engine, this); vnl_input_pins[pin.get_mac()] = &pin; } void Object::add_output(OutputPin& pin) { assert(vnl_dorun); pin.enable(vnl_engine); vnl_output_pins[pin.get_mac()] = &pin; vnl_output_channels[pin.get_mac()] = "OutputPin"; } Address Object::subscribe(const String& domain, const String& topic) { return subscribe(Address(domain, topic)); } Address Object::subscribe(Address address) { return vnl_stream.subscribe(address); } void Object::unsubscribe(Hash64 domain, Hash64 topic) { unsubscribe(Address(domain, topic)); } void Object::unsubscribe(Address address) { vnl_stream.unsubscribe(address); } void Object::publish(Value* data, const String& domain, const String& topic, bool no_drop) { Header* header = Header::create(); header->send_time = vnl::currentTimeMicros(); header->src_mac = vnl_stream.get_mac(); header->src_topic.domain = my_domain; header->src_topic.name = my_topic; header->dst_topic.domain = domain; header->dst_topic.name = topic; Sample* pkt = vnl_sample_buffer.create(); pkt->header = header; pkt->data = data; send_async(pkt, Address(domain, topic), no_drop); } void Object::publish(Value* data, Address topic, bool no_drop) { Header* header = Header::create(); header->send_time = vnl::currentTimeMicros(); header->src_mac = vnl_stream.get_mac(); Sample* pkt = vnl_sample_buffer.create(); pkt->header = header; pkt->data = data; send_async(pkt, topic, no_drop); } void Object::send(Packet* packet, Address dst, bool no_drop) { if(packet->src_addr.is_null()) { packet->src_addr = my_address; } vnl_stream.send(packet, dst, no_drop); } void Object::send_async(Packet* packet, Address dst, bool no_drop) { if(packet->src_addr.is_null()) { packet->src_addr = my_address; } vnl_stream.send_async(packet, dst, no_drop); } void Object::send(Packet* packet, Basic* dst, bool no_drop) { if(packet->src_addr.is_null()) { packet->src_addr = my_address; } vnl_stream.send(packet, dst, no_drop); } void Object::send_async(Packet* packet, Basic* dst, bool no_drop) { if(packet->src_addr.is_null()) { packet->src_addr = my_address; } vnl_stream.send_async(packet, dst, no_drop); } void Object::send(Message* msg, Basic* dst, bool no_drop) { vnl_stream.send(msg, dst, no_drop); } void Object::send_async(Message* msg, Basic* dst, bool no_drop) { vnl_stream.send_async(msg, dst, no_drop); } bool Object::poll(int64_t micros) { int64_t to = micros; int64_t now = currentTimeMicros(); for(Timer& timer : vnl_timers) { if(timer.active) { int64_t diff = timer.deadline - now; if(diff <= 0) { switch(timer.type) { case VNL_TIMER_REPEAT: timer.active = true; timer.deadline += timer.interval; if(timer.deadline < now) { timer.deadline = now; } break; case VNL_TIMER_MANUAL: case VNL_TIMER_ONCE: timer.active = false; break; } timer.func(); diff = timer.deadline - now; if(diff < 0) { diff = 0; } } if(diff < to || to == -1) { to = diff; } } } while(true) { Message* msg = vnl_stream.poll(to); if(!msg) { break; } if(!handle(msg)) { msg->ack(); } to = 0; } return vnl_dorun; } bool Object::handle(Message* msg) { vnl_input_nodes[msg->src_mac]++; vnl_input_channels[vnl_channel->get_mac()]++; if(msg->msg_id == Packet::MID) { Packet* pkt = (Packet*)msg; if(pkt->proxy) { vnl_input_nodes[pkt->proxy]++; } return handle(pkt); } if(msg->msg_id == OutputPin::pin_data_t::MID) { return handle((OutputPin::pin_data_t*)msg); } else if(msg->msg_id == Stream::notify_t::MID) { return handle((Stream::notify_t*)msg); } return false; } bool Object::handle(Stream::notify_t* notify) { Message* msg; while(notify->data->pop(msg)) { Stream* tmp_channel = vnl_channel; vnl_channel = notify->data; if(!handle(msg)) { msg->ack(); } vnl_channel = tmp_channel; } return false; } bool Object::handle(OutputPin::pin_data_t* msg) { if(msg->data && handle_switch(msg->data, msg->dst)) { msg->ack(); return true; } return false; } bool Object::handle(Packet* pkt) { int64_t& last_seq = vnl_sources[pkt->src_mac xor vnl_channel->get_mac()]; if(pkt->seq_num <= last_seq) { if(pkt->pkt_id == Frame::PID) { Frame* result = vnl_frame_buffer.create(); result->req_num = ((Frame*)pkt->payload)->req_num; send_async(result, pkt->src_addr); } pkt->ack(); return true; } last_seq = pkt->seq_num; uint64_t tmp_proxy = vnl_proxy; vnl_proxy = pkt->proxy; bool res = false; if(pkt->pkt_id == Sample::PID) { res = handle((Sample*)pkt->payload); } else if(pkt->pkt_id == Frame::PID) { res = handle((Frame*)pkt->payload); } vnl_proxy = tmp_proxy; return res; } bool Object::handle(Sample* sample) { if(sample->data) { handle_switch(sample->data, sample); } return false; } bool Object::handle(Frame* frame) { Frame* result = exec_vni_call(frame); if(result) { send_async(result, frame->src_addr, true); } vnl::info::ClientInfo& info = vnl_clients[frame->src_mac]; info.proxy = frame->proxy; info.num_requests++; info.num_errors += !result || result->type == Frame::EXCEPTION; return false; } Frame* Object::exec_vni_call(Frame* frame) { Frame* result = vnl_frame_buffer.create(); result->type = Frame::RESULT; result->req_num = frame->req_num; result->data = Page::alloc(); vnl_buf_out.wrap(result->data); vnl_buf_in.wrap(frame->data, frame->size); vnl_output.reset(); vnl_input.reset(); try { uint32_t hash; int size = 0; int id = vnl_input.getEntry(size); if(id == VNL_IO_CALL) { vnl_input.getHash(hash); bool res = vni_call(vnl_input, hash, size); if(!res) { throw NoSuchMethodException(); } } else if(id == VNL_IO_CONST_CALL) { vnl_input.getHash(hash); if(!vni_const_call(vnl_input, hash, size, vnl_output)) { throw NoSuchMethodException(); } } else { throw IOException(); } if(vnl_input.error()) { throw IOException(); } } catch (const Exception& ex) { result->type = Frame::EXCEPTION; vnl::write(vnl_output, ex); } vnl_output.flush(); result->size = vnl_buf_out.position(); vnl_buf_out.clear(); return result; } String Object::get_private_domain() const { return my_private_domain; } Map<String, String> Object::get_config_map() const { Map<String, String> res; for(int i = 0; i < get_num_fields(); ++i) { get_field(i , res[get_field_name(i)]); } return res; } String Object::get_config(const Hash32& name) const { String res; get_field(get_field_index(name), res); return res; } void Object::set_config(const Hash32& name, const String& value) { set_field(get_field_index(name), value); } void Object::handle(const vnl::Shutdown& event) { vnl_dorun = false; } bool Object::sleep(int64_t secs) { return usleep(secs*1000*1000); } bool Object::usleep(int64_t micros) { int64_t now = currentTimeMicros(); int64_t deadline = now + micros; while(vnl_dorun && now < deadline) { int64_t to = deadline - now; if(!poll(to)) { return false; } now = currentTimeMicros(); } return true; } void Object::run() { while(vnl_dorun && poll(-1)); } void Object::exec(Engine* engine_, Message* init, Pipe* pipe) { vnl_spawn_time = vnl::currentTimeMicros(); vnl_dorun = true; vnl_engine = engine_; vnl_stream.connect(engine_); vnl_stream.set_timeout(vnl_msg_timeout); vnl_channel = &vnl_stream; if(pipe) { pipe->open(this); } subscribe(my_address); subscribe(my_private_address); Announce* announce = Announce::create(); announce->instance.type = get_type_name(); announce->instance.domain = my_domain; announce->instance.topic = my_topic; announce->instance.src_mac = get_mac(); announce->instance.heartbeat_interval = vnl_heartbeat_interval; publish(announce, local_domain_name, "vnl.announce", true); set_timeout(vnl_heartbeat_interval, std::bind(&Object::heartbeat, this), VNL_TIMER_REPEAT); main(engine_, init); log(DEBUG).out << "Messages: num_sent=" << vnl_engine->num_sent << ", num_received=" << vnl_engine->num_received << ", num_timeout=" << vnl_engine->num_timeout << vnl::endl; for(InputPin* pin : vnl_input_pins.values()) { pin->close(); } for(OutputPin* pin : vnl_output_pins.values()) { pin->close(); } publish(Exit::create(), local_domain_name, "vnl.exit", true); if(pipe) { pipe->close(); } vnl_stream.close(); } void Object::heartbeat() { Heartbeat* msg = Heartbeat::create(); msg->src_mac = get_mac(); msg->type = get_type_name(); msg->domain = my_domain; msg->topic = my_topic; msg->interval = vnl_heartbeat_interval; msg->info.time = vnl::currentTimeMicros(); msg->info.spawn_time = vnl_spawn_time; msg->info.num_cycles = vnl_engine->num_cycles; msg->info.num_msg_sent = vnl_engine->num_sent; msg->info.num_msg_received = vnl_engine->num_received; msg->info.num_msg_dropped = vnl_engine->num_timeout; msg->info.sources = vnl_sources; msg->info.input_nodes = vnl_input_nodes; msg->info.input_channels = vnl_input_channels; msg->info.output_channels = vnl_output_channels; for(const auto& entry : vnl_input_pins) { msg->info.input_pins[entry.first] = entry.second->name; } for(const auto& entry : vnl_output_pins) { msg->info.output_pins[entry.first] = entry.second->name; } msg->info.clients = vnl_clients; publish(msg, local_domain_name, "vnl.heartbeat", true); } } // vnl <commit_msg>use private address as src_addr in Object<commit_after>/* * Object.cpp * * Created on: Mar 7, 2016 * Author: mad */ #include <vnl/Object.h> #include <vnl/Pipe.h> #include <vnl/Sample.h> #include <vnl/Announce.hxx> #include <vnl/LogMsg.hxx> #include <vnl/Topic.hxx> #include <vnl/Shutdown.hxx> #include <vnl/Heartbeat.hxx> #include <vnl/Exit.hxx> #include <vnl/NoSuchMethodException.hxx> namespace vnl { void Object::exit() { vnl_dorun = false; } StringWriter Object::log(int level) { StringOutput* out = 0; if(level <= vnl_log_level) { vnl_log_writer.level = level; out = &vnl_log_writer; } return StringWriter(out); } Timer* Object::set_timeout(int64_t micros, const std::function<void()>& func, int type) { Timer& timer = *vnl_timers.push_back(); timer.interval = micros; timer.func = func; timer.type = type; if(type != VNL_TIMER_MANUAL) { timer.reset(); } return &timer; } void Object::add_client(Client& client, Router* target) { assert(vnl_dorun); client.connect(vnl_engine, target); vnl_output_channels[client.get_mac()] = "Client"; } void Object::add_input(Stream& stream, Router* target) { assert(vnl_dorun); stream.connect(vnl_engine, target); stream.listen(this); vnl_output_channels[stream.get_mac()] = "Stream"; } void Object::add_input(InputPin& pin) { assert(vnl_dorun); pin.enable(vnl_engine, this); vnl_input_pins[pin.get_mac()] = &pin; } void Object::add_output(OutputPin& pin) { assert(vnl_dorun); pin.enable(vnl_engine); vnl_output_pins[pin.get_mac()] = &pin; vnl_output_channels[pin.get_mac()] = "OutputPin"; } Address Object::subscribe(const String& domain, const String& topic) { return subscribe(Address(domain, topic)); } Address Object::subscribe(Address address) { return vnl_stream.subscribe(address); } void Object::unsubscribe(Hash64 domain, Hash64 topic) { unsubscribe(Address(domain, topic)); } void Object::unsubscribe(Address address) { vnl_stream.unsubscribe(address); } void Object::publish(Value* data, const String& domain, const String& topic, bool no_drop) { Header* header = Header::create(); header->send_time = vnl::currentTimeMicros(); header->src_mac = get_mac(); header->src_topic.domain = my_domain; header->src_topic.name = my_topic; header->dst_topic.domain = domain; header->dst_topic.name = topic; Sample* pkt = vnl_sample_buffer.create(); pkt->header = header; pkt->data = data; send_async(pkt, Address(domain, topic), no_drop); } void Object::publish(Value* data, Address topic, bool no_drop) { Header* header = Header::create(); header->send_time = vnl::currentTimeMicros(); header->src_mac = get_mac(); Sample* pkt = vnl_sample_buffer.create(); pkt->header = header; pkt->data = data; send_async(pkt, topic, no_drop); } void Object::send(Packet* packet, Address dst, bool no_drop) { if(packet->src_addr.is_null()) { packet->src_addr = my_private_address; } vnl_stream.send(packet, dst, no_drop); } void Object::send_async(Packet* packet, Address dst, bool no_drop) { if(packet->src_addr.is_null()) { packet->src_addr = my_private_address; } vnl_stream.send_async(packet, dst, no_drop); } void Object::send(Packet* packet, Basic* dst, bool no_drop) { if(packet->src_addr.is_null()) { packet->src_addr = my_private_address; } vnl_stream.send(packet, dst, no_drop); } void Object::send_async(Packet* packet, Basic* dst, bool no_drop) { if(packet->src_addr.is_null()) { packet->src_addr = my_private_address; } vnl_stream.send_async(packet, dst, no_drop); } void Object::send(Message* msg, Basic* dst, bool no_drop) { vnl_stream.send(msg, dst, no_drop); } void Object::send_async(Message* msg, Basic* dst, bool no_drop) { vnl_stream.send_async(msg, dst, no_drop); } bool Object::poll(int64_t micros) { int64_t to = micros; int64_t now = currentTimeMicros(); for(Timer& timer : vnl_timers) { if(timer.active) { int64_t diff = timer.deadline - now; if(diff <= 0) { switch(timer.type) { case VNL_TIMER_REPEAT: timer.active = true; timer.deadline += timer.interval; if(timer.deadline < now) { timer.deadline = now; } break; case VNL_TIMER_MANUAL: case VNL_TIMER_ONCE: timer.active = false; break; } timer.func(); diff = timer.deadline - now; if(diff < 0) { diff = 0; } } if(diff < to || to == -1) { to = diff; } } } while(true) { Message* msg = vnl_stream.poll(to); if(!msg) { break; } if(!handle(msg)) { msg->ack(); } to = 0; } return vnl_dorun; } bool Object::handle(Message* msg) { vnl_input_nodes[msg->src_mac]++; vnl_input_channels[vnl_channel->get_mac()]++; if(msg->msg_id == Packet::MID) { Packet* pkt = (Packet*)msg; if(pkt->proxy) { vnl_input_nodes[pkt->proxy]++; } return handle(pkt); } if(msg->msg_id == OutputPin::pin_data_t::MID) { return handle((OutputPin::pin_data_t*)msg); } else if(msg->msg_id == Stream::notify_t::MID) { return handle((Stream::notify_t*)msg); } return false; } bool Object::handle(Stream::notify_t* notify) { Message* msg; while(notify->data->pop(msg)) { Stream* tmp_channel = vnl_channel; vnl_channel = notify->data; if(!handle(msg)) { msg->ack(); } vnl_channel = tmp_channel; } return false; } bool Object::handle(OutputPin::pin_data_t* msg) { if(msg->data && handle_switch(msg->data, msg->dst)) { msg->ack(); return true; } return false; } bool Object::handle(Packet* pkt) { int64_t& last_seq = vnl_sources[pkt->src_mac xor vnl_channel->get_mac()]; if(pkt->seq_num <= last_seq) { if(pkt->pkt_id == Frame::PID) { Frame* result = vnl_frame_buffer.create(); result->req_num = ((Frame*)pkt->payload)->req_num; send_async(result, pkt->src_addr); } pkt->ack(); return true; } last_seq = pkt->seq_num; uint64_t tmp_proxy = vnl_proxy; vnl_proxy = pkt->proxy; bool res = false; if(pkt->pkt_id == Sample::PID) { res = handle((Sample*)pkt->payload); } else if(pkt->pkt_id == Frame::PID) { res = handle((Frame*)pkt->payload); } vnl_proxy = tmp_proxy; return res; } bool Object::handle(Sample* sample) { if(sample->data) { handle_switch(sample->data, sample); } return false; } bool Object::handle(Frame* frame) { Frame* result = exec_vni_call(frame); if(result) { send_async(result, frame->src_addr, true); } vnl::info::ClientInfo& info = vnl_clients[frame->src_mac]; info.proxy = frame->proxy; info.num_requests++; info.num_errors += !result || result->type == Frame::EXCEPTION; return false; } Frame* Object::exec_vni_call(Frame* frame) { Frame* result = vnl_frame_buffer.create(); result->type = Frame::RESULT; result->req_num = frame->req_num; result->data = Page::alloc(); vnl_buf_out.wrap(result->data); vnl_buf_in.wrap(frame->data, frame->size); vnl_output.reset(); vnl_input.reset(); try { uint32_t hash; int size = 0; int id = vnl_input.getEntry(size); if(id == VNL_IO_CALL) { vnl_input.getHash(hash); if(!vni_call(vnl_input, hash, size)) { throw NoSuchMethodException(); } } else if(id == VNL_IO_CONST_CALL) { vnl_input.getHash(hash); if(!vni_const_call(vnl_input, hash, size, vnl_output)) { throw NoSuchMethodException(); } } else { throw IOException(); } if(vnl_input.error()) { throw IOException(); } } catch (const Exception& ex) { result->type = Frame::EXCEPTION; vnl::write(vnl_output, ex); } vnl_output.flush(); result->size = vnl_buf_out.position(); vnl_buf_out.clear(); return result; } String Object::get_private_domain() const { return my_private_domain; } Map<String, String> Object::get_config_map() const { Map<String, String> res; for(int i = 0; i < get_num_fields(); ++i) { get_field(i , res[get_field_name(i)]); } return res; } String Object::get_config(const Hash32& name) const { String res; get_field(get_field_index(name), res); return res; } void Object::set_config(const Hash32& name, const String& value) { set_field(get_field_index(name), value); } void Object::handle(const vnl::Shutdown& event) { vnl_dorun = false; } bool Object::sleep(int64_t secs) { return usleep(secs*1000*1000); } bool Object::usleep(int64_t micros) { int64_t now = currentTimeMicros(); int64_t deadline = now + micros; while(vnl_dorun && now < deadline) { int64_t to = deadline - now; if(!poll(to)) { return false; } now = currentTimeMicros(); } return true; } void Object::run() { while(vnl_dorun && poll(-1)); } void Object::exec(Engine* engine_, Message* init, Pipe* pipe) { vnl_spawn_time = vnl::currentTimeMicros(); vnl_dorun = true; vnl_engine = engine_; vnl_stream.connect(engine_); vnl_stream.set_timeout(vnl_msg_timeout); vnl_channel = &vnl_stream; if(pipe) { pipe->open(this); } subscribe(my_address); subscribe(my_private_address); Announce* announce = Announce::create(); announce->instance.type = get_type_name(); announce->instance.domain = my_domain; announce->instance.topic = my_topic; announce->instance.src_mac = get_mac(); announce->instance.heartbeat_interval = vnl_heartbeat_interval; publish(announce, local_domain_name, "vnl.announce", true); set_timeout(vnl_heartbeat_interval, std::bind(&Object::heartbeat, this), VNL_TIMER_REPEAT); main(engine_, init); log(DEBUG).out << "Messages: num_sent=" << vnl_engine->num_sent << ", num_received=" << vnl_engine->num_received << ", num_timeout=" << vnl_engine->num_timeout << vnl::endl; for(InputPin* pin : vnl_input_pins.values()) { pin->close(); } for(OutputPin* pin : vnl_output_pins.values()) { pin->close(); } publish(Exit::create(), local_domain_name, "vnl.exit", true); if(pipe) { pipe->close(); } vnl_stream.close(); } void Object::heartbeat() { Heartbeat* msg = Heartbeat::create(); msg->src_mac = get_mac(); msg->type = get_type_name(); msg->domain = my_domain; msg->topic = my_topic; msg->interval = vnl_heartbeat_interval; msg->info.time = vnl::currentTimeMicros(); msg->info.spawn_time = vnl_spawn_time; msg->info.num_cycles = vnl_engine->num_cycles; msg->info.num_msg_sent = vnl_engine->num_sent; msg->info.num_msg_received = vnl_engine->num_received; msg->info.num_msg_dropped = vnl_engine->num_timeout; msg->info.sources = vnl_sources; msg->info.input_nodes = vnl_input_nodes; msg->info.input_channels = vnl_input_channels; msg->info.output_channels = vnl_output_channels; for(const auto& entry : vnl_input_pins) { msg->info.input_pins[entry.first] = entry.second->name; } for(const auto& entry : vnl_output_pins) { msg->info.output_pins[entry.first] = entry.second->name; } msg->info.clients = vnl_clients; publish(msg, local_domain_name, "vnl.heartbeat", true); } } // vnl <|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "Parser.h" #include <algorithm> #include "IMedia.h" Parser::Parser(DBConnection dbConnection , IMediaLibraryCb* cb) : m_stopParser( false ) , m_dbConnection( dbConnection ) , m_callback( cb ) , m_nbParsed( 0 ) , m_nbToParse( 0 ) { } Parser::~Parser() { if ( m_thread.joinable() ) { { std::lock_guard<std::mutex> lock( m_lock ); if ( m_tasks.empty() == true ) m_cond.notify_all(); m_stopParser = true; } m_thread.join(); } while ( m_tasks.empty() == false ) { delete m_tasks.front(); m_tasks.pop(); } } void Parser::addService(std::unique_ptr<IMetadataService> service) { m_services.emplace_back( std::move( service ) ); std::push_heap( m_services.begin(), m_services.end(), []( const ServicePtr& a, const ServicePtr& b ) { // We want higher priority first return a->priority() < b->priority(); }); } void Parser::parse( std::shared_ptr<Media> file ) { std::lock_guard<std::mutex> lock( m_lock ); if ( m_services.size() == 0 ) return; m_tasks.push( new Task( file, m_services, m_callback ) ); updateStats( false, true ); m_cond.notify_all(); } void Parser::start() { // Ensure we don't start multiple times. assert( m_thread.joinable() == false ); m_thread = std::thread{ &Parser::run, this }; } void Parser::run() { LOG_INFO("Starting Parser thread"); restore(); while ( m_stopParser == false ) { Task* task = nullptr; { std::unique_lock<std::mutex> lock( m_lock ); if ( m_tasks.empty() == true ) { m_cond.wait( lock, [this]() { return m_tasks.empty() == false || m_stopParser == true; }); // We might have been woken up because the parser is being destroyed if ( m_stopParser == true ) break; } // Otherwise it's safe to assume we have at least one element. task = m_tasks.front(); m_tasks.pop(); } (*task->it)->run( task->file, task ); } LOG_INFO("Exiting Parser thread"); } void Parser::restore() { static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE parsed = 0"; auto media = Media::fetchAll( m_dbConnection, req ); std::lock_guard<std::mutex> lock( m_lock ); for ( auto& it : media ) { auto m = std::static_pointer_cast<Media>( it ); m_tasks.push( new Task( m, m_services, m_callback ) ); } } void Parser::updateStats( bool newMediaParsed, bool newMediaQueued ) { if ( m_callback == nullptr ) return; if ( newMediaParsed == true ) m_nbParsed++; else if ( newMediaQueued == true ) m_nbToParse++; else assert(false); if ( m_nbParsed == m_nbToParse ) { m_callback->onParsingStatsUpdated( m_nbParsed, m_nbToParse ); m_nbParsed = 0; m_nbToParse = 0; return; } // Only send an update every X new elem const uint32_t NbElems = 10; if ( ( newMediaParsed == true && m_nbParsed % NbElems == 0 ) || ( newMediaQueued == true && m_nbToParse % NbElems == 0 ) ) { m_callback->onParsingStatsUpdated( m_nbParsed, m_nbToParse ); } } Parser::Task::Task(std::shared_ptr<Media> file, Parser::ServiceList& serviceList, IMediaLibraryCb* metadataCb ) : file(file) , it( serviceList.begin() ) , end( serviceList.end() ) , cb( metadataCb ) { } void Parser::done(std::shared_ptr<Media> file, IMetadataService::Status status, void* data ) { Task *t = reinterpret_cast<Task*>( data ); if ( status == IMetadataService::Status::TemporaryUnavailable || status == IMetadataService::Status::Fatal ) { updateStats( true, false ); delete t; return; } else if ( status == IMetadataService::Status::Success ) { t->cb->onFileUpdated( file ); } ++t->it; if (t->it == t->end) { updateStats( true, false ); file->markParsed(); delete t; return; } std::lock_guard<std::mutex> lock( m_lock ); m_tasks.push( t ); m_cond.notify_all(); } <commit_msg>Parser: Increase update callback rate<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "Parser.h" #include <algorithm> #include "IMedia.h" Parser::Parser(DBConnection dbConnection , IMediaLibraryCb* cb) : m_stopParser( false ) , m_dbConnection( dbConnection ) , m_callback( cb ) , m_nbParsed( 0 ) , m_nbToParse( 0 ) { } Parser::~Parser() { if ( m_thread.joinable() ) { { std::lock_guard<std::mutex> lock( m_lock ); if ( m_tasks.empty() == true ) m_cond.notify_all(); m_stopParser = true; } m_thread.join(); } while ( m_tasks.empty() == false ) { delete m_tasks.front(); m_tasks.pop(); } } void Parser::addService(std::unique_ptr<IMetadataService> service) { m_services.emplace_back( std::move( service ) ); std::push_heap( m_services.begin(), m_services.end(), []( const ServicePtr& a, const ServicePtr& b ) { // We want higher priority first return a->priority() < b->priority(); }); } void Parser::parse( std::shared_ptr<Media> file ) { std::lock_guard<std::mutex> lock( m_lock ); if ( m_services.size() == 0 ) return; m_tasks.push( new Task( file, m_services, m_callback ) ); updateStats( false, true ); m_cond.notify_all(); } void Parser::start() { // Ensure we don't start multiple times. assert( m_thread.joinable() == false ); m_thread = std::thread{ &Parser::run, this }; } void Parser::run() { LOG_INFO("Starting Parser thread"); restore(); while ( m_stopParser == false ) { Task* task = nullptr; { std::unique_lock<std::mutex> lock( m_lock ); if ( m_tasks.empty() == true ) { m_cond.wait( lock, [this]() { return m_tasks.empty() == false || m_stopParser == true; }); // We might have been woken up because the parser is being destroyed if ( m_stopParser == true ) break; } // Otherwise it's safe to assume we have at least one element. task = m_tasks.front(); m_tasks.pop(); } (*task->it)->run( task->file, task ); } LOG_INFO("Exiting Parser thread"); } void Parser::restore() { static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE parsed = 0"; auto media = Media::fetchAll( m_dbConnection, req ); std::lock_guard<std::mutex> lock( m_lock ); for ( auto& it : media ) { auto m = std::static_pointer_cast<Media>( it ); m_tasks.push( new Task( m, m_services, m_callback ) ); } } void Parser::updateStats( bool newMediaParsed, bool newMediaQueued ) { if ( m_callback == nullptr ) return; if ( newMediaParsed == true ) m_nbParsed++; else if ( newMediaQueued == true ) m_nbToParse++; else assert(false); if ( m_nbParsed == m_nbToParse ) { m_callback->onParsingStatsUpdated( m_nbParsed, m_nbToParse ); m_nbParsed = 0; m_nbToParse = 0; return; } // Only send an update every X new elem const uint32_t NbElems = 3; if ( ( newMediaParsed == true && m_nbParsed % NbElems == 0 ) || ( newMediaQueued == true && m_nbToParse % NbElems == 0 ) ) { m_callback->onParsingStatsUpdated( m_nbParsed, m_nbToParse ); } } Parser::Task::Task(std::shared_ptr<Media> file, Parser::ServiceList& serviceList, IMediaLibraryCb* metadataCb ) : file(file) , it( serviceList.begin() ) , end( serviceList.end() ) , cb( metadataCb ) { } void Parser::done(std::shared_ptr<Media> file, IMetadataService::Status status, void* data ) { Task *t = reinterpret_cast<Task*>( data ); if ( status == IMetadataService::Status::TemporaryUnavailable || status == IMetadataService::Status::Fatal ) { updateStats( true, false ); delete t; return; } else if ( status == IMetadataService::Status::Success ) { t->cb->onFileUpdated( file ); } ++t->it; if (t->it == t->end) { updateStats( true, false ); file->markParsed(); delete t; return; } std::lock_guard<std::mutex> lock( m_lock ); m_tasks.push( t ); m_cond.notify_all(); } <|endoftext|>
<commit_before>#include "include/Player.h" Player::Player(bool isSolid, int xPosition, int yPosition, double dir, std::string fileName) : Entity(isSolid, xPosition, yPosition, dir, fileName) // Call the superclass constructor in the subclass' initialization list. { m_weaponDamage =1; m_weaponRange =1; m_floor=1; m_score=0; } void Player::attack(){ //implement. Play a sound? } <commit_msg>formating<commit_after>#include "include/Player.h" Player::Player(bool isSolid, int xPosition, int yPosition, double dir, std::string fileName) : Entity(isSolid, xPosition, yPosition, dir, fileName) // Call the superclass constructor in the subclass' initialization list. { m_weaponDamage = 1; m_weaponRange = 1; m_floor = 1; m_score = 0; } void Player::attack() { //implement. Play a sound? } <|endoftext|>
<commit_before>/*===================================================================== QGroundControl Open Source Ground Control Station (c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> This file is part of the QGROUNDCONTROL project QGROUNDCONTROL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ /** * @file * @brief Implementation of class QGCCore * * @author Lorenz Meier <mavteam@student.ethz.ch> * */ #include <QFile> #include <QFlags> #include <QThread> #include <QSplashScreen> #include <QPixmap> #include <QDesktopWidget> #include <QPainter> #include <QStyleFactory> #include <QAction> #include <QDebug> #include "configuration.h" #include "QGC.h" #include "QGCCore.h" #include "MainWindow.h" #include "GAudioOutput.h" #ifdef OPAL_RT #include "OpalLink.h" #endif #include "UDPLink.h" #include "MAVLinkSimulationLink.h" #include "SerialLink.h" /** * @brief Constructor for the main application. * * This constructor initializes and starts the whole application. It takes standard * command-line parameters * * @param argc The number of command-line parameters * @param argv The string array of parameters **/ QGCCore::QGCCore(int &argc, char* argv[]) : QApplication(argc, argv) { // Set application name this->setApplicationName(QGC_APPLICATION_NAME); this->setApplicationVersion(QGC_APPLICATION_VERSION); this->setOrganizationName(QLatin1String("diydrones")); this->setOrganizationDomain("org.diydrones"); // Set settings format QSettings::setDefaultFormat(QSettings::IniFormat); // Check application settings // clear them if they mismatch // QGC then falls back to default QSettings settings; // Show user an upgrade message if QGC got upgraded (see code below, after splash screen) bool upgraded = false; QString lastApplicationVersion(""); if (settings.contains("QGC_APPLICATION_VERSION")) { QString qgcVersion = settings.value("QGC_APPLICATION_VERSION").toString(); if (qgcVersion != QGC_APPLICATION_VERSION) { lastApplicationVersion = qgcVersion; settings.clear(); // Write current application version settings.setValue("QGC_APPLICATION_VERSION", QGC_APPLICATION_VERSION); upgraded = true; } } else { // If application version is not set, clear settings anyway settings.clear(); // Write current application version settings.setValue("QGC_APPLICATION_VERSION", QGC_APPLICATION_VERSION); } settings.sync(); // Show splash screen QPixmap splashImage(":/files/images/apm_planner_2_0-07.png"); QSplashScreen* splashScreen = new QSplashScreen(splashImage); // Delete splash screen after mainWindow was displayed splashScreen->setAttribute(Qt::WA_DeleteOnClose); splashScreen->show(); processEvents(); splashScreen->showMessage(tr("Loading application fonts"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141)); // Exit main application when last window is closed connect(this, SIGNAL(lastWindowClosed()), this, SLOT(quit())); // Load application font QFontDatabase fontDatabase = QFontDatabase(); const QString fontFileName = ":/general/vera.ttf"; ///< Font file is part of the QRC file and compiled into the app //const QString fontFamilyName = "Bitstream Vera Sans"; if(!QFile::exists(fontFileName)) printf("ERROR! font file: %s DOES NOT EXIST!\n", fontFileName.toStdString().c_str()); fontDatabase.addApplicationFont(fontFileName); // Avoid Using setFont(). In the Qt docu you can read the following: // "Warning: Do not use this function in conjunction with Qt Style Sheets." // setFont(fontDatabase.font(fontFamilyName, "Roman", 12)); // Start the comm link manager splashScreen->showMessage(tr("Starting Communication Links"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141)); startLinkManager(); // Start the UAS Manager splashScreen->showMessage(tr("Starting UAS Manager"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141)); startUASManager(); // Start the user interface splashScreen->showMessage(tr("Starting User Interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141)); // Start UI // Connect links // to make sure that all components are initialized when the // first messages arrive UDPLink* udpLink = new UDPLink(QHostAddress::Any, 14550); MainWindow::instance()->addLink(udpLink); // Listen on Multicast-Address 239.255.77.77, Port 14550 //QHostAddress * multicast_udp = new QHostAddress("239.255.77.77"); //UDPLink* udpLink = new UDPLink(*multicast_udp, 14550); #ifdef OPAL_RT // Add OpalRT Link, but do not connect OpalLink* opalLink = new OpalLink(); MainWindow::instance()->addLink(opalLink); #endif MAVLinkSimulationLink* simulationLink = new MAVLinkSimulationLink(":/demo-log.txt"); simulationLink->disconnect(); //We want to have a default serial link available for "quick" connecting. SerialLink *slink = new SerialLink(); MainWindow::instance()->addLink(slink); mainWindow = MainWindow::instance(splashScreen); // Remove splash screen splashScreen->finish(mainWindow); if (upgraded) mainWindow->showInfoMessage(tr("Default Settings Loaded"), tr("APM Planner has been upgraded from version %1 to version %2. Some of your user preferences have been reset to defaults for safety reasons. Please adjust them where needed.").arg(lastApplicationVersion).arg(QGC_APPLICATION_VERSION)); // Check if link could be connected if (!udpLink->connect()) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Critical); msgBox.setText("Could not connect UDP port. Is an instance of " + qAppName() + "already running?"); msgBox.setInformativeText("You will not be able to receive data via UDP. Please check that you're running the right executable and then re-start " + qAppName() + ". Do you want to close the application?"); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::No); int ret = msgBox.exec(); // Close the message box shortly after the click to prevent accidental clicks QTimer::singleShot(15000, &msgBox, SLOT(reject())); // Exit application if (ret == QMessageBox::Yes) { //mainWindow->close(); QTimer::singleShot(200, mainWindow, SLOT(close())); } } // forever // { // QGC::SLEEP::msleep(5000); // } // mainWindow->close(); // mainWindow->deleteLater(); // QGC::SLEEP::msleep(200); } /** * @brief Destructor for the groundstation. It destroys all loaded instances. * **/ QGCCore::~QGCCore() { //mainWindow->storeSettings(); //mainWindow->close(); //mainWindow->deleteLater(); // Delete singletons // First systems delete UASManager::instance(); // then links delete LinkManager::instance(); // Finally the main window //delete MainWindow::instance(); //The main window now autodeletes on close. } /** * @brief Start the link managing component. * * The link manager keeps track of all communication links and provides the global * packet queue. It is the main communication hub **/ void QGCCore::startLinkManager() { LinkManager::instance(); } /** * @brief Start the Unmanned Air System Manager * **/ void QGCCore::startUASManager() { // Load UAS plugins QDir pluginsDir = QDir(qApp->applicationDirPath()); #if defined(Q_OS_WIN) if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") pluginsDir.cdUp(); #elif defined(Q_OS_LINUX) if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") pluginsDir.cdUp(); #elif defined(Q_OS_MAC) if (pluginsDir.dirName() == "MacOS") { pluginsDir.cdUp(); pluginsDir.cdUp(); pluginsDir.cdUp(); } #endif pluginsDir.cd("plugins"); UASManager::instance(); // Load plugins QStringList pluginFileNames; foreach (QString fileName, pluginsDir.entryList(QDir::Files)) { QPluginLoader loader(pluginsDir.absoluteFilePath(fileName)); QObject *plugin = loader.instance(); if (plugin) { //populateMenus(plugin); pluginFileNames += fileName; //printf(QString("Loaded plugin from " + fileName + "\n").toStdString().c_str()); } } } <commit_msg>Change in Organization Domain of application<commit_after>/*===================================================================== QGroundControl Open Source Ground Control Station (c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> This file is part of the QGROUNDCONTROL project QGROUNDCONTROL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ /** * @file * @brief Implementation of class QGCCore * * @author Lorenz Meier <mavteam@student.ethz.ch> * */ #include <QFile> #include <QFlags> #include <QThread> #include <QSplashScreen> #include <QPixmap> #include <QDesktopWidget> #include <QPainter> #include <QStyleFactory> #include <QAction> #include <QDebug> #include "configuration.h" #include "QGC.h" #include "QGCCore.h" #include "MainWindow.h" #include "GAudioOutput.h" #ifdef OPAL_RT #include "OpalLink.h" #endif #include "UDPLink.h" #include "MAVLinkSimulationLink.h" #include "SerialLink.h" /** * @brief Constructor for the main application. * * This constructor initializes and starts the whole application. It takes standard * command-line parameters * * @param argc The number of command-line parameters * @param argv The string array of parameters **/ QGCCore::QGCCore(int &argc, char* argv[]) : QApplication(argc, argv) { // Set application name this->setApplicationName(QGC_APPLICATION_NAME); this->setApplicationVersion(QGC_APPLICATION_VERSION); this->setOrganizationName(QLatin1String("diydrones")); this->setOrganizationDomain("com.diydrones"); // Set settings format QSettings::setDefaultFormat(QSettings::IniFormat); // Check application settings // clear them if they mismatch // QGC then falls back to default QSettings settings; // Show user an upgrade message if QGC got upgraded (see code below, after splash screen) bool upgraded = false; QString lastApplicationVersion(""); if (settings.contains("QGC_APPLICATION_VERSION")) { QString qgcVersion = settings.value("QGC_APPLICATION_VERSION").toString(); if (qgcVersion != QGC_APPLICATION_VERSION) { lastApplicationVersion = qgcVersion; settings.clear(); // Write current application version settings.setValue("QGC_APPLICATION_VERSION", QGC_APPLICATION_VERSION); upgraded = true; } } else { // If application version is not set, clear settings anyway settings.clear(); // Write current application version settings.setValue("QGC_APPLICATION_VERSION", QGC_APPLICATION_VERSION); } settings.sync(); // Show splash screen QPixmap splashImage(":/files/images/apm_planner_2_0-07.png"); QSplashScreen* splashScreen = new QSplashScreen(splashImage); // Delete splash screen after mainWindow was displayed splashScreen->setAttribute(Qt::WA_DeleteOnClose); splashScreen->show(); processEvents(); splashScreen->showMessage(tr("Loading application fonts"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141)); // Exit main application when last window is closed connect(this, SIGNAL(lastWindowClosed()), this, SLOT(quit())); // Load application font QFontDatabase fontDatabase = QFontDatabase(); const QString fontFileName = ":/general/vera.ttf"; ///< Font file is part of the QRC file and compiled into the app //const QString fontFamilyName = "Bitstream Vera Sans"; if(!QFile::exists(fontFileName)) printf("ERROR! font file: %s DOES NOT EXIST!\n", fontFileName.toStdString().c_str()); fontDatabase.addApplicationFont(fontFileName); // Avoid Using setFont(). In the Qt docu you can read the following: // "Warning: Do not use this function in conjunction with Qt Style Sheets." // setFont(fontDatabase.font(fontFamilyName, "Roman", 12)); // Start the comm link manager splashScreen->showMessage(tr("Starting Communication Links"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141)); startLinkManager(); // Start the UAS Manager splashScreen->showMessage(tr("Starting UAS Manager"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141)); startUASManager(); // Start the user interface splashScreen->showMessage(tr("Starting User Interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141)); // Start UI // Connect links // to make sure that all components are initialized when the // first messages arrive UDPLink* udpLink = new UDPLink(QHostAddress::Any, 14550); MainWindow::instance()->addLink(udpLink); // Listen on Multicast-Address 239.255.77.77, Port 14550 //QHostAddress * multicast_udp = new QHostAddress("239.255.77.77"); //UDPLink* udpLink = new UDPLink(*multicast_udp, 14550); #ifdef OPAL_RT // Add OpalRT Link, but do not connect OpalLink* opalLink = new OpalLink(); MainWindow::instance()->addLink(opalLink); #endif MAVLinkSimulationLink* simulationLink = new MAVLinkSimulationLink(":/demo-log.txt"); simulationLink->disconnect(); //We want to have a default serial link available for "quick" connecting. SerialLink *slink = new SerialLink(); MainWindow::instance()->addLink(slink); mainWindow = MainWindow::instance(splashScreen); // Remove splash screen splashScreen->finish(mainWindow); if (upgraded) mainWindow->showInfoMessage(tr("Default Settings Loaded"), tr("APM Planner has been upgraded from version %1 to version %2. Some of your user preferences have been reset to defaults for safety reasons. Please adjust them where needed.").arg(lastApplicationVersion).arg(QGC_APPLICATION_VERSION)); // Check if link could be connected if (!udpLink->connect()) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Critical); msgBox.setText("Could not connect UDP port. Is an instance of " + qAppName() + "already running?"); msgBox.setInformativeText("You will not be able to receive data via UDP. Please check that you're running the right executable and then re-start " + qAppName() + ". Do you want to close the application?"); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::No); int ret = msgBox.exec(); // Close the message box shortly after the click to prevent accidental clicks QTimer::singleShot(15000, &msgBox, SLOT(reject())); // Exit application if (ret == QMessageBox::Yes) { //mainWindow->close(); QTimer::singleShot(200, mainWindow, SLOT(close())); } } // forever // { // QGC::SLEEP::msleep(5000); // } // mainWindow->close(); // mainWindow->deleteLater(); // QGC::SLEEP::msleep(200); } /** * @brief Destructor for the groundstation. It destroys all loaded instances. * **/ QGCCore::~QGCCore() { //mainWindow->storeSettings(); //mainWindow->close(); //mainWindow->deleteLater(); // Delete singletons // First systems delete UASManager::instance(); // then links delete LinkManager::instance(); // Finally the main window //delete MainWindow::instance(); //The main window now autodeletes on close. } /** * @brief Start the link managing component. * * The link manager keeps track of all communication links and provides the global * packet queue. It is the main communication hub **/ void QGCCore::startLinkManager() { LinkManager::instance(); } /** * @brief Start the Unmanned Air System Manager * **/ void QGCCore::startUASManager() { // Load UAS plugins QDir pluginsDir = QDir(qApp->applicationDirPath()); #if defined(Q_OS_WIN) if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") pluginsDir.cdUp(); #elif defined(Q_OS_LINUX) if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") pluginsDir.cdUp(); #elif defined(Q_OS_MAC) if (pluginsDir.dirName() == "MacOS") { pluginsDir.cdUp(); pluginsDir.cdUp(); pluginsDir.cdUp(); } #endif pluginsDir.cd("plugins"); UASManager::instance(); // Load plugins QStringList pluginFileNames; foreach (QString fileName, pluginsDir.entryList(QDir::Files)) { QPluginLoader loader(pluginsDir.absoluteFilePath(fileName)); QObject *plugin = loader.instance(); if (plugin) { //populateMenus(plugin); pluginFileNames += fileName; //printf(QString("Loaded plugin from " + fileName + "\n").toStdString().c_str()); } } } <|endoftext|>
<commit_before>/************************************************************************************\ This source file is part of the KS(X) audio library * For latest info, see http://code.google.com/p/libxal/ * ************************************************************************************** Copyright (c) 2010 Kresimir Spes (kreso@cateia.com), Boris Mikic * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php * \************************************************************************************/ #include <hltypes/hstring.h> #include "Category.h" #include "Source.h" #include "SoundBuffer.h" #include "StreamSound.h" #include "AudioManager.h" #ifndef __APPLE__ #include <AL/al.h> #else #include <OpenAL/al.h> #endif namespace xal { /******* CONSTRUCT / DESTRUCT ******************************************/ Source::Source(SoundBuffer* sound) : Sound(), sourceId(0), gain(1.0f), looping(false), paused(false), fadeTime(0.0f), fadeSpeed(0.0f), bound(true) { this->sound = sound; } Source::~Source() { this->stop(); } /******* METHODS *******************************************************/ void Source::update(float k) { if (this->sourceId == 0) { return; } this->sound->setSourceId(this->sourceId); this->sound->update(k); if (this->isPlaying()) { if (this->isFading()) { this->fadeTime += this->fadeSpeed * k; if (this->fadeTime >= 1.0f && this->fadeSpeed > 0.0f) { alSourcef(this->sourceId, AL_GAIN, this->gain * this->sound->getCategory()->getGain() * xal::mgr->getGlobalGain()); this->fadeTime = 0.0f; this->fadeSpeed = 0.0f; } else if (this->fadeTime <= 0.0f && this->fadeSpeed < 0.0f) { this->paused ? this->pause() : this->stop(); this->fadeTime = 0.0f; this->fadeSpeed = 0.0f; } else { alSourcef(this->sourceId, AL_GAIN, this->fadeTime * this->gain * this->sound->getCategory()->getGain() * xal::mgr->getGlobalGain()); } } } if (!this->isPlaying() && !this->isPaused()) { this->unbind(); } } Sound* Source::play(float fadeTime, bool looping) { if (this->sourceId == 0) { this->sourceId = xal::mgr->allocateSourceId(); if (this->sourceId == 0) { return NULL; } } if (!this->paused) { this->looping = looping; } if (this->sound->getCategory()->isStreamed()) { this->sound->setSourceId(this->sourceId); ((StreamSound*)this->sound)->queueBuffers(); alSourcei(this->sourceId, AL_LOOPING, false); } else if (!this->isPaused()) { alSourcei(this->sourceId, AL_BUFFER, this->getBuffer()); alSourcei(this->sourceId, AL_LOOPING, this->looping); } if (this->isPaused()) { alSourcef(this->sourceId, AL_SEC_OFFSET, this->sampleOffset); } bool alreadyFading = this->isFading(); if (fadeTime > 0) { this->fadeSpeed = 1.0f / fadeTime; } else { this->fadeTime = 1.0f; this->fadeSpeed = 0.0f; } alSourcef(this->sourceId, AL_GAIN, this->fadeTime * this->gain * this->sound->getCategory()->getGain() * xal::mgr->getGlobalGain()); if (!alreadyFading) { alSourcePlay(this->sourceId); } this->paused = false; return this; } void Source::stop(float fadeTime) { this->_stop(fadeTime); } void Source::pause(float fadeTime) { this->_stop(fadeTime, true); } void Source::_stop(float fadeTime, bool pause) { if (this->sourceId == 0) { return; } if (fadeTime > 0) { this->fadeSpeed = -1.0f / fadeTime; } else { this->fadeTime = 0.0f; this->fadeSpeed = 0.0f; if (pause) { alGetSourcef(this->sourceId, AL_SEC_OFFSET, &this->sampleOffset); if (this->sound->getCategory()->isStreamed()) { alSourcePause(this->sourceId); this->sound->setSourceId(this->sourceId); ((StreamSound*)this->sound)->unqueueBuffers(); } else { alSourceStop(this->sourceId); } if (!this->isLocked()) { this->sourceId = 0; } } else { alSourceStop(this->sourceId); if (this->sound->getCategory()->isStreamed()) { this->sound->setSourceId(this->sourceId); ((StreamSound*)this->sound)->rewindStream(); } this->unbind(); } } this->paused = pause; } void Source::unbind() { if (!this->isLocked()) { this->sourceId = 0; this->bound = false; } } /******* PROPERTIES ****************************************************/ void Source::setGain(float gain) { this->gain = gain; if (this->sourceId != 0) { alSourcef(this->sourceId, AL_GAIN, this->gain * this->sound->getCategory()->getGain() * xal::mgr->getGlobalGain()); } } unsigned int Source::getBuffer() { return this->sound->getBuffer(); } bool Source::isPlaying() { if (this->sourceId == 0) { return false; } if (this->sound->getCategory()->isStreamed()) { return (!this->isPaused()); } int state; alGetSourcei(this->sourceId, AL_SOURCE_STATE, &state); return (state == AL_PLAYING); } bool Source::isPaused() { return (this->paused && !this->isFading()); } bool Source::isFading() { return (this->fadeSpeed != 0); } bool Source::isFadingIn() { return (this->fadeSpeed < 0); } bool Source::isFadingOut() { return (this->fadeSpeed < 0); } } <commit_msg>- fixed bug when fading in a sound would prevent a fade out later when pausing or stopping<commit_after>/************************************************************************************\ This source file is part of the KS(X) audio library * For latest info, see http://code.google.com/p/libxal/ * ************************************************************************************** Copyright (c) 2010 Kresimir Spes (kreso@cateia.com), Boris Mikic * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php * \************************************************************************************/ #include <hltypes/hstring.h> #include "Category.h" #include "Source.h" #include "SoundBuffer.h" #include "StreamSound.h" #include "AudioManager.h" #ifndef __APPLE__ #include <AL/al.h> #else #include <OpenAL/al.h> #endif namespace xal { /******* CONSTRUCT / DESTRUCT ******************************************/ Source::Source(SoundBuffer* sound) : Sound(), sourceId(0), gain(1.0f), looping(false), paused(false), fadeTime(0.0f), fadeSpeed(0.0f), bound(true) { this->sound = sound; } Source::~Source() { this->stop(); } /******* METHODS *******************************************************/ void Source::update(float k) { if (this->sourceId == 0) { return; } this->sound->setSourceId(this->sourceId); this->sound->update(k); if (this->isPlaying()) { if (this->isFading()) { this->fadeTime += this->fadeSpeed * k; if (this->fadeTime >= 1.0f && this->fadeSpeed > 0.0f) { alSourcef(this->sourceId, AL_GAIN, this->gain * this->sound->getCategory()->getGain() * xal::mgr->getGlobalGain()); this->fadeTime = 1.0f; this->fadeSpeed = 0.0f; } else if (this->fadeTime <= 0.0f && this->fadeSpeed < 0.0f) { this->paused ? this->pause() : this->stop(); this->fadeTime = 0.0f; this->fadeSpeed = 0.0f; } else { alSourcef(this->sourceId, AL_GAIN, this->fadeTime * this->gain * this->sound->getCategory()->getGain() * xal::mgr->getGlobalGain()); } } } if (!this->isPlaying() && !this->isPaused()) { this->unbind(); } } Sound* Source::play(float fadeTime, bool looping) { if (this->sourceId == 0) { this->sourceId = xal::mgr->allocateSourceId(); if (this->sourceId == 0) { return NULL; } } if (!this->paused) { this->looping = looping; } if (this->sound->getCategory()->isStreamed()) { this->sound->setSourceId(this->sourceId); ((StreamSound*)this->sound)->queueBuffers(); alSourcei(this->sourceId, AL_LOOPING, false); } else if (!this->isPaused()) { alSourcei(this->sourceId, AL_BUFFER, this->getBuffer()); alSourcei(this->sourceId, AL_LOOPING, this->looping); } if (this->isPaused()) { alSourcef(this->sourceId, AL_SEC_OFFSET, this->sampleOffset); } bool alreadyFading = this->isFading(); if (fadeTime > 0) { this->fadeSpeed = 1.0f / fadeTime; } else { this->fadeTime = 1.0f; this->fadeSpeed = 0.0f; } alSourcef(this->sourceId, AL_GAIN, this->fadeTime * this->gain * this->sound->getCategory()->getGain() * xal::mgr->getGlobalGain()); if (!alreadyFading) { alSourcePlay(this->sourceId); } this->paused = false; return this; } void Source::stop(float fadeTime) { this->_stop(fadeTime); } void Source::pause(float fadeTime) { this->_stop(fadeTime, true); } void Source::_stop(float fadeTime, bool pause) { if (this->sourceId == 0) { return; } if (fadeTime > 0) { this->fadeSpeed = -1.0f / fadeTime; } else { this->fadeTime = 0.0f; this->fadeSpeed = 0.0f; if (pause) { alGetSourcef(this->sourceId, AL_SEC_OFFSET, &this->sampleOffset); if (this->sound->getCategory()->isStreamed()) { alSourcePause(this->sourceId); this->sound->setSourceId(this->sourceId); ((StreamSound*)this->sound)->unqueueBuffers(); } else { alSourceStop(this->sourceId); } if (!this->isLocked()) { this->sourceId = 0; } } else { alSourceStop(this->sourceId); if (this->sound->getCategory()->isStreamed()) { this->sound->setSourceId(this->sourceId); ((StreamSound*)this->sound)->rewindStream(); } this->unbind(); } } this->paused = pause; } void Source::unbind() { if (!this->isLocked()) { this->sourceId = 0; this->bound = false; } } /******* PROPERTIES ****************************************************/ void Source::setGain(float gain) { this->gain = gain; if (this->sourceId != 0) { alSourcef(this->sourceId, AL_GAIN, this->gain * this->sound->getCategory()->getGain() * xal::mgr->getGlobalGain()); } } unsigned int Source::getBuffer() { return this->sound->getBuffer(); } bool Source::isPlaying() { if (this->sourceId == 0) { return false; } if (this->sound->getCategory()->isStreamed()) { return (!this->isPaused()); } int state; alGetSourcei(this->sourceId, AL_SOURCE_STATE, &state); return (state == AL_PLAYING); } bool Source::isPaused() { return (this->paused && !this->isFading()); } bool Source::isFading() { return (this->fadeSpeed != 0); } bool Source::isFadingIn() { return (this->fadeSpeed < 0); } bool Source::isFadingOut() { return (this->fadeSpeed < 0); } } <|endoftext|>
<commit_before>#include <utility> #include <stdexcept> #include <iostream> #include "Sqlite.h" #include "SqliteError.h" #include <cstring> #include "Log.h" Sqlite::Sqlite(Log &log) : log_(&log), sql_(nullptr) { } Sqlite::~Sqlite() { close(); } void Sqlite::open(const std::string &filename, bool readOnly) { close(); log_->info("Opening database ", filename, " in ", readOnly ? "read-only" : "read-write", " mode"); R(sqlite3_open_v2(filename.c_str(), &sql_, readOnly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nullptr)); R(sqlite3_extended_result_codes(sql_, true)); } void Sqlite::close() { if (sql_) { log_->info("Closing database"); sqlite3_close(sql_); } sql_ = nullptr; } void Sqlite::Statement::destroy() { if (statement_) sqlite3_finalize(statement_); statement_ = nullptr; } Sqlite::Statement Sqlite::prepare(const std::string &sql) const { Sqlite::Statement statement(*log_); log_->debug("Preparing statement ", sql); R(sqlite3_prepare_v2(sql_, sql.c_str(), sql.size(), &statement.statement_, nullptr), sql); return std::move(statement); } Sqlite::Statement::Statement(Statement &&other) { log_ = other.log_; statement_ = other.statement_; other.statement_ = nullptr; } Sqlite::Statement &Sqlite::Statement::operator=(Sqlite::Statement &&other) { if (this == &other) return *this; destroy(); log_ = other.log_; statement_ = other.statement_; other.statement_ = nullptr; return *this; } Sqlite::Statement &Sqlite::Statement::reset() { R(sqlite3_reset(statement_)); return *this; } bool Sqlite::Statement::step() { auto res = sqlite3_step(statement_); if (res == SQLITE_DONE) return true; if (res == SQLITE_ROW) return false; throw SqliteError(res); } Sqlite::Statement &Sqlite::Statement::bindBlob( StringView param, const void *data, size_t length) { R(sqlite3_bind_blob(statement_, P(param), data, length, SQLITE_TRANSIENT)); return *this; } Sqlite::Statement &Sqlite::Statement::bindInt64(StringView param, int64_t data) { R(sqlite3_bind_int64(statement_, P(param), data)); return *this; } Sqlite::Statement &Sqlite::Statement::bindString(StringView param, StringView data) { R(sqlite3_bind_text(statement_, P(param), data.begin(), data.length(), SQLITE_TRANSIENT)); return *this; } int64_t Sqlite::Statement::columnInt64(int index) const { return sqlite3_column_int64(statement_, index); } std::string Sqlite::Statement::columnString(int index) const { return (const char *)sqlite3_column_text(statement_, index); } int Sqlite::Statement::columnCount() const { return sqlite3_column_count(statement_); } std::string Sqlite::Statement::columnName(int index) const { return sqlite3_column_name(statement_, index); } int Sqlite::Statement::P(StringView param) const { std::string asStringStorage; auto index = sqlite3_bind_parameter_index(statement_, param.c_str(asStringStorage)); if (index == 0) throw std::runtime_error( "Unable to find bound parameter '" + param.str() + "'"); return index; } std::vector<uint8_t> Sqlite::Statement::columnBlob(int index) const { auto ptr = sqlite3_column_blob(statement_, index); std::vector<uint8_t> data(sqlite3_column_bytes(statement_, index)); std::memcpy(&data[0], ptr, data.size()); return data; } void Sqlite::exec(const std::string &sql) { log_->debug("Executing ", sql); R(sqlite3_exec(sql_, sql.c_str(), nullptr, nullptr, nullptr), sql); } void Sqlite::R(int result) const { if (result != SQLITE_OK) throw SqliteError(sqlite3_errmsg(sql_)); } void Sqlite::R(int result, const std::string &context) const { if (result != SQLITE_OK) throw SqliteError(sqlite3_errmsg(sql_), context); } void Sqlite::Statement::R(int result) const { if (result != SQLITE_OK) throw SqliteError(sqlite3_errmsg(sqlite3_db_handle(statement_))); } <commit_msg>Another redundant move (thanks clang!)<commit_after>#include <utility> #include <stdexcept> #include <iostream> #include "Sqlite.h" #include "SqliteError.h" #include <cstring> #include "Log.h" Sqlite::Sqlite(Log &log) : log_(&log), sql_(nullptr) { } Sqlite::~Sqlite() { close(); } void Sqlite::open(const std::string &filename, bool readOnly) { close(); log_->info("Opening database ", filename, " in ", readOnly ? "read-only" : "read-write", " mode"); R(sqlite3_open_v2(filename.c_str(), &sql_, readOnly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nullptr)); R(sqlite3_extended_result_codes(sql_, true)); } void Sqlite::close() { if (sql_) { log_->info("Closing database"); sqlite3_close(sql_); } sql_ = nullptr; } void Sqlite::Statement::destroy() { if (statement_) sqlite3_finalize(statement_); statement_ = nullptr; } Sqlite::Statement Sqlite::prepare(const std::string &sql) const { Sqlite::Statement statement(*log_); log_->debug("Preparing statement ", sql); R(sqlite3_prepare_v2(sql_, sql.c_str(), sql.size(), &statement.statement_, nullptr), sql); return statement; } Sqlite::Statement::Statement(Statement &&other) { log_ = other.log_; statement_ = other.statement_; other.statement_ = nullptr; } Sqlite::Statement &Sqlite::Statement::operator=(Sqlite::Statement &&other) { if (this == &other) return *this; destroy(); log_ = other.log_; statement_ = other.statement_; other.statement_ = nullptr; return *this; } Sqlite::Statement &Sqlite::Statement::reset() { R(sqlite3_reset(statement_)); return *this; } bool Sqlite::Statement::step() { auto res = sqlite3_step(statement_); if (res == SQLITE_DONE) return true; if (res == SQLITE_ROW) return false; throw SqliteError(res); } Sqlite::Statement &Sqlite::Statement::bindBlob( StringView param, const void *data, size_t length) { R(sqlite3_bind_blob(statement_, P(param), data, length, SQLITE_TRANSIENT)); return *this; } Sqlite::Statement &Sqlite::Statement::bindInt64(StringView param, int64_t data) { R(sqlite3_bind_int64(statement_, P(param), data)); return *this; } Sqlite::Statement &Sqlite::Statement::bindString(StringView param, StringView data) { R(sqlite3_bind_text(statement_, P(param), data.begin(), data.length(), SQLITE_TRANSIENT)); return *this; } int64_t Sqlite::Statement::columnInt64(int index) const { return sqlite3_column_int64(statement_, index); } std::string Sqlite::Statement::columnString(int index) const { return (const char *)sqlite3_column_text(statement_, index); } int Sqlite::Statement::columnCount() const { return sqlite3_column_count(statement_); } std::string Sqlite::Statement::columnName(int index) const { return sqlite3_column_name(statement_, index); } int Sqlite::Statement::P(StringView param) const { std::string asStringStorage; auto index = sqlite3_bind_parameter_index(statement_, param.c_str(asStringStorage)); if (index == 0) throw std::runtime_error( "Unable to find bound parameter '" + param.str() + "'"); return index; } std::vector<uint8_t> Sqlite::Statement::columnBlob(int index) const { auto ptr = sqlite3_column_blob(statement_, index); std::vector<uint8_t> data(sqlite3_column_bytes(statement_, index)); std::memcpy(&data[0], ptr, data.size()); return data; } void Sqlite::exec(const std::string &sql) { log_->debug("Executing ", sql); R(sqlite3_exec(sql_, sql.c_str(), nullptr, nullptr, nullptr), sql); } void Sqlite::R(int result) const { if (result != SQLITE_OK) throw SqliteError(sqlite3_errmsg(sql_)); } void Sqlite::R(int result, const std::string &context) const { if (result != SQLITE_OK) throw SqliteError(sqlite3_errmsg(sql_), context); } void Sqlite::Statement::R(int result) const { if (result != SQLITE_OK) throw SqliteError(sqlite3_errmsg(sqlite3_db_handle(statement_))); } <|endoftext|>
<commit_before> #include <libclientserver.h> /** * SplitOne * @param[in] str The source string * @param[out] left This will be the value left of the deliminator * @param[out] right This will be the value right of the deliminator * @param[in] delim the value to split on * @return will return true if the operation succeeds. * * This function can fail if the deliminator is not in the string. * This function will also remvoe the deliminator from the output strings. * */ bool String::SplitOne(const std::string *str, std::string *left, std::string *right, const std::string delim) { size_t position = str->find_first_of(delim); if (position == std::string::npos) return false; *left = str->substr(0, position); *right = str->substr(position + 1, str->length() - position - 1); return true; } /** * Split * @param[in] str The source string * @param[in] delim the value to split on * @param[out] lst the output list if items found * @return will return true if the operation succeeds. * * This function can fail if the deliminator is not in the string. * This function will also remvoe the deliminator from the output strings. * * If the function fails or cannot find any occurances of the delimineter then an empty list * will be returned * */ bool String::Split(const std::string *str, const std::string delim, std::list<std::string> *lst) { size_t position = str->find_first_of(delim); lst->clear(); if (position == std::string::npos) return false; std::string left = str->substr(0, position); std::string right = str->substr(position + 1, str->length() - position - 1); while(true) { lst->push_back(left); size_t position = right.find_first_of(delim); if (position == std::string::npos) { lst->push_back(right); return true; } left = right.substr(0, position); right = right.substr(position + 1, right.length() - position - 1); } return true; } /** * Split * @param[in] str The source string * @param[in] delim1 the outer value to split on * @param[in] delim2 the inner value to split on * @param[out] lst the output list if items found * @return will return true if the operation succeeds. * * This function can fail if the deliminator is not in the outer string. * This function will also fail if the deliminator is not in the inner string. * This functions will also fail if it produced a duplucate map value; * * Example: Split("HELLO=WORLD IT=WORKS", " ", "=", map); * */ bool String::Split(const std::string *str, const std::string delim1, const std::string delim2, std::map<std::string, std::string> *map) { std::list<std::string> lst; map->clear(); if (Split(str, delim1, &lst) == false) return false; std::list<std::string>::iterator it = lst.begin(); while(it != lst.end()) { std::string innerstr = *it; std::string left; std::string right; if (SplitOne(&innerstr, &left, &right, delim2) == false) return false; //Find a duplicate if (map->find(left) != map->end()) return false; map->insert( std::pair<std::string, std::string>(left, right)); it++; } return true; } /** * Split * @param[in] str The source string * @param[in] delim the value to split on * @param[out] lst the output list if items found * @return will return true if the operation succeeds. * * This function can fail if the deliminator is not in the string. * This function will also remvoe the deliminator from the output strings. * * If the function fails or cannot find any occurances of the delimineter then an empty list * will be returned */ bool String::Split(const std::string *str, const std::string delim, std::vector<std::string> *lst) { size_t position = str->find_first_of(delim); lst->clear(); if (position == std::string::npos) return false; std::string left = str->substr(0, position); std::string right = str->substr(position + 1, str->length() - position - 1); while(true) { lst->push_back(left); size_t position = right.find_first_of(delim); if (position == std::string::npos) { lst->push_back(right); return true; } left = right.substr(0, position); right = right.substr(position + 1, right.length() - position - 1); } return true; } /** * Join * @param[in] vec A vector of string * @param[in] delim the value to join with * @return the output string * * This function will join string together seperated by the delim paramater. */ std::string String::Join(const std::vector<std::string> *vec, const std::string &delim) { std::vector<std::string>::const_iterator it = vec->begin(); std::string str = ""; while(it != vec->end()) { str += *it; it++; if (it != vec->end()) str += delim; } return str; } /** * Join * @param[in] lst A list of strings * @param[in] delim the value to join with * @return The output string * * This function will join string together seperated by the delim paramater. */ std::string String::Join(const std::list<std::string> *lst, const std::string &delim) { std::list<std::string>::const_iterator it = lst->begin(); std::string str = ""; while(it != lst->end()) { str += *it; it++; if (it != lst->end()) str += delim; } return str; } /** * Join * @param[in] lst A list of strings * @param[in] delim1 the value to join with * @param[in] delim2 the value to join with * @return The output string * * This function will join together a map<std::string, std::string> to the format of Key<delim2>Pair<delim1>Key<delim2>Pair */ std::string String::Join(const std::map<std::string, std::string> *map, const std::string &delim1, const std::string &delim2) { std::map<std::string, std::string>::const_iterator it = map->begin(); std::string str = ""; while(it != map->end()) { str += it->first; str += delim2; str += it->second; it++; if (it != map->end()) str += delim1; } return str; } <commit_msg>Fixed issue where Splitting to a map would ignore a single entry<commit_after> #include <libclientserver.h> /** * SplitOne * @param[in] str The source string * @param[out] left This will be the value left of the deliminator * @param[out] right This will be the value right of the deliminator * @param[in] delim the value to split on * @return will return true if the operation succeeds. * * This function can fail if the deliminator is not in the string. * This function will also remvoe the deliminator from the output strings. * */ bool String::SplitOne(const std::string *str, std::string *left, std::string *right, const std::string delim) { size_t position = str->find_first_of(delim); if (position == std::string::npos) return false; *left = str->substr(0, position); *right = str->substr(position + 1, str->length() - position - 1); return true; } /** * Split * @param[in] str The source string * @param[in] delim the value to split on * @param[out] lst the output list if items found * @return will return true if the operation succeeds. * * This function can fail if the deliminator is not in the string. * This function will also remvoe the deliminator from the output strings. * * If the function fails or cannot find any occurances of the delimineter then an empty list * will be returned * */ bool String::Split(const std::string *str, const std::string delim, std::list<std::string> *lst) { size_t position = str->find_first_of(delim); lst->clear(); if (position == std::string::npos) return false; std::string left = str->substr(0, position); std::string right = str->substr(position + 1, str->length() - position - 1); while(true) { lst->push_back(left); size_t position = right.find_first_of(delim); if (position == std::string::npos) { lst->push_back(right); return true; } left = right.substr(0, position); right = right.substr(position + 1, right.length() - position - 1); } return true; } /** * Split * @param[in] str The source string * @param[in] delim1 the outer value to split on * @param[in] delim2 the inner value to split on * @param[out] lst the output list if items found * @return will return true if the operation succeeds. * * This function can fail if the deliminator is not in the outer string. * This function will also fail if the deliminator is not in the inner string. * This functions will also fail if it produced a duplucate map value; * * Example: Split("HELLO=WORLD IT=WORKS", " ", "=", map); * */ bool String::Split(const std::string *str, const std::string delim1, const std::string delim2, std::map<std::string, std::string> *map) { std::list<std::string> lst; map->clear(); if (Split(str, delim1, &lst) == false) { lst.push_back(*str); //We may only have a single item } std::list<std::string>::iterator it = lst.begin(); while(it != lst.end()) { std::string innerstr = *it; std::string left; std::string right; if (SplitOne(&innerstr, &left, &right, delim2) == false) { return false; } //Find a duplicate if (map->find(left) != map->end()) return false; map->insert( std::pair<std::string, std::string>(left, right)); it++; } return true; } /** * Split * @param[in] str The source string * @param[in] delim the value to split on * @param[out] lst the output list if items found * @return will return true if the operation succeeds. * * This function can fail if the deliminator is not in the string. * This function will also remvoe the deliminator from the output strings. * * If the function fails or cannot find any occurances of the delimineter then an empty list * will be returned */ bool String::Split(const std::string *str, const std::string delim, std::vector<std::string> *lst) { size_t position = str->find_first_of(delim); lst->clear(); if (position == std::string::npos) return false; std::string left = str->substr(0, position); std::string right = str->substr(position + 1, str->length() - position - 1); while(true) { lst->push_back(left); size_t position = right.find_first_of(delim); if (position == std::string::npos) { lst->push_back(right); return true; } left = right.substr(0, position); right = right.substr(position + 1, right.length() - position - 1); } return true; } /** * Join * @param[in] vec A vector of string * @param[in] delim the value to join with * @return the output string * * This function will join string together seperated by the delim paramater. */ std::string String::Join(const std::vector<std::string> *vec, const std::string &delim) { std::vector<std::string>::const_iterator it = vec->begin(); std::string str = ""; while(it != vec->end()) { str += *it; it++; if (it != vec->end()) str += delim; } return str; } /** * Join * @param[in] lst A list of strings * @param[in] delim the value to join with * @return The output string * * This function will join string together seperated by the delim paramater. */ std::string String::Join(const std::list<std::string> *lst, const std::string &delim) { std::list<std::string>::const_iterator it = lst->begin(); std::string str = ""; while(it != lst->end()) { str += *it; it++; if (it != lst->end()) str += delim; } return str; } /** * Join * @param[in] lst A list of strings * @param[in] delim1 the value to join with * @param[in] delim2 the value to join with * @return The output string * * This function will join together a map<std::string, std::string> to the format of Key<delim2>Pair<delim1>Key<delim2>Pair */ std::string String::Join(const std::map<std::string, std::string> *map, const std::string &delim1, const std::string &delim2) { std::map<std::string, std::string>::const_iterator it = map->begin(); std::string str = ""; while(it != map->end()) { str += it->first; str += delim2; str += it->second; it++; if (it != map->end()) str += delim1; } return str; } <|endoftext|>
<commit_before><commit_msg>Revert "Fix issue with ROOT6 when merging with the alien plugin"<commit_after><|endoftext|>
<commit_before><commit_msg>Skip custom pile-up tagging in AOD filtering if available<commit_after><|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 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) { QualType DeclType = QualType::ReadVal(D); FieldDecl* decl = new FieldDecl(SourceLocation(),NULL,DeclType); 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>Added serialization of Union decls.<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(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) { QualType DeclType = QualType::ReadVal(D); FieldDecl* decl = new FieldDecl(SourceLocation(),NULL,DeclType); 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>#include "chromium_media_lib/resource_multibuffer.h" #include "base/lazy_instance.h" #include "net/http/http_response_headers.h" #include "net/proxy/proxy_config_service_fixed.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_response_writer.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_context_getter.h" namespace media { static int kMaxWaitForReaderOffset = 512 * 1024; // 512 kb static const int kHttpPartialContent = 206; struct RequestContextInitializer { RequestContextInitializer() { net::URLRequestContextBuilder builder; builder.set_data_enabled(true); builder.set_file_enabled(true); builder.set_proxy_config_service(base::WrapUnique( new net::ProxyConfigServiceFixed(net::ProxyConfig::CreateDirect()))); url_request_context_ = builder.Build(); } ~RequestContextInitializer() {} net::URLRequestContext* request_context() { return url_request_context_.get(); } std::unique_ptr<net::URLRequestContext> url_request_context_; }; class URLFetcherResponseWriterBridge : public net::URLFetcherResponseWriter { public: URLFetcherResponseWriterBridge(ResourceMultiBuffer* buffer) : buffer_(buffer) {} ~URLFetcherResponseWriterBridge() override {} int Initialize(const net::CompletionCallback& callback) override { buffer_->DidInitialize(); return 0; } int Write(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) override { return buffer_->OnWrite(buffer, num_bytes, callback); } int Finish(int net_error, const net::CompletionCallback& callback) override { buffer_->OnFinish(net_error, callback); return 0; } private: ResourceMultiBuffer* buffer_; }; static base::LazyInstance<RequestContextInitializer>::Leaky g_request_context_init = LAZY_INSTANCE_INITIALIZER; ResourceMultiBuffer::ResourceMultiBuffer( ResourceMultiBufferClient* client, const GURL& url, int32_t block_size_shift, const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner) : url_(url), io_task_runner_(io_task_runner), write_start_pos_(0), write_offset_(0), total_bytes_(-1), client_(client), block_size_shift_(block_size_shift) {} ResourceMultiBuffer::~ResourceMultiBuffer() {} void ResourceMultiBuffer::Start() { DCHECK(!fetcher_); if (!io_task_runner_->BelongsToCurrentThread()) { io_task_runner_->PostTask(FROM_HERE, base::Bind(&ResourceMultiBuffer::Start, base::Unretained(this))); return; } base::AutoLock auto_lock(lock_); CreateFetcherFrom(0); } MultiBufferBlockId ResourceMultiBuffer::ToBlockId(int position) { return position >> block_size_shift_; } int64_t ResourceMultiBuffer::GetSize() { base::AutoLock auto_lock(lock_); if (!fetcher_) return -1; return total_bytes_; } void ResourceMultiBuffer::Seek(int position) { base::AutoLock auto_lock(lock_); if (position < write_start_pos_ || position - kMaxWaitForReaderOffset > write_start_pos_ + write_offset_) { CreateFetcherFrom(position); } // otherwise it is ok to acces data or wait data received } int ResourceMultiBuffer::Fill(int position, int size, void* data) { base::AutoLock auto_lock(lock_); MultiBufferBlockId id = ToBlockId(position); const int buffer_size = 1 << block_size_shift_; auto it = cache_.upper_bound(id); DCHECK(it == cache_.end() || (it->first << block_size_shift_) > position); if (it == cache_.begin()) { return net::ERR_IO_PENDING; } --it; int write_bytes = 0; int index = it->first; DCHECK_LE(it->first << block_size_shift_, position); while (it != cache_.end() && size > 0 && ((it->first << block_size_shift_) + it->second->data_size() >= position) && index == it->first) { // copy buffer const int start_position = position - (it->first << block_size_shift_); const int remain_size = std::min(it->second->data_size() - start_position, size); DCHECK(remain_size >= 0); uint8_t* p = (uint8_t*)data + write_bytes; memcpy(p, it->second->data() + start_position, remain_size); size -= remain_size; position += remain_size; write_bytes += remain_size; // the buffer is not full, so need to wait until ready. if (it->second->data_size() != buffer_size) break; ++it; ++index; } return write_bytes > 0 ? write_bytes : net::ERR_IO_PENDING; } void ResourceMultiBuffer::OnURLFetchComplete(const net::URLFetcher* source) { LOG(INFO) << "OnURLFetchComplete source=" << source << " fetcher_=" << fetcher_.get(); } void ResourceMultiBuffer::DidInitialize() { client_->DidInitialize(); } int ResourceMultiBuffer::OnWrite(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) { DCHECK(io_task_runner_->BelongsToCurrentThread()); // int written = net::ERR_ABORTED; // http 2XX int written_bytes = num_bytes; LOG(INFO) << "write_offset=" << write_offset_ << " num_bytes=" << num_bytes; { base::AutoLock auto_lock(lock_); bool partial_response = fetcher_->GetResponseCode() == kHttpPartialContent; if (fetcher_->GetResponseCode() / 100 == 2) { if (partial_response) { net::HttpResponseHeaders* headers = fetcher_->GetResponseHeaders(); int64_t first_byte_pos, last_byte_pos, instance_length; bool success = headers->GetContentRangeFor206( &first_byte_pos, &last_byte_pos, &instance_length); if (success) total_bytes_ = instance_length; } else { total_bytes_ = fetcher_->GetReceivedResponseContentLength(); } MultiBufferBlockId id = ToBlockId(write_start_pos_ + write_offset_); const int buffer_size = 1 << block_size_shift_; char* read_data = buffer->data(); while (num_bytes > 0) { scoped_refptr<DataBuffer> entry; auto found = cache_.find(id); if (found == cache_.end()) { entry = new DataBuffer(buffer_size); cache_[id] = entry; } else { entry = found->second; } int write_start = entry->data_size(); int remain_size = std::min(buffer_size - write_start, num_bytes); memcpy(entry->writable_data() + write_start, read_data, remain_size); entry->set_data_size(write_start + remain_size); LOG(INFO) << "id=" << id << " data_size=" << (write_start + remain_size); read_data += remain_size; write_offset_ += remain_size; num_bytes -= remain_size; id++; } } } // client_->OnUpdateState(); return written_bytes; } int ResourceMultiBuffer::OnFinish(int net_error, const net::CompletionCallback& callback) { LOG(INFO) << "ResourceDataSource::OnFinish error=" << net_error; client_->OnUpdateState(); return 0; } void ResourceMultiBuffer::CreateFetcherFrom(int position) { fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::GET, this); fetcher_->SetRequestContext(new net::TrivialURLRequestContextGetter( g_request_context_init.Pointer()->request_context(), io_task_runner_)); std::unique_ptr<net::URLFetcherResponseWriter> response_writer = base::MakeUnique<URLFetcherResponseWriterBridge>(this); fetcher_->SetExtraRequestHeaders( "Accept-Encoding: identity;q=1, *;q=0\r\nUser-Agent:Mozilla/5.0 (X11; " "Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/59.0.3071.115 Safari/537.36\r\n"); fetcher_->SaveResponseWithWriter(std::move(response_writer)); std::stringstream range_header; write_start_pos_ = position; write_offset_ = 0; range_header << "Range: " << "bytes=" << position << "-"; LOG(INFO) << "CreateFetcherFrom range=" << range_header.str(); fetcher_->AddExtraRequestHeader(range_header.str()); fetcher_->Start(); } } // namespace media <commit_msg>Create new url fetcher if cache miss and the current fetcher already fetch it.<commit_after>#include "chromium_media_lib/resource_multibuffer.h" #include "base/lazy_instance.h" #include "net/http/http_response_headers.h" #include "net/proxy/proxy_config_service_fixed.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_response_writer.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_context_getter.h" namespace media { static int kMaxWaitForReaderOffset = 512 * 1024; // 512 kb static const int kHttpPartialContent = 206; struct RequestContextInitializer { RequestContextInitializer() { net::URLRequestContextBuilder builder; builder.set_data_enabled(true); builder.set_file_enabled(true); builder.set_proxy_config_service(base::WrapUnique( new net::ProxyConfigServiceFixed(net::ProxyConfig::CreateDirect()))); url_request_context_ = builder.Build(); } ~RequestContextInitializer() {} net::URLRequestContext* request_context() { return url_request_context_.get(); } std::unique_ptr<net::URLRequestContext> url_request_context_; }; class URLFetcherResponseWriterBridge : public net::URLFetcherResponseWriter { public: URLFetcherResponseWriterBridge(ResourceMultiBuffer* buffer) : buffer_(buffer) {} ~URLFetcherResponseWriterBridge() override {} int Initialize(const net::CompletionCallback& callback) override { buffer_->DidInitialize(); return 0; } int Write(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) override { return buffer_->OnWrite(buffer, num_bytes, callback); } int Finish(int net_error, const net::CompletionCallback& callback) override { buffer_->OnFinish(net_error, callback); return 0; } private: ResourceMultiBuffer* buffer_; }; static base::LazyInstance<RequestContextInitializer>::Leaky g_request_context_init = LAZY_INSTANCE_INITIALIZER; ResourceMultiBuffer::ResourceMultiBuffer( ResourceMultiBufferClient* client, const GURL& url, int32_t block_size_shift, const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner) : url_(url), io_task_runner_(io_task_runner), write_start_pos_(0), write_offset_(0), total_bytes_(-1), client_(client), block_size_shift_(block_size_shift) {} ResourceMultiBuffer::~ResourceMultiBuffer() {} void ResourceMultiBuffer::Start() { DCHECK(!fetcher_); if (!io_task_runner_->BelongsToCurrentThread()) { io_task_runner_->PostTask(FROM_HERE, base::Bind(&ResourceMultiBuffer::Start, base::Unretained(this))); return; } base::AutoLock auto_lock(lock_); CreateFetcherFrom(0); } MultiBufferBlockId ResourceMultiBuffer::ToBlockId(int position) { return position >> block_size_shift_; } int64_t ResourceMultiBuffer::GetSize() { base::AutoLock auto_lock(lock_); if (!fetcher_) return -1; return total_bytes_; } bool ResourceMultiBuffer::CheckCacheMiss(int position) { MultiBufferBlockId id = ToBlockId(position); auto i = cache_.upper_bound(id); bool write_behind = write_start_pos_ + write_offset_ > position; // the writer write entry is being purged if (!write_behind) return false; if (i == cache_.begin()) return true; --i; bool no_cache_entry = !((i->first << block_size_shift_) + i->second->data_size() > position); return no_cache_entry && write_behind; } void ResourceMultiBuffer::Seek(int position) { base::AutoLock auto_lock(lock_); int current_write_pos = write_start_pos_ + write_offset_; MultiBufferBlockId id = ToBlockId(position); if (position < write_start_pos_ || position - kMaxWaitForReaderOffset > current_write_pos || CheckCacheMiss(position)) { id = std::max(id - 1, 0); write_start_pos_ = id << block_size_shift_; write_offset_ = 0; CreateFetcherFrom(write_start_pos_); } // otherwise it is ok to acces data or wait data received } int ResourceMultiBuffer::Fill(int position, int size, void* data) { base::AutoLock auto_lock(lock_); MultiBufferBlockId id = ToBlockId(position); const int buffer_size = 1 << block_size_shift_; auto it = cache_.upper_bound(id); DCHECK(it == cache_.end() || (it->first << block_size_shift_) > position); if (it == cache_.begin()) { return net::ERR_IO_PENDING; } --it; int write_bytes = 0; int index = it->first; DCHECK_LE(it->first << block_size_shift_, position); while (it != cache_.end() && size > 0 && ((it->first << block_size_shift_) + it->second->data_size() >= position) && index == it->first) { // copy buffer const int start_position = position - (it->first << block_size_shift_); const int remain_size = std::min(it->second->data_size() - start_position, size); DCHECK(remain_size >= 0); uint8_t* p = (uint8_t*)data + write_bytes; memcpy(p, it->second->data() + start_position, remain_size); size -= remain_size; position += remain_size; write_bytes += remain_size; // the buffer is not full, so need to wait until ready. if (it->second->data_size() != buffer_size) break; ++it; ++index; } return write_bytes > 0 ? write_bytes : net::ERR_IO_PENDING; } void ResourceMultiBuffer::OnURLFetchComplete(const net::URLFetcher* source) { LOG(INFO) << "OnURLFetchComplete source=" << source << " fetcher_=" << fetcher_.get(); } void ResourceMultiBuffer::DidInitialize() { client_->DidInitialize(); } int ResourceMultiBuffer::OnWrite(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) { DCHECK(io_task_runner_->BelongsToCurrentThread()); // int written = net::ERR_ABORTED; // http 2XX int written_bytes = num_bytes; LOG(INFO) << "write_offset=" << write_offset_ << " num_bytes=" << num_bytes; { base::AutoLock auto_lock(lock_); bool partial_response = fetcher_->GetResponseCode() == kHttpPartialContent; if (fetcher_->GetResponseCode() / 100 == 2) { if (partial_response) { net::HttpResponseHeaders* headers = fetcher_->GetResponseHeaders(); int64_t first_byte_pos, last_byte_pos, instance_length; bool success = headers->GetContentRangeFor206( &first_byte_pos, &last_byte_pos, &instance_length); if (success) total_bytes_ = instance_length; } else { total_bytes_ = fetcher_->GetReceivedResponseContentLength(); } MultiBufferBlockId id = ToBlockId(write_start_pos_ + write_offset_); const int buffer_size = 1 << block_size_shift_; char* read_data = buffer->data(); while (num_bytes > 0) { scoped_refptr<DataBuffer> entry; auto found = cache_.find(id); if (found == cache_.end()) { entry = new DataBuffer(buffer_size); cache_[id] = entry; } else { entry = found->second; } int write_start = entry->data_size(); int remain_size = std::min(buffer_size - write_start, num_bytes); memcpy(entry->writable_data() + write_start, read_data, remain_size); entry->set_data_size(write_start + remain_size); LOG(INFO) << "id=" << id << " data_size=" << (write_start + remain_size); read_data += remain_size; write_offset_ += remain_size; num_bytes -= remain_size; id++; } } } // client_->OnUpdateState(); return written_bytes; } int ResourceMultiBuffer::OnFinish(int net_error, const net::CompletionCallback& callback) { LOG(INFO) << "ResourceDataSource::OnFinish error=" << net_error; client_->OnUpdateState(); return 0; } void ResourceMultiBuffer::CreateFetcherFrom(int position) { fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::GET, this); fetcher_->SetRequestContext(new net::TrivialURLRequestContextGetter( g_request_context_init.Pointer()->request_context(), io_task_runner_)); std::unique_ptr<net::URLFetcherResponseWriter> response_writer = base::MakeUnique<URLFetcherResponseWriterBridge>(this); fetcher_->SetExtraRequestHeaders( "Accept-Encoding: identity;q=1, *;q=0\r\nUser-Agent:Mozilla/5.0 (X11; " "Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/59.0.3071.115 Safari/537.36\r\n"); fetcher_->SaveResponseWithWriter(std::move(response_writer)); std::stringstream range_header; write_start_pos_ = position; write_offset_ = 0; range_header << "Range: " << "bytes=" << position << "-"; LOG(INFO) << "CreateFetcherFrom range=" << range_header.str(); fetcher_->AddExtraRequestHeader(range_header.str()); fetcher_->Start(); } } // namespace media <|endoftext|>
<commit_before>/** * Copyright (C) 2013 Regents of the University of California. * @author: Jeff Thompson <jefft0@remap.ucla.edu> * See COPYING for copyright and distribution information. */ #ifndef NDN_DATA_HPP #define NDN_DATA_HPP #include "common.hpp" #include "name.hpp" #include "util/signed-blob.hpp" #include "c/data.h" namespace ndn { /** * A Signature is an abstract base class providing methods to work with the signature information in a Data packet. */ class Signature { public: /** * Return a pointer to a new Signature which is a copy of this signature. * This is pure virtual, the subclass must implement it. */ virtual ptr_lib::shared_ptr<Signature> clone() const = 0; /** * The virtual destructor. */ virtual ~Signature(); /** * Set the signatureStruct to point to the values in this signature object, without copying any memory. * WARNING: The resulting pointers in signatureStruct are invalid after a further use of this object which could reallocate memory. * This is pure virtual, the subclass must implement it. * @param signatureStruct a C ndn_Signature struct where the name components array is already allocated. */ virtual void get(struct ndn_Signature& signatureStruct) const = 0; /** * Clear this signature, and set the values by copying from the ndn_Signature struct. * This is pure virtual, the subclass must implement it. * @param signatureStruct a C ndn_Signature struct */ virtual void set(const struct ndn_Signature& signatureStruct) = 0; }; /** * An MetaInfo holds the meta info which is signed inside the data packet. */ class MetaInfo { public: MetaInfo() { type_ = ndn_ContentType_DATA; freshnessSeconds_ = -1; } /** * Set the metaInfoStruct to point to the values in this meta info object, without copying any memory. * WARNING: The resulting pointers in metaInfoStruct are invalid after a further use of this object which could reallocate memory. * @param metaInfoStruct a C ndn_MetaInfo struct where the name components array is already allocated. */ void get(struct ndn_MetaInfo& metaInfoStruct) const; /** * Clear this meta info, and set the values by copying from the ndn_MetaInfo struct. * @param metaInfoStruct a C ndn_MetaInfo struct */ void set(const struct ndn_MetaInfo& metaInfoStruct); double getTimestampMilliseconds() const { return timestampMilliseconds_; } ndn_ContentType getType() const { return type_; } int getFreshnessSeconds() const { return freshnessSeconds_; } const Name::Component& getFinalBlockID() const { return finalBlockID_; } void setTimestampMilliseconds(double timestampMilliseconds) { timestampMilliseconds_ = timestampMilliseconds; } void setType(ndn_ContentType type) { type_ = type; } void setFreshnessSeconds(int freshnessSeconds) { freshnessSeconds_ = freshnessSeconds; } void setFinalBlockID(const std::vector<uint8_t>& finalBlockID) { finalBlockID_ = Name::Component(finalBlockID); } void setFinalBlockID(const uint8_t* finalBlockID, size_t finalBlockIdLength) { finalBlockID_ = Name::Component(finalBlockID, finalBlockIdLength); } private: double timestampMilliseconds_; /**< milliseconds since 1/1/1970. -1 for none */ ndn_ContentType type_; /**< default is ndn_ContentType_DATA. -1 for none */ int freshnessSeconds_; /**< -1 for none */ Name::Component finalBlockID_; /** size 0 for none */ }; class Data { public: /** * Create a new Data object with default values and where the signature is a blank Sha256WithRsaSignature. */ Data(); /** * Create a new Data object with the given name and default values and where the signature is a blank Sha256WithRsaSignature. * @param name A reference to the name which is copied. */ Data(const Name& name); /** * Encode this Data for a particular wire format. Also, set the wireEncoding field to the encoded result. * This is not const because it updates the wireEncoding. * @param wireFormat A WireFormat object used to encode the input. If omitted, use WireFormat getDefaultWireFormat(). * @return The encoded byte array. */ SignedBlob wireEncode(WireFormat& wireFormat = *WireFormat::getDefaultWireFormat()); /** * Decode the input using a particular wire format and update this Data. Also, set the wireEncoding field to the input. * @param input The input byte array to be decoded. * @param inputLength The length of input. * @param wireFormat A WireFormat object used to decode the input. If omitted, use WireFormat getDefaultWireFormat(). */ void wireDecode(const uint8_t* input, size_t inputLength, WireFormat& wireFormat = *WireFormat::getDefaultWireFormat()); /** * Decode the input using a particular wire format and update this Data. Also, set the wireEncoding field to the input. * @param input The input byte array to be decoded. * @param wireFormat A WireFormat object used to decode the input. If omitted, use WireFormat getDefaultWireFormat(). */ void wireDecode(const std::vector<uint8_t>& input, WireFormat& wireFormat = *WireFormat::getDefaultWireFormat()) { wireDecode(&input[0], input.size(), wireFormat); } /** * Set the dataStruct to point to the values in this interest, without copying any memory. * WARNING: The resulting pointers in dataStruct are invalid after a further use of this object which could reallocate memory. * @param dataStruct a C ndn_Data struct where the name components array is already allocated. */ void get(struct ndn_Data& dataStruct) const; /** * Clear this data object, and set the values by copying from the ndn_Data struct. * @param dataStruct a C ndn_Data struct */ void set(const struct ndn_Data& dataStruct); const Signature* getSignature() const { return signature_.get(); } Signature* getSignature() { // TODO: Should add an OnChanged listener instead of always calling onChanged. onChanged(); return signature_.get(); } const Name& getName() const { return name_; } Name& getName() { // TODO: Should add an OnChanged listener instead of always calling onChanged. onChanged(); return name_; } const MetaInfo& getMetaInfo() const { return metaInfo_; } MetaInfo& getMetaInfo() { // TODO: Should add an OnChanged listener instead of always calling onChanged. onChanged(); return metaInfo_; } const Blob& getContent() const { return content_; } /** * Return a pointer to the wireEncoding. It may be null. */ const SignedBlob& getWireEncoding() const { return wireEncoding_; } /** * Set the signature to a copy of the given signature. * @param signature The signature object which is cloned. */ void setSignature(const Signature& signature) { signature_ = signature.clone(); onChanged(); } /** * Set name to a copy of the given Name. * @param name The Name which is copied. */ void setName(const Name& name) { name_ = name; onChanged(); } /** * Set metaInfo to a copy of the given MetaInfo. * @param metaInfo The MetaInfo which is copied. */ void setMetainfo(const MetaInfo& metaInfo) { metaInfo_ = metaInfo; onChanged(); } /** * Set the content to a copy of the data in the vector. * @param content A vector whose contents are copied. */ void setContent(const std::vector<uint8_t>& content) { content_ = content; onChanged(); } void setContent(const uint8_t* content, size_t contentLength) { content_ = Blob(content, contentLength); onChanged(); } /** * Set content to point to an existing byte array. IMPORTANT: After calling this, * if you keep a pointer to the array then you must treat the array as immutable and promise not to change it. * @param content A pointer to a vector with the byte array. This takes another reference and does not copy the bytes. */ void setContent(const ptr_lib::shared_ptr<std::vector<uint8_t> > &content) { content_ = content; onChanged(); } void setContent(const ptr_lib::shared_ptr<const std::vector<uint8_t> > &content) { content_ = content; onChanged(); } private: /** * Clear the wire encoding. */ void onChanged(); ptr_lib::shared_ptr<Signature> signature_; Name name_; MetaInfo metaInfo_; Blob content_; SignedBlob wireEncoding_; }; } #endif <commit_msg>documentation: Fix comment in Signature class.<commit_after>/** * Copyright (C) 2013 Regents of the University of California. * @author: Jeff Thompson <jefft0@remap.ucla.edu> * See COPYING for copyright and distribution information. */ #ifndef NDN_DATA_HPP #define NDN_DATA_HPP #include "common.hpp" #include "name.hpp" #include "util/signed-blob.hpp" #include "c/data.h" namespace ndn { /** * A Signature is an abstract base class providing methods to work with the signature information in a Data packet. * You must create an object of a subclass, for example Sha256WithRsaSignature. */ class Signature { public: /** * Return a pointer to a new Signature which is a copy of this signature. * This is pure virtual, the subclass must implement it. */ virtual ptr_lib::shared_ptr<Signature> clone() const = 0; /** * The virtual destructor. */ virtual ~Signature(); /** * Set the signatureStruct to point to the values in this signature object, without copying any memory. * WARNING: The resulting pointers in signatureStruct are invalid after a further use of this object which could reallocate memory. * This is pure virtual, the subclass must implement it. * @param signatureStruct a C ndn_Signature struct where the name components array is already allocated. */ virtual void get(struct ndn_Signature& signatureStruct) const = 0; /** * Clear this signature, and set the values by copying from the ndn_Signature struct. * This is pure virtual, the subclass must implement it. * @param signatureStruct a C ndn_Signature struct */ virtual void set(const struct ndn_Signature& signatureStruct) = 0; }; /** * An MetaInfo holds the meta info which is signed inside the data packet. */ class MetaInfo { public: MetaInfo() { type_ = ndn_ContentType_DATA; freshnessSeconds_ = -1; } /** * Set the metaInfoStruct to point to the values in this meta info object, without copying any memory. * WARNING: The resulting pointers in metaInfoStruct are invalid after a further use of this object which could reallocate memory. * @param metaInfoStruct a C ndn_MetaInfo struct where the name components array is already allocated. */ void get(struct ndn_MetaInfo& metaInfoStruct) const; /** * Clear this meta info, and set the values by copying from the ndn_MetaInfo struct. * @param metaInfoStruct a C ndn_MetaInfo struct */ void set(const struct ndn_MetaInfo& metaInfoStruct); double getTimestampMilliseconds() const { return timestampMilliseconds_; } ndn_ContentType getType() const { return type_; } int getFreshnessSeconds() const { return freshnessSeconds_; } const Name::Component& getFinalBlockID() const { return finalBlockID_; } void setTimestampMilliseconds(double timestampMilliseconds) { timestampMilliseconds_ = timestampMilliseconds; } void setType(ndn_ContentType type) { type_ = type; } void setFreshnessSeconds(int freshnessSeconds) { freshnessSeconds_ = freshnessSeconds; } void setFinalBlockID(const std::vector<uint8_t>& finalBlockID) { finalBlockID_ = Name::Component(finalBlockID); } void setFinalBlockID(const uint8_t* finalBlockID, size_t finalBlockIdLength) { finalBlockID_ = Name::Component(finalBlockID, finalBlockIdLength); } private: double timestampMilliseconds_; /**< milliseconds since 1/1/1970. -1 for none */ ndn_ContentType type_; /**< default is ndn_ContentType_DATA. -1 for none */ int freshnessSeconds_; /**< -1 for none */ Name::Component finalBlockID_; /** size 0 for none */ }; class Data { public: /** * Create a new Data object with default values and where the signature is a blank Sha256WithRsaSignature. */ Data(); /** * Create a new Data object with the given name and default values and where the signature is a blank Sha256WithRsaSignature. * @param name A reference to the name which is copied. */ Data(const Name& name); /** * Encode this Data for a particular wire format. Also, set the wireEncoding field to the encoded result. * This is not const because it updates the wireEncoding. * @param wireFormat A WireFormat object used to encode the input. If omitted, use WireFormat getDefaultWireFormat(). * @return The encoded byte array. */ SignedBlob wireEncode(WireFormat& wireFormat = *WireFormat::getDefaultWireFormat()); /** * Decode the input using a particular wire format and update this Data. Also, set the wireEncoding field to the input. * @param input The input byte array to be decoded. * @param inputLength The length of input. * @param wireFormat A WireFormat object used to decode the input. If omitted, use WireFormat getDefaultWireFormat(). */ void wireDecode(const uint8_t* input, size_t inputLength, WireFormat& wireFormat = *WireFormat::getDefaultWireFormat()); /** * Decode the input using a particular wire format and update this Data. Also, set the wireEncoding field to the input. * @param input The input byte array to be decoded. * @param wireFormat A WireFormat object used to decode the input. If omitted, use WireFormat getDefaultWireFormat(). */ void wireDecode(const std::vector<uint8_t>& input, WireFormat& wireFormat = *WireFormat::getDefaultWireFormat()) { wireDecode(&input[0], input.size(), wireFormat); } /** * Set the dataStruct to point to the values in this interest, without copying any memory. * WARNING: The resulting pointers in dataStruct are invalid after a further use of this object which could reallocate memory. * @param dataStruct a C ndn_Data struct where the name components array is already allocated. */ void get(struct ndn_Data& dataStruct) const; /** * Clear this data object, and set the values by copying from the ndn_Data struct. * @param dataStruct a C ndn_Data struct */ void set(const struct ndn_Data& dataStruct); const Signature* getSignature() const { return signature_.get(); } Signature* getSignature() { // TODO: Should add an OnChanged listener instead of always calling onChanged. onChanged(); return signature_.get(); } const Name& getName() const { return name_; } Name& getName() { // TODO: Should add an OnChanged listener instead of always calling onChanged. onChanged(); return name_; } const MetaInfo& getMetaInfo() const { return metaInfo_; } MetaInfo& getMetaInfo() { // TODO: Should add an OnChanged listener instead of always calling onChanged. onChanged(); return metaInfo_; } const Blob& getContent() const { return content_; } /** * Return a pointer to the wireEncoding. It may be null. */ const SignedBlob& getWireEncoding() const { return wireEncoding_; } /** * Set the signature to a copy of the given signature. * @param signature The signature object which is cloned. */ void setSignature(const Signature& signature) { signature_ = signature.clone(); onChanged(); } /** * Set name to a copy of the given Name. * @param name The Name which is copied. */ void setName(const Name& name) { name_ = name; onChanged(); } /** * Set metaInfo to a copy of the given MetaInfo. * @param metaInfo The MetaInfo which is copied. */ void setMetainfo(const MetaInfo& metaInfo) { metaInfo_ = metaInfo; onChanged(); } /** * Set the content to a copy of the data in the vector. * @param content A vector whose contents are copied. */ void setContent(const std::vector<uint8_t>& content) { content_ = content; onChanged(); } void setContent(const uint8_t* content, size_t contentLength) { content_ = Blob(content, contentLength); onChanged(); } /** * Set content to point to an existing byte array. IMPORTANT: After calling this, * if you keep a pointer to the array then you must treat the array as immutable and promise not to change it. * @param content A pointer to a vector with the byte array. This takes another reference and does not copy the bytes. */ void setContent(const ptr_lib::shared_ptr<std::vector<uint8_t> > &content) { content_ = content; onChanged(); } void setContent(const ptr_lib::shared_ptr<const std::vector<uint8_t> > &content) { content_ = content; onChanged(); } private: /** * Clear the wire encoding. */ void onChanged(); ptr_lib::shared_ptr<Signature> signature_; Name name_; MetaInfo metaInfo_; Blob content_; SignedBlob wireEncoding_; }; } #endif <|endoftext|>
<commit_before>//---------------------------- rt_distorted_01.cc --------------------------- // rt_distorted_01.cc,v 1.3 2003/06/09 16:00:38 wolf Exp // Version: // // Copyright (C) 2003, 2005, 2006, 2007, 2010 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. // //---------------------------- rt_distorted_01.cc --------------------------- /* * Snippet to demonstrate some properties of the deal.II implementation of * the RT spaces. */ #include "../tests.h" #include <deal.II/base/logstream.h> #define PRECISION 2 #include <fstream> std::ofstream logfile ("rt_distorted_01/output"); #include <fstream> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/grid_out.h> #include <deal.II/fe/mapping_q.h> #include <deal.II/fe/mapping_q1_eulerian.h> #include <deal.II/numerics/vectors.h> #include <deal.II/numerics/matrices.h> #include <deal.II/numerics/data_out.h> #include <deal.II/lac/vector.h> #include <deal.II/lac/solver_cg.h> #include <deal.II/lac/precondition.h> #include <deal.II/lac/vector_memory.h> #include <deal.II/lac/sparsity_pattern.h> #include <deal.II/lac/sparse_matrix.h> #include <deal.II/base/function.h> #include <deal.II/base/quadrature_lib.h> #include <deal.II/lac/constraint_matrix.h> #include <deal.II/dofs/dof_tools.h> #include <deal.II/fe/fe_system.h> #include <deal.II/fe/fe.h> #include <deal.II/fe/fe_system.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_values.h> #include <deal.II/fe/fe_raviart_thomas.h> #include <deal.II/fe/fe_dgq.h> #include <deal.II/fe/mapping_q1_eulerian.h> #include <fstream> template <int dim> class TestMap1 : public Function<dim> { public: TestMap1 (const unsigned int n_components) : Function<dim> (n_components) {} virtual ~TestMap1 () {} virtual double value (const Point<dim> &p, const unsigned int component = 0) const; void vector_value (const Point<dim> &p, Vector<double> &return_value) const; }; template <int dim> double TestMap1<dim>::value (const Point<dim> &/*p*/, const unsigned int /*component*/) const { return (1); } template <int dim> void TestMap1<dim>::vector_value (const Point<dim> &p, Vector<double> &return_value) const { Assert (return_value.size() == this->n_components, ExcDimensionMismatch (return_value.size(), this->n_components)); // Parabolic inflow profile for (unsigned int iCount = 0; iCount < this->n_components; iCount++) return_value (iCount) = value (p, iCount); } ///----------------------------------------------------------------------- template <int dim> class TestDef1 : public Function<dim> { private: const double phi; public: TestDef1 (const unsigned int n_components, const double ph) : Function<dim> (n_components), phi (ph) {} virtual ~TestDef1 () {} virtual double value (const Point<dim> &p, const unsigned int component = 0) const; void vector_value (const Point<dim> &p, Vector<double> &return_value) const; }; template <int dim> double TestDef1<dim>::value (const Point<dim> &p, const unsigned int component) const { Point<2> center; center(0) = 0.5; center(1) = 0.5; double rad = p.distance (center), phi_p = atan2 (p(0) - center(0), p(1) - center(1)); if (component == 0) return rad * (sin (phi + phi_p) - sin (phi_p)); else return rad * (cos (phi + phi_p) - cos (phi_p)); } template <int dim> void TestDef1<dim>::vector_value (const Point<dim> &p, Vector<double> &return_value) const { Assert (return_value.size() == this->n_components, ExcDimensionMismatch (return_value.size(), this->n_components)); for (unsigned int iCount = 0; iCount < this->n_components; iCount++) return_value (iCount) = value (p, iCount); } ///----------------------------------------------------------------------- template <int dim> class TestDef2 : public Function<dim> { private: const double scale; public: TestDef2 (const unsigned int n_components, const double sc) : Function<dim> (n_components), scale (sc) {} virtual ~TestDef2 () {} virtual double value (const Point<dim> &p, const unsigned int component = 0) const; void vector_value (const Point<dim> &p, Vector<double> &return_value) const; }; template <int dim> double TestDef2<dim>::value (const Point<dim> &p, const unsigned int component) const { double x = p(0), y = p(1); if (component == 0) return scale * x; else return scale * y; } template <int dim> void TestDef2<dim>::vector_value (const Point<dim> &p, Vector<double> &return_value) const { Assert (return_value.size() == this->n_components, ExcDimensionMismatch (return_value.size(), this->n_components)); for (unsigned int iCount = 0; iCount < this->n_components; iCount++) return_value (iCount) = value (p, iCount); } ///----------------------------------------------------------------------- // testDef3 implements parallelograms ... template <int dim> class TestDef3 : public Function<dim> { private: const double scale; public: TestDef3 (const unsigned int n_components, const double sc) : Function<dim> (n_components), scale (sc) {} virtual ~TestDef3 () {} virtual double value (const Point<dim> &p, const unsigned int component = 0) const; void vector_value (const Point<dim> &p, Vector<double> &return_value) const; }; template <int dim> double TestDef3<dim>::value (const Point<dim> &p, const unsigned int component) const { double y = p(1); if (component == 0) return scale * y; else return 0; } template <int dim> void TestDef3<dim>::vector_value (const Point<dim> &p, Vector<double> &return_value) const { Assert (return_value.size() == this->n_components, ExcDimensionMismatch (return_value.size(), this->n_components)); for (unsigned int iCount = 0; iCount < this->n_components; iCount++) return_value (iCount) = value (p, iCount); } /* * Integrate the function value over the element. */ double EvaluateArea (Mapping<2> &mapping, DoFHandler<2> *dof_handler, Vector<double> &solution) { // Use a high order quadrature. QGauss<2> quad (6); FEValues<2> fe_values (mapping, dof_handler->get_fe (), quad, UpdateFlags(update_values | update_q_points | update_JxW_values)); const unsigned int n_q_points = quad.size(); const unsigned int n_components = dof_handler->get_fe().n_components(); // Cell iterators DoFHandler<2>::active_cell_iterator cell = dof_handler->begin_active(), endc = dof_handler->end(); double result_u = 0, result_v = 0; for (; cell!=endc; ++cell) { fe_values.reinit (cell); // Get values from solution vector (For Trap.Rule) std::vector<Vector<double> > this_value (n_q_points, Vector<double>(n_components)); fe_values.get_function_values (solution, this_value); for (unsigned int q_point=0; q_point<n_q_points; ++q_point) { double JxW = fe_values.JxW (q_point); result_u += this_value[q_point](0) * JxW; result_v += this_value[q_point](1) * JxW; } } return (result_v); } int main (int /*argc*/, char **/*argv*/) { logfile.precision (PRECISION); logfile.setf(std::ios::fixed); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); Triangulation<2> tria_test; DoFHandler<2> *dof_handler, *dof_handler_def; Point<2> p1 (0,0), p2 (1, 1); GridGenerator::hyper_rectangle (tria_test, p1, p2); tria_test.refine_global (1); // Uncommenting the following line, demonstrates the problem // of RT elements on distorted Quads! tria_test.distort_random (0.4); // Create a DoFHandler for the RT space FE_RaviartThomas<2> fe (2); dof_handler = new DoFHandler<2> (tria_test); dof_handler->distribute_dofs (fe); // Create an deformation object for the Eulerian mapping FESystem<2> fe_def (FE_Q<2>(1), 2); dof_handler_def = new DoFHandler<2> (tria_test); dof_handler_def->distribute_dofs (fe_def); // Alloc some DoFs Vector<double> solution, solution_q, deformation; solution.reinit (dof_handler->n_dofs ()); solution_q.reinit (dof_handler_def->n_dofs ()); deformation.reinit (dof_handler_def->n_dofs ()); // Project solution onto RT FE field ConstraintMatrix hn_constraints; hn_constraints.clear (); DoFTools::make_hanging_node_constraints (*dof_handler, hn_constraints); hn_constraints.close (); VectorTools::project (*dof_handler, hn_constraints, QGauss<2> (6), TestMap1<2>(2), solution); // Project reference solution onto RT FE field ConstraintMatrix hn_constraints_def; hn_constraints_def.clear (); DoFTools::make_hanging_node_constraints (*dof_handler_def, hn_constraints_def); hn_constraints_def.close (); VectorTools::project (*dof_handler_def, hn_constraints_def, QGauss<2> (6), TestMap1<2>(2), solution_q); MappingQ1Eulerian<2> *mapping_euler = new MappingQ1Eulerian<2> (deformation, *dof_handler_def); char buf[1000]; sprintf (buf, "FE_RT Area %e FE_Q Area %e\n", EvaluateArea (*mapping_euler, dof_handler, solution), EvaluateArea (*mapping_euler, dof_handler_def, solution_q)); deallog << buf; unsigned int test_out = 0; // Try rotating the elements for (double rotat = 0; rotat < 2 * M_PI; rotat += 0.25 * M_PI) { // Rotate element VectorTools::project (*dof_handler_def, hn_constraints_def, QGauss<2> (6), TestDef1<2>(2, rotat), deformation); // Project 1 function to element VectorTools::project (*mapping_euler, *dof_handler, hn_constraints, QGauss<2> (6), TestMap1<2>(2), solution); // Write output files DataOut<2> *data_out = new DataOut<2>; data_out->attach_dof_handler (*dof_handler); data_out->add_data_vector (solution, "solution"); data_out->build_patches (*mapping_euler, 8, 1); data_out->write_gnuplot (deallog.get_file_stream()); test_out++; delete data_out; double area_rt = EvaluateArea (*mapping_euler, dof_handler, solution); double area_q = EvaluateArea (*mapping_euler, dof_handler_def, solution_q); char buf[100]; sprintf (buf, "phi = %e FE_RT Area %e FE_Q Area %e\n", rotat, area_rt, area_q); deallog << buf; } // Try resizing the elements for (double scale = -0.75; scale < 4.0; scale += 0.25) { VectorTools::project (*dof_handler_def, hn_constraints_def, QGauss<2> (6), TestDef2<2>(2, scale), deformation); // Project 1 function to element VectorTools::project (*mapping_euler, *dof_handler, hn_constraints, QGauss<2> (6), TestMap1<2>(2), solution); char buf[1000]; sprintf (buf, "Scale = %e FE_RT Area %e FE_Q Area %e\n", scale, EvaluateArea (*mapping_euler, dof_handler, solution), EvaluateArea (*mapping_euler, dof_handler_def, solution_q)); deallog << buf; } // Try parallelograms for (double scale = -1.0; scale < 1.0; scale += 0.25) { VectorTools::project (*dof_handler_def, hn_constraints_def, QGauss<2> (6), TestDef3<2>(2, scale), deformation); // Project 1 function to element VectorTools::project (*mapping_euler, *dof_handler, hn_constraints, QGauss<2> (6), TestMap1<2>(2), solution); char buf[1000]; sprintf (buf, "Parallelogram = %e FE_RT Area %e FE_Q Area %e\n", scale, EvaluateArea (*mapping_euler, dof_handler, solution), EvaluateArea (*mapping_euler, dof_handler_def, solution_q)); deallog << buf; } delete (mapping_euler); delete (dof_handler); delete (dof_handler_def); return (0); } <commit_msg>Remove long outdated n_threads parameter.<commit_after>//---------------------------- rt_distorted_01.cc --------------------------- // rt_distorted_01.cc,v 1.3 2003/06/09 16:00:38 wolf Exp // Version: // // Copyright (C) 2003, 2005, 2006, 2007, 2010, 2011 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. // //---------------------------- rt_distorted_01.cc --------------------------- /* * Snippet to demonstrate some properties of the deal.II implementation of * the RT spaces. */ #include "../tests.h" #include <deal.II/base/logstream.h> #define PRECISION 2 #include <fstream> std::ofstream logfile ("rt_distorted_01/output"); #include <fstream> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/grid_out.h> #include <deal.II/fe/mapping_q.h> #include <deal.II/fe/mapping_q1_eulerian.h> #include <deal.II/numerics/vectors.h> #include <deal.II/numerics/matrices.h> #include <deal.II/numerics/data_out.h> #include <deal.II/lac/vector.h> #include <deal.II/lac/solver_cg.h> #include <deal.II/lac/precondition.h> #include <deal.II/lac/vector_memory.h> #include <deal.II/lac/sparsity_pattern.h> #include <deal.II/lac/sparse_matrix.h> #include <deal.II/base/function.h> #include <deal.II/base/quadrature_lib.h> #include <deal.II/lac/constraint_matrix.h> #include <deal.II/dofs/dof_tools.h> #include <deal.II/fe/fe_system.h> #include <deal.II/fe/fe.h> #include <deal.II/fe/fe_system.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_values.h> #include <deal.II/fe/fe_raviart_thomas.h> #include <deal.II/fe/fe_dgq.h> #include <deal.II/fe/mapping_q1_eulerian.h> #include <fstream> template <int dim> class TestMap1 : public Function<dim> { public: TestMap1 (const unsigned int n_components) : Function<dim> (n_components) {} virtual ~TestMap1 () {} virtual double value (const Point<dim> &p, const unsigned int component = 0) const; void vector_value (const Point<dim> &p, Vector<double> &return_value) const; }; template <int dim> double TestMap1<dim>::value (const Point<dim> &/*p*/, const unsigned int /*component*/) const { return (1); } template <int dim> void TestMap1<dim>::vector_value (const Point<dim> &p, Vector<double> &return_value) const { Assert (return_value.size() == this->n_components, ExcDimensionMismatch (return_value.size(), this->n_components)); // Parabolic inflow profile for (unsigned int iCount = 0; iCount < this->n_components; iCount++) return_value (iCount) = value (p, iCount); } ///----------------------------------------------------------------------- template <int dim> class TestDef1 : public Function<dim> { private: const double phi; public: TestDef1 (const unsigned int n_components, const double ph) : Function<dim> (n_components), phi (ph) {} virtual ~TestDef1 () {} virtual double value (const Point<dim> &p, const unsigned int component = 0) const; void vector_value (const Point<dim> &p, Vector<double> &return_value) const; }; template <int dim> double TestDef1<dim>::value (const Point<dim> &p, const unsigned int component) const { Point<2> center; center(0) = 0.5; center(1) = 0.5; double rad = p.distance (center), phi_p = atan2 (p(0) - center(0), p(1) - center(1)); if (component == 0) return rad * (sin (phi + phi_p) - sin (phi_p)); else return rad * (cos (phi + phi_p) - cos (phi_p)); } template <int dim> void TestDef1<dim>::vector_value (const Point<dim> &p, Vector<double> &return_value) const { Assert (return_value.size() == this->n_components, ExcDimensionMismatch (return_value.size(), this->n_components)); for (unsigned int iCount = 0; iCount < this->n_components; iCount++) return_value (iCount) = value (p, iCount); } ///----------------------------------------------------------------------- template <int dim> class TestDef2 : public Function<dim> { private: const double scale; public: TestDef2 (const unsigned int n_components, const double sc) : Function<dim> (n_components), scale (sc) {} virtual ~TestDef2 () {} virtual double value (const Point<dim> &p, const unsigned int component = 0) const; void vector_value (const Point<dim> &p, Vector<double> &return_value) const; }; template <int dim> double TestDef2<dim>::value (const Point<dim> &p, const unsigned int component) const { double x = p(0), y = p(1); if (component == 0) return scale * x; else return scale * y; } template <int dim> void TestDef2<dim>::vector_value (const Point<dim> &p, Vector<double> &return_value) const { Assert (return_value.size() == this->n_components, ExcDimensionMismatch (return_value.size(), this->n_components)); for (unsigned int iCount = 0; iCount < this->n_components; iCount++) return_value (iCount) = value (p, iCount); } ///----------------------------------------------------------------------- // testDef3 implements parallelograms ... template <int dim> class TestDef3 : public Function<dim> { private: const double scale; public: TestDef3 (const unsigned int n_components, const double sc) : Function<dim> (n_components), scale (sc) {} virtual ~TestDef3 () {} virtual double value (const Point<dim> &p, const unsigned int component = 0) const; void vector_value (const Point<dim> &p, Vector<double> &return_value) const; }; template <int dim> double TestDef3<dim>::value (const Point<dim> &p, const unsigned int component) const { double y = p(1); if (component == 0) return scale * y; else return 0; } template <int dim> void TestDef3<dim>::vector_value (const Point<dim> &p, Vector<double> &return_value) const { Assert (return_value.size() == this->n_components, ExcDimensionMismatch (return_value.size(), this->n_components)); for (unsigned int iCount = 0; iCount < this->n_components; iCount++) return_value (iCount) = value (p, iCount); } /* * Integrate the function value over the element. */ double EvaluateArea (Mapping<2> &mapping, DoFHandler<2> *dof_handler, Vector<double> &solution) { // Use a high order quadrature. QGauss<2> quad (6); FEValues<2> fe_values (mapping, dof_handler->get_fe (), quad, UpdateFlags(update_values | update_q_points | update_JxW_values)); const unsigned int n_q_points = quad.size(); const unsigned int n_components = dof_handler->get_fe().n_components(); // Cell iterators DoFHandler<2>::active_cell_iterator cell = dof_handler->begin_active(), endc = dof_handler->end(); double result_u = 0, result_v = 0; for (; cell!=endc; ++cell) { fe_values.reinit (cell); // Get values from solution vector (For Trap.Rule) std::vector<Vector<double> > this_value (n_q_points, Vector<double>(n_components)); fe_values.get_function_values (solution, this_value); for (unsigned int q_point=0; q_point<n_q_points; ++q_point) { double JxW = fe_values.JxW (q_point); result_u += this_value[q_point](0) * JxW; result_v += this_value[q_point](1) * JxW; } } return (result_v); } int main (int /*argc*/, char **/*argv*/) { logfile.precision (PRECISION); logfile.setf(std::ios::fixed); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); Triangulation<2> tria_test; DoFHandler<2> *dof_handler, *dof_handler_def; Point<2> p1 (0,0), p2 (1, 1); GridGenerator::hyper_rectangle (tria_test, p1, p2); tria_test.refine_global (1); // Uncommenting the following line, demonstrates the problem // of RT elements on distorted Quads! tria_test.distort_random (0.4); // Create a DoFHandler for the RT space FE_RaviartThomas<2> fe (2); dof_handler = new DoFHandler<2> (tria_test); dof_handler->distribute_dofs (fe); // Create an deformation object for the Eulerian mapping FESystem<2> fe_def (FE_Q<2>(1), 2); dof_handler_def = new DoFHandler<2> (tria_test); dof_handler_def->distribute_dofs (fe_def); // Alloc some DoFs Vector<double> solution, solution_q, deformation; solution.reinit (dof_handler->n_dofs ()); solution_q.reinit (dof_handler_def->n_dofs ()); deformation.reinit (dof_handler_def->n_dofs ()); // Project solution onto RT FE field ConstraintMatrix hn_constraints; hn_constraints.clear (); DoFTools::make_hanging_node_constraints (*dof_handler, hn_constraints); hn_constraints.close (); VectorTools::project (*dof_handler, hn_constraints, QGauss<2> (6), TestMap1<2>(2), solution); // Project reference solution onto RT FE field ConstraintMatrix hn_constraints_def; hn_constraints_def.clear (); DoFTools::make_hanging_node_constraints (*dof_handler_def, hn_constraints_def); hn_constraints_def.close (); VectorTools::project (*dof_handler_def, hn_constraints_def, QGauss<2> (6), TestMap1<2>(2), solution_q); MappingQ1Eulerian<2> *mapping_euler = new MappingQ1Eulerian<2> (deformation, *dof_handler_def); char buf[1000]; sprintf (buf, "FE_RT Area %e FE_Q Area %e\n", EvaluateArea (*mapping_euler, dof_handler, solution), EvaluateArea (*mapping_euler, dof_handler_def, solution_q)); deallog << buf; unsigned int test_out = 0; // Try rotating the elements for (double rotat = 0; rotat < 2 * M_PI; rotat += 0.25 * M_PI) { // Rotate element VectorTools::project (*dof_handler_def, hn_constraints_def, QGauss<2> (6), TestDef1<2>(2, rotat), deformation); // Project 1 function to element VectorTools::project (*mapping_euler, *dof_handler, hn_constraints, QGauss<2> (6), TestMap1<2>(2), solution); // Write output files DataOut<2> *data_out = new DataOut<2>; data_out->attach_dof_handler (*dof_handler); data_out->add_data_vector (solution, "solution"); data_out->build_patches (*mapping_euler, 8); data_out->write_gnuplot (deallog.get_file_stream()); test_out++; delete data_out; double area_rt = EvaluateArea (*mapping_euler, dof_handler, solution); double area_q = EvaluateArea (*mapping_euler, dof_handler_def, solution_q); char buf[100]; sprintf (buf, "phi = %e FE_RT Area %e FE_Q Area %e\n", rotat, area_rt, area_q); deallog << buf; } // Try resizing the elements for (double scale = -0.75; scale < 4.0; scale += 0.25) { VectorTools::project (*dof_handler_def, hn_constraints_def, QGauss<2> (6), TestDef2<2>(2, scale), deformation); // Project 1 function to element VectorTools::project (*mapping_euler, *dof_handler, hn_constraints, QGauss<2> (6), TestMap1<2>(2), solution); char buf[1000]; sprintf (buf, "Scale = %e FE_RT Area %e FE_Q Area %e\n", scale, EvaluateArea (*mapping_euler, dof_handler, solution), EvaluateArea (*mapping_euler, dof_handler_def, solution_q)); deallog << buf; } // Try parallelograms for (double scale = -1.0; scale < 1.0; scale += 0.25) { VectorTools::project (*dof_handler_def, hn_constraints_def, QGauss<2> (6), TestDef3<2>(2, scale), deformation); // Project 1 function to element VectorTools::project (*mapping_euler, *dof_handler, hn_constraints, QGauss<2> (6), TestMap1<2>(2), solution); char buf[1000]; sprintf (buf, "Parallelogram = %e FE_RT Area %e FE_Q Area %e\n", scale, EvaluateArea (*mapping_euler, dof_handler, solution), EvaluateArea (*mapping_euler, dof_handler_def, solution_q)); deallog << buf; } delete (mapping_euler); delete (dof_handler); delete (dof_handler_def); return (0); } <|endoftext|>
<commit_before>// // Copyright 2011-2013 Jeff Bush // // 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 "Barrier.h" #include "Matrix2x2.h" typedef int veci16 __attribute__((ext_vector_type(16))); typedef float vecf16 __attribute__((ext_vector_type(16))); veci16* const kFrameBufferAddress = (veci16*) 0x10000000; const vecf16 kXOffsets = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f }; extern unsigned int kImage[]; const int kImageWidth = 16; const int kImageHeight = 16; const int kBytesPerPixel = 4; const int kScreenWidth = 640; const int kScreenHeight = 480; extern "C" void dflush(void*); Barrier<4> gFrameBarrier; // We don't execute global ctors yet, but I know this is fine. int main() { Matrix2x2 displayMatrix; // 1/64 step rotation Matrix2x2 stepMatrix( 0.9987954562, -0.04906767432, 0.04906767432, 0.9987954562); stepMatrix = stepMatrix * Matrix2x2(0.99, 0.0, 0.0, 0.99); // Scale slightly // Strands work on interleaved chunks of pixels. The strand ID determines // the starting point. int myStrandId = __builtin_vp_get_current_strand(); while (true) { unsigned int imageBase = (unsigned int) kImage; veci16 *outputPtr = kFrameBufferAddress + myStrandId; for (int y = 0; y < kScreenHeight; y++) { for (int x = myStrandId * 16; x < kScreenWidth; x += 64) { vecf16 xv = kXOffsets + __builtin_vp_makevectorf((float) x) - __builtin_vp_makevectorf(kScreenWidth / 2); vecf16 yv = __builtin_vp_makevectorf((float) y) - __builtin_vp_makevectorf(kScreenHeight / 2);; vecf16 u = xv * __builtin_vp_makevectorf(displayMatrix.a) + yv * __builtin_vp_makevectorf(displayMatrix.b); vecf16 v = xv * __builtin_vp_makevectorf(displayMatrix.c) + yv * __builtin_vp_makevectorf(displayMatrix.d); veci16 tx = (__builtin_vp_vftoi(u) & __builtin_vp_makevectori(kImageWidth - 1)); veci16 ty = (__builtin_vp_vftoi(v) & __builtin_vp_makevectori(kImageHeight - 1)); veci16 pixelPtrs = (ty * __builtin_vp_makevectori(kImageWidth * kBytesPerPixel)) + (tx * __builtin_vp_makevectori(kBytesPerPixel)) + __builtin_vp_makevectori(imageBase); *outputPtr = __builtin_vp_gather_loadi(pixelPtrs); dflush(outputPtr); outputPtr += 4; // Skip over four chunks because there are four threads. } } displayMatrix = displayMatrix * stepMatrix; #if 0 gFrameBarrier.wait(); #endif } return 0; } unsigned int kImage[] = { 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xfffff8, 0xc8ffeb, 0x68ffe3, 0x28ffdf, 0x7ffdf, 0x7ffe3, 0x28ffeb, 0x68fff8, 0xc8ffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffeb, 0x68ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffeb, 0x68ffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffe7, 0x48ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffe7, 0x48ffff, 0xffffff, 0xffffff, 0xffffeb, 0x68ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffeb, 0x68ffff, 0xfffff8, 0xc8ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xfff8, 0xc8ffeb, 0x68ffde, 0xffde, 0xffde, 0x0, 0x0, 0xffde, 0xffde, 0xffde, 0x0, 0x0, 0xffde, 0xffde, 0xffde, 0xffde, 0xffeb, 0x68ffe3, 0x28ffde, 0xffde, 0xffde, 0x0, 0x0, 0xffde, 0xffde, 0xffde, 0x0, 0x0, 0xffde, 0xffde, 0xffde, 0xffde, 0xffe3, 0x28ffdf, 0x7ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffdf, 0x7ffdf, 0x7ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffdf, 0x7ffe3, 0x28ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffe3, 0x28ffeb, 0x68ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0x0, 0xffde, 0xffde, 0xffde, 0xffeb, 0x68fff8, 0xc8ffde, 0xffde, 0x0, 0x0, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0x0, 0xffde, 0xffde, 0xffde, 0xfff8, 0xc8ffff, 0xffffeb, 0x68ffde, 0xffde, 0x0, 0x0, 0x0, 0xffde, 0xffde, 0x0, 0x0, 0x0, 0xffde, 0xffde, 0xffeb, 0x68ffff, 0xffffff, 0xffffff, 0xffffe7, 0x48ffde, 0xffde, 0xffde, 0x0, 0x0, 0x0, 0x0, 0xffde, 0xffde, 0xffde, 0xffe7, 0x48ffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffeb, 0x68ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffeb, 0x68ffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xfffff8, 0xc8ffeb, 0x68ffe3, 0x28ffdf, 0x7ffdf, 0x7ffe3, 0x28ffeb, 0x68fff8, 0xc8ffff, 0xffffff, 0xffffff, 0xffffff }; <commit_msg>Update<commit_after>// // Copyright 2011-2013 Jeff Bush // // 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 "Barrier.h" #include "Matrix2x2.h" typedef int veci16 __attribute__((ext_vector_type(16))); typedef float vecf16 __attribute__((ext_vector_type(16))); veci16* const kFrameBufferAddress = (veci16*) 0x10000000; const vecf16 kXOffsets = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f }; extern unsigned int kImage[]; const int kImageWidth = 16; const int kImageHeight = 16; const int kBytesPerPixel = 4; const int kScreenWidth = 640; const int kScreenHeight = 480; extern "C" void dflush(void*); Barrier<4> gFrameBarrier; // We don't execute global ctors yet, but I know this is fine. int main() { Matrix2x2 displayMatrix; // 1/64 step rotation Matrix2x2 stepMatrix( 0.9987954562, -0.04906767432, 0.04906767432, 0.9987954562); stepMatrix = stepMatrix * Matrix2x2(0.99, 0.0, 0.0, 0.99); // Scale slightly // Strands work on interleaved chunks of pixels. The strand ID determines // the starting point. int myStrandId = __builtin_vp_get_current_strand(); while (true) { unsigned int imageBase = (unsigned int) kImage; veci16 *outputPtr = kFrameBufferAddress + myStrandId; for (int y = 0; y < kScreenHeight; y++) { for (int x = myStrandId * 16; x < kScreenWidth; x += 64) { vecf16 xv = kXOffsets + __builtin_vp_makevectorf((float) x) - __builtin_vp_makevectorf(kScreenWidth / 2); vecf16 yv = __builtin_vp_makevectorf((float) y) - __builtin_vp_makevectorf(kScreenHeight / 2);; vecf16 u = xv * __builtin_vp_makevectorf(displayMatrix.a) + yv * __builtin_vp_makevectorf(displayMatrix.b); vecf16 v = xv * __builtin_vp_makevectorf(displayMatrix.c) + yv * __builtin_vp_makevectorf(displayMatrix.d); veci16 tx = (__builtin_vp_vftoi(u) & __builtin_vp_makevectori(kImageWidth - 1)); veci16 ty = (__builtin_vp_vftoi(v) & __builtin_vp_makevectori(kImageHeight - 1)); veci16 pixelPtrs = (ty * __builtin_vp_makevectori(kImageWidth * kBytesPerPixel)) + (tx * __builtin_vp_makevectori(kBytesPerPixel)) + __builtin_vp_makevectori(imageBase); *outputPtr = __builtin_vp_gather_loadi(pixelPtrs); dflush(outputPtr); outputPtr += 4; // Skip over four chunks because there are four threads. } } displayMatrix = displayMatrix * stepMatrix; } return 0; } unsigned int kImage[] = { 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xfffff8, 0xc8ffeb, 0x68ffe3, 0x28ffdf, 0x7ffdf, 0x7ffe3, 0x28ffeb, 0x68fff8, 0xc8ffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffeb, 0x68ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffeb, 0x68ffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffe7, 0x48ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffe7, 0x48ffff, 0xffffff, 0xffffff, 0xffffeb, 0x68ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffeb, 0x68ffff, 0xfffff8, 0xc8ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xfff8, 0xc8ffeb, 0x68ffde, 0xffde, 0xffde, 0x0, 0x0, 0xffde, 0xffde, 0xffde, 0x0, 0x0, 0xffde, 0xffde, 0xffde, 0xffde, 0xffeb, 0x68ffe3, 0x28ffde, 0xffde, 0xffde, 0x0, 0x0, 0xffde, 0xffde, 0xffde, 0x0, 0x0, 0xffde, 0xffde, 0xffde, 0xffde, 0xffe3, 0x28ffdf, 0x7ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffdf, 0x7ffdf, 0x7ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffdf, 0x7ffe3, 0x28ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffe3, 0x28ffeb, 0x68ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0x0, 0xffde, 0xffde, 0xffde, 0xffeb, 0x68fff8, 0xc8ffde, 0xffde, 0x0, 0x0, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0x0, 0xffde, 0xffde, 0xffde, 0xfff8, 0xc8ffff, 0xffffeb, 0x68ffde, 0xffde, 0x0, 0x0, 0x0, 0xffde, 0xffde, 0x0, 0x0, 0x0, 0xffde, 0xffde, 0xffeb, 0x68ffff, 0xffffff, 0xffffff, 0xffffe7, 0x48ffde, 0xffde, 0xffde, 0x0, 0x0, 0x0, 0x0, 0xffde, 0xffde, 0xffde, 0xffe7, 0x48ffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffeb, 0x68ffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffde, 0xffeb, 0x68ffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xfffff8, 0xc8ffeb, 0x68ffe3, 0x28ffdf, 0x7ffdf, 0x7ffe3, 0x28ffeb, 0x68fff8, 0xc8ffff, 0xffffff, 0xffffff, 0xffffff }; <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // device_test.cpp // // Identification: tests/logging/device_test.cpp // // Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "harness.h" #include <iostream> #include <fcntl.h> #include <string> #include <cstdio> #include <cstdlib> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <cstring> #include <cassert> #include <getopt.h> #include <cstdint> #include "backend/common/timer.h" #include "backend/storage/storage_manager.h" // Logging mode extern LoggingType peloton_logging_mode; namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Device Test //===--------------------------------------------------------------------===// class DeviceTest : public PelotonTest {}; #define CACHELINE_SIZE 64 #define roundup2(x, y) (((x)+((y)-1))&(~((y)-1))) /* if y is powers of two */ TEST_F(DeviceTest, BenchmarkTest) { peloton_logging_mode = LOGGING_TYPE_HDD_HDD; auto &storage_manager = storage::StorageManager::GetInstance(); size_t chunk_size = 1024; std::string source_buf(chunk_size, 'a'); auto data = reinterpret_cast<char *>(storage_manager.Allocate(BACKEND_TYPE_HDD, chunk_size)); EXPECT_NE(data, nullptr); std::memcpy(data, source_buf.c_str(), chunk_size); storage_manager.Sync(BACKEND_TYPE_HDD, data, 0); } } // End test namespace } // End peloton namespace <commit_msg>Updated device test<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // device_test.cpp // // Identification: tests/logging/device_test.cpp // // Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "harness.h" #include <iostream> #include <fcntl.h> #include <string> #include <cstdio> #include <cstdlib> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <cstring> #include <cassert> #include <getopt.h> #include <cstdint> #include <string> #include <vector> #include "backend/common/timer.h" #include "backend/common/types.h" namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Device Test //===--------------------------------------------------------------------===// class DeviceTest : public PelotonTest {}; #define DATA_FILE_LEN 1024 * 1024 * UINT64_C(512) // 512 MB #define DATA_FILE_NAME "peloton.pmem" TEST_F(DeviceTest, BenchmarkTest) { std::vector<std::string> data_file_dirs = {NVM_DIR, HDD_DIR}; int data_fd; size_t data_file_len = DATA_FILE_LEN; oid_t num_trials = 3; std::size_t begin_chunk_size = 9, end_chunk_size = 21; // lg base 2 // Go over all the dirs for(auto data_file_dir : data_file_dirs){ // Create a data file std::string data_file_name = data_file_dir + DATA_FILE_NAME; std::cout << "Data File Name : " << data_file_name << "\n"; if ((data_fd = open(data_file_name.c_str(), O_CREAT | O_RDWR | O_DIRECT | O_SYNC, 0666)) < 0) { perror(data_file_name.c_str()); exit(EXIT_FAILURE); } // Allocate the data file if ((errno = posix_fallocate(data_fd, 0, data_file_len)) != 0) { perror("posix_fallocate"); exit(EXIT_FAILURE); } // Go over all the chunk sizes for(oid_t chunk_size_itr = begin_chunk_size; chunk_size_itr <= end_chunk_size; chunk_size_itr++){ // READS for(oid_t trial_itr = 0; trial_itr < num_trials; trial_itr++) { } // WRITES for(oid_t trial_itr = 0; trial_itr < num_trials; trial_itr++) { } } // Close the pmem file close(data_fd); } } } // End test namespace } // End peloton namespace <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 * * (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <sofa/simulation/tree/Simulation.h> #include <sofa/helper/system/SetDirectory.h> #include <sofa/helper/system/FileRepository.h> #include <sofa/simulation/common/PrintVisitor.h> #include <sofa/simulation/common/FindByTypeVisitor.h> #include <sofa/simulation/common/ExportGnuplotVisitor.h> #include <sofa/simulation/common/InitVisitor.h> #include <sofa/simulation/common/InstrumentVisitor.h> #include <sofa/simulation/common/AnimateVisitor.h> #include <sofa/simulation/common/MechanicalVisitor.h> #include <sofa/simulation/common/CollisionVisitor.h> #include <sofa/simulation/common/UpdateContextVisitor.h> #include <sofa/simulation/common/UpdateMappingVisitor.h> #include <sofa/simulation/common/ResetVisitor.h> #include <sofa/simulation/common/VisualVisitor.h> #include <sofa/simulation/tree/DeleteVisitor.h> #include <sofa/simulation/common/ExportOBJVisitor.h> #include <sofa/simulation/common/WriteStateVisitor.h> #include <sofa/simulation/common/XMLPrintVisitor.h> #include <sofa/simulation/common/PropagateEventVisitor.h> #include <sofa/simulation/common/AnimateBeginEvent.h> #include <sofa/simulation/common/AnimateEndEvent.h> #include <sofa/simulation/common/UpdateMappingEndEvent.h> #include <sofa/core/ObjectFactory.h> #include <sofa/helper/system/PipeProcess.h> #include <fstream> #include <string.h> namespace sofa { namespace simulation { namespace tree { using namespace sofa::defaulttype; /// The (unique) simulation which controls the scene Simulation* theSimulation = NULL; void setSimulation ( Simulation* s ) { theSimulation = s; } Simulation* getSimulation() { if ( theSimulation==NULL ) theSimulation = new Simulation; return theSimulation; } /// Load a scene from a file GNode* Simulation::processXML(xml::BaseElement* xml, const char *filename) { if ( xml==NULL ) { return NULL; } // We go the the current file's directory so that all relative path are correct helper::system::SetDirectory chdir ( filename ); // std::cout << "Initializing objects"<<std::endl; if ( !xml->init() ) { std::cerr << "Objects initialization failed."<<std::endl; } GNode* root = dynamic_cast<GNode*> ( xml->getObject() ); if ( root == NULL ) { std::cerr << "Objects initialization failed."<<std::endl; delete xml; return NULL; } // std::cout << "Initializing simulation "<<root->getName() <<std::endl; // Find the Simulation component in the scene FindByTypeVisitor<Simulation> findSimu; findSimu.execute(root); if( !findSimu.found.empty() ) setSimulation( findSimu.found[0] ); // if no Simulation is found, getSimulation() will automatically create one, of the default type. getSimulation()->init ( root ); // As mappings might be initialized after visual models, it is necessary to update them // BUGFIX (Jeremie A.): disabled as initTexture was not called yet, and the GUI might not even be up yet //root->execute<VisualUpdateVisitor>(); return root; } /// Load from a string in memory GNode* Simulation::loadFromMemory ( const char *filename, const char *data, unsigned int size ) { //::sofa::simulation::init(); // std::cerr << "Loading simulation XML file "<<filename<<std::endl; xml::BaseElement* xml = xml::loadFromMemory (filename, data, size ); GNode* root = processXML(xml, filename); // std::cout << "load done."<<std::endl; delete xml; return root; } /// Load a scene from a file GNode* Simulation::loadFromFile ( const char *filename ) { //::sofa::simulation::init(); // std::cerr << "Loading simulation XML file "<<filename<<std::endl; xml::BaseElement* xml = xml::loadFromFile ( filename ); GNode* root = processXML(xml, filename); // std::cout << "load done."<<std::endl; delete xml; return root; } /// Load a scene GNode* Simulation::load ( const char *filename ) { std::string ext = sofa::helper::system::SetDirectory::GetExtension(filename); if (ext == "php" || ext == "pscn") { std::string out="",error=""; std::vector<std::string> args; //TODO : replace when PipeProcess will get file as stdin //at the moment, the filename is given as an argument args.push_back(std::string("-f" + std::string(filename))); //args.push_back("-w"); std::string newFilename=""; //std::string newFilename=filename; helper::system::FileRepository fp("PATH", "."); #ifdef WIN32 std::string command = "php.exe"; #else std::string command = "php"; #endif if (!fp.findFile(command,"")) { std::cerr << "Simulation : Error : php not found in your PATH environment" << std::endl; return NULL; } sofa::helper::system::PipeProcess::executeProcess(command.c_str(), args, newFilename, out, error); if(error != "") { std::cerr << "Simulation : load : "<< error << std::endl; if (out == "") return NULL; } return loadFromMemory(filename, out.c_str(), out.size()); } if (ext == "scn" || ext == "xml") { return loadFromFile(filename); } std::cerr << "Simulation : Error : extension not handled" << std::endl; return NULL; } Simulation::Simulation() : numMechSteps( initData(&numMechSteps,(unsigned) 1,"numMechSteps","Number of mechanical steps within one update step. If the update time step is dt, the mechanical time step is dt/numMechSteps.") ), gnuplotDirectory( initData(&gnuplotDirectory,std::string(""),"gnuplotDirectory","Directory where the gnuplot files will be saved")), instrumentInUse( initData( &instrumentInUse, -1, "instrumentinuse", "Numero of the instrument currently used")) {} Simulation::~Simulation() { setSimulation( NULL ); } /// Print all object in the graph void Simulation::print ( Node* root ) { if ( !root ) return; root->execute<PrintVisitor>(); } /// Print all object in the graph void Simulation::printXML ( Node* root, const char* fileName ) { if ( !root ) return; if ( fileName!=NULL ) { std::ofstream out ( fileName ); XMLPrintVisitor print ( out ); root->execute ( print ); } else { XMLPrintVisitor print ( std::cout ); root->execute ( print ); } } /// Initialize the scene. void Simulation::init ( Node* root ) { //cerr<<"Simulation::init"<<endl; setContext( root->getContext()); if ( !root ) return; root->execute<InitVisitor>(); // Save reset state for later uses in reset() root->execute<MechanicalPropagatePositionAndVelocityVisitor>(); root->execute<MechanicalPropagateFreePositionVisitor>(); root->execute<StoreResetStateVisitor>(); //Get the list of instruments present in the scene graph getInstruments(root); } void Simulation::getInstruments( Node *node) { InstrumentVisitor fetchInstrument; node->execute<InstrumentVisitor>(); fetchInstrument.execute(node); instruments = fetchInstrument.getInstruments(); } /// Execute one timestep. If dt is 0, the dt parameter in the graph will be used void Simulation::animate ( Node* root, double dt ) { if ( !root ) return; if ( root->getMultiThreadSimulation() ) return; { AnimateBeginEvent ev ( dt ); PropagateEventVisitor act ( &ev ); root->execute ( act ); } //std::cout << "animate\n"; double startTime = root->getTime(); double mechanicalDt = dt/numMechSteps.getValue(); //double nextTime = root->getTime() + root->getDt(); // CHANGE to support MasterSolvers : CollisionVisitor is now activated within AnimateVisitor //root->execute<CollisionVisitor>(); AnimateVisitor act; act.setDt ( mechanicalDt ); for( unsigned i=0; i<numMechSteps.getValue(); i++ ) { root->execute ( act ); root->setTime ( startTime + (i+1)* act.getDt() ); root->execute<UpdateSimulationContextVisitor>(); } { AnimateEndEvent ev ( dt ); PropagateEventVisitor act ( &ev ); root->execute ( act ); } root->execute<UpdateMappingVisitor>(); { UpdateMappingEndEvent ev ( dt ); PropagateEventVisitor act ( &ev ); root->execute ( act ); } root->execute<VisualUpdateVisitor>(); } /// Reset to initial state void Simulation::reset ( Node* root ) { if ( !root ) return; root->execute<ResetVisitor>(); root->execute<MechanicalPropagatePositionAndVelocityVisitor>(); root->execute<UpdateMappingVisitor>(); root->execute<VisualUpdateVisitor>(); } /// Initialize the textures void Simulation::initTextures ( Node* root ) { if ( !root ) return; root->execute<VisualInitVisitor>(); // Do a visual update now as it is not done in load() anymore /// \todo Separate this into another method? root->execute<VisualUpdateVisitor>(); } /// Compute the bounding box of the scene. void Simulation::computeBBox ( Node* root, SReal* minBBox, SReal* maxBBox ) { VisualComputeBBoxVisitor act; if ( root ) root->execute ( act ); minBBox[0] = (SReal)(act.minBBox[0]); minBBox[1] = (SReal)(act.minBBox[1]); minBBox[2] = (SReal)(act.minBBox[2]); maxBBox[0] = (SReal)(act.maxBBox[0]); maxBBox[1] = (SReal)(act.maxBBox[1]); maxBBox[2] = (SReal)(act.maxBBox[2]); } /// Update contexts. Required before drawing the scene if root flags are modified. void Simulation::updateContext ( Node* root ) { if ( !root ) return; root->execute<UpdateContextVisitor>(); } /// Update only Visual contexts. Required before drawing the scene if root flags are modified.( can filter by specifying a specific element) void Simulation::updateVisualContext ( Node* root, int FILTER) { if ( !root ) return; UpdateVisualContextVisitor vis(FILTER); vis.execute(root); } /// Render the scene void Simulation::draw ( Node* root ) { if ( !root ) return; VisualDrawVisitor act ( core::VisualModel::Std ); root->execute ( &act ); VisualDrawVisitor act2 ( core::VisualModel::Transparent ); root->execute ( &act2 ); } /// Render the scene - shadow pass void Simulation::drawShadows ( Node* root ) { if ( !root ) return; //std::cout << "drawShadows\n"; VisualDrawVisitor act ( core::VisualModel::Shadow ); root->execute ( &act ); } /// Delete a scene from memory. After this call the pointer is invalid void Simulation::unload ( GNode* root ) { if ( !root ) return; instruments.clear(); instrumentInUse.setValue(-1); root->execute<DeleteVisitor>(); if ( root->getParent() !=NULL ) root->getParent()->removeChild ( root ); delete root; } /// Export a scene to an OBJ 3D Scene void Simulation::exportOBJ ( Node* root, const char* filename, bool exportMTL ) { if ( !root ) return; std::ofstream fout ( filename ); fout << "# Generated from SOFA Simulation" << std::endl; if ( !exportMTL ) { ExportOBJVisitor act ( &fout ); root->execute ( &act ); } else { const char *path1 = strrchr ( filename, '/' ); const char *path2 = strrchr ( filename, '\\' ); const char* path = ( path1==NULL ) ? ( ( path2==NULL ) ?filename : path2+1 ) : ( path2==NULL ) ? path1+1 : ( ( path1-filename ) > ( path2-filename ) ) ? path1+1 : path2+1; const char *ext = strrchr ( path, '.' ); if ( !ext ) ext = path + strlen ( path ); std::string mtlfilename ( path, ext ); mtlfilename += ".mtl"; std::string mtlpathname ( filename, ext ); mtlpathname += ".mtl"; std::ofstream mtl ( mtlpathname.c_str() ); mtl << "# Generated from SOFA Simulation" << std::endl; fout << "mtllib "<<mtlfilename<<'\n'; ExportOBJVisitor act ( &fout,&mtl ); root->execute ( &act ); } } /// Export a scene to XML void Simulation::exportXML ( Node* root, const char* filename ) { if ( !root ) return; std::ofstream fout ( filename ); XMLPrintVisitor act ( fout ); root->execute ( &act ); } void Simulation::dumpState ( Node* root, std::ofstream& out ) { out<<root->getTime() <<" "; WriteStateVisitor ( out ).execute ( root ); out<<endl; } /// Initialize gnuplot file output void Simulation::initGnuplot ( Node* root ) { if ( !root ) return; InitGnuplotVisitor v(gnuplotDirectory.getValue()); root->execute( v ); } /// Update gnuplot file output void Simulation::exportGnuplot ( Node* root, double time ) { if ( !root ) return; ExportGnuplotVisitor expg ( time ); root->execute ( expg ); } SOFA_DECL_CLASS ( Simulation ); // Register in the Factory int SimulationClass = core::RegisterObject ( "Main simulation algorithm" ) .add< Simulation >() ; } // namespace tree } // namespace simulation } // namespace sofa <commit_msg>r2807/sofa-dev : BUGFIX: parsing errors when reloading files on Mac (fix bug #5981)<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 * * (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <sofa/simulation/tree/Simulation.h> #include <sofa/helper/system/SetDirectory.h> #include <sofa/helper/system/FileRepository.h> #include <sofa/simulation/common/PrintVisitor.h> #include <sofa/simulation/common/FindByTypeVisitor.h> #include <sofa/simulation/common/ExportGnuplotVisitor.h> #include <sofa/simulation/common/InitVisitor.h> #include <sofa/simulation/common/InstrumentVisitor.h> #include <sofa/simulation/common/AnimateVisitor.h> #include <sofa/simulation/common/MechanicalVisitor.h> #include <sofa/simulation/common/CollisionVisitor.h> #include <sofa/simulation/common/UpdateContextVisitor.h> #include <sofa/simulation/common/UpdateMappingVisitor.h> #include <sofa/simulation/common/ResetVisitor.h> #include <sofa/simulation/common/VisualVisitor.h> #include <sofa/simulation/tree/DeleteVisitor.h> #include <sofa/simulation/common/ExportOBJVisitor.h> #include <sofa/simulation/common/WriteStateVisitor.h> #include <sofa/simulation/common/XMLPrintVisitor.h> #include <sofa/simulation/common/PropagateEventVisitor.h> #include <sofa/simulation/common/AnimateBeginEvent.h> #include <sofa/simulation/common/AnimateEndEvent.h> #include <sofa/simulation/common/UpdateMappingEndEvent.h> #include <sofa/core/ObjectFactory.h> #include <sofa/helper/system/PipeProcess.h> #include <fstream> #include <string.h> #ifndef WIN32 #include <locale.h> #endif namespace sofa { namespace simulation { namespace tree { using namespace sofa::defaulttype; /// The (unique) simulation which controls the scene Simulation* theSimulation = NULL; void setSimulation ( Simulation* s ) { theSimulation = s; } Simulation* getSimulation() { if ( theSimulation==NULL ) theSimulation = new Simulation; return theSimulation; } /// Load a scene from a file GNode* Simulation::processXML(xml::BaseElement* xml, const char *filename) { if ( xml==NULL ) { return NULL; } // We go the the current file's directory so that all relative path are correct helper::system::SetDirectory chdir ( filename ); #ifndef WIN32 // Reset local settings to make sure that floating-point values are interpreted correctly setlocale(LC_ALL,"C"); setlocale(LC_NUMERIC,"C"); #endif // std::cout << "Initializing objects"<<std::endl; if ( !xml->init() ) { std::cerr << "Objects initialization failed."<<std::endl; } GNode* root = dynamic_cast<GNode*> ( xml->getObject() ); if ( root == NULL ) { std::cerr << "Objects initialization failed."<<std::endl; delete xml; return NULL; } // std::cout << "Initializing simulation "<<root->getName() <<std::endl; // Find the Simulation component in the scene FindByTypeVisitor<Simulation> findSimu; findSimu.execute(root); if( !findSimu.found.empty() ) setSimulation( findSimu.found[0] ); // if no Simulation is found, getSimulation() will automatically create one, of the default type. getSimulation()->init ( root ); // As mappings might be initialized after visual models, it is necessary to update them // BUGFIX (Jeremie A.): disabled as initTexture was not called yet, and the GUI might not even be up yet //root->execute<VisualUpdateVisitor>(); return root; } /// Load from a string in memory GNode* Simulation::loadFromMemory ( const char *filename, const char *data, unsigned int size ) { //::sofa::simulation::init(); // std::cerr << "Loading simulation XML file "<<filename<<std::endl; xml::BaseElement* xml = xml::loadFromMemory (filename, data, size ); GNode* root = processXML(xml, filename); // std::cout << "load done."<<std::endl; delete xml; return root; } /// Load a scene from a file GNode* Simulation::loadFromFile ( const char *filename ) { //::sofa::simulation::init(); // std::cerr << "Loading simulation XML file "<<filename<<std::endl; xml::BaseElement* xml = xml::loadFromFile ( filename ); GNode* root = processXML(xml, filename); // std::cout << "load done."<<std::endl; delete xml; return root; } /// Load a scene GNode* Simulation::load ( const char *filename ) { std::string ext = sofa::helper::system::SetDirectory::GetExtension(filename); if (ext == "php" || ext == "pscn") { std::string out="",error=""; std::vector<std::string> args; //TODO : replace when PipeProcess will get file as stdin //at the moment, the filename is given as an argument args.push_back(std::string("-f" + std::string(filename))); //args.push_back("-w"); std::string newFilename=""; //std::string newFilename=filename; helper::system::FileRepository fp("PATH", "."); #ifdef WIN32 std::string command = "php.exe"; #else std::string command = "php"; #endif if (!fp.findFile(command,"")) { std::cerr << "Simulation : Error : php not found in your PATH environment" << std::endl; return NULL; } sofa::helper::system::PipeProcess::executeProcess(command.c_str(), args, newFilename, out, error); if(error != "") { std::cerr << "Simulation : load : "<< error << std::endl; if (out == "") return NULL; } return loadFromMemory(filename, out.c_str(), out.size()); } if (ext == "scn" || ext == "xml") { return loadFromFile(filename); } std::cerr << "Simulation : Error : extension not handled" << std::endl; return NULL; } Simulation::Simulation() : numMechSteps( initData(&numMechSteps,(unsigned) 1,"numMechSteps","Number of mechanical steps within one update step. If the update time step is dt, the mechanical time step is dt/numMechSteps.") ), gnuplotDirectory( initData(&gnuplotDirectory,std::string(""),"gnuplotDirectory","Directory where the gnuplot files will be saved")), instrumentInUse( initData( &instrumentInUse, -1, "instrumentinuse", "Numero of the instrument currently used")) {} Simulation::~Simulation() { setSimulation( NULL ); } /// Print all object in the graph void Simulation::print ( Node* root ) { if ( !root ) return; root->execute<PrintVisitor>(); } /// Print all object in the graph void Simulation::printXML ( Node* root, const char* fileName ) { if ( !root ) return; if ( fileName!=NULL ) { std::ofstream out ( fileName ); XMLPrintVisitor print ( out ); root->execute ( print ); } else { XMLPrintVisitor print ( std::cout ); root->execute ( print ); } } /// Initialize the scene. void Simulation::init ( Node* root ) { //cerr<<"Simulation::init"<<endl; setContext( root->getContext()); if ( !root ) return; root->execute<InitVisitor>(); // Save reset state for later uses in reset() root->execute<MechanicalPropagatePositionAndVelocityVisitor>(); root->execute<MechanicalPropagateFreePositionVisitor>(); root->execute<StoreResetStateVisitor>(); //Get the list of instruments present in the scene graph getInstruments(root); } void Simulation::getInstruments( Node *node) { InstrumentVisitor fetchInstrument; node->execute<InstrumentVisitor>(); fetchInstrument.execute(node); instruments = fetchInstrument.getInstruments(); } /// Execute one timestep. If dt is 0, the dt parameter in the graph will be used void Simulation::animate ( Node* root, double dt ) { if ( !root ) return; if ( root->getMultiThreadSimulation() ) return; { AnimateBeginEvent ev ( dt ); PropagateEventVisitor act ( &ev ); root->execute ( act ); } //std::cout << "animate\n"; double startTime = root->getTime(); double mechanicalDt = dt/numMechSteps.getValue(); //double nextTime = root->getTime() + root->getDt(); // CHANGE to support MasterSolvers : CollisionVisitor is now activated within AnimateVisitor //root->execute<CollisionVisitor>(); AnimateVisitor act; act.setDt ( mechanicalDt ); for( unsigned i=0; i<numMechSteps.getValue(); i++ ) { root->execute ( act ); root->setTime ( startTime + (i+1)* act.getDt() ); root->execute<UpdateSimulationContextVisitor>(); } { AnimateEndEvent ev ( dt ); PropagateEventVisitor act ( &ev ); root->execute ( act ); } root->execute<UpdateMappingVisitor>(); { UpdateMappingEndEvent ev ( dt ); PropagateEventVisitor act ( &ev ); root->execute ( act ); } root->execute<VisualUpdateVisitor>(); } /// Reset to initial state void Simulation::reset ( Node* root ) { if ( !root ) return; root->execute<ResetVisitor>(); root->execute<MechanicalPropagatePositionAndVelocityVisitor>(); root->execute<UpdateMappingVisitor>(); root->execute<VisualUpdateVisitor>(); } /// Initialize the textures void Simulation::initTextures ( Node* root ) { if ( !root ) return; root->execute<VisualInitVisitor>(); // Do a visual update now as it is not done in load() anymore /// \todo Separate this into another method? root->execute<VisualUpdateVisitor>(); } /// Compute the bounding box of the scene. void Simulation::computeBBox ( Node* root, SReal* minBBox, SReal* maxBBox ) { VisualComputeBBoxVisitor act; if ( root ) root->execute ( act ); minBBox[0] = (SReal)(act.minBBox[0]); minBBox[1] = (SReal)(act.minBBox[1]); minBBox[2] = (SReal)(act.minBBox[2]); maxBBox[0] = (SReal)(act.maxBBox[0]); maxBBox[1] = (SReal)(act.maxBBox[1]); maxBBox[2] = (SReal)(act.maxBBox[2]); } /// Update contexts. Required before drawing the scene if root flags are modified. void Simulation::updateContext ( Node* root ) { if ( !root ) return; root->execute<UpdateContextVisitor>(); } /// Update only Visual contexts. Required before drawing the scene if root flags are modified.( can filter by specifying a specific element) void Simulation::updateVisualContext ( Node* root, int FILTER) { if ( !root ) return; UpdateVisualContextVisitor vis(FILTER); vis.execute(root); } /// Render the scene void Simulation::draw ( Node* root ) { if ( !root ) return; VisualDrawVisitor act ( core::VisualModel::Std ); root->execute ( &act ); VisualDrawVisitor act2 ( core::VisualModel::Transparent ); root->execute ( &act2 ); } /// Render the scene - shadow pass void Simulation::drawShadows ( Node* root ) { if ( !root ) return; //std::cout << "drawShadows\n"; VisualDrawVisitor act ( core::VisualModel::Shadow ); root->execute ( &act ); } /// Delete a scene from memory. After this call the pointer is invalid void Simulation::unload ( GNode* root ) { if ( !root ) return; instruments.clear(); instrumentInUse.setValue(-1); root->execute<DeleteVisitor>(); if ( root->getParent() !=NULL ) root->getParent()->removeChild ( root ); delete root; } /// Export a scene to an OBJ 3D Scene void Simulation::exportOBJ ( Node* root, const char* filename, bool exportMTL ) { if ( !root ) return; std::ofstream fout ( filename ); fout << "# Generated from SOFA Simulation" << std::endl; if ( !exportMTL ) { ExportOBJVisitor act ( &fout ); root->execute ( &act ); } else { const char *path1 = strrchr ( filename, '/' ); const char *path2 = strrchr ( filename, '\\' ); const char* path = ( path1==NULL ) ? ( ( path2==NULL ) ?filename : path2+1 ) : ( path2==NULL ) ? path1+1 : ( ( path1-filename ) > ( path2-filename ) ) ? path1+1 : path2+1; const char *ext = strrchr ( path, '.' ); if ( !ext ) ext = path + strlen ( path ); std::string mtlfilename ( path, ext ); mtlfilename += ".mtl"; std::string mtlpathname ( filename, ext ); mtlpathname += ".mtl"; std::ofstream mtl ( mtlpathname.c_str() ); mtl << "# Generated from SOFA Simulation" << std::endl; fout << "mtllib "<<mtlfilename<<'\n'; ExportOBJVisitor act ( &fout,&mtl ); root->execute ( &act ); } } /// Export a scene to XML void Simulation::exportXML ( Node* root, const char* filename ) { if ( !root ) return; std::ofstream fout ( filename ); XMLPrintVisitor act ( fout ); root->execute ( &act ); } void Simulation::dumpState ( Node* root, std::ofstream& out ) { out<<root->getTime() <<" "; WriteStateVisitor ( out ).execute ( root ); out<<endl; } /// Initialize gnuplot file output void Simulation::initGnuplot ( Node* root ) { if ( !root ) return; InitGnuplotVisitor v(gnuplotDirectory.getValue()); root->execute( v ); } /// Update gnuplot file output void Simulation::exportGnuplot ( Node* root, double time ) { if ( !root ) return; ExportGnuplotVisitor expg ( time ); root->execute ( expg ); } SOFA_DECL_CLASS ( Simulation ); // Register in the Factory int SimulationClass = core::RegisterObject ( "Main simulation algorithm" ) .add< Simulation >() ; } // namespace tree } // namespace simulation } // namespace sofa <|endoftext|>
<commit_before>#include "HeatGeneration.h" #include "HeatStructureBase.h" #include "HeatStructureCylindrical.h" #include "HeatStructurePlate.h" #include "ReactorPower.h" registerMooseObject("THMApp", HeatGeneration); template <> InputParameters validParams<HeatGeneration>() { InputParameters params = validParams<Component>(); params.addRequiredParam<std::string>( "hs", "The name of the heat structure component to put the heat source onto"); params.addRequiredParam<std::vector<std::string>>( "regions", "The names of the heat structure regions where heat generation is to be applied"); params.addParam<std::string>("power", "The component name that provides reactor power"); params.addParam<Real>( "power_fraction", 1., "The fraction of reactor power that goes into the heat structure"); params.addParam<FunctionName>("power_shape_function", "axial power shape of the fuel"); params.addParam<std::string>("power_density", "The name of the power density variable"); return params; } HeatGeneration::HeatGeneration(const InputParameters & parameters) : Component(parameters), _region_names(getParam<std::vector<std::string>>("regions")), _power_fraction(getParam<Real>("power_fraction")), _has_psf(isParamValid("power_shape_function")), _power_shape_func(_has_psf ? getParam<FunctionName>("power_shape_function") : ""), _has_power_density(isParamValid("power_density")), _power_density_name(_has_power_density ? getParam<std::string>("power_density") : "") { checkSizeGreaterThan<std::string>("regions", 0); } void HeatGeneration::init() { Component::init(); if (isParamValid("power")) if (hasComponent<ReactorPower>("power")) { const ReactorPower & rp = getComponent<ReactorPower>("power"); _power_var_name = rp.getPowerVariableName(); } } void HeatGeneration::check() const { Component::check(); checkComponentOfTypeExists<HeatStructureBase>("hs"); if (hasComponent<HeatStructureBase>("hs")) { const HeatStructureBase & hs = getComponent<HeatStructureBase>("hs"); for (auto && region : _region_names) if (!hs.hasBlock(region)) logError("Region '", region, "' does not exist in heat structure '", getParam<std::string>("hs"), "'."); } checkMutuallyExclusiveParameters({"power", "power_density"}); if (isParamValid("power")) checkComponentOfTypeExists<ReactorPower>("power"); } void HeatGeneration::addMooseObjects() { /// The heat structure component we work with const HeatStructureBase & hs = getComponent<HeatStructureBase>("hs"); Real volume = 0.; std::vector<SubdomainName> subdomain_names; for (auto && region : _region_names) { const unsigned int idx = hs.getIndexFromName(region); subdomain_names.push_back(hs.getSubdomainNames()[idx]); volume += hs.getVolumes()[idx]; } if (!_has_psf) { _power_shape_func = genName(name(), "power_shape_fn"); std::string class_name = "ConstantFunction"; InputParameters pars = _factory.getValidParams(class_name); pars.set<Real>("value") = 1. / hs.getLength(); _sim.addFunction(class_name, _power_shape_func, pars); } const HeatStructureCylindrical * hs_cyl = dynamic_cast<const HeatStructureCylindrical *>(&hs); if (hs_cyl != nullptr) { if (_has_power_density) { std::string class_name = "CoupledForceRZ"; InputParameters pars = _factory.getValidParams(class_name); pars.set<NonlinearVariableName>("variable") = HeatConductionModel::TEMPERATURE; pars.set<std::vector<SubdomainName>>("block") = subdomain_names; pars.set<std::vector<VariableName>>("v") = std::vector<VariableName>(1, _power_density_name); pars.set<Point>("axis_point") = hs.getPosition(); pars.set<RealVectorValue>("axis_dir") = hs.getDirection(); std::string mon = genName(name(), "heat_src"); _sim.addKernel(class_name, mon, pars); } else { std::string class_name = "OneDHeatForcingFunctionRZ"; InputParameters pars = _factory.getValidParams(class_name); pars.set<NonlinearVariableName>("variable") = HeatConductionModel::TEMPERATURE; pars.set<std::vector<SubdomainName>>("block") = subdomain_names; pars.set<Real>("power_fraction") = _power_fraction; pars.set<Real>("volume") = volume; pars.set<FunctionName>("power_shape_function") = _power_shape_func; pars.set<std::vector<VariableName>>("total_power") = std::vector<VariableName>(1, _power_var_name); pars.set<Point>("axis_point") = hs.getPosition(); pars.set<RealVectorValue>("axis_dir") = hs.getDirection(); std::string mon = genName(name(), "heat_src"); _sim.addKernel(class_name, mon, pars); connectObject(pars, mon, "power_fraction"); } } const HeatStructurePlate * hs_plate = dynamic_cast<const HeatStructurePlate *>(&hs); if (hs_plate != nullptr) { if (_has_power_density) { std::string class_name = "CoupledForce"; InputParameters pars = _factory.getValidParams(class_name); pars.set<NonlinearVariableName>("variable") = HeatConductionModel::TEMPERATURE; pars.set<std::vector<SubdomainName>>("block") = subdomain_names; pars.set<std::vector<VariableName>>("v") = std::vector<VariableName>(1, _power_density_name); std::string mon = genName(name(), "heat_src"); _sim.addKernel(class_name, mon, pars); } else { std::string class_name = "OneDHeatForcingFunction"; InputParameters pars = _factory.getValidParams(class_name); pars.set<NonlinearVariableName>("variable") = HeatConductionModel::TEMPERATURE; pars.set<std::vector<SubdomainName>>("block") = subdomain_names; pars.set<Real>("power_fraction") = _power_fraction; pars.set<Real>("volume") = volume; pars.set<FunctionName>("power_shape_function") = _power_shape_func; pars.set<std::vector<VariableName>>("total_power") = std::vector<VariableName>(1, _power_var_name); std::string mon = genName(name(), "heat_src"); _sim.addKernel(class_name, mon, pars); connectObject(pars, mon, "power_fraction"); } } } <commit_msg>Decreased code duplication in HeatGeneration<commit_after>#include "HeatGeneration.h" #include "HeatStructureBase.h" #include "HeatStructureCylindrical.h" #include "HeatStructurePlate.h" #include "ReactorPower.h" registerMooseObject("THMApp", HeatGeneration); template <> InputParameters validParams<HeatGeneration>() { InputParameters params = validParams<Component>(); params.addRequiredParam<std::string>( "hs", "The name of the heat structure component to put the heat source onto"); params.addRequiredParam<std::vector<std::string>>( "regions", "The names of the heat structure regions where heat generation is to be applied"); params.addParam<std::string>("power", "The component name that provides reactor power"); params.addParam<Real>( "power_fraction", 1., "The fraction of reactor power that goes into the heat structure"); params.addParam<FunctionName>("power_shape_function", "axial power shape of the fuel"); params.addParam<std::string>("power_density", "The name of the power density variable"); return params; } HeatGeneration::HeatGeneration(const InputParameters & parameters) : Component(parameters), _region_names(getParam<std::vector<std::string>>("regions")), _power_fraction(getParam<Real>("power_fraction")), _has_psf(isParamValid("power_shape_function")), _power_shape_func(_has_psf ? getParam<FunctionName>("power_shape_function") : ""), _has_power_density(isParamValid("power_density")), _power_density_name(_has_power_density ? getParam<std::string>("power_density") : "") { checkSizeGreaterThan<std::string>("regions", 0); } void HeatGeneration::init() { Component::init(); if (isParamValid("power")) if (hasComponent<ReactorPower>("power")) { const ReactorPower & rp = getComponent<ReactorPower>("power"); _power_var_name = rp.getPowerVariableName(); } } void HeatGeneration::check() const { Component::check(); checkComponentOfTypeExists<HeatStructureBase>("hs"); if (hasComponent<HeatStructureBase>("hs")) { if (!hasComponent<HeatStructurePlate>("hs") && !hasComponent<HeatStructureCylindrical>("hs")) logError( "Heat structure must be of type 'HeatStructurePlate' or 'HeatStructureCylindrical'."); const HeatStructureBase & hs = getComponent<HeatStructureBase>("hs"); for (auto && region : _region_names) if (!hs.hasBlock(region)) logError("Region '", region, "' does not exist in heat structure '", getParam<std::string>("hs"), "'."); } checkMutuallyExclusiveParameters({"power", "power_density"}); if (isParamValid("power")) checkComponentOfTypeExists<ReactorPower>("power"); } void HeatGeneration::addMooseObjects() { /// The heat structure component we work with const HeatStructureBase & hs = getComponent<HeatStructureBase>("hs"); Real volume = 0.; std::vector<SubdomainName> subdomain_names; for (auto && region : _region_names) { const unsigned int idx = hs.getIndexFromName(region); subdomain_names.push_back(hs.getSubdomainNames()[idx]); volume += hs.getVolumes()[idx]; } const HeatStructureCylindrical * hs_cyl = dynamic_cast<const HeatStructureCylindrical *>(&hs); const bool is_cylindrical = hs_cyl != nullptr; if (_has_power_density) { const std::string class_name = is_cylindrical ? "CoupledForceRZ" : "CoupledForce"; InputParameters pars = _factory.getValidParams(class_name); pars.set<NonlinearVariableName>("variable") = HeatConductionModel::TEMPERATURE; pars.set<std::vector<SubdomainName>>("block") = subdomain_names; pars.set<std::vector<VariableName>>("v") = std::vector<VariableName>(1, _power_density_name); if (is_cylindrical) { pars.set<Point>("axis_point") = hs.getPosition(); pars.set<RealVectorValue>("axis_dir") = hs.getDirection(); } std::string mon = genName(name(), "heat_src"); _sim.addKernel(class_name, mon, pars); } else { if (!_has_psf) { _power_shape_func = genName(name(), "power_shape_fn"); std::string class_name = "ConstantFunction"; InputParameters pars = _factory.getValidParams(class_name); pars.set<Real>("value") = 1. / hs.getLength(); _sim.addFunction(class_name, _power_shape_func, pars); } { const std::string class_name = is_cylindrical ? "OneDHeatForcingFunctionRZ" : "OneDHeatForcingFunction"; InputParameters pars = _factory.getValidParams(class_name); pars.set<NonlinearVariableName>("variable") = HeatConductionModel::TEMPERATURE; pars.set<std::vector<SubdomainName>>("block") = subdomain_names; pars.set<Real>("power_fraction") = _power_fraction; pars.set<Real>("volume") = volume; pars.set<FunctionName>("power_shape_function") = _power_shape_func; pars.set<std::vector<VariableName>>("total_power") = std::vector<VariableName>(1, _power_var_name); if (is_cylindrical) { pars.set<Point>("axis_point") = hs.getPosition(); pars.set<RealVectorValue>("axis_dir") = hs.getDirection(); } std::string mon = genName(name(), "heat_src"); _sim.addKernel(class_name, mon, pars); connectObject(pars, mon, "power_fraction"); } } } <|endoftext|>
<commit_before>/* * System.cpp * * Created on: Apr 29, 2014 * Author: Pimenta */ // this #include "System.hpp" // local #include "Defines.hpp" #include "FileSystem.hpp" using namespace std; using namespace concurrency; using namespace network; Thread* System::thread = nullptr; bool System::started = false; bool System::initialized = false; bool System::start() { if (started | initialized) return false; started = true; thread = new Thread([]() { network::init(); { System sys; initialized = true; sys.run(); } network::close(); initialized = false; }); thread->start(); return true; } void System::stop(bool wait) { if (wait && thread == nullptr) { while (initialized) Thread::sleep(200); return; } if (!started | !initialized) return; started = false; if (wait) thread->join(); delete thread; thread = nullptr; return; } bool System::changing() { return started ^ initialized; } bool System::running() { return started & initialized; } System::System() : state(STATE_NONE), localAddress(Address::local()), multicastAddress(IP_MAIN, TCPUDP_MAIN), mainUDPSocket(multicastAddress, SIZE_MULTICAST_MAXLEN), mainTCPServer(TCPUDP_MAIN), httpTCPServer(TCP_HTTPSERVER), httpThread([]() {}), downloadsRemaining(0) { changeToLogin(); } System::~System() { state = STATE_NONE; httpThread.join(); while (downloadsRemaining) Thread::sleep(MS_SLEEP); } void System::run() { while (started) { switch (state) { case STATE_NONE: break; case STATE_LOGIN: stateLogin(); break; case STATE_IDLE: stateIdle(); break; } Thread::sleep(MS_SLEEP); } } <commit_msg>Removing STATE_NONE in switch case<commit_after>/* * System.cpp * * Created on: Apr 29, 2014 * Author: Pimenta */ // this #include "System.hpp" // local #include "Defines.hpp" #include "FileSystem.hpp" using namespace std; using namespace concurrency; using namespace network; Thread* System::thread = nullptr; bool System::started = false; bool System::initialized = false; bool System::start() { if (started | initialized) return false; started = true; thread = new Thread([]() { network::init(); { System sys; initialized = true; sys.run(); } network::close(); initialized = false; }); thread->start(); return true; } void System::stop(bool wait) { if (wait && thread == nullptr) { while (initialized) Thread::sleep(200); return; } if (!started | !initialized) return; started = false; if (wait) thread->join(); delete thread; thread = nullptr; return; } bool System::changing() { return started ^ initialized; } bool System::running() { return started & initialized; } System::System() : state(STATE_NONE), localAddress(Address::local()), multicastAddress(IP_MAIN, TCPUDP_MAIN), mainUDPSocket(multicastAddress, SIZE_MULTICAST_MAXLEN), mainTCPServer(TCPUDP_MAIN), httpTCPServer(TCP_HTTPSERVER), httpThread([]() {}), downloadsRemaining(0) { changeToLogin(); } System::~System() { state = STATE_NONE; httpThread.join(); while (downloadsRemaining) Thread::sleep(MS_SLEEP); } void System::run() { while (started && state != STATE_NONE) { switch (state) { case STATE_LOGIN: stateLogin(); break; case STATE_IDLE: stateIdle(); break; } Thread::sleep(MS_SLEEP); } } <|endoftext|>
<commit_before>#include <OpenCLcontext.h> #include <random> #include <iostream> #define X 800 #define Y 600 int main(void) { try { std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<unsigned int> dist; unsigned int framebuffer[X*Y]; OpenCL_Manager mgr; mgr.initialize(X, Y); unsigned long redpixels = 0; while (true) { for (size_t i = 0; i < X*Y; ++i) framebuffer[i] = dist(mt); redpixels = 0; mgr.processCameraFrame(reinterpret_cast<unsigned char*>(framebuffer), &redpixels); std::cout << "FRAME red pixels: " << redpixels << "\n"; } } catch (std::exception &e) { std::cerr << "ERROR: " << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>Add timing to examples/accel/accel_countred.cpp<commit_after>#include <OpenCLcontext.h> #include <random> #include <iostream> #define X 800 #define Y 600 int main(void) { try { std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<unsigned int> dist; unsigned int framebuffer[X*Y]; OpenCL_Manager mgr; mgr.initialize(X, Y); unsigned long redpixels = 0; while (true) { using clock_type = std::chrono::steady_clock; using second_type = std::chrono::duration<double, std::ratio<1> >; for (size_t i = 0; i < X*Y; ++i) framebuffer[i] = dist(mt); redpixels = 0; std::chrono::time_point<clock_type> m_beg { clock_type::now() }; mgr.processCameraFrame(reinterpret_cast<unsigned char*>(framebuffer), &redpixels); std::chrono::time_point<clock_type> m_end { clock_type::now() }; double diff = std::chrono::duration_cast<second_type>(m_end - m_beg).count(); std::cout << "FRAME red pixels: " << redpixels << " time: " << diff << "\n"; } } catch (std::exception &e) { std::cerr << "ERROR: " << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** * OpenAL cross platform audio library * Copyright (C) 2009 by Chris Robinson. * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * Or go to http://www.gnu.org/copyleft/lgpl.html */ #include "config.h" #include <cmath> #include <cstdlib> #include <cmath> #include <algorithm> #include "alMain.h" #include "alcontext.h" #include "alAuxEffectSlot.h" #include "alError.h" #include "alu.h" #include "filters/biquad.h" #include "vecmat.h" namespace { #define MAX_UPDATE_SAMPLES 128 #define WAVEFORM_FRACBITS 24 #define WAVEFORM_FRACONE (1<<WAVEFORM_FRACBITS) #define WAVEFORM_FRACMASK (WAVEFORM_FRACONE-1) inline ALfloat Sin(ALsizei index) { return std::sin(static_cast<ALfloat>(index) * (al::MathDefs<float>::Tau() / ALfloat{WAVEFORM_FRACONE})); } inline ALfloat Saw(ALsizei index) { return static_cast<ALfloat>(index)*(2.0f/WAVEFORM_FRACONE) - 1.0f; } inline ALfloat Square(ALsizei index) { return static_cast<ALfloat>(((index>>(WAVEFORM_FRACBITS-2))&2) - 1); } inline ALfloat One(ALsizei UNUSED(index)) { return 1.0f; } template<ALfloat func(ALsizei)> void Modulate(ALfloat *RESTRICT dst, ALsizei index, const ALsizei step, ALsizei todo) { ALsizei i; for(i = 0;i < todo;i++) { index += step; index &= WAVEFORM_FRACMASK; dst[i] = func(index); } } struct ModulatorState final : public EffectState { void (*mGetSamples)(ALfloat*RESTRICT, ALsizei, const ALsizei, ALsizei){}; ALsizei mIndex{0}; ALsizei mStep{1}; struct { BiquadFilter Filter; ALfloat CurrentGains[MAX_OUTPUT_CHANNELS]{}; ALfloat TargetGains[MAX_OUTPUT_CHANNELS]{}; } mChans[MAX_AMBI_CHANNELS]; ALboolean deviceUpdate(const ALCdevice *device) override; void update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target) override; void process(const ALsizei samplesToDo, const FloatBufferLine *RESTRICT samplesIn, const ALsizei numInput, const al::span<FloatBufferLine> samplesOut) override; DEF_NEWDEL(ModulatorState) }; ALboolean ModulatorState::deviceUpdate(const ALCdevice *UNUSED(device)) { for(auto &e : mChans) { e.Filter.clear(); std::fill(std::begin(e.CurrentGains), std::end(e.CurrentGains), 0.0f); } return AL_TRUE; } void ModulatorState::update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target) { const ALCdevice *device{context->Device}; const float step{props->Modulator.Frequency / static_cast<ALfloat>(device->Frequency)}; mStep = fastf2i(clampf(step*WAVEFORM_FRACONE, 0.0f, ALfloat{WAVEFORM_FRACONE-1})); if(mStep == 0) mGetSamples = Modulate<One>; else if(props->Modulator.Waveform == AL_RING_MODULATOR_SINUSOID) mGetSamples = Modulate<Sin>; else if(props->Modulator.Waveform == AL_RING_MODULATOR_SAWTOOTH) mGetSamples = Modulate<Saw>; else /*if(Slot->Params.EffectProps.Modulator.Waveform == AL_RING_MODULATOR_SQUARE)*/ mGetSamples = Modulate<Square>; ALfloat f0norm{props->Modulator.HighPassCutoff / static_cast<ALfloat>(device->Frequency)}; f0norm = clampf(f0norm, 1.0f/512.0f, 0.49f); /* Bandwidth value is constant in octaves. */ mChans[0].Filter.setParams(BiquadType::HighPass, 1.0f, f0norm, BiquadFilter::rcpQFromBandwidth(f0norm, 0.75f)); for(ALuint i{1u};i < slot->Wet.NumChannels;++i) mChans[i].Filter.copyParamsFrom(mChans[0].Filter); mOutTarget = {target.Main->Buffer, target.Main->NumChannels}; for(ALuint i{0u};i < slot->Wet.NumChannels;++i) { auto coeffs = GetAmbiIdentityRow(i); ComputePanGains(target.Main, coeffs.data(), slot->Params.Gain, mChans[i].TargetGains); } } void ModulatorState::process(const ALsizei samplesToDo, const FloatBufferLine *RESTRICT samplesIn, const ALsizei numInput, const al::span<FloatBufferLine> samplesOut) { const ALsizei step{mStep}; for(ALsizei base{0};base < samplesToDo;) { alignas(16) ALfloat modsamples[MAX_UPDATE_SAMPLES]; ALsizei td = mini(MAX_UPDATE_SAMPLES, samplesToDo-base); ALsizei c, i; mGetSamples(modsamples, mIndex, step, td); mIndex += (step*td) & WAVEFORM_FRACMASK; mIndex &= WAVEFORM_FRACMASK; ASSUME(numInput > 0); for(c = 0;c < numInput;c++) { alignas(16) ALfloat temps[MAX_UPDATE_SAMPLES]; mChans[c].Filter.process(temps, &samplesIn[c][base], td); for(i = 0;i < td;i++) temps[i] *= modsamples[i]; MixSamples(temps, samplesOut, mChans[c].CurrentGains, mChans[c].TargetGains, samplesToDo-base, base, td); } base += td; } } void Modulator_setParamf(EffectProps *props, ALCcontext *context, ALenum param, ALfloat val) { switch(param) { case AL_RING_MODULATOR_FREQUENCY: if(!(val >= AL_RING_MODULATOR_MIN_FREQUENCY && val <= AL_RING_MODULATOR_MAX_FREQUENCY)) SETERR_RETURN(context, AL_INVALID_VALUE,, "Modulator frequency out of range"); props->Modulator.Frequency = val; break; case AL_RING_MODULATOR_HIGHPASS_CUTOFF: if(!(val >= AL_RING_MODULATOR_MIN_HIGHPASS_CUTOFF && val <= AL_RING_MODULATOR_MAX_HIGHPASS_CUTOFF)) SETERR_RETURN(context, AL_INVALID_VALUE,, "Modulator high-pass cutoff out of range"); props->Modulator.HighPassCutoff = val; break; default: alSetError(context, AL_INVALID_ENUM, "Invalid modulator float property 0x%04x", param); } } void Modulator_setParamfv(EffectProps *props, ALCcontext *context, ALenum param, const ALfloat *vals) { Modulator_setParamf(props, context, param, vals[0]); } void Modulator_setParami(EffectProps *props, ALCcontext *context, ALenum param, ALint val) { switch(param) { case AL_RING_MODULATOR_FREQUENCY: case AL_RING_MODULATOR_HIGHPASS_CUTOFF: Modulator_setParamf(props, context, param, static_cast<ALfloat>(val)); break; case AL_RING_MODULATOR_WAVEFORM: if(!(val >= AL_RING_MODULATOR_MIN_WAVEFORM && val <= AL_RING_MODULATOR_MAX_WAVEFORM)) SETERR_RETURN(context, AL_INVALID_VALUE,, "Invalid modulator waveform"); props->Modulator.Waveform = val; break; default: alSetError(context, AL_INVALID_ENUM, "Invalid modulator integer property 0x%04x", param); } } void Modulator_setParamiv(EffectProps *props, ALCcontext *context, ALenum param, const ALint *vals) { Modulator_setParami(props, context, param, vals[0]); } void Modulator_getParami(const EffectProps *props, ALCcontext *context, ALenum param, ALint *val) { switch(param) { case AL_RING_MODULATOR_FREQUENCY: *val = static_cast<ALint>(props->Modulator.Frequency); break; case AL_RING_MODULATOR_HIGHPASS_CUTOFF: *val = static_cast<ALint>(props->Modulator.HighPassCutoff); break; case AL_RING_MODULATOR_WAVEFORM: *val = props->Modulator.Waveform; break; default: alSetError(context, AL_INVALID_ENUM, "Invalid modulator integer property 0x%04x", param); } } void Modulator_getParamiv(const EffectProps *props, ALCcontext *context, ALenum param, ALint *vals) { Modulator_getParami(props, context, param, vals); } void Modulator_getParamf(const EffectProps *props, ALCcontext *context, ALenum param, ALfloat *val) { switch(param) { case AL_RING_MODULATOR_FREQUENCY: *val = props->Modulator.Frequency; break; case AL_RING_MODULATOR_HIGHPASS_CUTOFF: *val = props->Modulator.HighPassCutoff; break; default: alSetError(context, AL_INVALID_ENUM, "Invalid modulator float property 0x%04x", param); } } void Modulator_getParamfv(const EffectProps *props, ALCcontext *context, ALenum param, ALfloat *vals) { Modulator_getParamf(props, context, param, vals); } DEFINE_ALEFFECT_VTABLE(Modulator); struct ModulatorStateFactory final : public EffectStateFactory { EffectState *create() override { return new ModulatorState{}; } EffectProps getDefaultProps() const noexcept override; const EffectVtable *getEffectVtable() const noexcept override { return &Modulator_vtable; } }; EffectProps ModulatorStateFactory::getDefaultProps() const noexcept { EffectProps props{}; props.Modulator.Frequency = AL_RING_MODULATOR_DEFAULT_FREQUENCY; props.Modulator.HighPassCutoff = AL_RING_MODULATOR_DEFAULT_HIGHPASS_CUTOFF; props.Modulator.Waveform = AL_RING_MODULATOR_DEFAULT_WAVEFORM; return props; } } // namespace EffectStateFactory *ModulatorStateFactory_getFactory() { static ModulatorStateFactory ModulatorFactory{}; return &ModulatorFactory; } <commit_msg>avoid extra local member declaration<commit_after>/** * OpenAL cross platform audio library * Copyright (C) 2009 by Chris Robinson. * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * Or go to http://www.gnu.org/copyleft/lgpl.html */ #include "config.h" #include <cmath> #include <cstdlib> #include <cmath> #include <algorithm> #include "alMain.h" #include "alcontext.h" #include "alAuxEffectSlot.h" #include "alError.h" #include "alu.h" #include "filters/biquad.h" #include "vecmat.h" namespace { #define MAX_UPDATE_SAMPLES 128 #define WAVEFORM_FRACBITS 24 #define WAVEFORM_FRACONE (1<<WAVEFORM_FRACBITS) #define WAVEFORM_FRACMASK (WAVEFORM_FRACONE-1) inline ALfloat Sin(ALsizei index) { return std::sin(static_cast<ALfloat>(index) * (al::MathDefs<float>::Tau() / ALfloat{WAVEFORM_FRACONE})); } inline ALfloat Saw(ALsizei index) { return static_cast<ALfloat>(index)*(2.0f/WAVEFORM_FRACONE) - 1.0f; } inline ALfloat Square(ALsizei index) { return static_cast<ALfloat>(((index>>(WAVEFORM_FRACBITS-2))&2) - 1); } inline ALfloat One(ALsizei UNUSED(index)) { return 1.0f; } template<ALfloat func(ALsizei)> void Modulate(ALfloat *RESTRICT dst, ALsizei index, const ALsizei step, ALsizei todo) { ALsizei i; for(i = 0;i < todo;i++) { index += step; index &= WAVEFORM_FRACMASK; dst[i] = func(index); } } struct ModulatorState final : public EffectState { void (*mGetSamples)(ALfloat*RESTRICT, ALsizei, const ALsizei, ALsizei){}; ALsizei mIndex{0}; ALsizei mStep{1}; struct { BiquadFilter Filter; ALfloat CurrentGains[MAX_OUTPUT_CHANNELS]{}; ALfloat TargetGains[MAX_OUTPUT_CHANNELS]{}; } mChans[MAX_AMBI_CHANNELS]; ALboolean deviceUpdate(const ALCdevice *device) override; void update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target) override; void process(const ALsizei samplesToDo, const FloatBufferLine *RESTRICT samplesIn, const ALsizei numInput, const al::span<FloatBufferLine> samplesOut) override; DEF_NEWDEL(ModulatorState) }; ALboolean ModulatorState::deviceUpdate(const ALCdevice *UNUSED(device)) { for(auto &e : mChans) { e.Filter.clear(); std::fill(std::begin(e.CurrentGains), std::end(e.CurrentGains), 0.0f); } return AL_TRUE; } void ModulatorState::update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target) { const ALCdevice *device{context->Device}; const float step{props->Modulator.Frequency / static_cast<ALfloat>(device->Frequency)}; mStep = fastf2i(clampf(step*WAVEFORM_FRACONE, 0.0f, ALfloat{WAVEFORM_FRACONE-1})); if(mStep == 0) mGetSamples = Modulate<One>; else if(props->Modulator.Waveform == AL_RING_MODULATOR_SINUSOID) mGetSamples = Modulate<Sin>; else if(props->Modulator.Waveform == AL_RING_MODULATOR_SAWTOOTH) mGetSamples = Modulate<Saw>; else /*if(Slot->Params.EffectProps.Modulator.Waveform == AL_RING_MODULATOR_SQUARE)*/ mGetSamples = Modulate<Square>; ALfloat f0norm{props->Modulator.HighPassCutoff / static_cast<ALfloat>(device->Frequency)}; f0norm = clampf(f0norm, 1.0f/512.0f, 0.49f); /* Bandwidth value is constant in octaves. */ mChans[0].Filter.setParams(BiquadType::HighPass, 1.0f, f0norm, BiquadFilter::rcpQFromBandwidth(f0norm, 0.75f)); for(ALuint i{1u};i < slot->Wet.NumChannels;++i) mChans[i].Filter.copyParamsFrom(mChans[0].Filter); mOutTarget = {target.Main->Buffer, target.Main->NumChannels}; for(ALuint i{0u};i < slot->Wet.NumChannels;++i) { auto coeffs = GetAmbiIdentityRow(i); ComputePanGains(target.Main, coeffs.data(), slot->Params.Gain, mChans[i].TargetGains); } } void ModulatorState::process(const ALsizei samplesToDo, const FloatBufferLine *RESTRICT samplesIn, const ALsizei numInput, const al::span<FloatBufferLine> samplesOut) { for(ALsizei base{0};base < samplesToDo;) { alignas(16) ALfloat modsamples[MAX_UPDATE_SAMPLES]; ALsizei td = mini(MAX_UPDATE_SAMPLES, samplesToDo-base); ALsizei c, i; mGetSamples(modsamples, mIndex, mStep, td); mIndex += (mStep*td) & WAVEFORM_FRACMASK; mIndex &= WAVEFORM_FRACMASK; ASSUME(numInput > 0); for(c = 0;c < numInput;c++) { alignas(16) ALfloat temps[MAX_UPDATE_SAMPLES]; mChans[c].Filter.process(temps, &samplesIn[c][base], td); for(i = 0;i < td;i++) temps[i] *= modsamples[i]; MixSamples(temps, samplesOut, mChans[c].CurrentGains, mChans[c].TargetGains, samplesToDo-base, base, td); } base += td; } } void Modulator_setParamf(EffectProps *props, ALCcontext *context, ALenum param, ALfloat val) { switch(param) { case AL_RING_MODULATOR_FREQUENCY: if(!(val >= AL_RING_MODULATOR_MIN_FREQUENCY && val <= AL_RING_MODULATOR_MAX_FREQUENCY)) SETERR_RETURN(context, AL_INVALID_VALUE,, "Modulator frequency out of range"); props->Modulator.Frequency = val; break; case AL_RING_MODULATOR_HIGHPASS_CUTOFF: if(!(val >= AL_RING_MODULATOR_MIN_HIGHPASS_CUTOFF && val <= AL_RING_MODULATOR_MAX_HIGHPASS_CUTOFF)) SETERR_RETURN(context, AL_INVALID_VALUE,, "Modulator high-pass cutoff out of range"); props->Modulator.HighPassCutoff = val; break; default: alSetError(context, AL_INVALID_ENUM, "Invalid modulator float property 0x%04x", param); } } void Modulator_setParamfv(EffectProps *props, ALCcontext *context, ALenum param, const ALfloat *vals) { Modulator_setParamf(props, context, param, vals[0]); } void Modulator_setParami(EffectProps *props, ALCcontext *context, ALenum param, ALint val) { switch(param) { case AL_RING_MODULATOR_FREQUENCY: case AL_RING_MODULATOR_HIGHPASS_CUTOFF: Modulator_setParamf(props, context, param, static_cast<ALfloat>(val)); break; case AL_RING_MODULATOR_WAVEFORM: if(!(val >= AL_RING_MODULATOR_MIN_WAVEFORM && val <= AL_RING_MODULATOR_MAX_WAVEFORM)) SETERR_RETURN(context, AL_INVALID_VALUE,, "Invalid modulator waveform"); props->Modulator.Waveform = val; break; default: alSetError(context, AL_INVALID_ENUM, "Invalid modulator integer property 0x%04x", param); } } void Modulator_setParamiv(EffectProps *props, ALCcontext *context, ALenum param, const ALint *vals) { Modulator_setParami(props, context, param, vals[0]); } void Modulator_getParami(const EffectProps *props, ALCcontext *context, ALenum param, ALint *val) { switch(param) { case AL_RING_MODULATOR_FREQUENCY: *val = static_cast<ALint>(props->Modulator.Frequency); break; case AL_RING_MODULATOR_HIGHPASS_CUTOFF: *val = static_cast<ALint>(props->Modulator.HighPassCutoff); break; case AL_RING_MODULATOR_WAVEFORM: *val = props->Modulator.Waveform; break; default: alSetError(context, AL_INVALID_ENUM, "Invalid modulator integer property 0x%04x", param); } } void Modulator_getParamiv(const EffectProps *props, ALCcontext *context, ALenum param, ALint *vals) { Modulator_getParami(props, context, param, vals); } void Modulator_getParamf(const EffectProps *props, ALCcontext *context, ALenum param, ALfloat *val) { switch(param) { case AL_RING_MODULATOR_FREQUENCY: *val = props->Modulator.Frequency; break; case AL_RING_MODULATOR_HIGHPASS_CUTOFF: *val = props->Modulator.HighPassCutoff; break; default: alSetError(context, AL_INVALID_ENUM, "Invalid modulator float property 0x%04x", param); } } void Modulator_getParamfv(const EffectProps *props, ALCcontext *context, ALenum param, ALfloat *vals) { Modulator_getParamf(props, context, param, vals); } DEFINE_ALEFFECT_VTABLE(Modulator); struct ModulatorStateFactory final : public EffectStateFactory { EffectState *create() override { return new ModulatorState{}; } EffectProps getDefaultProps() const noexcept override; const EffectVtable *getEffectVtable() const noexcept override { return &Modulator_vtable; } }; EffectProps ModulatorStateFactory::getDefaultProps() const noexcept { EffectProps props{}; props.Modulator.Frequency = AL_RING_MODULATOR_DEFAULT_FREQUENCY; props.Modulator.HighPassCutoff = AL_RING_MODULATOR_DEFAULT_HIGHPASS_CUTOFF; props.Modulator.Waveform = AL_RING_MODULATOR_DEFAULT_WAVEFORM; return props; } } // namespace EffectStateFactory *ModulatorStateFactory_getFactory() { static ModulatorStateFactory ModulatorFactory{}; return &ModulatorFactory; } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "application.h" #include "midiio.h" #include "midiportsmodel.h" #include "programproxymodel.h" #include "utils.h" #include <QComboBox> #include <QFileDialog> #include <QPushButton> #include <QStandardPaths> #include <QtDebug> MainWindow::MainWindow(Application* app, QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), app(app) { Q_CHECK_PTR(app); ui->setupUi(this); setStatusBar(Q_NULLPTR); QComboBox* clientComboBox = new QComboBox(this); ui->toolBar->addWidget(clientComboBox); ui->toolBar->addAction(ui->actionRescan); ui->newProgramButton->setDefaultAction(ui->actionNewProgram); ui->deleteProgramButton->setDefaultAction(ui->actionDeleteProgram); ProgramProxyModel* programsProxyModel = new ProgramProxyModel(this); programsProxyModel->setSourceModel(app->programs()); programsProxyModel->setActiveProgramId(app->activeProgramId()); ui->programsView->setModel(programsProxyModel); connect(app, &Application::activeProgramIdChanged, [=](int programId) { programsProxyModel->setActiveProgramId(programId); refreshWidgetStack(); }); ui->programsView->setModelColumn(programModelColumn()); ui->padsView->setModel(app->pads()); ui->padsView->hideColumn(0); ui->padsView->hideColumn(1); ui->padsView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); ui->knobsView->setModel(app->knobs()); ui->knobsView->hideColumn(0); ui->knobsView->hideColumn(1); ui->knobsView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); connect(app->programs(), &QAbstractItemModel::modelReset, this, &MainWindow::refreshActionDeleteProgram ); refreshActionDeleteProgram(); refreshWidgetStack(); QGridLayout* l = new QGridLayout; l->setSizeConstraint(QLayout::SetMinimumSize); for (int i=1 ; i <= 16 ; ++i) { QPushButton* b = new QPushButton(this); b->setMaximumWidth(b->height()*3); b->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); b->setText(QString::number(i)); b->setCheckable(true); b->setAutoExclusive(true); connect(b, &QPushButton::clicked, [=](){ Q_CHECK_PTR(app); app->setActiveProgramChannel(i); }); const int row = (i - 1) < 8 ? 0 : 1; const int col = (i - 1) % 8; l->addWidget(b, row, col, 1, 1); midiChannelButtons.append(b); } connect(app, &Application::activeProgramChannelChanged, this, &MainWindow::setMidiChannel); ui->groupBoxMidiChannel->setLayout(l); connect(clientComboBox, QOverload<int>::of(&QComboBox::activated), [=](int row) { Q_CHECK_PTR(app->midiIO()); QAbstractItemModel* midiPortsModel = app->midiIO()->midiPortsModel(); const QModelIndex index(midiPortsModel->index(row, 0)); app->midiIO()->connectPort(index); }); clientComboBox->setModel(app->midiIO()->midiPortsModel()); } MainWindow::~MainWindow() { delete ui; } void MainWindow::setMidiChannel(int channel) { Q_ASSERT(channel == -1 || (channel >= 1 && channel <= 16)); QPushButton* b; if (channel == -1) { foreach (b, midiChannelButtons) { b->setChecked(false); } } else { midiChannelButtons[--channel]->setChecked(true); } } int MainWindow::programModelColumn() const { return 1; } void MainWindow::refreshWidgetStack() { Q_CHECK_PTR(app); QWidget* w = app->activeProgramId() > 0 ? ui->pageEditor : ui->pageDefault; ui->stackedWidget->setCurrentWidget(w); } void MainWindow::on_actionNewProgram_triggered() { Q_CHECK_PTR(app); app->newProgram("New program"); } void MainWindow::on_actionQuit_triggered() { qApp->quit(); } void MainWindow::on_programsView_activated(const QModelIndex& idx) { Q_ASSERT(idx.isValid()); Q_CHECK_PTR(idx.model()); Q_CHECK_PTR(app); app->setActiveProgramId(getProgramId(idx.model(), idx.row())); } void MainWindow::on_actionDeleteProgram_triggered() { Q_CHECK_PTR(app); app->deleteProgram(app->activeProgramId()); } void MainWindow::refreshActionDeleteProgram() { Q_CHECK_PTR(app); ui->actionDeleteProgram->setEnabled(app->programs()->rowCount() > 0); } void MainWindow::on_actionImportProgram_triggered() { Q_CHECK_PTR(app); const QString path( QFileDialog::getOpenFileName( this, "Import LPD8 program", QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation))); if (path.isEmpty()) { return; } app->importProgram(path); } void MainWindow::on_actionExportProgram_triggered() { Q_CHECK_PTR(app); const QString path( QFileDialog::getSaveFileName( this, "Export LPD8 program", QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation))); if (path.isEmpty()) { return; } app->exportActiveProgram(path); } void MainWindow::on_actionGetProgram1_triggered() { Q_CHECK_PTR(app); app->fetchProgram(1); } void MainWindow::on_actionGetProgram2_triggered() { Q_CHECK_PTR(app); app->fetchProgram(2); } void MainWindow::on_actionGetProgram3_triggered() { Q_CHECK_PTR(app); app->fetchProgram(3); } void MainWindow::on_actionGetProgram4_triggered() { Q_CHECK_PTR(app); app->fetchProgram(4); } void MainWindow::on_actionSendToProgram1_triggered() { Q_CHECK_PTR(app); app->sendProgram(1); } void MainWindow::on_actionSendToProgram2_triggered() { Q_CHECK_PTR(app); app->sendProgram(2); } void MainWindow::on_actionSendToProgram3_triggered() { Q_CHECK_PTR(app); app->sendProgram(3); } void MainWindow::on_actionSendToProgram4_triggered() { Q_CHECK_PTR(app); app->sendProgram(4); } void MainWindow::on_actionRescan_triggered() { Q_CHECK_PTR(app->midiIO()); app->midiIO()->rescanPorts(); } //void MainWindow::on_listView_activated(const QModelIndex& index) { // Q_CHECK_PTR(app); // MidiPortsModel* portsModel = qobject_cast<MidiPortsModel*>(app->midiIO()->midiPortsModel()); // Q_CHECK_PTR(portsModel); // portsModel->connect(index); //} <commit_msg>Connect to the first client after a refresh<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "application.h" #include "midiio.h" #include "midiportsmodel.h" #include "programproxymodel.h" #include "utils.h" #include <QComboBox> #include <QFileDialog> #include <QPushButton> #include <QStandardPaths> #include <QtDebug> MainWindow::MainWindow(Application* app, QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), app(app) { Q_CHECK_PTR(app); ui->setupUi(this); setStatusBar(Q_NULLPTR); QComboBox* clientComboBox = new QComboBox(this); ui->toolBar->addWidget(clientComboBox); ui->toolBar->addAction(ui->actionRescan); ui->newProgramButton->setDefaultAction(ui->actionNewProgram); ui->deleteProgramButton->setDefaultAction(ui->actionDeleteProgram); ProgramProxyModel* programsProxyModel = new ProgramProxyModel(this); programsProxyModel->setSourceModel(app->programs()); programsProxyModel->setActiveProgramId(app->activeProgramId()); ui->programsView->setModel(programsProxyModel); connect(app, &Application::activeProgramIdChanged, [=](int programId) { programsProxyModel->setActiveProgramId(programId); refreshWidgetStack(); }); ui->programsView->setModelColumn(programModelColumn()); ui->padsView->setModel(app->pads()); ui->padsView->hideColumn(0); ui->padsView->hideColumn(1); ui->padsView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); ui->knobsView->setModel(app->knobs()); ui->knobsView->hideColumn(0); ui->knobsView->hideColumn(1); ui->knobsView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); connect(app->programs(), &QAbstractItemModel::modelReset, this, &MainWindow::refreshActionDeleteProgram ); refreshActionDeleteProgram(); refreshWidgetStack(); QGridLayout* l = new QGridLayout; l->setSizeConstraint(QLayout::SetMinimumSize); for (int i=1 ; i <= 16 ; ++i) { QPushButton* b = new QPushButton(this); b->setMaximumWidth(b->height()*3); b->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); b->setText(QString::number(i)); b->setCheckable(true); b->setAutoExclusive(true); connect(b, &QPushButton::clicked, [=](){ Q_CHECK_PTR(app); app->setActiveProgramChannel(i); }); const int row = (i - 1) < 8 ? 0 : 1; const int col = (i - 1) % 8; l->addWidget(b, row, col, 1, 1); midiChannelButtons.append(b); } connect(app, &Application::activeProgramChannelChanged, this, &MainWindow::setMidiChannel); ui->groupBoxMidiChannel->setLayout(l); connect(clientComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [=](int row) { Q_CHECK_PTR(app->midiIO()); QAbstractItemModel* midiPortsModel = app->midiIO()->midiPortsModel(); const QModelIndex index(midiPortsModel->index(row, 0)); app->midiIO()->connectPort(index); }); clientComboBox->setModel(app->midiIO()->midiPortsModel()); } MainWindow::~MainWindow() { delete ui; } void MainWindow::setMidiChannel(int channel) { Q_ASSERT(channel == -1 || (channel >= 1 && channel <= 16)); QPushButton* b; if (channel == -1) { foreach (b, midiChannelButtons) { b->setChecked(false); } } else { midiChannelButtons[--channel]->setChecked(true); } } int MainWindow::programModelColumn() const { return 1; } void MainWindow::refreshWidgetStack() { Q_CHECK_PTR(app); QWidget* w = app->activeProgramId() > 0 ? ui->pageEditor : ui->pageDefault; ui->stackedWidget->setCurrentWidget(w); } void MainWindow::on_actionNewProgram_triggered() { Q_CHECK_PTR(app); app->newProgram("New program"); } void MainWindow::on_actionQuit_triggered() { qApp->quit(); } void MainWindow::on_programsView_activated(const QModelIndex& idx) { Q_ASSERT(idx.isValid()); Q_CHECK_PTR(idx.model()); Q_CHECK_PTR(app); app->setActiveProgramId(getProgramId(idx.model(), idx.row())); } void MainWindow::on_actionDeleteProgram_triggered() { Q_CHECK_PTR(app); app->deleteProgram(app->activeProgramId()); } void MainWindow::refreshActionDeleteProgram() { Q_CHECK_PTR(app); ui->actionDeleteProgram->setEnabled(app->programs()->rowCount() > 0); } void MainWindow::on_actionImportProgram_triggered() { Q_CHECK_PTR(app); const QString path( QFileDialog::getOpenFileName( this, "Import LPD8 program", QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation))); if (path.isEmpty()) { return; } app->importProgram(path); } void MainWindow::on_actionExportProgram_triggered() { Q_CHECK_PTR(app); const QString path( QFileDialog::getSaveFileName( this, "Export LPD8 program", QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation))); if (path.isEmpty()) { return; } app->exportActiveProgram(path); } void MainWindow::on_actionGetProgram1_triggered() { Q_CHECK_PTR(app); app->fetchProgram(1); } void MainWindow::on_actionGetProgram2_triggered() { Q_CHECK_PTR(app); app->fetchProgram(2); } void MainWindow::on_actionGetProgram3_triggered() { Q_CHECK_PTR(app); app->fetchProgram(3); } void MainWindow::on_actionGetProgram4_triggered() { Q_CHECK_PTR(app); app->fetchProgram(4); } void MainWindow::on_actionSendToProgram1_triggered() { Q_CHECK_PTR(app); app->sendProgram(1); } void MainWindow::on_actionSendToProgram2_triggered() { Q_CHECK_PTR(app); app->sendProgram(2); } void MainWindow::on_actionSendToProgram3_triggered() { Q_CHECK_PTR(app); app->sendProgram(3); } void MainWindow::on_actionSendToProgram4_triggered() { Q_CHECK_PTR(app); app->sendProgram(4); } void MainWindow::on_actionRescan_triggered() { Q_CHECK_PTR(app->midiIO()); app->midiIO()->rescanPorts(); } //void MainWindow::on_listView_activated(const QModelIndex& index) { // Q_CHECK_PTR(app); // MidiPortsModel* portsModel = qobject_cast<MidiPortsModel*>(app->midiIO()->midiPortsModel()); // Q_CHECK_PTR(portsModel); // portsModel->connect(index); //} <|endoftext|>
<commit_before>#include "p2Defs.h" #include "p2Log.h" #include "j1App.h" #include "j1Input.h" #include "j1Textures.h" #include "j1Audio.h" #include "j1Render.h" #include "j1Window.h" #include "j1Map.h" #include "j1Colliders.h" #include "j1Scene.h" #include "j1Scene2.h" #include "j1Player.h" j1Scene::j1Scene() : j1Module() { name.create("scene"); } // Destructor j1Scene::~j1Scene() {} // Called before render is available bool j1Scene::Awake(pugi::xml_node& config) { LOG("Loading Scene"); bool ret = true; return ret; } // Called before the first frame bool j1Scene::Start() { App->map->Load("test1.tmx"); App->audio->PlayMusic("audio/music/map1_music.ogg"); //Colliders //App->colliders->AddCollider({ 0,415,10000,10 }, COLLIDER_FLOOR); App->map->Draw_Colliders(); return true; } // Called each loop iteration bool j1Scene::PreUpdate() { return true; } // Called each loop iteration bool j1Scene::Update(float dt) { if(App->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN) App->SaveGame(); if(App->input->GetKey(SDL_SCANCODE_F6) == KEY_DOWN) App->LoadGame(); if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN) { active = false; App->scene2->active = true; CleanUp(); App->scene2->Start(); App->player->position.y = 215; App->player->position.x = 60; } if (App->player->position.x >= App->player->win_width/2 && App->player->position.x <= 15000)//App->player->win_width) { App->render->camera.x = -App->player->position.x + App->player->win_width / 2;// + App->player->win_width / 2; LOG("PositionCharacterX %i PoisitonCameraX %i",App->player->position.x,App->render->camera.x ); } //App->render->Blit(img, 0, 0); App->map->Draw(); // TODO 7: Set the window title like // "Map:%dx%d Tiles:%dx%d Tilesets:%d" p2SString title("Map:%dx%d Tiles:%dx%d Tilesets:%d Player.x=%i Player.y=%i CameraPosition.x=%i CameraPosition.y=%i Acceleration=%d X=%d Y=%d", App->map->data.width, App->map->data.height, App->map->data.tile_width, App->map->data.tile_height, App->map->data.tilesets.count(), App->player->position.x, App->player->position.y, App->render->camera.x, App->render->camera.y, App->player->acceleration, App->player->position.x,App->player->position.y); App->win->SetTitle(title.GetString()); return true; } // Called each loop iteration bool j1Scene::PostUpdate() { bool ret = true; if(App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN) ret = false; return ret; } // Called before quitting bool j1Scene::CleanUp() { LOG("Freeing scene"); App->map->CleanUp(); App->colliders->CleanUp(); return true; } <commit_msg>camera reset<commit_after>#include "p2Defs.h" #include "p2Log.h" #include "j1App.h" #include "j1Input.h" #include "j1Textures.h" #include "j1Audio.h" #include "j1Render.h" #include "j1Window.h" #include "j1Map.h" #include "j1Colliders.h" #include "j1Scene.h" #include "j1Scene2.h" #include "j1Player.h" j1Scene::j1Scene() : j1Module() { name.create("scene"); } // Destructor j1Scene::~j1Scene() {} // Called before render is available bool j1Scene::Awake(pugi::xml_node& config) { LOG("Loading Scene"); bool ret = true; return ret; } // Called before the first frame bool j1Scene::Start() { App->map->Load("test1.tmx"); App->audio->PlayMusic("audio/music/map1_music.ogg"); //Colliders //App->colliders->AddCollider({ 0,415,10000,10 }, COLLIDER_FLOOR); App->map->Draw_Colliders(); return true; } // Called each loop iteration bool j1Scene::PreUpdate() { return true; } // Called each loop iteration bool j1Scene::Update(float dt) { if(App->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN) App->SaveGame(); if(App->input->GetKey(SDL_SCANCODE_F6) == KEY_DOWN) App->LoadGame(); if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN) { active = false; App->scene2->active = true; CleanUp(); App->scene2->Start(); App->player->position.y = 215; App->player->position.x = 60; App->render->camera.x = 0; App->render->camera.y = 0; } if (App->player->position.x >= App->player->win_width/2 && App->player->position.x <= 15000)//App->player->win_width) { App->render->camera.x = -App->player->position.x + App->player->win_width / 2;// + App->player->win_width / 2; LOG("PositionCharacterX %i PoisitonCameraX %i",App->player->position.x,App->render->camera.x ); } //App->render->Blit(img, 0, 0); App->map->Draw(); // TODO 7: Set the window title like // "Map:%dx%d Tiles:%dx%d Tilesets:%d" p2SString title("Map:%dx%d Tiles:%dx%d Tilesets:%d Player.x=%i Player.y=%i CameraPosition.x=%i CameraPosition.y=%i Acceleration=%d X=%d Y=%d", App->map->data.width, App->map->data.height, App->map->data.tile_width, App->map->data.tile_height, App->map->data.tilesets.count(), App->player->position.x, App->player->position.y, App->render->camera.x, App->render->camera.y, App->player->acceleration, App->player->position.x,App->player->position.y); App->win->SetTitle(title.GetString()); return true; } // Called each loop iteration bool j1Scene::PostUpdate() { bool ret = true; if(App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN) ret = false; return ret; } // Called before quitting bool j1Scene::CleanUp() { LOG("Freeing scene"); App->map->CleanUp(); App->colliders->CleanUp(); return true; } <|endoftext|>
<commit_before>/** ========================================================================== * 2011 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * * For more information see g3log/LICENSE or refer refer to http://unlicense.org * ============================================================================*/ #include <g3log/g3log.hpp> #include <g3log/logworker.hpp> #include <iomanip> #include <thread> #include <iostream> #include <memory> namespace { #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) const std::string path_to_log_file = "./"; #else const std::string path_to_log_file = "/tmp/"; #endif } namespace example_fatal { // on Ubunti this caused get a compiler warning with gcc4.6 // from gcc 4.7.2 (at least) it causes a crash (as expected) // On windows it'll probably crash too. void tryToKillWithIllegalPrintout() { std::cout << "\n\n***** Be ready this last example may 'abort' if on Windows/Linux_gcc4.7 " << std::endl << std::flush; std::cout << "************************************************************\n\n" << std::endl << std::flush; std::this_thread::sleep_for(std::chrono::seconds(1)); const std::string logging = "logging"; LOGF(DEBUG, "ILLEGAL PRINTF_SYNTAX EXAMPLE. WILL GENERATE compiler warning.\n\nbadly formatted message:[Printf-type %s is the number 1 for many %s]", logging.c_str()); } // The function above 'tryToKillWithIllegalPrintout' IS system / compiler dependent. Older compilers sometimes did NOT generate a SIGSEGV // fault as expected by the illegal printf-format usage. just in case we exit by zero division" void killByZeroDivision(int value) { int zero = 0; // trying to fool the compiler to automatically warn LOG(INFO) << "This is a bad operation [value/zero] : " << value / zero; } } // example fatal int main(int argc, char **argv) { double pi_d = 3.1415926535897932384626433832795; float pi_f = 3.1415926535897932384626433832795f; using namespace g3; std::unique_ptr<LogWorker> logworker {LogWorker::createLogWorker()}; auto sinkHandle = logworker->addSink(std2::make_unique<FileSink>(argv[0], path_to_log_file), &FileSink::fileWrite); initializeLogging(logworker.get()); std::future<std::string> log_file_name = sinkHandle->call(&FileSink::fileName); std::cout << "* This is an example of g3log. It WILL exit by a FATAL trigger" << std::endl; std::cout << "* Please see the generated log and compare to the code at" << std::endl; std::cout << "* g3log/test_example/main.cpp" << std::endl; std::cout << "*\n* Log file: [" << log_file_name.get() << "]\n\n" << std::endl; LOGF(INFO, "Hi log %d", 123); LOG(INFO) << "Test SLOG INFO"; LOG(DEBUG) << "Test SLOG DEBUG"; LOG(INFO) << "one: " << 1; LOG(INFO) << "two: " << 2; LOG(INFO) << "one and two: " << 1 << " and " << 2; LOG(DEBUG) << "float 2.14: " << 1000 / 2.14f; LOG(DEBUG) << "pi double: " << pi_d; LOG(DEBUG) << "pi float: " << pi_f; LOG(DEBUG) << "pi float (width 10): " << std::setprecision(10) << pi_f; LOGF(INFO, "pi float printf:%f", pi_f); // // START: LOG Entris that were in the CodeProject article // //LOG(UNKNOWN_LEVEL) << "This log attempt will cause a compiler error"; LOG(INFO) << "Simple to use with streaming syntax, easy as abc or " << 123; LOGF(WARNING, "Printf-style syntax is also %s", "available"); LOG_IF(INFO, (1 < 2)) << "If true this text will be logged"; LOGF_IF(INFO, (1 < 2), "if %d<%d : then this text will be logged", 1, 2); LOG_IF(FATAL, (2 > 3)) << "This message should NOT throw"; LOGF(DEBUG, "This API is popular with some %s", "programmers"); LOGF_IF(DEBUG, (1 < 2), "If true, then this %s will be logged", "message"); // OK --- on Ubunti this caused get a compiler warning with gcc4.6 // from gcc 4.7.2 (at least) it causes a crash (as expected) // On windows itll probably crash //example_fatal::tryToKillWithIllegalPrintout(); int value = 1; // system dependent but it SHOULD never reach this line example_fatal::killByZeroDivision(value); return 0; } <commit_msg>The sigsegv example exited by sigfpe. Fixed!<commit_after>/** ========================================================================== * 2011 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * * For more information see g3log/LICENSE or refer refer to http://unlicense.org * ============================================================================*/ #include <g3log/g3log.hpp> #include <g3log/logworker.hpp> #include <iomanip> #include <thread> #include <iostream> #include <memory> namespace { #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) const std::string path_to_log_file = "./"; #else const std::string path_to_log_file = "/tmp/"; #endif } namespace example_fatal { // on Ubunti this caused get a compiler warning with gcc4.6 // from gcc 4.7.2 (at least) it causes a crash (as expected) // On windows it'll probably crash too. void tryToKillWithIllegalPrintout() { std::cout << "\n\n***** Be ready this last example may 'abort' if on Windows/Linux_gcc4.7 " << std::endl << std::flush; std::cout << "************************************************************\n\n" << std::endl << std::flush; std::this_thread::sleep_for(std::chrono::seconds(1)); const std::string logging = "logging"; LOGF(DEBUG, "ILLEGAL PRINTF_SYNTAX EXAMPLE. WILL GENERATE compiler warning.\n\nbadly formatted message:[Printf-type %s is the number 1 for many %s]", logging.c_str()); } // The function above 'tryToKillWithIllegalPrintout' IS system / compiler dependent. Older compilers sometimes did NOT generate a SIGSEGV // fault as expected by the illegal printf-format usage. just in case we exit by zero division" void killByZeroDivision(int value) { int zero = 0; // trying to fool the compiler to automatically warn LOG(INFO) << "This is a bad operation [value/zero] : " << value / zero; } void tryToKillWithAccessingIllegalPointer(std::unique_ptr<std::string> badStringPtr) { auto badPtr = std::move(badStringPtr); LOG(INFO) << "Function calls through a nullptr object will trigger SIGSEGV"; badStringPtr->append("crashing"); } } // example fatal int main(int argc, char **argv) { double pi_d = 3.1415926535897932384626433832795; float pi_f = 3.1415926535897932384626433832795f; using namespace g3; std::unique_ptr<LogWorker> logworker {LogWorker::createLogWorker()}; auto sinkHandle = logworker->addSink(std2::make_unique<FileSink>(argv[0], path_to_log_file), &FileSink::fileWrite); initializeLogging(logworker.get()); std::future<std::string> log_file_name = sinkHandle->call(&FileSink::fileName); std::cout << "* This is an example of g3log. It WILL exit by a FATAL trigger" << std::endl; std::cout << "* Please see the generated log and compare to the code at" << std::endl; std::cout << "* g3log/test_example/main.cpp" << std::endl; std::cout << "*\n* Log file: [" << log_file_name.get() << "]\n\n" << std::endl; LOGF(INFO, "Hi log %d", 123); LOG(INFO) << "Test SLOG INFO"; LOG(DEBUG) << "Test SLOG DEBUG"; LOG(INFO) << "one: " << 1; LOG(INFO) << "two: " << 2; LOG(INFO) << "one and two: " << 1 << " and " << 2; LOG(DEBUG) << "float 2.14: " << 1000 / 2.14f; LOG(DEBUG) << "pi double: " << pi_d; LOG(DEBUG) << "pi float: " << pi_f; LOG(DEBUG) << "pi float (width 10): " << std::setprecision(10) << pi_f; LOGF(INFO, "pi float printf:%f", pi_f); // // START: LOG Entris that were in the CodeProject article // //LOG(UNKNOWN_LEVEL) << "This log attempt will cause a compiler error"; LOG(INFO) << "Simple to use with streaming syntax, easy as abc or " << 123; LOGF(WARNING, "Printf-style syntax is also %s", "available"); LOG_IF(INFO, (1 < 2)) << "If true this text will be logged"; LOGF_IF(INFO, (1 < 2), "if %d<%d : then this text will be logged", 1, 2); LOG_IF(FATAL, (2 > 3)) << "This message should NOT throw"; LOGF(DEBUG, "This API is popular with some %s", "programmers"); LOGF_IF(DEBUG, (1 < 2), "If true, then this %s will be logged", "message"); // OK --- on Ubunti this caused get a compiler warning with gcc4.6 // from gcc 4.7.2 (at least) it causes a crash (as expected) // On windows itll probably crash example_fatal::tryToKillWithIllegalPrintout(); // try 2 std::unique_ptr<std::string> badStringPtr; example_fatal::tryToKillWithAccessingIllegalPointer(std::move(badStringPtr)); // what happened? OK. let us just exit with SIGFPE int value = 1; // system dependent but it SHOULD never reach this line example_fatal::killByZeroDivision(value); return 0; } <|endoftext|>
<commit_before>#ifndef BFC_AST_TRAITS_HPP #define BFC_AST_TRAITS_HPP #include "types.h" #include "ast/base.hpp" #include "ast/seq.hpp" #include "ast/visitor.hpp" #include "source_loc.hpp" #include <cstddef> namespace bfc { namespace ast { /* Default implementations for accept and clone. We use the CRTP to avoid * having to define boilerplate for each class. To use these defaults, * inherit from base_crtp. */ template <class derived_type> class base_crtp : public base { public: visitor::status accept(visitor &obj) override { return obj.visit(reinterpret_cast<derived_type &>(*this)); } visitor::status accept(visitor &obj) const override { return obj.visit(reinterpret_cast<const derived_type &>(*this)); } private: base *clone(void) const override { return new derived_type(reinterpret_cast<const derived_type &>(*this)); } }; /* Trait for nodes having a source position. */ class has_loc { public: has_loc(source_loc node_loc) noexcept : node_loc{std::move(node_loc)} {} source_loc loc(void) const noexcept { return node_loc; } protected: ~has_loc() = default; private: source_loc node_loc; }; /* Trait for nodes holding an offset (to the brainfuck heap pointer). */ class has_offset { public: has_offset(ptrdiff_t node_offset) noexcept : node_offset{node_offset} {} ptrdiff_t offset(void) const noexcept { return node_offset; } void offset(ptrdiff_t new_offset) noexcept { node_offset = new_offset; } protected: ~has_offset() = default; private: ptrdiff_t node_offset; }; /* Trait for nodes holding a (brainfuck) value. */ class has_value { public: has_value(bf_value node_value) noexcept : node_value{node_value} {} bf_value value(void) const noexcept { return node_value; } void value(bf_value value) noexcept { node_value = value; } private: bf_value node_value; }; /* Abstract base class for arithmetic operation nodes. */ class arith : public has_loc, public has_offset, public has_value { public: arith(source_loc loc, ptrdiff_t offset, bf_value value) noexcept : has_loc{loc}, has_offset{offset}, has_value{value} {} protected: ~arith() = default; }; /* Abstract base class for pointer arithmetic operation nodes. */ class ptr_op : public has_loc, public has_offset { public: ptr_op(source_loc loc, ptrdiff_t offset) noexcept : has_loc{loc}, has_offset{offset} {} protected: ~ptr_op() = default; }; /* Abstract base class for io operation nodes. */ class io : public base, public has_loc, public has_offset { public: io(source_loc loc, ptrdiff_t offset) noexcept : has_loc{std::move(loc)}, has_offset{offset} {} protected: ~io() = default; }; } } #endif /* !BFC_AST_TRAITS_HPP */ <commit_msg>make trait constructors protected to avoid accidental instantiation<commit_after>#ifndef BFC_AST_TRAITS_HPP #define BFC_AST_TRAITS_HPP #include "types.h" #include "ast/base.hpp" #include "ast/seq.hpp" #include "ast/visitor.hpp" #include "sourceloc.hpp" #include <cstddef> namespace bfc { namespace ast { /* Default implementations for accept and clone. We use the CRTP to avoid * having to define boilerplate for each class. To use these defaults, * inherit from base_crtp. */ template <class derived_type> class base_crtp : public base { public: visitor::status accept(visitor &obj) override { return obj.visit(reinterpret_cast<derived_type &>(*this)); } visitor::status accept(visitor &obj) const override { return obj.visit(reinterpret_cast<const derived_type &>(*this)); } private: base *clone(void) const override { return new derived_type(reinterpret_cast<const derived_type &>(*this)); } }; /* Trait for nodes having a source position. */ class has_loc { public: sourceloc loc(void) const noexcept { return node_loc; } protected: has_loc(sourceloc node_loc) noexcept : node_loc{std::move(node_loc)} {} ~has_loc() = default; private: sourceloc node_loc; }; /* Trait for nodes holding an offset (to the brainfuck heap pointer). */ class has_offset { public: ptrdiff_t offset(void) const noexcept { return node_offset; } void offset(ptrdiff_t new_offset) noexcept { node_offset = new_offset; } protected: has_offset(ptrdiff_t node_offset) noexcept : node_offset{node_offset} {} ~has_offset() = default; private: ptrdiff_t node_offset; }; /* Trait for nodes holding a (brainfuck) value. */ class has_value { public: bf_value value(void) const noexcept { return node_value; } void value(bf_value value) noexcept { node_value = value; } protected: has_value(bf_value node_value) noexcept : node_value{node_value} {} ~has_value() = default; private: bf_value node_value; }; /* Abstract base class for arithmetic operation nodes. */ class arith : public has_loc, public has_offset, public has_value { protected: arith(sourceloc loc, ptrdiff_t offset, bf_value value) noexcept : has_loc{loc}, has_offset{offset}, has_value{value} {} ~arith() = default; }; /* Abstract base class for pointer arithmetic operation nodes. */ class ptr_op : public has_loc, public has_offset { protected: ptr_op(sourceloc loc, ptrdiff_t offset) noexcept : has_loc{loc}, has_offset{offset} {} ~ptr_op() = default; }; /* Abstract base class for io operation nodes. */ class io : public base, public has_loc, public has_offset { protected: io(sourceloc loc, ptrdiff_t offset) noexcept : has_loc{std::move(loc)}, has_offset{offset} {} ~io() = default; }; } } #endif /* !BFC_AST_TRAITS_HPP */ <|endoftext|>
<commit_before>#include <catch.hpp> #include <rapidcheck-catch.h> #include "rapidcheck/shrink/Shrink.h" #include "rapidcheck/seq/Operations.h" #include "util/Util.h" #include "util/Meta.h" #include "util/TypeListMacros.h" using namespace rc; namespace { struct RemoveChunksProperties { template<typename T> static void exec() { typedef DeepDecay<typename T::value_type> Element; static auto fewValues = gen::scale(0.3, gen::arbitrary<T>()); // TODO non-empty generator static auto fewNonEmptyValues = gen::suchThat( fewValues, [](const T &x) { return !x.empty(); }); templatedProp<T>( "first tries empty collection", [] { auto collection = *fewNonEmptyValues; RC_ASSERT(shrink::removeChunks(collection).next()->empty()); }); templatedProp<T>( "successively increases in size for each shrink", [] { auto seq = shrink::removeChunks(*fewValues); T c; seq::forEach(std::move(seq), [&](T &&next) { RC_ASSERT(containerSize(next) >= containerSize(c)); c = std::move(next); }); }); templatedProp<T>( "shrinks to a subset of the original", [] { auto elements = *fewValues; auto seq = shrink::removeChunks(elements); seq::forEach(std::move(seq), [&](T &&c) { auto diff(setDifference<Element>(c, elements)); RC_ASSERT(diff.size() == 0); }); }); templatedProp<T>( "every removal of consecutive elements is a possible shrink", [] { auto elements = *fewNonEmptyValues; auto size = containerSize(elements); int a = *gen::ranged<int>(0, size + 1); int b = *gen::distinctFrom(gen::ranged<int>(0, size + 1), a); int begin = std::min(a, b); int end = std::max(a, b); detail::CollectionBuilder<T> builder; int i = 0; for (const auto &x : elements) { if ((i < begin) && (i >= end)) builder.add(x); i++; } RC_ASSERT(seq::contains(shrink::removeChunks(elements), builder.result())); }); templatedProp<T>( "never yields the original value", [] { auto elements = *fewValues; RC_ASSERT(!seq::contains(shrink::removeChunks(elements), elements)); }); } }; struct NewRemoveChunksProperties { template<typename T> static void exec() { static const auto fewValues = gen::scale(0.3, gen::arbitrary<T>()); // TODO non-empty generator static const auto fewNonEmptyValues = gen::suchThat( fewValues, [](const T &x) { return !x.empty(); }); templatedProp<T>( "first tries empty collection", [] { const auto collection = *fewNonEmptyValues; RC_ASSERT(shrink::newRemoveChunks(collection).next()->empty()); }); templatedProp<T>( "successively increases in size for each shrink", [] { const auto seq = shrink::newRemoveChunks(*fewValues); T c; seq::forEach(std::move(seq), [&](T &&next) { RC_ASSERT(next.size() >= c.size()); c = std::move(next); }); }); templatedProp<T>( "shrinks to a subset of the original", [] { const auto elements = *fewValues; const auto seq = shrink::newRemoveChunks(elements); seq::forEach(std::move(seq), [&](T &&c) { auto diff(setDifference<char>(c, elements)); RC_ASSERT(diff.size() == 0); }); }); templatedProp<T>( "every removal of consecutive elements is a possible shrink", [] { const auto elements = *fewNonEmptyValues; const auto size = elements.size(); const auto a = *gen::ranged<int>(0, size + 1); const auto b = *gen::distinctFrom(gen::ranged<int>(0, size + 1), a); const auto left = std::min(a, b); const auto right = std::max(a, b); T shrink; shrink.reserve(size - (right - left)); shrink.insert(end(shrink), begin(elements), begin(elements) + left); shrink.insert(end(shrink), begin(elements) + right, end(elements)); RC_ASSERT(seq::contains(shrink::newRemoveChunks(elements), shrink)); }); templatedProp<T>( "never yields the original value", [] { auto elements = *fewValues; RC_ASSERT(!seq::contains(shrink::newRemoveChunks(elements), elements)); }); } }; } // namespace TEST_CASE("shrink::removeChunks") { meta::forEachType<RemoveChunksProperties, RC_GENERIC_CONTAINERS(int), std::string, std::wstring>(); } TEST_CASE("shrink::newRemoveChunks") { meta::forEachType<NewRemoveChunksProperties, std::vector<char>, std::string>(); } namespace { struct EachElementProperties { template<typename T> static void exec() { typedef DeepDecay<typename T::value_type> Element; static auto smallValue = gen::scale(0.3, gen::arbitrary<Element>()); static auto smallValues = gen::collection<T>(smallValue); templatedProp<T>( "the container size stays the same", [&] { auto elements = *smallValues; auto seq = shrink::eachElement( elements, [&] (const Element &x) { return smallValue.shrink(x); }); auto size = containerSize(elements); seq::forEach(seq, [=](const T &shrink) { if (containerSize(shrink) != size) RC_ASSERT(containerSize(shrink) == size); }); }); TEMPLATED_SECTION(T, "has no shrinks for empty collections") { auto seq = shrink::eachElement( T(), [] (const Element &x) { return gen::arbitrary<Element>().shrink(x); }); REQUIRE(!seq.next()); } templatedProp<T>( "has no shrinks if elements have no shrinks", [] { auto seq = shrink::eachElement( *smallValues, [] (const Element &x) { return Seq<Element>(); }); RC_ASSERT(!seq.next()); }); templatedProp<T>( "the number of shrinks is never greater than the sum of the " "shrink counts for the iterators of the elements", [] { auto elements = *smallValues; auto seq = shrink::eachElement( elements, [=] (const Element &x) { return smallValue.shrink(x); }); std::size_t count = 0; for (const auto &element : elements) { count += seq::length(smallValue.shrink(element)); } RC_ASSERT(seq::length(seq) <= count); }); templatedProp<T>( "for every shrink, a value is replaced with one of its possible " "shrinks", [] { auto elements = *smallValues; auto seq = shrink::eachElement( elements, [&] (const Element &x) { return smallValue.shrink(x); }); seq::forEach(seq, [&](const T &shrunk) { auto added = setDifference<Element>(shrunk, elements); auto removed = setDifference<Element>(elements, shrunk); RC_ASSERT(added.size() == 1); RC_ASSERT(removed.size() == 1); RC_ASSERT(seq::contains( smallValue.shrink(removed[0]), added[0])); }); }); } }; struct NewEachElementProperties { template<typename T> static void exec() { templatedProp<T>( "every shrink for every element is tried in order", [] { const auto elements = *gen::collection<T>( gen::nonNegative<char>()); auto seq = shrink::newEachElement( elements, [=] (char x) { return seq::range(x - 1, -1); }); for (std::size_t i = 0; i < elements.size(); i++) { auto x = elements[i]; while (x > 0) { auto expected = elements; expected[i] = --x; RC_ASSERT(*seq.next() == expected); } } RC_ASSERT(!seq.next()); }); } }; } // namespace TEST_CASE("shrink::eachElement") { meta::forEachType<EachElementProperties, RC_GENERIC_CONTAINERS(int), RC_STRING_TYPES, std::array<int, 100>>(); } TEST_CASE("shrink::newEachElement") { meta::forEachType<NewEachElementProperties, std::vector<char>, std::string>(); } namespace { struct ShrinkTowardsProperties { template<typename T> static void exec() { templatedProp<T>( "first tries target immediately", [] (T target) { T value = *gen::distinctFrom(target); auto seq = shrink::towards(value, target); auto first = seq.next(); RC_ASSERT(first); RC_ASSERT(*first == target); }); templatedProp<T>( "tries an adjacent value last", [] (T target) { T value = *gen::distinctFrom(target); auto seq = shrink::towards(value, target); auto fin = seq::last(seq); RC_ASSERT(fin); T diff = (value > target) ? (value - *fin) : (*fin - value); RC_ASSERT(diff == 1); }); templatedProp<T>( "shrinking towards self yields empty shrink", [] (T target) { RC_ASSERT(!shrink::towards(target, target).next()); }); } }; } // namespace TEST_CASE("shrink::towards") { meta::forEachType<ShrinkTowardsProperties, RC_INTEGRAL_TYPES>(); } namespace { struct IntegralProperties { template<typename T> static void exec() { templatedProp<T>( "always tries zero first", [] { T value = *gen::nonZero<T>(); RC_ASSERT(*shrink::integral<T>(value).next() == 0); }); TEMPLATED_SECTION(T, "zero has no shrinks") { REQUIRE(!shrink::integral<T>(0).next()); } templatedProp<T>( "never contains original value", [](T x) { RC_ASSERT(!seq::contains(shrink::integral<T>(x), x)); }); } }; struct SignedIntegralProperties { template<typename T> static void exec() { templatedProp<T>( "shrinks negative values to their positive equivalent", [] { T value = *gen::negative<T>(); RC_ASSERT(seq::contains<T>(shrink::integral<T>(value), -value)); }); templatedProp<T>( "always tries zero first", [] { T value = *gen::nonZero<T>(); RC_ASSERT(*shrink::integral<T>(value).next() == 0); }); TEMPLATED_SECTION(T, "zero has no shrinks") { REQUIRE(!shrink::integral<T>(0).next()); } } }; } // namespace TEST_CASE("shrink::integral") { meta::forEachType<IntegralProperties, RC_INTEGRAL_TYPES>(); meta::forEachType<SignedIntegralProperties, RC_SIGNED_INTEGRAL_TYPES>(); } namespace { struct RealProperties { template<typename T> static void exec() { templatedProp<T>( "shrinks to nearest integer", [] { T value = *gen::nonZero<T>(); RC_PRE(value != std::trunc(value)); RC_ASSERT(seq::contains(shrink::real(value), std::trunc(value))); }); TEMPLATED_SECTION(T, "zero has no shrinks") { REQUIRE(!shrink::real<T>(0.0).next()); } templatedProp<T>( "tries 0.0 first", [] { T value = *gen::nonZero<T>(); REQUIRE(*shrink::real<T>(value).next() == 0.0); }); templatedProp<T>( "never contains original value", [](T x) { RC_ASSERT(!seq::contains(shrink::real<T>(x), x)); }); } }; } // namespace TEST_CASE("shrink::real") { meta::forEachType<RealProperties, RC_REAL_TYPES>(); } TEST_CASE("shrink::bool") { SECTION("shrinks 'true' to 'false'") { REQUIRE(shrink::boolean(true) == seq::just(false)); } SECTION("does not shrink 'false'") { REQUIRE(!shrink::boolean(false).next()); } } <commit_msg>Move (most) ShrinkTests to new framework<commit_after>#include <catch.hpp> #include <rapidcheck-catch.h> #include "rapidcheck/shrink/Shrink.h" #include "rapidcheck/seq/Operations.h" #include "util/Util.h" #include "util/Meta.h" #include "util/TypeListMacros.h" using namespace rc; namespace { struct RemoveChunksProperties { template<typename T> static void exec() { typedef DeepDecay<typename T::value_type> Element; static auto fewValues = gen::scale(0.3, gen::arbitrary<T>()); // TODO non-empty generator static auto fewNonEmptyValues = gen::suchThat( fewValues, [](const T &x) { return !x.empty(); }); templatedProp<T>( "first tries empty collection", [] { auto collection = *fewNonEmptyValues; RC_ASSERT(shrink::removeChunks(collection).next()->empty()); }); templatedProp<T>( "successively increases in size for each shrink", [] { auto seq = shrink::removeChunks(*fewValues); T c; seq::forEach(std::move(seq), [&](T &&next) { RC_ASSERT(containerSize(next) >= containerSize(c)); c = std::move(next); }); }); templatedProp<T>( "shrinks to a subset of the original", [] { auto elements = *fewValues; auto seq = shrink::removeChunks(elements); seq::forEach(std::move(seq), [&](T &&c) { auto diff(setDifference<Element>(c, elements)); RC_ASSERT(diff.size() == 0); }); }); templatedProp<T>( "every removal of consecutive elements is a possible shrink", [] { auto elements = *fewNonEmptyValues; auto size = containerSize(elements); int a = *gen::ranged<int>(0, size + 1); int b = *gen::distinctFrom(gen::ranged<int>(0, size + 1), a); int begin = std::min(a, b); int end = std::max(a, b); detail::CollectionBuilder<T> builder; int i = 0; for (const auto &x : elements) { if ((i < begin) && (i >= end)) builder.add(x); i++; } RC_ASSERT(seq::contains(shrink::removeChunks(elements), builder.result())); }); templatedProp<T>( "never yields the original value", [] { auto elements = *fewValues; RC_ASSERT(!seq::contains(shrink::removeChunks(elements), elements)); }); } }; struct NewRemoveChunksProperties { template<typename T> static void exec() { static const auto fewValues = newgen::scale(0.3, newgen::arbitrary<T>()); // TODO non-empty generator static const auto fewNonEmptyValues = newgen::suchThat( fewValues, [](const T &x) { return !x.empty(); }); newtemplatedProp<T>( "first tries empty collection", [] { const auto collection = *fewNonEmptyValues; RC_ASSERT(shrink::newRemoveChunks(collection).next()->empty()); }); newtemplatedProp<T>( "successively increases in size for each shrink", [] { const auto seq = shrink::newRemoveChunks(*fewValues); T c; seq::forEach(std::move(seq), [&](T &&next) { RC_ASSERT(next.size() >= c.size()); c = std::move(next); }); }); newtemplatedProp<T>( "shrinks to a subset of the original", [] { const auto elements = *fewValues; const auto seq = shrink::newRemoveChunks(elements); seq::forEach(std::move(seq), [&](T &&c) { auto diff(setDifference<char>(c, elements)); RC_ASSERT(diff.size() == 0); }); }); newtemplatedProp<T>( "every removal of consecutive elements is a possible shrink", [] { const auto elements = *fewNonEmptyValues; const auto size = elements.size(); const auto a = *newgen::inRange<int>(0, size + 1); const auto b = *newgen::distinctFrom(newgen::inRange<int>(0, size + 1), a); const auto left = std::min(a, b); const auto right = std::max(a, b); T shrink; shrink.reserve(size - (right - left)); shrink.insert(end(shrink), begin(elements), begin(elements) + left); shrink.insert(end(shrink), begin(elements) + right, end(elements)); RC_ASSERT(seq::contains(shrink::newRemoveChunks(elements), shrink)); }); newtemplatedProp<T>( "never yields the original value", [] { auto elements = *fewValues; RC_ASSERT(!seq::contains(shrink::newRemoveChunks(elements), elements)); }); } }; } // namespace TEST_CASE("shrink::removeChunks") { meta::forEachType<RemoveChunksProperties, RC_GENERIC_CONTAINERS(int), std::string, std::wstring>(); } TEST_CASE("shrink::newRemoveChunks") { meta::forEachType<NewRemoveChunksProperties, std::vector<char>, std::string>(); } namespace { struct EachElementProperties { template<typename T> static void exec() { typedef DeepDecay<typename T::value_type> Element; static auto smallValue = gen::scale(0.3, gen::arbitrary<Element>()); static auto smallValues = gen::collection<T>(smallValue); templatedProp<T>( "the container size stays the same", [&] { auto elements = *smallValues; auto seq = shrink::eachElement( elements, [&] (const Element &x) { return smallValue.shrink(x); }); auto size = containerSize(elements); seq::forEach(seq, [=](const T &shrink) { if (containerSize(shrink) != size) RC_ASSERT(containerSize(shrink) == size); }); }); TEMPLATED_SECTION(T, "has no shrinks for empty collections") { auto seq = shrink::eachElement( T(), [] (const Element &x) { return gen::arbitrary<Element>().shrink(x); }); REQUIRE(!seq.next()); } templatedProp<T>( "has no shrinks if elements have no shrinks", [] { auto seq = shrink::eachElement( *smallValues, [] (const Element &x) { return Seq<Element>(); }); RC_ASSERT(!seq.next()); }); templatedProp<T>( "the number of shrinks is never greater than the sum of the " "shrink counts for the iterators of the elements", [] { auto elements = *smallValues; auto seq = shrink::eachElement( elements, [=] (const Element &x) { return smallValue.shrink(x); }); std::size_t count = 0; for (const auto &element : elements) { count += seq::length(smallValue.shrink(element)); } RC_ASSERT(seq::length(seq) <= count); }); templatedProp<T>( "for every shrink, a value is replaced with one of its possible " "shrinks", [] { auto elements = *smallValues; auto seq = shrink::eachElement( elements, [&] (const Element &x) { return smallValue.shrink(x); }); seq::forEach(seq, [&](const T &shrunk) { auto added = setDifference<Element>(shrunk, elements); auto removed = setDifference<Element>(elements, shrunk); RC_ASSERT(added.size() == 1); RC_ASSERT(removed.size() == 1); RC_ASSERT(seq::contains( smallValue.shrink(removed[0]), added[0])); }); }); } }; struct NewEachElementProperties { template<typename T> static void exec() { newtemplatedProp<T>( "every shrink for every element is tried in order", [] { const auto elements = *newgen::container<T>( newgen::nonNegative<char>()); auto seq = shrink::newEachElement( elements, [=] (char x) { return seq::range(x - 1, -1); }); for (std::size_t i = 0; i < elements.size(); i++) { auto x = elements[i]; while (x > 0) { auto expected = elements; expected[i] = --x; RC_ASSERT(*seq.next() == expected); } } RC_ASSERT(!seq.next()); }); } }; } // namespace TEST_CASE("shrink::eachElement") { meta::forEachType<EachElementProperties, RC_GENERIC_CONTAINERS(int), RC_STRING_TYPES, std::array<int, 100>>(); } TEST_CASE("shrink::newEachElement") { meta::forEachType<NewEachElementProperties, std::vector<char>, std::string>(); } namespace { struct ShrinkTowardsProperties { template<typename T> static void exec() { newtemplatedProp<T>( "first tries target immediately", [] (T target) { T value = *newgen::distinctFrom(target); auto seq = shrink::towards(value, target); auto first = seq.next(); RC_ASSERT(first); RC_ASSERT(*first == target); }); newtemplatedProp<T>( "tries an adjacent value last", [] (T target) { T value = *newgen::distinctFrom(target); auto seq = shrink::towards(value, target); auto fin = seq::last(seq); RC_ASSERT(fin); T diff = (value > target) ? (value - *fin) : (*fin - value); RC_ASSERT(diff == 1); }); newtemplatedProp<T>( "shrinking towards self yields empty shrink", [] (T target) { RC_ASSERT(!shrink::towards(target, target).next()); }); } }; } // namespace TEST_CASE("shrink::towards") { meta::forEachType<ShrinkTowardsProperties, RC_INTEGRAL_TYPES>(); } namespace { struct IntegralProperties { template<typename T> static void exec() { newtemplatedProp<T>( "always tries zero first", [] { T value = *newgen::nonZero<T>(); RC_ASSERT(*shrink::integral<T>(value).next() == 0); }); TEMPLATED_SECTION(T, "zero has no shrinks") { REQUIRE(!shrink::integral<T>(0).next()); } newtemplatedProp<T>( "never contains original value", [](T x) { RC_ASSERT(!seq::contains(shrink::integral<T>(x), x)); }); } }; struct SignedIntegralProperties { template<typename T> static void exec() { newtemplatedProp<T>( "shrinks negative values to their positive equivalent", [] { T value = *newgen::negative<T>(); RC_ASSERT(seq::contains<T>(shrink::integral<T>(value), -value)); }); newtemplatedProp<T>( "always tries zero first", [] { T value = *newgen::nonZero<T>(); RC_ASSERT(*shrink::integral<T>(value).next() == 0); }); TEMPLATED_SECTION(T, "zero has no shrinks") { REQUIRE(!shrink::integral<T>(0).next()); } } }; } // namespace TEST_CASE("shrink::integral") { meta::forEachType<IntegralProperties, RC_INTEGRAL_TYPES>(); meta::forEachType<SignedIntegralProperties, RC_SIGNED_INTEGRAL_TYPES>(); } namespace { struct RealProperties { template<typename T> static void exec() { newtemplatedProp<T>( "shrinks to nearest integer", [] { T value = *newgen::scale(0.25, newgen::nonZero<T>()); std::cout << value << std::endl; RC_PRE(value != std::trunc(value)); RC_ASSERT(seq::contains(shrink::real(value), std::trunc(value))); }); TEMPLATED_SECTION(T, "zero has no shrinks") { REQUIRE(!shrink::real<T>(0.0).next()); } newtemplatedProp<T>( "tries 0.0 first", [] { T value = *newgen::nonZero<T>(); REQUIRE(*shrink::real<T>(value).next() == 0.0); }); newtemplatedProp<T>( "never contains original value", [](T x) { RC_ASSERT(!seq::contains(shrink::real<T>(x), x)); }); } }; } // namespace TEST_CASE("shrink::real") { meta::forEachType<RealProperties, RC_REAL_TYPES>(); } TEST_CASE("shrink::bool") { SECTION("shrinks 'true' to 'false'") { REQUIRE(shrink::boolean(true) == seq::just(false)); } SECTION("does not shrink 'false'") { REQUIRE(!shrink::boolean(false).next()); } } <|endoftext|>
<commit_before>/* Copyright (c) 2006 Volker Krause <vkrause@kde.org> Copyright (c) 2008 Sebastian Trueg <trueg@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "nepomukemailfeeder.h" #include "email.h" #include "emailaddress.h" #include "personcontact.h" #include "selectsqarqlbuilder.h" #include <akonadi/changerecorder.h> #include <akonadi/item.h> #include <akonadi/itemfetchscope.h> #include <akonadi/kmime/messageparts.h> #include <kmime/kmime_message.h> #include <kmime/kmime_content.h> #include <boost/shared_ptr.hpp> #include <Nepomuk/Resource> #include <Nepomuk/ResourceManager> #include <Nepomuk/Variant> #include <kurl.h> #include <Soprano/Vocabulary/Xesam> #include <Soprano/Vocabulary/NAO> #include <Soprano/Vocabulary/XMLSchema> #include <Soprano/Model> #include <Soprano/QueryResultIterator> #include <soprano/node.h> #include <soprano/nodeiterator.h> #include <soprano/nrl.h> #define USING_SOPRANO_NRLMODEL_UNSTABLE_API 1 #include <soprano/nrlmodel.h> using namespace Akonadi; Akonadi::NepomukEMailFeeder::NepomukEMailFeeder( const QString &id ) : NepomukFeederAgent( id ) { addSupportedMimeType( "message/rfc822" ); addSupportedMimeType( "message/news" ); changeRecorder()->itemFetchScope().fetchFullPayload(); mNrlModel = new Soprano::NRLModel( Nepomuk::ResourceManager::instance()->mainModel() ); } NepomukEMailFeeder::~NepomukEMailFeeder() { delete mNrlModel; } void NepomukEMailFeeder::updateItem(const Akonadi::Item & item) { if ( !item.hasPayload<KMime::Message::Ptr>() ) return; // first remove the item: since we use a graph that has a reference to all parts // of the item's semantic representation this is a really fast operation removeItemFromNepomuk( item ); // create a new graph for the item QUrl metaDataGraphUri; QUrl graphUri = mNrlModel->createGraph( Soprano::Vocabulary::NRL::InstanceBase(), &metaDataGraphUri ); // remember to which graph the item belongs to (used in search query in removeItemFromNepomuk()) mNrlModel->addStatement( graphUri, QUrl::fromEncoded( "http://www.semanticdesktop.org/ontologies/2007/01/19/nie#dataGraphFor", QUrl::StrictMode ), item.url(), metaDataGraphUri ); const KMime::Message::Ptr msg = item.payload<KMime::Message::Ptr>(); // FIXME: make a distinction between email and news NepomukFast::Email r( item.url(), graphUri ); if ( msg->subject( false ) ) { r.setMessageSubject( msg->subject()->asUnicodeString() ); r.setLabel( msg->subject()->asUnicodeString() ); } if ( msg->date( false ) ) { r.setReceivedDate( msg->date()->dateTime().dateTime() ); } if ( msg->from( false ) ) { r.setFroms( extractContactsFromMailboxes( msg->from()->mailboxes(), graphUri ) ); } if ( msg->sender( false ) ) r.setSenders( extractContactsFromMailboxes( msg->sender()->mailboxes(), graphUri ) ); if ( msg->to( false ) ) { r.setTos( extractContactsFromMailboxes( msg->to()->mailboxes(), graphUri ) ); } if ( msg->cc( false ) ) { r.setCcs( extractContactsFromMailboxes( msg->cc()->mailboxes(), graphUri ) ); } if ( msg->bcc( false ) ) { r.setBccs( extractContactsFromMailboxes( msg->bcc()->mailboxes(), graphUri ) ); } KMime::Content* content = msg->mainBodyPart( "text/plain" ); // FIXME: simplyfy this text as in: remove all html tags. Is there a quick way to do this? if ( content ) { const QString text = content->decodedText( true, true ); if ( !text.isEmpty() ) { r.addProperty( Soprano::Vocabulary::Xesam::asText(), Soprano::LiteralValue( text ) ); r.setPlainTextMessageContents( QStringList( text ) ); } } if ( msg->messageID( false ) ) { r.setMessageIds( QStringList( msg->messageID()->asUnicodeString() ) ); } // IDEA: use Strigi to index the attachments } QList<NepomukFast::Contact> NepomukEMailFeeder::extractContactsFromMailboxes( const KMime::Types::Mailbox::List& mbs, const QUrl &graphUri ) { QList<NepomukFast::Contact> contacts; foreach( const KMime::Types::Mailbox& mbox, mbs ) { if ( mbox.hasAddress() ) { bool found = false; NepomukFast::Contact c = findContact( mbox.address(), graphUri, &found ); if ( !found && mbox.hasName() ) { c.addFullname( mbox.name() ); c.setLabel( mbox.name() ); } contacts << c; } } return contacts; } NepomukFast::PersonContact NepomukEMailFeeder::findContact( const QByteArray& address, const QUrl &graphUri, bool *found ) { // // Querying with the exact address string is not perfect since email addresses // are case insensitive. But for the moment we stick to it and hope Nepomuk // alignment fixes any duplicates // SelectSparqlBuilder::BasicGraphPattern graph; graph.addTriple( "?r", NepomukFast::Role::emailAddressUri(), SparqlBuilder::QueryVariable("?a") ); graph.addTriple( "?a", NepomukFast::EmailAddress::emailAddressUri(), QString::fromAscii( address ) ); SelectSparqlBuilder qb; qb.setGraphPattern( graph ); qb.addQueryVariable( "?r" ); Soprano::QueryResultIterator it = Nepomuk::ResourceManager::instance()->mainModel()->executeQuery( qb.query(), Soprano::Query::QueryLanguageSparql ); if ( it.next() ) { *found = true; const QUrl uri = it.binding( 0 ).uri(); it.close(); return NepomukFast::PersonContact( uri, graphUri ); } else { *found = false; // create a new contact NepomukFast::PersonContact contact( QUrl(), graphUri ); NepomukFast::EmailAddress email( QUrl( "mailto:" + address ), graphUri ); email.setEmailAddress( QString::fromAscii( address ) ); contact.addEmailAddress( email ); return contact; } } AKONADI_AGENT_MAIN( NepomukEMailFeeder ) #include "nepomukemailfeeder.moc" <commit_msg>- set correct lables on contacts if they don't have a name - only set the actual mail content once<commit_after>/* Copyright (c) 2006 Volker Krause <vkrause@kde.org> Copyright (c) 2008 Sebastian Trueg <trueg@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "nepomukemailfeeder.h" #include "email.h" #include "emailaddress.h" #include "personcontact.h" #include "selectsqarqlbuilder.h" #include <akonadi/changerecorder.h> #include <akonadi/item.h> #include <akonadi/itemfetchscope.h> #include <akonadi/kmime/messageparts.h> #include <kmime/kmime_message.h> #include <kmime/kmime_content.h> #include <boost/shared_ptr.hpp> #include <Nepomuk/Resource> #include <Nepomuk/ResourceManager> #include <Nepomuk/Variant> #include <kurl.h> #include <Soprano/Vocabulary/Xesam> #include <Soprano/Vocabulary/NAO> #include <Soprano/Vocabulary/XMLSchema> #include <Soprano/Model> #include <Soprano/QueryResultIterator> #include <soprano/node.h> #include <soprano/nodeiterator.h> #include <soprano/nrl.h> #define USING_SOPRANO_NRLMODEL_UNSTABLE_API 1 #include <soprano/nrlmodel.h> using namespace Akonadi; Akonadi::NepomukEMailFeeder::NepomukEMailFeeder( const QString &id ) : NepomukFeederAgent( id ) { addSupportedMimeType( "message/rfc822" ); addSupportedMimeType( "message/news" ); changeRecorder()->itemFetchScope().fetchFullPayload(); mNrlModel = new Soprano::NRLModel( Nepomuk::ResourceManager::instance()->mainModel() ); } NepomukEMailFeeder::~NepomukEMailFeeder() { delete mNrlModel; } void NepomukEMailFeeder::updateItem(const Akonadi::Item & item) { if ( !item.hasPayload<KMime::Message::Ptr>() ) return; // first remove the item: since we use a graph that has a reference to all parts // of the item's semantic representation this is a really fast operation removeItemFromNepomuk( item ); // create a new graph for the item QUrl metaDataGraphUri; QUrl graphUri = mNrlModel->createGraph( Soprano::Vocabulary::NRL::InstanceBase(), &metaDataGraphUri ); // remember to which graph the item belongs to (used in search query in removeItemFromNepomuk()) mNrlModel->addStatement( graphUri, QUrl::fromEncoded( "http://www.semanticdesktop.org/ontologies/2007/01/19/nie#dataGraphFor", QUrl::StrictMode ), item.url(), metaDataGraphUri ); const KMime::Message::Ptr msg = item.payload<KMime::Message::Ptr>(); // FIXME: make a distinction between email and news NepomukFast::Email r( item.url(), graphUri ); if ( msg->subject( false ) ) { r.setMessageSubject( msg->subject()->asUnicodeString() ); r.setLabel( msg->subject()->asUnicodeString() ); } if ( msg->date( false ) ) { r.setReceivedDate( msg->date()->dateTime().dateTime() ); } if ( msg->from( false ) ) { r.setFroms( extractContactsFromMailboxes( msg->from()->mailboxes(), graphUri ) ); } if ( msg->sender( false ) ) r.setSenders( extractContactsFromMailboxes( msg->sender()->mailboxes(), graphUri ) ); if ( msg->to( false ) ) { r.setTos( extractContactsFromMailboxes( msg->to()->mailboxes(), graphUri ) ); } if ( msg->cc( false ) ) { r.setCcs( extractContactsFromMailboxes( msg->cc()->mailboxes(), graphUri ) ); } if ( msg->bcc( false ) ) { r.setBccs( extractContactsFromMailboxes( msg->bcc()->mailboxes(), graphUri ) ); } KMime::Content* content = msg->mainBodyPart( "text/plain" ); // FIXME: simplyfy this text as in: remove all html tags. Is there a quick way to do this? if ( content ) { const QString text = content->decodedText( true, true ); if ( !text.isEmpty() ) { r.setPlainTextMessageContents( QStringList( text )` ); } } if ( msg->messageID( false ) ) { r.setMessageIds( QStringList( msg->messageID()->asUnicodeString() ) ); } // IDEA: use Strigi to index the attachments } QList<NepomukFast::Contact> NepomukEMailFeeder::extractContactsFromMailboxes( const KMime::Types::Mailbox::List& mbs, const QUrl &graphUri ) { QList<NepomukFast::Contact> contacts; foreach( const KMime::Types::Mailbox& mbox, mbs ) { if ( mbox.hasAddress() ) { bool found = false; NepomukFast::Contact c = findContact( mbox.address(), graphUri, &found ); if ( !found ) { if ( mbox.hasName() ) { c.addFullname( mbox.name() ); c.setLabel( mbox.name() ); } else { c.setLabel( mbox.address() ); } } contacts << c; } } return contacts; } NepomukFast::PersonContact NepomukEMailFeeder::findContact( const QByteArray& address, const QUrl &graphUri, bool *found ) { // // Querying with the exact address string is not perfect since email addresses // are case insensitive. But for the moment we stick to it and hope Nepomuk // alignment fixes any duplicates // SelectSparqlBuilder::BasicGraphPattern graph; graph.addTriple( "?r", NepomukFast::Role::emailAddressUri(), SparqlBuilder::QueryVariable("?a") ); graph.addTriple( "?a", NepomukFast::EmailAddress::emailAddressUri(), QString::fromAscii( address ) ); SelectSparqlBuilder qb; qb.setGraphPattern( graph ); qb.addQueryVariable( "?r" ); Soprano::QueryResultIterator it = Nepomuk::ResourceManager::instance()->mainModel()->executeQuery( qb.query(), Soprano::Query::QueryLanguageSparql ); if ( it.next() ) { *found = true; const QUrl uri = it.binding( 0 ).uri(); it.close(); return NepomukFast::PersonContact( uri, graphUri ); } else { *found = false; // create a new contact NepomukFast::PersonContact contact( QUrl(), graphUri ); NepomukFast::EmailAddress email( QUrl( "mailto:" + address ), graphUri ); email.setEmailAddress( QString::fromAscii( address ) ); contact.addEmailAddress( email ); return contact; } } AKONADI_AGENT_MAIN( NepomukEMailFeeder ) #include "nepomukemailfeeder.moc" <|endoftext|>
<commit_before>/*- * Copyright (c) 2010 Benjamin Close <Benjamin.Close@clearchain.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 <assert.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <iostream> #include "GrayCode.h" using namespace std; GrayCode::GrayCode(const unsigned iwidth, const unsigned iheight ): width(iwidth), height(iheight), totalGrayCodes(0), codedImages(NULL),stage(0), decodedColumns(iwidth, iheight), decodedRows(iwidth, iheight) { // Work out how many patterns are needed for the // specified rows and columns. Since we are trying to // encode a binary sequence, this is: count = log2(x) // where x is the width or the height - depending if we // are encoding columns or rows. We also have to cater // for rounding in c hence we ceil to the next // highest value then cast the value to get count; this->grayCodeColumnCount = (unsigned)ceil(log2(this->width)); this->grayCodeRowCount = (unsigned)ceil(log2(this->height)); // Record the total amount of patterns required for // both the columns and the rows, we also cater for the inverts and the // initial images this->totalGrayCodes = ((this->grayCodeColumnCount + this->grayCodeRowCount) * 2) +4; // Create the data storage for the patterns. this->createStorage(); // Build the various images required for graycode displaying this->buildGrayCodes(); // zero the decode matrixes this->decodedColumns.storeZeros(); this->decodedRows.storeZeros(); }; GrayCode::~GrayCode() { if( this->codedImages ){ for( unsigned i = 0; i < this->totalGrayCodes; i++ ) delete this->codedImages[i]; delete this->codedImages; } } bool GrayCode::next() { this->stage++; if( this->stage >= this->totalGrayCodes){ this->stage=0; return false; } return true; } const unsigned char *GrayCode::generate() { return this->codedImages[this->stage]; } void GrayCode::buildGrayCodes() { // // Build the required gray code images. // When building the images we build both the initial image and // the image invert to aid in detection // // The first two images are the most sigificant bit and full black/white // this allows us to work out the region the graycodes are projected onto // We set the initial pattern here we calculate all inverts below memset( *this->codedImages, 255, this->width * this->height ); unsigned char **codedColumnImages = this->codedImages+2; // We start by building the graycoded columns. for(unsigned column = 0; column < this->width; column++ ) { for ( unsigned imageCount = 0; imageCount < this->grayCodeColumnCount; imageCount++ ){ unsigned char *data = codedColumnImages[imageCount*2]; // // Work out the value for this column // // Binary encoding. Put basically, a particular column over // grayCodeColumnCount images represents a binary number. What // we do here is work out what bit value that number is for this // particular (imageCount) image. Ie the number for column 0 is // always 0..n where n is grayCodeColumnCount long. Column 1 always // equates to 1 in binary. Hence in image 0 column 1 is black. In // image grayCodeColumnCount column 1 is white. // // To work what colour (white/black) a column should be in this particular image // we need to work out the bit value for this image. Hence if column =10 // which is binary n-4..1010 and we're in the second to last image the // column must be white. To calculate colour we bitshift the column // count (ie the value for the column) by the imagecount we are in. // This shifts the bit we care about down to the least significant // bit. We can simply test it using a bit comparison against 1 to // then see if we need to be white or black. // Now the only issue with this is we work from least significant // bit up to most siginificate bit. This makes decoding the number // harder. Hence instead we shift by grayCodeColumnCount-imageCount. // This then works from most significant bit down to least // significant bit which makes deciding easier. // unsigned char value = ( toGrayCode(column) >> (this->grayCodeColumnCount - imageCount -1)) & 1; // We now update the value of the column to be in the range 0 // (black) or 255 (white). As this is what GL expects for a texture value *=255; // Store the value in the image this->setPixel(data,column,0 /* y */, value); // Copy the value down for all rows of the image. // after this the entire column for this image is set for( unsigned row = 1; row < this->height; row++ ) this->setPixel(data,column,row, value); } } // // We now repeat the above setup but focus on the rows not // the columns // memset( *codedColumnImages+(this->grayCodeColumnCount*2)+1, 255, this->width * this->height ); unsigned char **codedRowImages= codedColumnImages+(this->grayCodeColumnCount*2)+2; for( unsigned row=0; row < this->height; row++){ for ( unsigned imageCount = 0; imageCount < this->grayCodeRowCount; imageCount++ ){ unsigned char *data = codedRowImages[imageCount*2]; unsigned char value = ( row >> (this->grayCodeRowCount - imageCount -1)) & 1; value *=255; this->setPixel(data,0 /* X */,row, value); for( unsigned column = 1; column < this->width; column++ ) this->setPixel(data,column,row, value); } } // // Now create the invert images for each pattern // for( unsigned count = 0; count < this->totalGrayCodes; count+=2 ){ for( unsigned row = 0; row < this->height; row++ ){ for( unsigned column = 0; column < this->width; column++ ){ this->codedImages[count+1][row*this->width+column] = this->codedImages[count][row*this->width+column] ? 0 : 255; } } } } /** * Create the memory required for all the required gray code images */ void GrayCode::createStorage() { this->codedImages = new unsigned char *[this->totalGrayCodes]; for( unsigned i = 0; i < this->totalGrayCodes; i++ ) this->codedImages[i] = new unsigned char [this->width * this->height]; } void GrayCode::setPixel(unsigned char *data, const unsigned x, const unsigned y, const unsigned char colour ) { assert(x < this->width && "Column out of bounds" ); assert(y < this->height && "Row out of bounds"); data[(y*this->width)+x]= colour; } /** * Given a camera coo */ wcl::Vector GrayCode::getRowCol(const wcl::Vector &input) const { wcl::Vector v(2); int col = input[0]; int row = input[1]; // Search the row/column matrixes for the input pixel values v[0] = this->decodedColumns[col][row]; v[1] = this->decodedRows[col][row]; return v; } unsigned int GrayCode::fromGrayCode(const unsigned value) { unsigned int temp = value ^ (value>>8); temp ^= (temp>>4); temp ^= (temp>>2); temp ^= (temp>>1); return temp; } unsigned int GrayCode::toGrayCode(const unsigned value) { return ( value >> 1 ) ^ (value); } /** * Given the correct amount of images, decode the structured light sequence. * Note the images are expected to be in 8 bit grayscale. * * @param capturedImages the images captured for each structured light sequence */ void GrayCode::decode(const unsigned char **capturedImages) { // First we separate the rows from the columns; const unsigned char **columnImages = capturedImages; const unsigned char **rowImages = capturedImages+ this->grayCodeRowCount; // We now begin the process of decoding the images back into the relevant // graycodes. The decoding works as follows. When capturing the graycodes // we generated both the gray code image and the image invert. By looking // at the difference between these two images we find what the bit is at // each pixel of the imagepair. For pixels that are not part of the // projected image they get assigned a bit value of zero. Ie all undetected // pixels are 0. for(unsigned columnCount = 0; columnCount < this->grayCodeColumnCount; columnCount++){ // Obtain pointers to the gray code image and the image invert const unsigned char *gray = columnImages[ columnCount ]; const unsigned char *invgray = columnImages[ columnCount + 1]; // Now decode each pixel of the image pair. for( unsigned y = 0; y < this->height; y++ ){ for( unsigned x = 0; x < this->width; x++ ){ unsigned offset = (this->height * y) + x; // Find the bit value for this pixel in the image bool bitvalue = gray[offset] >= invgray[offset]; // Store the value of this bit in decoded matrix at the correct // location. The columnCount indicates the significance of the // bit in the number. int bit = this->grayCodeColumnCount - columnCount - 1; if( bitvalue ){ int value = (int)this->decodedColumns[x][y]; value |= 2 << bit; this->decodedColumns[x][y] = value; } } } } // Repeat for rows for(unsigned rowCount = 0; rowCount < this->grayCodeRowCount; rowCount++){ // Obtain pointers to the gray code image and the image invert const unsigned char *gray = rowImages[ rowCount ]; const unsigned char *invgray = rowImages[ rowCount + 1]; // Now decode each pixel of the image pair. for( unsigned y = 0; y < this->height; y++ ){ for( unsigned x = 0; x < this->width; x++ ){ unsigned offset = (this->height * y) + x; bool bitvalue = gray[offset] >= invgray[offset]; int bit = this->grayCodeRowCount - rowCount - 1; if( bitvalue ){ int value = (int)this->decodedRows[x][y]; value |= 2 << bit; this->decodedRows[x][y] = value; } } } } // Each stored value in the matrixes are gray coded still. We now // convert the values back to binary. for(unsigned rowCount = 0; rowCount < this->grayCodeRowCount; rowCount++ ){ for(unsigned colCount=0; colCount < this->grayCodeColumnCount; colCount++){ this->decodedRows[colCount][rowCount] = fromGrayCode((unsigned) this->decodedRows[colCount][rowCount]); this->decodedColumns[colCount][rowCount] = fromGrayCode((unsigned) this->decodedColumns[colCount][rowCount]); } } this->decodedRows.print(); } unsigned GrayCode::getRequiredImageCount() const { return this->totalGrayCodes; } void GrayCode::reset() { this->decodedColumns.storeZeros(); this->decodedRows.storeZeros(); } <commit_msg>Correct a calculation bug with stride calculations<commit_after>/*- * Copyright (c) 2010 Benjamin Close <Benjamin.Close@clearchain.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 <assert.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <iostream> #include "GrayCode.h" using namespace std; GrayCode::GrayCode(const unsigned iwidth, const unsigned iheight ): width(iwidth), height(iheight), totalGrayCodes(0), codedImages(NULL),stage(0), decodedColumns(iwidth, iheight), decodedRows(iwidth, iheight) { // Work out how many patterns are needed for the // specified rows and columns. Since we are trying to // encode a binary sequence, this is: count = log2(x) // where x is the width or the height - depending if we // are encoding columns or rows. We also have to cater // for rounding in c hence we ceil to the next // highest value then cast the value to get count; this->grayCodeColumnCount = (unsigned)ceil(log2(this->width)); this->grayCodeRowCount = (unsigned)ceil(log2(this->height)); // Record the total amount of patterns required for // both the columns and the rows, we also cater for the inverts and the // initial images this->totalGrayCodes = ((this->grayCodeColumnCount + this->grayCodeRowCount) * 2) +4; // Create the data storage for the patterns. this->createStorage(); // Build the various images required for graycode displaying this->buildGrayCodes(); // zero the decode matrixes this->decodedColumns.storeZeros(); this->decodedRows.storeZeros(); }; GrayCode::~GrayCode() { if( this->codedImages ){ for( unsigned i = 0; i < this->totalGrayCodes; i++ ) delete this->codedImages[i]; delete this->codedImages; } } bool GrayCode::next() { this->stage++; if( this->stage >= this->totalGrayCodes){ this->stage=0; return false; } return true; } const unsigned char *GrayCode::generate() { return this->codedImages[this->stage]; } void GrayCode::buildGrayCodes() { // // Build the required gray code images. // When building the images we build both the initial image and // the image invert to aid in detection // // The first two images are the most sigificant bit and full black/white // this allows us to work out the region the graycodes are projected onto // We set the initial pattern here we calculate all inverts below memset( *this->codedImages, 255, this->width * this->height ); unsigned char **codedColumnImages = this->codedImages+2; // We start by building the graycoded columns. for(unsigned column = 0; column < this->width; column++ ) { for ( unsigned imageCount = 0; imageCount < this->grayCodeColumnCount; imageCount++ ){ unsigned char *data = codedColumnImages[imageCount*2]; // // Work out the value for this column // // Binary encoding. Put basically, a particular column over // grayCodeColumnCount images represents a binary number. What // we do here is work out what bit value that number is for this // particular (imageCount) image. Ie the number for column 0 is // always 0..n where n is grayCodeColumnCount long. Column 1 always // equates to 1 in binary. Hence in image 0 column 1 is black. In // image grayCodeColumnCount column 1 is white. // // To work what colour (white/black) a column should be in this particular image // we need to work out the bit value for this image. Hence if column =10 // which is binary n-4..1010 and we're in the second to last image the // column must be white. To calculate colour we bitshift the column // count (ie the value for the column) by the imagecount we are in. // This shifts the bit we care about down to the least significant // bit. We can simply test it using a bit comparison against 1 to // then see if we need to be white or black. // Now the only issue with this is we work from least significant // bit up to most siginificate bit. This makes decoding the number // harder. Hence instead we shift by grayCodeColumnCount-imageCount. // This then works from most significant bit down to least // significant bit which makes deciding easier. // unsigned char value = ( toGrayCode(column) >> (this->grayCodeColumnCount - imageCount -1)) & 1; // We now update the value of the column to be in the range 0 // (black) or 255 (white). As this is what GL expects for a texture value *=255; // Store the value in the image this->setPixel(data,column,0 /* y */, value); // Copy the value down for all rows of the image. // after this the entire column for this image is set for( unsigned row = 1; row < this->height; row++ ) this->setPixel(data,column,row, value); } } // // We now repeat the above setup but focus on the rows not // the columns // memset( *codedColumnImages+(this->grayCodeColumnCount*2)+1, 255, this->width * this->height ); unsigned char **codedRowImages= codedColumnImages+(this->grayCodeColumnCount*2)+2; for( unsigned row=0; row < this->height; row++){ for ( unsigned imageCount = 0; imageCount < this->grayCodeRowCount; imageCount++ ){ unsigned char *data = codedRowImages[imageCount*2]; unsigned char value = ( row >> (this->grayCodeRowCount - imageCount -1)) & 1; value *=255; this->setPixel(data,0 /* X */,row, value); for( unsigned column = 1; column < this->width; column++ ) this->setPixel(data,column,row, value); } } // // Now create the invert images for each pattern // for( unsigned count = 0; count < this->totalGrayCodes; count+=2 ){ for( unsigned row = 0; row < this->height; row++ ){ for( unsigned column = 0; column < this->width; column++ ){ this->codedImages[count+1][row*this->width+column] = this->codedImages[count][row*this->width+column] ? 0 : 255; } } } } /** * Create the memory required for all the required gray code images */ void GrayCode::createStorage() { this->codedImages = new unsigned char *[this->totalGrayCodes]; for( unsigned i = 0; i < this->totalGrayCodes; i++ ) this->codedImages[i] = new unsigned char [this->width * this->height]; } void GrayCode::setPixel(unsigned char *data, const unsigned x, const unsigned y, const unsigned char colour ) { assert(x < this->width && "Column out of bounds" ); assert(y < this->height && "Row out of bounds"); data[(y*this->width)+x]= colour; } /** * Given a camera coo */ wcl::Vector GrayCode::getRowCol(const wcl::Vector &input) const { wcl::Vector v(2); int col = input[0]; int row = input[1]; // Search the row/column matrixes for the input pixel values v[0] = this->decodedColumns[col][row]; v[1] = this->decodedRows[col][row]; return v; } unsigned int GrayCode::fromGrayCode(const unsigned value) { unsigned int temp = value ^ (value>>8); temp ^= (temp>>4); temp ^= (temp>>2); temp ^= (temp>>1); return temp; } unsigned int GrayCode::toGrayCode(const unsigned value) { return ( value >> 1 ) ^ (value); } /** * Given the correct amount of images, decode the structured light sequence. * Note the images are expected to be in 8 bit grayscale. * * @param capturedImages the images captured for each structured light sequence */ void GrayCode::decode(const unsigned char **capturedImages) { // First we separate the rows from the columns; const unsigned char **columnImages = capturedImages; const unsigned char **rowImages = capturedImages+ this->grayCodeRowCount; // We now begin the process of decoding the images back into the relevant // graycodes. The decoding works as follows. When capturing the graycodes // we generated both the gray code image and the image invert. By looking // at the difference between these two images we find what the bit is at // each pixel of the imagepair. For pixels that are not part of the // projected image they get assigned a bit value of zero. Ie all undetected // pixels are 0. for(unsigned columnCount = 0; columnCount < this->grayCodeColumnCount; columnCount++){ // Obtain pointers to the gray code image and the image invert const unsigned char *gray = columnImages[ columnCount ]; const unsigned char *invgray = columnImages[ columnCount + 1]; // Now decode each pixel of the image pair. for( unsigned y = 0; y < this->height; y++ ){ for( unsigned x = 0; x < this->width; x++ ){ unsigned offset = (this->width * y) + x; // Find the bit value for this pixel in the image bool bitvalue = gray[offset] >= invgray[offset]; // Store the value of this bit in decoded matrix at the correct // location. The columnCount indicates the significance of the // bit in the number. int bit = this->grayCodeColumnCount - columnCount - 1; if( bitvalue ){ int value = (int)this->decodedColumns[x][y]; value |= 2 << bit; this->decodedColumns[x][y] = value; } } } } // Repeat for rows for(unsigned rowCount = 0; rowCount < this->grayCodeRowCount; rowCount++){ // Obtain pointers to the gray code image and the image invert const unsigned char *gray = rowImages[ rowCount ]; const unsigned char *invgray = rowImages[ rowCount + 1]; // Now decode each pixel of the image pair. for( unsigned y = 0; y < this->height; y++ ){ for( unsigned x = 0; x < this->width; x++ ){ unsigned offset = (this->width * y) + x; bool bitvalue = gray[offset] >= invgray[offset]; int bit = this->grayCodeRowCount - rowCount - 1; if( bitvalue ){ int value = (int)this->decodedRows[x][y]; value |= 2 << bit; this->decodedRows[x][y] = value; } } } } // Each stored value in the matrixes are gray coded still. We now // convert the values back to binary. for(unsigned rowCount = 0; rowCount < this->grayCodeRowCount; rowCount++ ){ for(unsigned colCount=0; colCount < this->grayCodeColumnCount; colCount++){ this->decodedRows[colCount][rowCount] = fromGrayCode((unsigned) this->decodedRows[colCount][rowCount]); this->decodedColumns[colCount][rowCount] = fromGrayCode((unsigned) this->decodedColumns[colCount][rowCount]); } } this->decodedRows.print(); } unsigned GrayCode::getRequiredImageCount() const { return this->totalGrayCodes; } void GrayCode::reset() { this->decodedColumns.storeZeros(); this->decodedRows.storeZeros(); } <|endoftext|>
<commit_before>// main.cpp #include <stdio.h> // This file implements an extremely simple example of loading and // executing a Slang shader program on the CPU. // // More information about generation C++ or CPU code can be found in docs/cpu-target.md // // NOTE! This test will only run on a system correctly where slang can find a suitable // C++ compiler - such as clang/gcc/visual studio // // The comments in the file will attempt to explain concepts as // they are introduced. // // Of course, in order to use the Slang API, we need to include // its header. We have set up the build options for this project // so that it is as simple as: #include <slang.h> // Allows use of ComPtr - which we can use to scope any 'com-like' pointers easily #include <slang-com-ptr.h> // Provides macros for handling SlangResult values easily #include <slang-com-helper.h> // This includes a useful small function for setting up the prelude (described more further below). #include "../../source/core/slang-test-tool-util.h" // Slang namespace is used for elements support code (like core) which we use here // for ComPtr<> and TestToolUtil using namespace Slang; // Slang source is converted into C++ code which is compiled by a backend compiler. // That process uses a 'prelude' which defines types and functions that are needed // for everything else to work. // // We include the prelude here, so we can directly use the types as were used by the // compiled code. It is not necessary to include the prelude, as long as memory is // laid out in the manner that the generated slang code expects. #define SLANG_PRELUDE_NAMESPACE CPPPrelude #include "../../prelude/slang-cpp-types.h" static SlangResult _innerMain(int argc, char** argv) { // First, we need to create a "session" for interacting with the Slang // compiler. This scopes all of our application's interactions // with the Slang library. At the moment, creating a session causes // Slang to load and validate its standard library, so this is a // somewhat heavy-weight operation. When possible, an application // should try to re-use the same session across multiple compiles. // ComPtr<slang::IGlobalSession> slangSession(spCreateSession(NULL)); // As touched on earlier, in order to generate the final executable code, // the slang code is converted into C++, and that C++ needs a 'prelude' which // is just definitions that the generated code needed to work correctly. // There is a simple default definition of a prelude provided in the prelude // directory called 'slang-cpp-prelude.h'. // // We need to tell slang either the contents of the prelude, or suitable include/s // that will work. The actual API call to set the prelude is `setDownstreamCompilerPrelude` // and this just sets for a specific backend a bit of text placed before generated code. // // Most downstream C++ compilers work on files. In that case slang may generate temporary // files that contain the generated code. Typically the generated files will not be in the // same directory as the original source so handling includes becomes awkward. The mechanism used here // is for the prelude code to be an *absolute* path to the 'slang-cpp-prelude.h' - which means // this will work wherever the generated code is, and allows accessing other files via relative paths. // // Look at the source to TestToolUtil::setSessionDefaultPrelude to see what's involed. TestToolUtil::setSessionDefaultPrelude(argv[0], slangSession); // A compile request represents a single invocation of the compiler, // to process some inputs and produce outputs (or errors). // SlangCompileRequest* slangRequest = spCreateCompileRequest(slangSession); // We would like to request a CPU code that can be executed directly on the host - // which is the 'SLANG_HOST_CALLABLE' target. // If we wanted a just a shared library/dll, we could have used SLANG_SHARED_LIBRARY. int targetIndex = spAddCodeGenTarget(slangRequest, SLANG_HOST_CALLABLE); // A compile request can include one or more "translation units," which more or // less amount to individual source files (think `.c` files, not the `.h` files they // might include). // // For this example, our code will all be in the Slang language. The user may // also specify HLSL input here, but that currently doesn't affect the compiler's // behavior much. // int translationUnitIndex = spAddTranslationUnit(slangRequest, SLANG_SOURCE_LANGUAGE_SLANG, nullptr); // We will load source code for our translation unit from the file `shader.slang`. // There are also variations of this API for adding source code from application-provided buffers. // spAddTranslationUnitSourceFile(slangRequest, translationUnitIndex, "shader.slang"); // Next we will specify the entry points we'd like to compile. // It is often convenient to put more than one entry point in the same file, // and the Slang API makes it convenient to use a single run of the compiler // to compile all entry points. // const char entryPointName[] = "computeMain"; int computeIndex = spAddEntryPoint(slangRequest, translationUnitIndex, entryPointName, SLANG_STAGE_COMPUTE); // Once all of the input options for the compiler have been specified, // we can invoke `spCompile` to run the compiler and see if any errors // were detected. // const SlangResult compileRes = spCompile(slangRequest); // Even if there were no errors that forced compilation to fail, the // compiler may have produced "diagnostic" output such as warnings. // We will go ahead and print that output here. // if(auto diagnostics = spGetDiagnosticOutput(slangRequest)) { printf("%s", diagnostics); } // If compilation failed, there is no point in continuing any further. if(SLANG_FAILED(compileRes)) { spDestroyCompileRequest(slangRequest); return compileRes; } // Get the 'shared library' (note that this doesn't necessarily have to be implemented as a shared library // it's just an interface to executable code). ComPtr<ISlangSharedLibrary> sharedLibrary; SLANG_RETURN_ON_FAIL(spGetEntryPointHostCallable(slangRequest, 0, 0, sharedLibrary.writeRef())); // Once we have the sharedLibrary, we no longer need the request // unless we want to use reflection, to for example workout how 'UniformState' and 'UniformEntryPointParams' are laid out // at runtime. We don't do that here - as we hard code the structures. spDestroyCompileRequest(slangRequest); // Get the function we are going to execute CPPPrelude::ComputeFunc func = (CPPPrelude::ComputeFunc)sharedLibrary->findFuncByName(entryPointName); if (!func) { spDestroyCompileRequest(slangRequest); return SLANG_FAIL; } // Define the uniform state structure that is *specific* to our shader defined in shader.slang // That the layout of the structure can be determined through reflection, or can be inferred from // the original slang source. Look at the documentation in docs/cpu-target.md which describes // how different resources map. // The order of the resources is in the order that they are defined in the source. struct UniformState { CPPPrelude::RWStructuredBuffer<float> ioBuffer; }; // the uniformState will be passed as a pointer to the CPU code UniformState uniformState; // The contents of the buffer are modified, so we'll copy it const float startBufferContents[] = { 2.0f, -10.0f, -3.0f, 5.0f }; float bufferContents[SLANG_COUNT_OF(startBufferContents)]; memcpy(bufferContents, startBufferContents, sizeof(startBufferContents)); // Set up the ioBuffer such that it uses bufferContents. It is important to set the .count // such that bounds checking can be performed in the kernel. uniformState.ioBuffer.data = bufferContents; uniformState.ioBuffer.count = SLANG_COUNT_OF(bufferContents); // In shader.slang, then entry point is attributed with `[numthreads(4, 1, 1)]` meaning each group // consists of 4 'thread' in x. Our input buffer is 4 wide, and we index the input array via `SV_DispatchThreadID` // so we only need to run a single group to execute over all of the 4 elements here. // The group range from { 0, 0, 0 } -> { 1, 1, 1 } means it will execute over the single group { 0, 0, 0 }. const CPPPrelude::uint3 startGroupID = { 0, 0, 0}; const CPPPrelude::uint3 endGroupID = { 1, 1, 1 }; CPPPrelude::ComputeVaryingInput varyingInput; varyingInput.startGroupID = startGroupID; varyingInput.endGroupID = endGroupID; // We don't have any entry point parameters so that's passed as NULL // We need to cast our definition of the uniform state to the undefined CPPPrelude::UniformState as // that type is just a name to indicate what kind of thing needs to be passed in. func(&varyingInput, NULL, (CPPPrelude::UniformState*)&uniformState); // bufferContents holds the output // Print out the values before the computation printf("Before:\n"); for (float v : startBufferContents) { printf("%f, ", v); } printf("\n"); // Print out the values the the kernel produced printf("After: \n"); for (float v : bufferContents) { printf("%f, ", v); } printf("\n"); return SLANG_OK; } int main(int argc, char** argv) { return SLANG_SUCCEEDED(_innerMain(argc, argv)) ? 0 : -1; } <commit_msg>Fix ref counting bug in cpu-hello-world (#1119)<commit_after>// main.cpp #include <stdio.h> // This file implements an extremely simple example of loading and // executing a Slang shader program on the CPU. // // More information about generation C++ or CPU code can be found in docs/cpu-target.md // // NOTE! This test will only run on a system correctly where slang can find a suitable // C++ compiler - such as clang/gcc/visual studio // // The comments in the file will attempt to explain concepts as // they are introduced. // // Of course, in order to use the Slang API, we need to include // its header. We have set up the build options for this project // so that it is as simple as: #include <slang.h> // Allows use of ComPtr - which we can use to scope any 'com-like' pointers easily #include <slang-com-ptr.h> // Provides macros for handling SlangResult values easily #include <slang-com-helper.h> // This includes a useful small function for setting up the prelude (described more further below). #include "../../source/core/slang-test-tool-util.h" // Slang namespace is used for elements support code (like core) which we use here // for ComPtr<> and TestToolUtil using namespace Slang; // Slang source is converted into C++ code which is compiled by a backend compiler. // That process uses a 'prelude' which defines types and functions that are needed // for everything else to work. // // We include the prelude here, so we can directly use the types as were used by the // compiled code. It is not necessary to include the prelude, as long as memory is // laid out in the manner that the generated slang code expects. #define SLANG_PRELUDE_NAMESPACE CPPPrelude #include "../../prelude/slang-cpp-types.h" static SlangResult _innerMain(int argc, char** argv) { // First, we need to create a "session" for interacting with the Slang // compiler. This scopes all of our application's interactions // with the Slang library. At the moment, creating a session causes // Slang to load and validate its standard library, so this is a // somewhat heavy-weight operation. When possible, an application // should try to re-use the same session across multiple compiles. // // NOTE that we use attach instead of setting via assignment, as assignment will increase // the refcount. spCreateSession returns a IGlobalSession with a refcount of 1. ComPtr<slang::IGlobalSession> slangSession; slangSession.attach(spCreateSession(NULL)); // As touched on earlier, in order to generate the final executable code, // the slang code is converted into C++, and that C++ needs a 'prelude' which // is just definitions that the generated code needed to work correctly. // There is a simple default definition of a prelude provided in the prelude // directory called 'slang-cpp-prelude.h'. // // We need to tell slang either the contents of the prelude, or suitable include/s // that will work. The actual API call to set the prelude is `setDownstreamCompilerPrelude` // and this just sets for a specific backend a bit of text placed before generated code. // // Most downstream C++ compilers work on files. In that case slang may generate temporary // files that contain the generated code. Typically the generated files will not be in the // same directory as the original source so handling includes becomes awkward. The mechanism used here // is for the prelude code to be an *absolute* path to the 'slang-cpp-prelude.h' - which means // this will work wherever the generated code is, and allows accessing other files via relative paths. // // Look at the source to TestToolUtil::setSessionDefaultPrelude to see what's involed. TestToolUtil::setSessionDefaultPrelude(argv[0], slangSession); // A compile request represents a single invocation of the compiler, // to process some inputs and produce outputs (or errors). // SlangCompileRequest* slangRequest = spCreateCompileRequest(slangSession); // We would like to request a CPU code that can be executed directly on the host - // which is the 'SLANG_HOST_CALLABLE' target. // If we wanted a just a shared library/dll, we could have used SLANG_SHARED_LIBRARY. int targetIndex = spAddCodeGenTarget(slangRequest, SLANG_HOST_CALLABLE); // A compile request can include one or more "translation units," which more or // less amount to individual source files (think `.c` files, not the `.h` files they // might include). // // For this example, our code will all be in the Slang language. The user may // also specify HLSL input here, but that currently doesn't affect the compiler's // behavior much. // int translationUnitIndex = spAddTranslationUnit(slangRequest, SLANG_SOURCE_LANGUAGE_SLANG, nullptr); // We will load source code for our translation unit from the file `shader.slang`. // There are also variations of this API for adding source code from application-provided buffers. // spAddTranslationUnitSourceFile(slangRequest, translationUnitIndex, "shader.slang"); // Next we will specify the entry points we'd like to compile. // It is often convenient to put more than one entry point in the same file, // and the Slang API makes it convenient to use a single run of the compiler // to compile all entry points. // const char entryPointName[] = "computeMain"; int computeIndex = spAddEntryPoint(slangRequest, translationUnitIndex, entryPointName, SLANG_STAGE_COMPUTE); // Once all of the input options for the compiler have been specified, // we can invoke `spCompile` to run the compiler and see if any errors // were detected. // const SlangResult compileRes = spCompile(slangRequest); // Even if there were no errors that forced compilation to fail, the // compiler may have produced "diagnostic" output such as warnings. // We will go ahead and print that output here. // if(auto diagnostics = spGetDiagnosticOutput(slangRequest)) { printf("%s", diagnostics); } // If compilation failed, there is no point in continuing any further. if(SLANG_FAILED(compileRes)) { spDestroyCompileRequest(slangRequest); return compileRes; } // Get the 'shared library' (note that this doesn't necessarily have to be implemented as a shared library // it's just an interface to executable code). ComPtr<ISlangSharedLibrary> sharedLibrary; SLANG_RETURN_ON_FAIL(spGetEntryPointHostCallable(slangRequest, 0, 0, sharedLibrary.writeRef())); // Once we have the sharedLibrary, we no longer need the request // unless we want to use reflection, to for example workout how 'UniformState' and 'UniformEntryPointParams' are laid out // at runtime. We don't do that here - as we hard code the structures. spDestroyCompileRequest(slangRequest); // Get the function we are going to execute CPPPrelude::ComputeFunc func = (CPPPrelude::ComputeFunc)sharedLibrary->findFuncByName(entryPointName); if (!func) { spDestroyCompileRequest(slangRequest); return SLANG_FAIL; } // Define the uniform state structure that is *specific* to our shader defined in shader.slang // That the layout of the structure can be determined through reflection, or can be inferred from // the original slang source. Look at the documentation in docs/cpu-target.md which describes // how different resources map. // The order of the resources is in the order that they are defined in the source. struct UniformState { CPPPrelude::RWStructuredBuffer<float> ioBuffer; }; // the uniformState will be passed as a pointer to the CPU code UniformState uniformState; // The contents of the buffer are modified, so we'll copy it const float startBufferContents[] = { 2.0f, -10.0f, -3.0f, 5.0f }; float bufferContents[SLANG_COUNT_OF(startBufferContents)]; memcpy(bufferContents, startBufferContents, sizeof(startBufferContents)); // Set up the ioBuffer such that it uses bufferContents. It is important to set the .count // such that bounds checking can be performed in the kernel. uniformState.ioBuffer.data = bufferContents; uniformState.ioBuffer.count = SLANG_COUNT_OF(bufferContents); // In shader.slang, then entry point is attributed with `[numthreads(4, 1, 1)]` meaning each group // consists of 4 'thread' in x. Our input buffer is 4 wide, and we index the input array via `SV_DispatchThreadID` // so we only need to run a single group to execute over all of the 4 elements here. // The group range from { 0, 0, 0 } -> { 1, 1, 1 } means it will execute over the single group { 0, 0, 0 }. const CPPPrelude::uint3 startGroupID = { 0, 0, 0}; const CPPPrelude::uint3 endGroupID = { 1, 1, 1 }; CPPPrelude::ComputeVaryingInput varyingInput; varyingInput.startGroupID = startGroupID; varyingInput.endGroupID = endGroupID; // We don't have any entry point parameters so that's passed as NULL // We need to cast our definition of the uniform state to the undefined CPPPrelude::UniformState as // that type is just a name to indicate what kind of thing needs to be passed in. func(&varyingInput, NULL, (CPPPrelude::UniformState*)&uniformState); // bufferContents holds the output // Print out the values before the computation printf("Before:\n"); for (float v : startBufferContents) { printf("%f, ", v); } printf("\n"); // Print out the values the the kernel produced printf("After: \n"); for (float v : bufferContents) { printf("%f, ", v); } printf("\n"); return SLANG_OK; } int main(int argc, char** argv) { return SLANG_SUCCEEDED(_innerMain(argc, argv)) ? 0 : -1; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QApplication> #include <QDebug> #include "qsysteminfo.h" using namespace QtMobility; #define X(expr) qDebug() << #expr << "->" << (expr); struct symbol_t { const char *key; int val; }; int lookup(const symbol_t *stab, const char *key, int def) { for(;stab->key;++stab) { if(!strcmp(stab->key,key)) return stab->val; } return def; } const char *rlookup(const symbol_t *stab, int val, const char *def) { for(;stab->key; ++stab) { if(stab->val == val) return stab->key; } return def; } #define SYM(x) { #x, x } static const symbol_t Version_lut[] = { SYM(QSystemInfo::Os), SYM(QSystemInfo::QtCore), SYM(QSystemInfo::Firmware), SYM(QSystemInfo::QtMobility), {0,0} }; static const symbol_t Feature_lut[] = { SYM(QSystemInfo::BluetoothFeature), SYM(QSystemInfo::CameraFeature), SYM(QSystemInfo::FmradioFeature), SYM(QSystemInfo::IrFeature), SYM(QSystemInfo::LedFeature), SYM(QSystemInfo::MemcardFeature), SYM(QSystemInfo::UsbFeature), SYM(QSystemInfo::VibFeature), SYM(QSystemInfo::WlanFeature), SYM(QSystemInfo::SimFeature), SYM(QSystemInfo::LocationFeature), SYM(QSystemInfo::VideoOutFeature), SYM(QSystemInfo::HapticsFeature), SYM(QSystemInfo::FmTransmitterFeature), {0,0} }; static const symbol_t NetworkStatus_lut[] = { SYM(QSystemNetworkInfo::UndefinedStatus), SYM(QSystemNetworkInfo::NoNetworkAvailable), SYM(QSystemNetworkInfo::EmergencyOnly), SYM(QSystemNetworkInfo::Searching), SYM(QSystemNetworkInfo::Busy), SYM(QSystemNetworkInfo::Connected), SYM(QSystemNetworkInfo::HomeNetwork), SYM(QSystemNetworkInfo::Denied), SYM(QSystemNetworkInfo::Roaming), {0,0} }; static const symbol_t NetworkMode_lut[] = { SYM(QSystemNetworkInfo::UnknownMode), SYM(QSystemNetworkInfo::GsmMode), SYM(QSystemNetworkInfo::CdmaMode), SYM(QSystemNetworkInfo::WcdmaMode), SYM(QSystemNetworkInfo::WlanMode), SYM(QSystemNetworkInfo::EthernetMode), SYM(QSystemNetworkInfo::BluetoothMode), SYM(QSystemNetworkInfo::WimaxMode), SYM(QSystemNetworkInfo::GprsMode), SYM(QSystemNetworkInfo::EdgeMode), SYM(QSystemNetworkInfo::HspaMode), SYM(QSystemNetworkInfo::LteMode), {0,0} }; /* ------------------------------------------------------------------------- * * test_systeminfo * ------------------------------------------------------------------------- */ static void test_systeminfo(void) { QSystemInfo info; X(info.currentLanguage()); X(info.availableLanguages()); X(info.currentCountryCode()); X(info.version(QSystemInfo::Os)); X(info.version(QSystemInfo::QtCore)); X(info.version(QSystemInfo::Firmware)); X(info.version(QSystemInfo::QtMobility)); X(info.hasFeatureSupported(QSystemInfo::BluetoothFeature)); X(info.hasFeatureSupported(QSystemInfo::CameraFeature)); X(info.hasFeatureSupported(QSystemInfo::FmradioFeature)); X(info.hasFeatureSupported(QSystemInfo::IrFeature)); X(info.hasFeatureSupported(QSystemInfo::LedFeature)); X(info.hasFeatureSupported(QSystemInfo::MemcardFeature)); X(info.hasFeatureSupported(QSystemInfo::UsbFeature)); X(info.hasFeatureSupported(QSystemInfo::VibFeature)); X(info.hasFeatureSupported(QSystemInfo::WlanFeature)); X(info.hasFeatureSupported(QSystemInfo::SimFeature)); X(info.hasFeatureSupported(QSystemInfo::LocationFeature)); X(info.hasFeatureSupported(QSystemInfo::VideoOutFeature)); X(info.hasFeatureSupported(QSystemInfo::HapticsFeature)); X(info.hasFeatureSupported(QSystemInfo::FmTransmitterFeature)); } /* ------------------------------------------------------------------------- * * test_systemdeviceinfo * ------------------------------------------------------------------------- */ static void test_systemdeviceinfo(void) { QSystemDeviceInfo deviceinfo; X(deviceinfo.batteryLevel()); X(deviceinfo.batteryStatus()); X(deviceinfo.currentBluetoothPowerState()); X(deviceinfo.currentPowerState()); X(deviceinfo.currentProfile()); X(deviceinfo.imei()); X(deviceinfo.imsi()); X(deviceinfo.inputMethodType()); X(deviceinfo.isDeviceLocked()); X(deviceinfo.isKeyboardFlipOpen()); X(deviceinfo.isWirelessKeyboardConnected()); X(deviceinfo.keyboardType()); X(deviceinfo.manufacturer()); X(deviceinfo.model()); X(deviceinfo.productName()); X(deviceinfo.simStatus()); X(deviceinfo.typeOfLock()); } /* ------------------------------------------------------------------------- * * test_systemdisplayinfo * ------------------------------------------------------------------------- */ static void test_systemdisplayinfo(void) { QSystemDisplayInfo displayinfo; for( int display = 0; display < 4; ++display ) { qDebug() << ""; qDebug() << "Display:" << display; int depth = displayinfo.colorDepth(display); qDebug() << " displayinfo.colorDepth() ->" << depth; int value = displayinfo.displayBrightness(display); qDebug() << " displayinfo.displayBrightness() ->" << value; QSystemDisplayInfo::DisplayOrientation orientation = displayinfo.getOrientation(display); qDebug() << " displayinfo.getOrientation() ->" << orientation; float contrast = displayinfo.contrast(display); qDebug() << " displayinfo.getContrast() ->" << contrast; int dpiWidth = displayinfo.getDPIWidth(display); qDebug() << " displayinfo.getDPIWidth() ->" << dpiWidth; int dpiHeight = displayinfo.getDPIHeight(display); qDebug() << " displayinfo.getDPIHeight() ->" << dpiHeight; int physicalHeight = displayinfo.physicalHeight(display); qDebug() << " displayinfo.physicalHeight() ->" << physicalHeight; int physicalWidth = displayinfo.physicalWidth(display); qDebug() << " displayinfo.physicalWidth() ->" << physicalWidth; } } /* ------------------------------------------------------------------------- * * test_systemstorageinfo * ------------------------------------------------------------------------- */ static const char *human_size(qlonglong n) { if(n == 0) return "0B"; static char buf[256]; char *pos = buf; char *end = buf + sizeof buf; int b = n & 1023; n >>= 10; int k = n & 1023; n >>= 10; int m = n & 1023; n >>= 10; int g = n & 1023; n >>= 10; *pos = 0; #if defined(Q_WS_WIN) if(g) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dGB", *buf?" ":"", g), pos = strchr(pos,0); if(m) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dMB", *buf?" ":"", m), pos = strchr(pos,0); if(k) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dkB", *buf?" ":"", k), pos = strchr(pos,0); if(b) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dB", *buf?" ":"", b), pos = strchr(pos,0); #else if(g) snprintf(pos, end-pos, "%s%dGB", *buf?" ":"", g), pos = strchr(pos,0); if(m) snprintf(pos, end-pos, "%s%dMB", *buf?" ":"", m), pos = strchr(pos,0); if(k) snprintf(pos, end-pos, "%s%dkB", *buf?" ":"", k), pos = strchr(pos,0); if(b) snprintf(pos, end-pos, "%s%dB", *buf?" ":"", b), pos = strchr(pos,0); #endif return buf; } static void test_systemstorageinfo(void) { QSystemStorageInfo storageinfo; QStringList lst = storageinfo.logicalDrives(); qDebug() << "storageinfo.logicalDrives ->" << lst; for(int i = 0; i < lst.size(); ++i) { const QString &drv = lst.at(i); qDebug() << "Logical drive:" << drv; qlonglong avail = storageinfo.availableDiskSpace(drv); qDebug() << " storageinfo.availableDiskSpace() ->" << human_size(avail); qlonglong total = storageinfo.totalDiskSpace(drv); qDebug() << " storageinfo.totalDiskSpace() ->" << human_size(total); QSystemStorageInfo::DriveType dtype = storageinfo.typeForDrive(drv); qDebug() << " storageinfo.typeForDrive() ->" << dtype; QString duri = storageinfo.uriForDrive(drv); qDebug() << " storageinfo.uriForDrive() ->" << duri; QSystemStorageInfo::StorageState dstate = storageinfo.getStorageState(drv); qDebug() << " storageinfo.getStorageState() ->" << dstate; } } /* ------------------------------------------------------------------------- * * test_systemnetworkinfo * ------------------------------------------------------------------------- */ static void test_systemnetworkinfo(void) { QSystemNetworkInfo networkinfo; X(networkinfo.cellId()); X(networkinfo.currentMobileCountryCode()); X(networkinfo.currentMobileNetworkCode()); X(networkinfo.homeMobileCountryCode()); X(networkinfo.homeMobileNetworkCode()); X(networkinfo.locationAreaCode()); for(const symbol_t *sym = NetworkMode_lut; sym->key; ++sym) { QtMobility::QSystemNetworkInfo::NetworkMode mode = (QtMobility::QSystemNetworkInfo::NetworkMode) sym->val; qDebug() << ""; qDebug() << "NetworkMode:" << sym->key; QNetworkInterface iface = networkinfo.interfaceForMode(mode); qDebug() << " networkinfo.interfaceForMode() ->" << iface; QString macaddr = networkinfo.macAddress(mode); qDebug() << " networkinfo.macAddress() ->" << macaddr; QSystemNetworkInfo::NetworkStatus status = networkinfo.networkStatus(mode); qDebug() << " networkinfo.networkStatus() ->" << status; QString network = networkinfo.networkName(mode); qDebug() << " networkinfo.networkName() ->" << network; int sigstr = networkinfo.networkSignalStrength(mode); qDebug() << " networkinfo.networkSignalStrength() ->" << sigstr; } } static void test_systemscreensaver(void) { QSystemScreenSaver screensaver; X(screensaver.screenSaverInhibited()); X(screensaver.setScreenSaverInhibit()); } struct dummy_t { const char *name; void (*func)(void); } lut[] = { #define ADD(x) {#x, test_##x } ADD(systeminfo), ADD(systemdeviceinfo), ADD(systemstorageinfo), ADD(systemnetworkinfo), ADD(systemscreensaver), ADD(systemdisplayinfo), #undef ADD {0,0} }; static bool endswith(const char *str, const char *pat) { int slen = strlen(str); int plen = strlen(pat); return (slen >= plen) && !strcmp(str+slen-plen, pat); } int lookup_test(const char *name) { for(int i = 0; lut[i].name; ++i) { if(!strcmp(lut[i].name, name)) return i; } for(int i = 0; lut[i].name; ++i) { if(endswith(lut[i].name, name)) return i; } for(int i = 0; lut[i].name; ++i) { if(strstr(lut[i].name, name)) return i; } return -1; } int main(int ac, char **av) { #if !defined(Q_WS_WIN) if(!getenv("DISPLAY")) { qDebug() << "$DISPLAY not set, assuming :0"; setenv("DISPLAY", ":0", 1); } if(!getenv("DBUS_SESSION_BUS_ADDRESS")) { qDebug() << "session bus not configured"; } #endif QApplication app(ac, av, true); if(ac < 2) { qDebug() << "available tests:"; for(int k = 0; lut[k].name; ++k) { qDebug() << *av << lut[k].name; } exit(0); } for(int i = 1; i < ac; ++i) { const char *name = av[i]; int k = lookup_test(name); if(k != -1) { qDebug() << ""; qDebug() << "----(" << lut[k].name << ")----"; qDebug() << ""; lut[k].func(); } else if( !strcmp(name, "all")) { for(int k = 0; lut[k].name; ++k) { qDebug() << ""; qDebug() << "----(" << lut[k].name << ")----"; qDebug() << ""; lut[k].func(); } } else { break; } } } // EOF <commit_msg>add batteryinfo<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QApplication> #include <QDebug> #include "qsysteminfo.h" using namespace QtMobility; #define X(expr) qDebug() << #expr << "->" << (expr); struct symbol_t { const char *key; int val; }; int lookup(const symbol_t *stab, const char *key, int def) { for(;stab->key;++stab) { if(!strcmp(stab->key,key)) return stab->val; } return def; } const char *rlookup(const symbol_t *stab, int val, const char *def) { for(;stab->key; ++stab) { if(stab->val == val) return stab->key; } return def; } #define SYM(x) { #x, x } static const symbol_t Version_lut[] = { SYM(QSystemInfo::Os), SYM(QSystemInfo::QtCore), SYM(QSystemInfo::Firmware), SYM(QSystemInfo::QtMobility), {0,0} }; static const symbol_t Feature_lut[] = { SYM(QSystemInfo::BluetoothFeature), SYM(QSystemInfo::CameraFeature), SYM(QSystemInfo::FmradioFeature), SYM(QSystemInfo::IrFeature), SYM(QSystemInfo::LedFeature), SYM(QSystemInfo::MemcardFeature), SYM(QSystemInfo::UsbFeature), SYM(QSystemInfo::VibFeature), SYM(QSystemInfo::WlanFeature), SYM(QSystemInfo::SimFeature), SYM(QSystemInfo::LocationFeature), SYM(QSystemInfo::VideoOutFeature), SYM(QSystemInfo::HapticsFeature), SYM(QSystemInfo::FmTransmitterFeature), {0,0} }; static const symbol_t NetworkStatus_lut[] = { SYM(QSystemNetworkInfo::UndefinedStatus), SYM(QSystemNetworkInfo::NoNetworkAvailable), SYM(QSystemNetworkInfo::EmergencyOnly), SYM(QSystemNetworkInfo::Searching), SYM(QSystemNetworkInfo::Busy), SYM(QSystemNetworkInfo::Connected), SYM(QSystemNetworkInfo::HomeNetwork), SYM(QSystemNetworkInfo::Denied), SYM(QSystemNetworkInfo::Roaming), {0,0} }; static const symbol_t NetworkMode_lut[] = { SYM(QSystemNetworkInfo::UnknownMode), SYM(QSystemNetworkInfo::GsmMode), SYM(QSystemNetworkInfo::CdmaMode), SYM(QSystemNetworkInfo::WcdmaMode), SYM(QSystemNetworkInfo::WlanMode), SYM(QSystemNetworkInfo::EthernetMode), SYM(QSystemNetworkInfo::BluetoothMode), SYM(QSystemNetworkInfo::WimaxMode), SYM(QSystemNetworkInfo::GprsMode), SYM(QSystemNetworkInfo::EdgeMode), SYM(QSystemNetworkInfo::HspaMode), SYM(QSystemNetworkInfo::LteMode), {0,0} }; /* ------------------------------------------------------------------------- * * test_systeminfo * ------------------------------------------------------------------------- */ static void test_systeminfo(void) { QSystemInfo info; X(info.currentLanguage()); X(info.availableLanguages()); X(info.currentCountryCode()); X(info.version(QSystemInfo::Os)); X(info.version(QSystemInfo::QtCore)); X(info.version(QSystemInfo::Firmware)); X(info.version(QSystemInfo::QtMobility)); X(info.hasFeatureSupported(QSystemInfo::BluetoothFeature)); X(info.hasFeatureSupported(QSystemInfo::CameraFeature)); X(info.hasFeatureSupported(QSystemInfo::FmradioFeature)); X(info.hasFeatureSupported(QSystemInfo::IrFeature)); X(info.hasFeatureSupported(QSystemInfo::LedFeature)); X(info.hasFeatureSupported(QSystemInfo::MemcardFeature)); X(info.hasFeatureSupported(QSystemInfo::UsbFeature)); X(info.hasFeatureSupported(QSystemInfo::VibFeature)); X(info.hasFeatureSupported(QSystemInfo::WlanFeature)); X(info.hasFeatureSupported(QSystemInfo::SimFeature)); X(info.hasFeatureSupported(QSystemInfo::LocationFeature)); X(info.hasFeatureSupported(QSystemInfo::VideoOutFeature)); X(info.hasFeatureSupported(QSystemInfo::HapticsFeature)); X(info.hasFeatureSupported(QSystemInfo::FmTransmitterFeature)); } /* ------------------------------------------------------------------------- * * test_systemdeviceinfo * ------------------------------------------------------------------------- */ static void test_systemdeviceinfo(void) { QSystemDeviceInfo deviceinfo; X(deviceinfo.batteryLevel()); X(deviceinfo.batteryStatus()); X(deviceinfo.currentBluetoothPowerState()); X(deviceinfo.currentPowerState()); X(deviceinfo.currentProfile()); X(deviceinfo.imei()); X(deviceinfo.imsi()); X(deviceinfo.inputMethodType()); X(deviceinfo.isDeviceLocked()); X(deviceinfo.isKeyboardFlipOpen()); X(deviceinfo.isWirelessKeyboardConnected()); X(deviceinfo.keyboardType()); X(deviceinfo.manufacturer()); X(deviceinfo.model()); X(deviceinfo.productName()); X(deviceinfo.simStatus()); X(deviceinfo.typeOfLock()); } /* ------------------------------------------------------------------------- * * test_systemdisplayinfo * ------------------------------------------------------------------------- */ static void test_systemdisplayinfo(void) { QSystemDisplayInfo displayinfo; for( int display = 0; display < 4; ++display ) { qDebug() << ""; qDebug() << "Display:" << display; int depth = displayinfo.colorDepth(display); qDebug() << " displayinfo.colorDepth() ->" << depth; int value = displayinfo.displayBrightness(display); qDebug() << " displayinfo.displayBrightness() ->" << value; QSystemDisplayInfo::DisplayOrientation orientation = displayinfo.getOrientation(display); qDebug() << " displayinfo.getOrientation() ->" << orientation; float contrast = displayinfo.contrast(display); qDebug() << " displayinfo.getContrast() ->" << contrast; int dpiWidth = displayinfo.getDPIWidth(display); qDebug() << " displayinfo.getDPIWidth() ->" << dpiWidth; int dpiHeight = displayinfo.getDPIHeight(display); qDebug() << " displayinfo.getDPIHeight() ->" << dpiHeight; int physicalHeight = displayinfo.physicalHeight(display); qDebug() << " displayinfo.physicalHeight() ->" << physicalHeight; int physicalWidth = displayinfo.physicalWidth(display); qDebug() << " displayinfo.physicalWidth() ->" << physicalWidth; } } /* ------------------------------------------------------------------------- * * test_systemstorageinfo * ------------------------------------------------------------------------- */ static const char *human_size(qlonglong n) { if(n == 0) return "0B"; static char buf[256]; char *pos = buf; char *end = buf + sizeof buf; int b = n & 1023; n >>= 10; int k = n & 1023; n >>= 10; int m = n & 1023; n >>= 10; int g = n & 1023; n >>= 10; *pos = 0; #if defined(Q_WS_WIN) if(g) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dGB", *buf?" ":"", g), pos = strchr(pos,0); if(m) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dMB", *buf?" ":"", m), pos = strchr(pos,0); if(k) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dkB", *buf?" ":"", k), pos = strchr(pos,0); if(b) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dB", *buf?" ":"", b), pos = strchr(pos,0); #else if(g) snprintf(pos, end-pos, "%s%dGB", *buf?" ":"", g), pos = strchr(pos,0); if(m) snprintf(pos, end-pos, "%s%dMB", *buf?" ":"", m), pos = strchr(pos,0); if(k) snprintf(pos, end-pos, "%s%dkB", *buf?" ":"", k), pos = strchr(pos,0); if(b) snprintf(pos, end-pos, "%s%dB", *buf?" ":"", b), pos = strchr(pos,0); #endif return buf; } static void test_systemstorageinfo(void) { QSystemStorageInfo storageinfo; QStringList lst = storageinfo.logicalDrives(); qDebug() << "storageinfo.logicalDrives ->" << lst; for(int i = 0; i < lst.size(); ++i) { const QString &drv = lst.at(i); qDebug() << "Logical drive:" << drv; qlonglong avail = storageinfo.availableDiskSpace(drv); qDebug() << " storageinfo.availableDiskSpace() ->" << human_size(avail); qlonglong total = storageinfo.totalDiskSpace(drv); qDebug() << " storageinfo.totalDiskSpace() ->" << human_size(total); QSystemStorageInfo::DriveType dtype = storageinfo.typeForDrive(drv); qDebug() << " storageinfo.typeForDrive() ->" << dtype; QString duri = storageinfo.uriForDrive(drv); qDebug() << " storageinfo.uriForDrive() ->" << duri; QSystemStorageInfo::StorageState dstate = storageinfo.getStorageState(drv); qDebug() << " storageinfo.getStorageState() ->" << dstate; } } /* ------------------------------------------------------------------------- * * test_systemnetworkinfo * ------------------------------------------------------------------------- */ static void test_systemnetworkinfo(void) { QSystemNetworkInfo networkinfo; X(networkinfo.cellId()); X(networkinfo.currentMobileCountryCode()); X(networkinfo.currentMobileNetworkCode()); X(networkinfo.homeMobileCountryCode()); X(networkinfo.homeMobileNetworkCode()); X(networkinfo.locationAreaCode()); for(const symbol_t *sym = NetworkMode_lut; sym->key; ++sym) { QtMobility::QSystemNetworkInfo::NetworkMode mode = (QtMobility::QSystemNetworkInfo::NetworkMode) sym->val; qDebug() << ""; qDebug() << "NetworkMode:" << sym->key; QNetworkInterface iface = networkinfo.interfaceForMode(mode); qDebug() << " networkinfo.interfaceForMode() ->" << iface; QString macaddr = networkinfo.macAddress(mode); qDebug() << " networkinfo.macAddress() ->" << macaddr; QSystemNetworkInfo::NetworkStatus status = networkinfo.networkStatus(mode); qDebug() << " networkinfo.networkStatus() ->" << status; QString network = networkinfo.networkName(mode); qDebug() << " networkinfo.netwoerkName() ->" << network; int sigstr = networkinfo.networkSignalStrength(mode); qDebug() << " networkinfo.networkSignalStrength() ->" << sigstr; } } static void test_systemscreensaver(void) { QSystemScreenSaver screensaver; X(screensaver.screenSaverInhibited()); X(screensaver.setScreenSaverInhibit()); } static void test_systembatteryinfo(void) { QSystemBatteryInfo batInfo; X(batInfo.chargerType()); X(batInfo.chargingState() ); X(batInfo.nominalCapacity()); X(batInfo.remainingCapacityPercent()); X(batInfo.remainingCapacitymAh()); X(batInfo.voltage()); X(batInfo.remainingChargingTime()); X(batInfo.currentFlow()); X(batInfo.cumulativeCurrentFlow()); X(batInfo.remainingCapacityBars()); X(batInfo.maxBars()); X(batInfo.batteryStatus()); } struct dummy_t { const char *name; void (*func)(void); } lut[] = { #define ADD(x) {#x, test_##x } ADD(systeminfo), ADD(systemdeviceinfo), ADD(systemstorageinfo), ADD(systemnetworkinfo), ADD(systemscreensaver), ADD(systemdisplayinfo), ADD(systembatteryinfo), #undef ADD {0,0} }; static bool endswith(const char *str, const char *pat) { int slen = strlen(str); int plen = strlen(pat); return (slen >= plen) && !strcmp(str+slen-plen, pat); } int lookup_test(const char *name) { for(int i = 0; lut[i].name; ++i) { if(!strcmp(lut[i].name, name)) return i; } for(int i = 0; lut[i].name; ++i) { if(endswith(lut[i].name, name)) return i; } for(int i = 0; lut[i].name; ++i) { if(strstr(lut[i].name, name)) return i; } return -1; } int main(int ac, char **av) { #if !defined(Q_WS_WIN) if(!getenv("DISPLAY")) { qDebug() << "$DISPLAY not set, assuming :0"; setenv("DISPLAY", ":0", 1); } if(!getenv("DBUS_SESSION_BUS_ADDRESS")) { qDebug() << "session bus not configured"; } #endif QApplication app(ac, av, true); if(ac < 2) { qDebug() << "available tests:"; for(int k = 0; lut[k].name; ++k) { qDebug() << *av << lut[k].name; } exit(0); } for(int i = 1; i < ac; ++i) { const char *name = av[i]; int k = lookup_test(name); if(k != -1) { qDebug() << ""; qDebug() << "----(" << lut[k].name << ")----"; qDebug() << ""; lut[k].func(); } else if( !strcmp(name, "all")) { for(int k = 0; lut[k].name; ++k) { qDebug() << ""; qDebug() << "----(" << lut[k].name << ")----"; qDebug() << ""; lut[k].func(); } } else { break; } } } // EOF <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dbwizsetup.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2005-02-17 11:08:12 $ * * 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 EXPRESS 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 DBAUI_DBWIZ2_HXX #define DBAUI_DBWIZ2_HXX #ifndef _SFXTABDLG_HXX #include <sfx2/tabdlg.hxx> #endif #ifndef _DBAUI_DSNTYPES_HXX_ #include "dsntypes.hxx" #endif #ifndef DBAUI_ITEMSETHELPER_HXX #include "IItemSetHelper.hxx" #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #include <memory> #ifndef SVTOOLS_INC_ROADMAPWIZARD_HXX #include <svtools/roadmapwizard.hxx> #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include <connectivity/dbtools.hxx> #endif FORWARD_DECLARE_INTERFACE(beans,XPropertySet) FORWARD_DECLARE_INTERFACE(sdbc,XConnection) FORWARD_DECLARE_INTERFACE(lang,XMultiServiceFactory) //......................................................................... namespace dbaui { //......................................................................... class ODsnTypeCollection; class OGenericAdministrationPage; //========================================================================= //= ODbTypeWizDialogSetup //========================================================================= class OGeneralPage; struct OPageSettings; class ODbDataSourceAdministrationHelper; /** tab dialog for administrating the office wide registered data sources */ class OMySQLIntroPageSetup; class ODbTypeWizDialogSetup : public svt::RoadmapWizard , public IItemSetHelper, public IAdminHelper,public dbaui::OModuleClient { private: ::std::auto_ptr<ODbDataSourceAdministrationHelper> m_pImpl; SfxItemSet* m_pOutSet; DATASOURCE_TYPE m_eType; DATASOURCE_TYPE m_eOldType; sal_Bool m_bResetting : 1; /// sal_True while we're resetting the pages sal_Bool m_bApplied : 1; /// sal_True if any changes have been applied while the dialog was executing sal_Bool m_bUIEnabled : 1; /// <TRUE/> if the UI is enabled, false otherwise. Cannot be switched back to <TRUE/>, once it is <FALSE/> sal_Bool m_bIsConnectable : 1; String m_sRM_IntroText; String m_sRM_dBaseText; String m_sRM_TextText; String m_sRM_MSAccessText; String m_sRM_LDAPText; String m_sRM_ADABASText; String m_sRM_ADOText; String m_sRM_JDBCText; String m_sRM_OracleText; String m_sRM_MySQLText; String m_sRM_ODBCText; String m_sRM_SpreadSheetText; String m_sRM_AuthentificationText; String m_sRM_FinalText; // String m_sWizardTitle; INetURLObject m_aDocURL; String m_sWorkPath; OGeneralPage* m_pGeneralPage; OMySQLIntroPageSetup* m_pMySQLIntroPage; ODsnTypeCollection* m_pCollection; /// the DSN type collection instance public: /** ctor. The itemset given should have been created by <method>createItemSet</method> and should be destroyed after the dialog has been destroyed */ ODbTypeWizDialogSetup(Window* pParent ,SfxItemSet* _pItems ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB ,const ::com::sun::star::uno::Any& _aDataSourceName ); virtual ~ODbTypeWizDialogSetup(); virtual const SfxItemSet* getOutputSet() const; virtual SfxItemSet* getWriteOutputSet(); // forwards to ODbDataSourceAdministrationHelper virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB(); virtual ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >,sal_Bool> createConnection(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > getDriver(); virtual DATASOURCE_TYPE getDatasourceType(const SfxItemSet& _rSet) const; virtual void clearPassword(); virtual void setTitle(const ::rtl::OUString& _sTitle); virtual sal_Bool saveDatasource(); virtual String getStateDisplayName( WizardState _nState ); virtual short Execute(); /** returns <TRUE/> if the database should be opened, otherwise <FALSE/>. */ sal_Bool IsDatabaseDocumentToBeOpened(); /** returns <TRUE/> if the table wizard should be opened, otherwise <FALSE/>. */ sal_Bool IsTableWizardToBeStarted(); protected: /// to override to create new pages virtual TabPage* createPage(WizardState _nState); // virtual ::svt::WizardTypes::WizardState determineNextState(::svt::WizardTypes::WizardState _nCurrentState); virtual sal_Bool leaveState(WizardState _nState); virtual void enterState(WizardState _nState); virtual ::svt::IWizardPage* getWizardPage(TabPage* _pCurrentPage) const; virtual sal_Bool onFinish(sal_Int32 _nResult); protected: inline sal_Bool isUIEnabled() const { return m_bUIEnabled; } inline void disabledUI() { m_bUIEnabled = sal_False; } /// select a datasource with a given name, adjust the item set accordingly, and everything like that .. void implSelectDatasource(const ::rtl::OUString& _rRegisteredName); void resetPages(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDatasource); enum ApplyResult { AR_LEAVE_MODIFIED, // somthing was modified and has successfully been committed AR_LEAVE_UNCHANGED, // no changes were made AR_KEEP // don't leave the page (e.g. because an error occured) }; /** apply all changes made */ ApplyResult implApplyChanges(); private: sal_Bool StartTableWizard(); //const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB void RegisterDataSourceByLocation(const ::rtl::OUString& sPath); void OpenDatabaseDocument(const ::rtl::OUString& _sPath); sal_Bool SaveDatabaseDocument(); void activateDatabasePath(OGeneralPage* _pTabpage); void createUniqueFileName(INetURLObject* pURL); void CreateDatabase(); void createUniqueFolderName(INetURLObject* pURL); DATASOURCE_TYPE VerifyDataSourceType(const DATASOURCE_TYPE _DatabaseType) const; void ToggleFollowingRoadmapSteps(); sal_Bool callSaveAsDialog(); // sal_Bool DocUrlHasValue(); sal_Bool IsConnectionUrlRequired(); DECL_LINK(OnTypeSelected, OGeneralPage*); DECL_LINK(ImplCreateDBHdl, OGeneralPage*); DECL_LINK(ImplClickHdl, OMySQLIntroPageSetup*); DECL_LINK(ImplModifiedHdl, OGenericAdministrationPage*); }; //......................................................................... } // namespace dbaui //......................................................................... #endif // DBAUI_DBWIZ2_HXX <commit_msg>INTEGRATION: CWS dba24 (1.4.2); FILE MERGED 2005/02/23 07:41:49 oj 1.4.2.1: #i42461# reinvent the opening of database documents<commit_after>/************************************************************************* * * $RCSfile: dbwizsetup.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2005-03-10 16:51:17 $ * * 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 EXPRESS 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 DBAUI_DBWIZ2_HXX #define DBAUI_DBWIZ2_HXX #ifndef _SFXTABDLG_HXX #include <sfx2/tabdlg.hxx> #endif #ifndef _DBAUI_DSNTYPES_HXX_ #include "dsntypes.hxx" #endif #ifndef DBAUI_ITEMSETHELPER_HXX #include "IItemSetHelper.hxx" #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #include <memory> #ifndef SVTOOLS_INC_ROADMAPWIZARD_HXX #include <svtools/roadmapwizard.hxx> #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include <connectivity/dbtools.hxx> #endif FORWARD_DECLARE_INTERFACE(beans,XPropertySet) FORWARD_DECLARE_INTERFACE(sdbc,XConnection) FORWARD_DECLARE_INTERFACE(lang,XMultiServiceFactory) //......................................................................... namespace dbaui { //......................................................................... class ODsnTypeCollection; class OGenericAdministrationPage; //========================================================================= //= ODbTypeWizDialogSetup //========================================================================= class OGeneralPage; struct OPageSettings; class ODbDataSourceAdministrationHelper; /** tab dialog for administrating the office wide registered data sources */ class OMySQLIntroPageSetup; class ODbTypeWizDialogSetup : public svt::RoadmapWizard , public IItemSetHelper, public IAdminHelper,public dbaui::OModuleClient { private: ::std::auto_ptr<ODbDataSourceAdministrationHelper> m_pImpl; SfxItemSet* m_pOutSet; DATASOURCE_TYPE m_eType; DATASOURCE_TYPE m_eOldType; sal_Bool m_bResetting : 1; /// sal_True while we're resetting the pages sal_Bool m_bApplied : 1; /// sal_True if any changes have been applied while the dialog was executing sal_Bool m_bUIEnabled : 1; /// <TRUE/> if the UI is enabled, false otherwise. Cannot be switched back to <TRUE/>, once it is <FALSE/> sal_Bool m_bIsConnectable : 1; String m_sRM_IntroText; String m_sRM_dBaseText; String m_sRM_TextText; String m_sRM_MSAccessText; String m_sRM_LDAPText; String m_sRM_ADABASText; String m_sRM_ADOText; String m_sRM_JDBCText; String m_sRM_OracleText; String m_sRM_MySQLText; String m_sRM_ODBCText; String m_sRM_SpreadSheetText; String m_sRM_AuthentificationText; String m_sRM_FinalText; // String m_sWizardTitle; INetURLObject m_aDocURL; String m_sWorkPath; OGeneralPage* m_pGeneralPage; OMySQLIntroPageSetup* m_pMySQLIntroPage; ODsnTypeCollection* m_pCollection; /// the DSN type collection instance public: /** ctor. The itemset given should have been created by <method>createItemSet</method> and should be destroyed after the dialog has been destroyed */ ODbTypeWizDialogSetup(Window* pParent ,SfxItemSet* _pItems ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB ,const ::com::sun::star::uno::Any& _aDataSourceName ); virtual ~ODbTypeWizDialogSetup(); virtual const SfxItemSet* getOutputSet() const; virtual SfxItemSet* getWriteOutputSet(); // forwards to ODbDataSourceAdministrationHelper virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB(); virtual ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >,sal_Bool> createConnection(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > getDriver(); virtual DATASOURCE_TYPE getDatasourceType(const SfxItemSet& _rSet) const; virtual void clearPassword(); virtual void setTitle(const ::rtl::OUString& _sTitle); virtual sal_Bool saveDatasource(); virtual String getStateDisplayName( WizardState _nState ); virtual short Execute(); /** returns <TRUE/> if the database should be opened, otherwise <FALSE/>. */ sal_Bool IsDatabaseDocumentToBeOpened(); /** returns <TRUE/> if the table wizard should be opened, otherwise <FALSE/>. */ sal_Bool IsTableWizardToBeStarted(); protected: /// to override to create new pages virtual TabPage* createPage(WizardState _nState); // virtual ::svt::WizardTypes::WizardState determineNextState(::svt::WizardTypes::WizardState _nCurrentState); virtual sal_Bool leaveState(WizardState _nState); virtual void enterState(WizardState _nState); virtual ::svt::IWizardPage* getWizardPage(TabPage* _pCurrentPage) const; virtual sal_Bool onFinish(sal_Int32 _nResult); protected: inline sal_Bool isUIEnabled() const { return m_bUIEnabled; } inline void disabledUI() { m_bUIEnabled = sal_False; } /// select a datasource with a given name, adjust the item set accordingly, and everything like that .. void implSelectDatasource(const ::rtl::OUString& _rRegisteredName); void resetPages(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDatasource); enum ApplyResult { AR_LEAVE_MODIFIED, // somthing was modified and has successfully been committed AR_LEAVE_UNCHANGED, // no changes were made AR_KEEP // don't leave the page (e.g. because an error occured) }; /** apply all changes made */ ApplyResult implApplyChanges(); private: void RegisterDataSourceByLocation(const ::rtl::OUString& sPath); sal_Bool SaveDatabaseDocument(); void activateDatabasePath(OGeneralPage* _pTabpage); void createUniqueFileName(INetURLObject* pURL); void CreateDatabase(); void createUniqueFolderName(INetURLObject* pURL); DATASOURCE_TYPE VerifyDataSourceType(const DATASOURCE_TYPE _DatabaseType) const; void ToggleFollowingRoadmapSteps(); sal_Bool callSaveAsDialog(); // sal_Bool DocUrlHasValue(); sal_Bool IsConnectionUrlRequired(); DECL_LINK(OnTypeSelected, OGeneralPage*); DECL_LINK(ImplCreateDBHdl, OGeneralPage*); DECL_LINK(ImplClickHdl, OMySQLIntroPageSetup*); DECL_LINK(ImplModifiedHdl, OGenericAdministrationPage*); }; //......................................................................... } // namespace dbaui //......................................................................... #endif // DBAUI_DBWIZ2_HXX <|endoftext|>
<commit_before>/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS 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 * @brief Tests of IronBee capture interface * * @author Nick LeRoy <nleroy@qualys.com> */ /* Testing fixture. */ #include "base_fixture.h" /* Header of what we are testing. */ #include <ironbee/capture.h> #include <ironbee/data.h> #include <ironbee/field.h> #include <ironbee/list.h> #include <ironbee/mpool.h> /** * Test capture */ class CaptureTest : public BaseTransactionFixture { void SetUp() { BaseFixture::SetUp(); configureIronBee(); performTx(); } public: ib_status_t CaptureGet( int num, ib_field_t **pfield) { return ib_data_get(ib_tx->data, ib_capture_fullname(ib_tx, NULL, 0), pfield); }; ib_status_t CaptureGet( const char *capture, int num, ib_field_t **pfield) { return ib_data_get(ib_tx->data, ib_capture_fullname(ib_tx, capture, 0), pfield); }; ib_status_t CaptureBytestr( const char *capture, int num, const char *value, ib_field_t **pfield) { const char *name; ib_bytestr_t *bstr; ib_status_t rc; name = ib_capture_name(num); rc = ib_bytestr_dup_nulstr(&bstr, MainPool(), value); if (rc != IB_OK) { throw std::runtime_error("Failed to dup NulStr into ByteStr"); } rc = ib_field_create(pfield, MainPool(), IB_FIELD_NAME(name), IB_FTYPE_BYTESTR, ib_ftype_bytestr_in(bstr)); if (rc != IB_OK) { throw std::runtime_error("Failed to create ByteStr field"); } rc = ib_capture_set_item(ib_tx, capture, num, *pfield); return rc; } }; #define CAP_NAME "xyzzy" TEST_F(CaptureTest, test_names) { const char *name; name = ib_capture_name(0); ASSERT_STREQ("0", name); name = ib_capture_name(9); ASSERT_STREQ("9", name); name = ib_capture_name(10); ASSERT_STREQ("??", name); name = ib_capture_fullname(ib_tx, NULL, 0); ASSERT_STREQ(IB_TX_CAPTURE":0", name); name = ib_capture_fullname(ib_tx, NULL, 9); ASSERT_STREQ(IB_TX_CAPTURE":9", name); name = ib_capture_fullname(ib_tx, NULL, 10); ASSERT_STREQ(IB_TX_CAPTURE":??", name); name = ib_capture_fullname(ib_tx, CAP_NAME, 0); ASSERT_STREQ(CAP_NAME":0", name); name = ib_capture_fullname(ib_tx, CAP_NAME, 9); ASSERT_STREQ(CAP_NAME":9", name); name = ib_capture_fullname(ib_tx, CAP_NAME, 10); ASSERT_STREQ(CAP_NAME":??", name); } TEST_F(CaptureTest, basic) { ib_status_t rc; ib_field_t *ifield; ib_field_t *ofield; const ib_bytestr_t *bs; rc = CaptureGet(0, &ofield); ASSERT_EQ(IB_ENOENT, rc); rc = CaptureBytestr(NULL, 0, "value0", &ifield); ASSERT_EQ(IB_OK, rc); rc = CaptureGet(0, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_BYTESTR, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_bytestr_out(&bs))); ASSERT_EQ(0, memcmp("value0", ib_bytestr_const_ptr(bs), 5)); rc = CaptureGet(1, &ofield); ASSERT_EQ(IB_ENOENT, rc); rc = CaptureBytestr(NULL, 1, "value1", &ifield); ASSERT_EQ(IB_OK, rc); rc = CaptureGet(1, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_BYTESTR, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_bytestr_out(&bs))); ASSERT_EQ(0, memcmp("value1", ib_bytestr_const_ptr(bs), 5)); rc = CaptureGet(2, &ofield); ASSERT_EQ(IB_ENOENT, rc); rc = ib_capture_clear(ib_tx, NULL); ASSERT_EQ(IB_OK, rc); rc = CaptureGet(0, &ofield); ASSERT_EQ(IB_ENOENT, rc); rc = CaptureGet(1, &ofield); ASSERT_EQ(IB_ENOENT, rc); rc = CaptureGet(2, &ofield); ASSERT_EQ(IB_ENOENT, rc); } TEST_F(CaptureTest, collection_type) { ib_status_t rc; ib_field_t *ifield; ib_field_t *ofield; const ib_bytestr_t *bs; ib_num_t n = 666; rc = ib_field_create(&ofield, MainPool(), IB_FIELD_NAME(CAP_NAME), IB_FTYPE_NUM, ib_ftype_num_in(&n)); ASSERT_EQ(IB_OK, rc); rc = ib_data_get(ib_tx->data, ib_capture_fullname(ib_tx, CAP_NAME, 0), &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_NUM, ofield->type); rc = CaptureBytestr(CAP_NAME, 0, "value0", &ifield); ASSERT_EQ(IB_OK, rc); rc = CaptureGet(0, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_BYTESTR, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_bytestr_out(&bs))); ASSERT_EQ(0, memcmp("value0", ib_bytestr_const_ptr(bs), 5)); rc = CaptureGet(1, &ofield); ASSERT_EQ(IB_ENOENT, rc); rc = CaptureBytestr(CAP_NAME, 1, "value1", &ifield); ASSERT_EQ(IB_OK, rc); rc = CaptureGet(1, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_BYTESTR, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_bytestr_out(&bs))); ASSERT_EQ(0, memcmp("value1", ib_bytestr_const_ptr(bs), 5)); rc = CaptureGet(2, &ofield); ASSERT_EQ(IB_ENOENT, rc); rc = ib_capture_clear(ib_tx, CAP_NAME); ASSERT_EQ(IB_OK, rc); rc = CaptureGet(CAP_NAME, 0, &ofield); ASSERT_EQ(IB_ENOENT, rc); rc = CaptureGet(CAP_NAME, 1, &ofield); ASSERT_EQ(IB_ENOENT, rc); rc = CaptureGet(CAP_NAME, 2, &ofield); ASSERT_EQ(IB_ENOENT, rc); } <commit_msg>Fixed capture test<commit_after>/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS 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 * @brief Tests of IronBee capture interface * * @author Nick LeRoy <nleroy@qualys.com> */ /* Testing fixture. */ #include "base_fixture.h" /* Header of what we are testing. */ #include <ironbee/capture.h> #include <ironbee/data.h> #include <ironbee/field.h> #include <ironbee/list.h> #include <ironbee/mpool.h> /** * Test capture */ class CaptureTest : public BaseTransactionFixture { void SetUp() { BaseFixture::SetUp(); configureIronBee(); performTx(); } public: ib_status_t CaptureGet( int num, ib_field_t **pfield) { return ib_data_get(ib_tx->data, ib_capture_fullname(ib_tx, NULL, num), pfield); }; ib_status_t CaptureGet( const char *capture, int num, ib_field_t **pfield) { return ib_data_get(ib_tx->data, ib_capture_fullname(ib_tx, capture, num), pfield); }; ib_status_t CaptureBytestr( const char *capture, int num, const char *value, ib_field_t **pfield) { const char *name; ib_bytestr_t *bstr; ib_status_t rc; name = ib_capture_name(num); name = ib_mpool_strdup(MainPool(), name); if (name == NULL) { throw std::runtime_error("Failed to dup name"); } rc = ib_bytestr_dup_nulstr(&bstr, MainPool(), value); if (rc != IB_OK) { throw std::runtime_error("Failed to dup NulStr into ByteStr"); } rc = ib_field_create(pfield, MainPool(), IB_FIELD_NAME(name), IB_FTYPE_BYTESTR, ib_ftype_bytestr_in(bstr)); if (rc != IB_OK) { throw std::runtime_error("Failed to create ByteStr field"); } rc = ib_capture_set_item(ib_tx, capture, num, *pfield); return rc; } }; #define CAP_NAME "xyzzy" TEST_F(CaptureTest, test_names) { const char *name; name = ib_capture_name(0); ASSERT_STREQ("0", name); name = ib_capture_name(9); ASSERT_STREQ("9", name); name = ib_capture_name(10); ASSERT_STREQ("??", name); name = ib_capture_fullname(ib_tx, NULL, 0); ASSERT_STREQ(IB_TX_CAPTURE":0", name); name = ib_capture_fullname(ib_tx, NULL, 9); ASSERT_STREQ(IB_TX_CAPTURE":9", name); name = ib_capture_fullname(ib_tx, NULL, 10); ASSERT_STREQ(IB_TX_CAPTURE":??", name); name = ib_capture_fullname(ib_tx, CAP_NAME, 0); ASSERT_STREQ(CAP_NAME":0", name); name = ib_capture_fullname(ib_tx, CAP_NAME, 9); ASSERT_STREQ(CAP_NAME":9", name); name = ib_capture_fullname(ib_tx, CAP_NAME, 10); ASSERT_STREQ(CAP_NAME":??", name); } TEST_F(CaptureTest, basic) { ib_status_t rc; ib_field_t *ifield; ib_field_t *ofield; const ib_field_t *tfield; const ib_list_node_t *node; const ib_list_t *l; const ib_bytestr_t *bs; rc = CaptureGet(0, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_list_out(&l))); ASSERT_EQ(0U, ib_list_elements(l)); rc = CaptureBytestr(NULL, 0, "value0", &ifield); ASSERT_EQ(IB_OK, rc); rc = CaptureGet(0, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_LIST, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_list_out(&l))); ASSERT_EQ(1U, ib_list_elements(l)); node = ib_list_first_const(l); ASSERT_TRUE(node != NULL); tfield = (const ib_field_t *)node->data; ASSERT_EQ(IB_FTYPE_BYTESTR, tfield->type); ASSERT_EQ(IB_OK, ib_field_value(tfield, ib_ftype_bytestr_out(&bs))); ASSERT_EQ(6U, ib_bytestr_length(bs)); ASSERT_EQ(0, memcmp("value0", ib_bytestr_const_ptr(bs), 6)); /* */ rc = CaptureBytestr(NULL, 1, "xyzzy1", &ifield); ASSERT_EQ(IB_OK, rc); rc = CaptureGet(1, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_LIST, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_list_out(&l))); ASSERT_EQ(1U, ib_list_elements(l)); node = ib_list_first_const(l); ASSERT_TRUE(node != NULL); tfield = (const ib_field_t *)node->data; ASSERT_EQ(IB_FTYPE_BYTESTR, tfield->type); ASSERT_EQ(IB_OK, ib_field_value(tfield, ib_ftype_bytestr_out(&bs))); ASSERT_EQ(6U, ib_bytestr_length(bs)); ASSERT_EQ(0, memcmp("xyzzy1", ib_bytestr_const_ptr(bs), 6)); rc = CaptureGet(2, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_LIST, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_list_out(&l))); ASSERT_EQ(0U, ib_list_elements(l)); rc = ib_capture_clear(ib_tx, NULL); ASSERT_EQ(IB_OK, rc); rc = CaptureGet(0, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_LIST, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_list_out(&l))); ASSERT_EQ(0U, ib_list_elements(l)); rc = CaptureGet(1, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_LIST, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_list_out(&l))); ASSERT_EQ(0U, ib_list_elements(l)); rc = CaptureGet(1, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_LIST, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_list_out(&l))); ASSERT_EQ(0U, ib_list_elements(l)); } TEST_F(CaptureTest, named_collection) { ib_status_t rc; ib_field_t *ifield; ib_field_t *ofield; const ib_field_t *tfield; const ib_list_node_t *node; const ib_list_t *l; const ib_bytestr_t *bs; rc = CaptureBytestr(CAP_NAME, 0, "value0", &ifield); ASSERT_EQ(IB_OK, rc); rc = CaptureGet(CAP_NAME, 0, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_LIST, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_list_out(&l))); ASSERT_EQ(1U, ib_list_elements(l)); node = ib_list_first_const(l); ASSERT_TRUE(node != NULL); tfield = (const ib_field_t *)node->data; ASSERT_EQ(IB_FTYPE_BYTESTR, tfield->type); ASSERT_EQ(IB_OK, ib_field_value(tfield, ib_ftype_bytestr_out(&bs))); ASSERT_EQ(6U, ib_bytestr_length(bs)); ASSERT_EQ(0, memcmp("value0", ib_bytestr_const_ptr(bs), 6)); /* */ rc = CaptureBytestr(CAP_NAME, 1, "xyzzy1", &ifield); ASSERT_EQ(IB_OK, rc); rc = CaptureGet(CAP_NAME, 1, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_LIST, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_list_out(&l))); ASSERT_EQ(1U, ib_list_elements(l)); node = ib_list_first_const(l); ASSERT_TRUE(node != NULL); tfield = (const ib_field_t *)node->data; ASSERT_EQ(IB_FTYPE_BYTESTR, tfield->type); ASSERT_EQ(IB_OK, ib_field_value(tfield, ib_ftype_bytestr_out(&bs))); ASSERT_EQ(6U, ib_bytestr_length(bs)); ASSERT_EQ(0, memcmp("xyzzy1", ib_bytestr_const_ptr(bs), 6)); rc = CaptureGet(CAP_NAME, 2, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_LIST, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_list_out(&l))); ASSERT_EQ(0U, ib_list_elements(l)); rc = ib_capture_clear(ib_tx, CAP_NAME); ASSERT_EQ(IB_OK, rc); rc = CaptureGet(CAP_NAME, 0, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_LIST, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_list_out(&l))); ASSERT_EQ(0U, ib_list_elements(l)); rc = CaptureGet(CAP_NAME, 1, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_LIST, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_list_out(&l))); ASSERT_EQ(0U, ib_list_elements(l)); rc = CaptureGet(CAP_NAME, 1, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_LIST, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_list_out(&l))); ASSERT_EQ(0U, ib_list_elements(l)); } TEST_F(CaptureTest, collection_type) { ib_status_t rc; ib_field_t *ifield; ib_field_t *ofield; const ib_field_t *tfield; const ib_list_node_t *node; const ib_list_t *l; const ib_bytestr_t *bs; rc = ib_data_add_num(ib_tx->data, CAP_NAME, 666, &ifield); ASSERT_EQ(IB_OK, rc); rc = ib_data_get(ib_tx->data, CAP_NAME, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_NUM, ofield->type); rc = CaptureBytestr(CAP_NAME, 0, "value0", &ifield); ASSERT_EQ(IB_OK, rc); rc = CaptureGet(CAP_NAME, 0, &ofield); ASSERT_EQ(IB_OK, rc); ASSERT_EQ(IB_FTYPE_LIST, ofield->type); ASSERT_EQ(IB_OK, ib_field_value(ofield, ib_ftype_list_out(&l))); ASSERT_EQ(1U, ib_list_elements(l)); node = ib_list_first_const(l); ASSERT_TRUE(node != NULL); tfield = (const ib_field_t *)node->data; ASSERT_EQ(IB_FTYPE_BYTESTR, tfield->type); ASSERT_EQ(IB_OK, ib_field_value(tfield, ib_ftype_bytestr_out(&bs))); ASSERT_EQ(6U, ib_bytestr_length(bs)); ASSERT_EQ(0, memcmp("value0", ib_bytestr_const_ptr(bs), 6)); } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2008 - 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stefan Marr, Vrije Universiteit Brussel - Initial Implementation ******************************************************************************/ # include <gtest/gtest.h> # include "headers.h" # define ODSI OstDomainSelector_Indices TEST(OstDomain_CustomizationEncoding, domain_customizes_selectors_AT) { Oop encoding = Oop::from_int(54493200); // This is ATActor, only reqExec overridden // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, )); ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_Of_On__Mask )); ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_Of_On__Mask )); ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_Of_On__Mask )); ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_With_Of_On__Mask )); ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_With_With_Of_On__Mask )); ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_With_With_With_Of_On__Mask )); ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_With_With_With_With_Of_On__Mask )); // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_With_With_With_With_With_Of_On__Mask )); // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_With_With_With_With_With_With_Of_On__Mask )); // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_With_With_With_With_With_With_With_Of_On__Mask)); } <commit_msg>The OstDomain tests are done in the Image<commit_after>/****************************************************************************** * Copyright (c) 2008 - 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stefan Marr, Vrije Universiteit Brussel - Initial Implementation ******************************************************************************/ # include <gtest/gtest.h> # include "headers.h" # define ODSI OstDomainSelector_Indices // This test has been disabled and is done now on the image side instead. TEST(OstDomain_CustomizationEncoding, domain_customizes_selectors_AT) { // Oop encoding = Oop::from_int(54493200); // This is ATActor, only reqExec overridden // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, )); // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_Of_On__Mask )); // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_Of_On__Mask )); // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_Of_On__Mask )); // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_With_Of_On__Mask )); // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_With_With_Of_On__Mask )); // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_With_With_With_Of_On__Mask )); // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_With_With_With_With_Of_On__Mask )); // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_With_With_With_With_With_Of_On__Mask )); // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_With_With_With_With_With_With_Of_On__Mask )); // ASSERT_TRUE(OstDomain::domain_customizes_selectors(encoding, ODSI::RequestExecution_With_With_With_With_With_With_With_With_With_Of_On__Mask)); } <|endoftext|>
<commit_before>// // Created by Ivan Shynkarenka on 03.02.2017. // #include "catch.hpp" #include "server/nanomsg/publisher_server.h" #include "server/nanomsg/subscriber_client.h" #include "threads/thread.h" #include <atomic> #include <chrono> #include <memory> #include <vector> using namespace CppCommon; using namespace CppServer::Nanomsg; class TestSubscriberClient : public SubscriberClient { public: std::atomic<bool> connected; std::atomic<bool> disconnected; std::atomic<bool> error; explicit TestSubscriberClient(const std::string& address, const std::string& topic = "") : SubscriberClient(address, topic), connected(false), disconnected(false), error(false) { } protected: void onConnected() override { connected = true; } void onDisconnected() override { disconnected = true; } void onError(int error, const std::string& message) override { error = true; } }; class TestPublisherServer : public PublisherServer { public: std::atomic<bool> started; std::atomic<bool> stopped; std::atomic<bool> error; explicit TestPublisherServer(const std::string& address) : PublisherServer(address), started(false), stopped(false), error(false) { } protected: void onStarted() override { started = true; } void onStopped() override { stopped = true; } void onError(int error, const std::string& message) override { error = true; } }; TEST_CASE("Nanomsg subscriber client & publisher server", "[CppServer][Nanomsg]") { const std::string server_address = "tcp://*:6672"; const std::string client_address = "tcp://localhost:6672"; // Create and start Nanomsg publisher server auto server = std::make_shared<TestPublisherServer>(server_address); REQUIRE(server->Start()); while (!server->IsStarted()) Thread::Yield(); // Create and connect Nanomsg subscriber client auto client = std::make_shared<TestSubscriberClient>(client_address, "foo"); REQUIRE(client->Connect()); while (!client->IsConnected()) Thread::Yield(); while (client->socket().bytes_received() == 0) { // Publish messages to all subscribed clients server->Send("test"); server->Send("footest"); Thread::Yield(); } // Disconnect the client REQUIRE(client->Disconnect()); while (client->IsConnected()) Thread::Yield(); // Stop the server REQUIRE(server->Stop()); while (server->IsStarted()) Thread::Yield(); // Check the server state REQUIRE(server->started); REQUIRE(server->stopped); REQUIRE(server->socket().accepted_connections() == 1); REQUIRE(server->socket().messages_sent() > 0); REQUIRE(server->socket().bytes_sent() > 0); REQUIRE(!server->error); // Check the client state REQUIRE(client->connected); REQUIRE(client->disconnected); REQUIRE(client->socket().established_connections() == 1); REQUIRE(client->socket().messages_received() > 0); REQUIRE(client->socket().bytes_received() > 0); REQUIRE(!client->error); } TEST_CASE("Nanomsg publish/subscribe random test", "[CppServer][Nanomsg]") { const std::string server_address = "tcp://*:6673"; const std::string client_address = "tcp://localhost:6673"; // Create and start Nanomsg publisher server auto server = std::make_shared<TestPublisherServer>(server_address); REQUIRE(server->Start()); while (!server->IsStarted()) Thread::Yield(); // Test duration in seconds const int duration = 10; // Clients collection std::vector<std::shared_ptr<TestSubscriberClient>> clients; // Start random test auto start = std::chrono::high_resolution_clock::now(); while (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - start).count() < duration) { // Create a new client and connect if ((rand() % 100) == 0) { // Create and connect Nanomsg subscriber client auto client = std::make_shared<TestSubscriberClient>(client_address); client->Connect(); clients.emplace_back(client); } // Connect/Disconnect the random client else if ((rand() % 100) == 0) { if (!clients.empty()) { size_t index = rand() % clients.size(); auto client = clients.at(index); if (client->IsConnected()) client->Disconnect(); else client->Connect(); } } // Reconnect the random client else if ((rand() % 100) == 0) { if (!clients.empty()) { size_t index = rand() % clients.size(); auto client = clients.at(index); if (client->IsConnected()) client->Reconnect(); } } // Publish a message to all subscribed clients else if ((rand() % 1) == 0) { server->Send("test"); } // Sleep for a while... Thread::Sleep(1); } // Stop the server REQUIRE(server->Stop()); while (server->IsStarted()) Thread::Yield(); // Check the server state REQUIRE(server->started); REQUIRE(server->stopped); REQUIRE(server->socket().accepted_connections() > 0); REQUIRE(server->socket().messages_sent() > 0); REQUIRE(server->socket().bytes_sent() > 0); REQUIRE(!server->error); } <commit_msg>Fix tests<commit_after>// // Created by Ivan Shynkarenka on 03.02.2017. // #include "catch.hpp" #include "server/nanomsg/publisher_server.h" #include "server/nanomsg/subscriber_client.h" #include "threads/thread.h" #include <atomic> #include <chrono> #include <memory> #include <vector> using namespace CppCommon; using namespace CppServer::Nanomsg; class TestSubscriberClient : public SubscriberClient { public: std::atomic<bool> connected; std::atomic<bool> disconnected; std::atomic<bool> error; explicit TestSubscriberClient(const std::string& address, const std::string& topic = "") : SubscriberClient(address, topic), connected(false), disconnected(false), error(false) { } protected: void onConnected() override { connected = true; } void onDisconnected() override { disconnected = true; } void onError(int error, const std::string& message) override { error = true; } }; class TestPublisherServer : public PublisherServer { public: std::atomic<bool> started; std::atomic<bool> stopped; std::atomic<bool> error; explicit TestPublisherServer(const std::string& address) : PublisherServer(address), started(false), stopped(false), error(false) { } protected: void onStarted() override { started = true; } void onStopped() override { stopped = true; } void onError(int error, const std::string& message) override { error = true; } }; TEST_CASE("Nanomsg subscriber client & publisher server", "[CppServer][Nanomsg]") { const std::string server_address = "tcp://*:6672"; const std::string client_address = "tcp://localhost:6672"; // Create and start Nanomsg publisher server auto server = std::make_shared<TestPublisherServer>(server_address); REQUIRE(server->Start()); while (!server->IsStarted()) Thread::Yield(); // Create and connect Nanomsg subscriber client auto client = std::make_shared<TestSubscriberClient>(client_address, "foo"); REQUIRE(client->Connect()); while (!client->IsConnected()) Thread::Yield(); // Sleep for a while... Thread::Sleep(100); // Publish messages to all subscribed clients server->Send("test"); // Wait for all data processed... while (client->socket().bytes_received() != 4) Thread::Yield(); // Disconnect the client REQUIRE(client->Disconnect()); while (client->IsConnected()) Thread::Yield(); // Stop the server REQUIRE(server->Stop()); while (server->IsStarted()) Thread::Yield(); // Check the server state REQUIRE(server->started); REQUIRE(server->stopped); REQUIRE(server->socket().accepted_connections() == 1); REQUIRE(server->socket().messages_sent() == 1); REQUIRE(server->socket().bytes_sent() == 4); REQUIRE(!server->error); // Check the client state REQUIRE(client->connected); REQUIRE(client->disconnected); REQUIRE(client->socket().established_connections() == 1); REQUIRE(client->socket().messages_received() == 1); REQUIRE(client->socket().bytes_received() == 4); REQUIRE(!client->error); } TEST_CASE("Nanomsg publish/subscribe random test", "[CppServer][Nanomsg]") { const std::string server_address = "tcp://*:6673"; const std::string client_address = "tcp://localhost:6673"; // Create and start Nanomsg publisher server auto server = std::make_shared<TestPublisherServer>(server_address); REQUIRE(server->Start()); while (!server->IsStarted()) Thread::Yield(); // Test duration in seconds const int duration = 10; // Clients collection std::vector<std::shared_ptr<TestSubscriberClient>> clients; // Start random test auto start = std::chrono::high_resolution_clock::now(); while (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - start).count() < duration) { // Create a new client and connect if ((rand() % 100) == 0) { // Create and connect Nanomsg subscriber client auto client = std::make_shared<TestSubscriberClient>(client_address); client->Connect(); clients.emplace_back(client); } // Connect/Disconnect the random client else if ((rand() % 100) == 0) { if (!clients.empty()) { size_t index = rand() % clients.size(); auto client = clients.at(index); if (client->IsConnected()) client->Disconnect(); else client->Connect(); } } // Reconnect the random client else if ((rand() % 100) == 0) { if (!clients.empty()) { size_t index = rand() % clients.size(); auto client = clients.at(index); if (client->IsConnected()) client->Reconnect(); } } // Publish a message to all subscribed clients else if ((rand() % 1) == 0) { server->Send("test"); } // Sleep for a while... Thread::Sleep(1); } // Stop the server REQUIRE(server->Stop()); while (server->IsStarted()) Thread::Yield(); // Check the server state REQUIRE(server->started); REQUIRE(server->stopped); REQUIRE(server->socket().accepted_connections() > 0); REQUIRE(server->socket().messages_sent() > 0); REQUIRE(server->socket().bytes_sent() > 0); REQUIRE(!server->error); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: RowSetCacheIterator.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: oj $ $Date: 2002-11-13 06:56:59 $ * * 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 DBACCESS_ROWSETCACHEITERATOR_HXX #include "RowSetCacheIterator.hxx" #endif #ifndef DBACCESS_CORE_API_ROWSETCACHE_HXX #include "RowSetCache.hxx" #endif using namespace dbaccess; ORowSetCacheIterator::ORowSetCacheIterator(const ORowSetCacheIterator& _rRH) : m_pCache(_rRH.m_pCache) , m_aIter(_rRH.m_aIter) { } // ----------------------------------------------------------------------------- ORowSetCacheIterator::operator ORowSetMatrix::iterator() { if(m_aIter->second.aIterator == NULL || m_aIter->second.aIterator == m_pCache->m_pMatrix->end()) { // OSL_ENSURE(m_aIter->second.aBookmark.hasValue(),"bookmark has no value!"); // m_pCache->moveToBookmark(m_aIter->second.aBookmark); // m_aIter->second.aIterator = m_pCache->m_aMatrixIter; } return m_aIter->second.aIterator; } // ----------------------------------------------------------------------------- ORowSetCacheIterator& ORowSetCacheIterator::operator =(const ORowSetCacheIterator& _rRH) { if(this == &_rRH) return *this; m_pCache = _rRH.m_pCache; m_aIter = _rRH.m_aIter; return *this; } // ----------------------------------------------------------------------------- ORowSetCacheIterator& ORowSetCacheIterator::operator =(const ORowSetMatrix::iterator& _rIter) { m_aIter->second.aIterator = _rIter; return *this; } // ----------------------------------------------------------------------------- ORowSetRow& ORowSetCacheIterator::operator *() { return *m_aIter->second.aIterator; } // ----------------------------------------------------------------------------- const ORowSetRow& ORowSetCacheIterator::operator *() const { if(m_aIter->second.aIterator == NULL || m_aIter->second.aIterator == m_pCache->m_pMatrix->end()) { OSL_ENSURE(m_aIter->second.aBookmark.hasValue(),"bookmark has no value!"); m_pCache->moveToBookmark(m_aIter->second.aBookmark); m_aIter->second.aIterator = m_pCache->m_aMatrixIter; } return *m_aIter->second.aIterator; } // ----------------------------------------------------------------------------- ORowSetMatrix::iterator& ORowSetCacheIterator::operator ->() { return m_aIter->second.aIterator; } // ----------------------------------------------------------------------------- const ORowSetMatrix::iterator& ORowSetCacheIterator::operator ->() const { if(m_aIter->second.aIterator == NULL || m_aIter->second.aIterator == m_pCache->m_pMatrix->end()) { OSL_ENSURE(m_aIter->second.aBookmark.hasValue(),"bookmark has no value!"); m_pCache->moveToBookmark(m_aIter->second.aBookmark); m_aIter->second.aIterator = m_pCache->m_aMatrixIter; } return m_aIter->second.aIterator; } // ----------------------------------------------------------------------------- bool ORowSetCacheIterator::operator <=(const ORowSetMatrix::iterator& _rRH) const { return m_aIter->second.aIterator <= _rRH; } // ----------------------------------------------------------------------------- bool ORowSetCacheIterator::operator !=(const ORowSetMatrix::iterator& _rRH) const { return m_aIter->second.aIterator != _rRH; } // ----------------------------------------------------------------------------- bool ORowSetCacheIterator::operator ==(const ORowSetMatrix::iterator& _rRH) const { return m_aIter->second.aIterator == _rRH; } // ----------------------------------------------------------------------------- void ORowSetCacheIterator::setBookmark(const ::com::sun::star::uno::Any& _rBookmark) { m_aIter->second.aBookmark = _rBookmark; } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS hr18 (1.7.462); FILE MERGED 2005/08/10 16:45:22 hr 1.7.462.1: #i51878#,#i53108#: cleanup STL iterator usage<commit_after>/************************************************************************* * * $RCSfile: RowSetCacheIterator.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-05 08:58:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the License); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef DBACCESS_ROWSETCACHEITERATOR_HXX #include "RowSetCacheIterator.hxx" #endif #ifndef DBACCESS_CORE_API_ROWSETCACHE_HXX #include "RowSetCache.hxx" #endif using namespace dbaccess; ORowSetCacheIterator::ORowSetCacheIterator(const ORowSetCacheIterator& _rRH) : m_pCache(_rRH.m_pCache) , m_aIter(_rRH.m_aIter) { } // ----------------------------------------------------------------------------- ORowSetCacheIterator::operator ORowSetMatrix::iterator() { if ( m_aIter->second.aIterator == m_pCache->m_pMatrix->end() ) { // OSL_ENSURE(m_aIter->second.aBookmark.hasValue(),"bookmark has no value!"); // m_pCache->moveToBookmark(m_aIter->second.aBookmark); // m_aIter->second.aIterator = m_pCache->m_aMatrixIter; } return m_aIter->second.aIterator; } // ----------------------------------------------------------------------------- ORowSetCacheIterator& ORowSetCacheIterator::operator =(const ORowSetCacheIterator& _rRH) { if(this == &_rRH) return *this; m_pCache = _rRH.m_pCache; m_aIter = _rRH.m_aIter; return *this; } // ----------------------------------------------------------------------------- ORowSetCacheIterator& ORowSetCacheIterator::operator =(const ORowSetMatrix::iterator& _rIter) { m_aIter->second.aIterator = _rIter; return *this; } // ----------------------------------------------------------------------------- ORowSetRow& ORowSetCacheIterator::operator *() { return *m_aIter->second.aIterator; } // ----------------------------------------------------------------------------- const ORowSetRow& ORowSetCacheIterator::operator *() const { if ( m_aIter->second.aIterator == m_pCache->m_pMatrix->end() ) { OSL_ENSURE(m_aIter->second.aBookmark.hasValue(),"bookmark has no value!"); m_pCache->moveToBookmark(m_aIter->second.aBookmark); m_aIter->second.aIterator = m_pCache->m_aMatrixIter; } return *m_aIter->second.aIterator; } // ----------------------------------------------------------------------------- ORowSetMatrix::iterator& ORowSetCacheIterator::operator ->() { return m_aIter->second.aIterator; } // ----------------------------------------------------------------------------- const ORowSetMatrix::iterator& ORowSetCacheIterator::operator ->() const { if ( m_aIter->second.aIterator == m_pCache->m_pMatrix->end() ) { OSL_ENSURE(m_aIter->second.aBookmark.hasValue(),"bookmark has no value!"); m_pCache->moveToBookmark(m_aIter->second.aBookmark); m_aIter->second.aIterator = m_pCache->m_aMatrixIter; } return m_aIter->second.aIterator; } // ----------------------------------------------------------------------------- bool ORowSetCacheIterator::operator <=(const ORowSetMatrix::iterator& _rRH) const { return m_aIter->second.aIterator <= _rRH; } // ----------------------------------------------------------------------------- bool ORowSetCacheIterator::operator !=(const ORowSetMatrix::iterator& _rRH) const { return m_aIter->second.aIterator != _rRH; } // ----------------------------------------------------------------------------- bool ORowSetCacheIterator::operator ==(const ORowSetMatrix::iterator& _rRH) const { return m_aIter->second.aIterator == _rRH; } // ----------------------------------------------------------------------------- void ORowSetCacheIterator::setBookmark(const ::com::sun::star::uno::Any& _rBookmark) { m_aIter->second.aBookmark = _rBookmark; } // ----------------------------------------------------------------------------- sal_Bool ORowSetCacheIterator::isNull() const { return !m_pCache || m_aIter == m_pCache->m_aCacheIterators.end() || m_aIter->second.aIterator == m_pCache->m_pMatrix->end(); } <|endoftext|>
<commit_before> #include "zipios++/zipios-config.h" #include "zipios++/meta-iostreams.h" #include <vector> #include "zipios++/simplesmartptr.h" using namespace zipios ; using std::cerr ; using std::cout ; using std::endl ; using std::auto_ptr ; using std::ofstream ; using std::vector ; class Bogus { protected: friend SimpleSmartPointer< Bogus > ; friend SimpleSmartPointer< const Bogus > ; void ref() const { _refcount.ref() ; } unsigned int unref() const { return _refcount.unref() ; } ReferenceCount< Bogus > _refcount ; }; typedef SimpleSmartPointer< Bogus > SPBogus ; int main() { Bogus *p = new Bogus ; SPBogus sp1( p ) ; SPBogus sp2 ; sp2 = sp1 ; SPBogus sp3 ; sp3 = p ; cerr << " p = " << p << endl ; cerr << " sp1.get() = " << sp1.get() << endl ; cerr << " sp2.get() = " << sp2.get() << endl ; cerr << " sp3.get() = " << sp3.get() << endl ; vector< int > vec( 3 ) ; vec[ 0 ] = 1 ; vec[ 1 ] = 2 ; vec[ 2 ] = 3 ; std::vector< int >::iterator it ; for( it = vec.begin() ; it != vec.end() ; ++it ) cerr << *it << endl ; } /** \file \anchor test_zip_anchor Source code to a small program that tests the functionality of Zipios++. */ /* Zipios++ - a small C++ library that provides easy access to .zip files. Copyright (C) 2000 Thomas Sndergaard This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ <commit_msg>*** empty log message ***<commit_after> #include "zipios++/zipios-config.h" #include "zipios++/meta-iostreams.h" #include <vector> #include "zipios++/simplesmartptr.h" using namespace zipios ; using std::cerr ; using std::cout ; using std::endl ; using std::auto_ptr ; using std::ofstream ; using std::vector ; class Bogus { protected: friend SimpleSmartPointer< Bogus > ; friend SimpleSmartPointer< const Bogus > ; void ref() const { _refcount.ref() ; } unsigned int unref() const { return _refcount.unref() ; } ReferenceCount< Bogus > _refcount ; }; typedef SimpleSmartPointer< Bogus > SPBogus ; int main() { Bogus *p = new Bogus ; SPBogus sp1( p ) ; SPBogus sp2 ; sp2 = sp1 ; SPBogus sp3 ; sp3 = p ; cerr << " p = " << p << endl ; cerr << " sp1.get() = " << sp1.get() << endl ; cerr << " sp2.get() = " << sp2.get() << endl ; cerr << " sp3.get() = " << sp3.get() << endl ; } /** \file \anchor test_zip_anchor Source code to a small program that tests the functionality of Zipios++. */ /* Zipios++ - a small C++ library that provides easy access to .zip files. Copyright (C) 2000 Thomas Sndergaard This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ <|endoftext|>
<commit_before>#include "cardcreator_app.h" #include <set> #include <sdl.h> #include <utils/filesystem/filesystem.h> #include <game_utils/tween/tween_utils.h> #include "component_framework/EntityManager.h" #include "component_framework/EventManager.h" #include "component_framework/gcomponents.h" #include "component_framework/SystemManager.h" #include "component_framework/ComponentUpdator.h" #include "misc_utils/debug_layer.h" #include "misc_utils/config_ui.h" #include "misc_utils/simple_profiler.h" #include <utils/imagetoarray/imagetoarray.h> #include "global_data.h" //--------------------------------------------------------------------------------------- template< class T > inline void SWAP_RED_AND_BLUE( T& color ) { T red = 0; T blue = 0; red = 0x00ff0000 & color; blue = 0x000000ff & color; red = red >> 16; blue = blue << 16; color = ( color & 0xff00ff00 ) | red | blue; } struct Page { Page() { card_count = 0; types::ivector2 pagesize( 2480, 3508 ); data.Resize( pagesize.x, pagesize.y ); data.SetEverythingTo( 0xFFFFFFFF ); size.Set( 707, 1005 ); border_buffer.Set( 2, 2 ); types::ivector2 start_pos = ( pagesize - 3 * ( size + border_buffer ) ) * 0.5f; types::ivector2 pos = start_pos; for( int y = 0; y < 3; ++y ) { for( int x = 0; x < 3; ++x ) { points.push_back( pos ); pos.x += size.x + border_buffer.x; } pos.x = start_pos.x; pos.y += size.y + border_buffer.y; } } void Clear() { card_count = 0; data.SetEverythingTo( 0xFFFFFFFF ); } ceng::CArray2D< Uint32 > data; int card_count; std::vector< types::ivector2 > points; types::ivector2 size; types::ivector2 border_buffer; void AddCardToPage( const ceng::CArray2D< Uint32 >& image ) { types::ivector2 image_pos = ( types::ivector2( image.GetWidth(), image.GetHeight() ) - size ) * 0.5f; types::ivector2 page_pos = points[ card_count ]; for( int y = 0; y < size.y + border_buffer.y; ++y ) { for( int x = 0; x < size.x + border_buffer.x; ++x ) { if( x < size.x && y < size.y ) { data.At( x + page_pos.x, y + page_pos.y ) = image.At( x + image_pos.x, y + image_pos.y ); SWAP_RED_AND_BLUE( data.At( x + page_pos.x, y + page_pos.y ) ); } else { data.At( x + page_pos.x, y + page_pos.y ) = 0xFFe8e8e8; } } } card_count++; } bool IsFull() { if( card_count >= 9 ) return true; else return false; } }; void LoadCSVFile( const std::string& csv_file, std::vector< std::map< std::string, std::string > >& result ); void ParseCards( const std::string& filename ) { std::vector< std::map< std::string, std::string > > values; LoadCSVFile( filename, values ); // void LoadImage( const std::string& filename, ceng::CArray2D< poro::types::Uint32 >& out_array2d, bool include_alpha ); Page p; int pagec = 0; for( std::size_t i = 0; i < values.size(); ++i ) { int count = ceng::CastFromString< int >(values[i]["count"]); std::string filename = values[i]["filename"]; if( filename.empty() ) continue; ceng::CArray2D< poro::types::Uint32 > image; LoadImage( filename, image, true ); for( int j = 0; j < count; ++j ) { p.AddCardToPage( image ); if( p.IsFull() ) { SaveImage( "output/test_case_" + ceng::CastToString( pagec ) + ".png", p.data ); pagec++; p.Clear(); } } } // last case SaveImage( "output/test_case_" + ceng::CastToString( pagec ) + ".png", p.data ); pagec++; p.Clear(); } //--------------------------------------------------------------------------------------- #define CONFIG_MARCHING_HOLES(list_) \ list_(bool, display_libtess2, true, NULL ) \ list_(bool, display_poly2tri, false, NULL ) \ list_(float, camera_zoom, 6.0f, MetaData( 1.f, 20.f ) ) \ list_(int, stat_fps_count, 0, NULL ) \ DEFINE_CONFIG_UI( ConfigMarchingHoles, CONFIG_MARCHING_HOLES ) namespace { ConfigMarchingHoles g_config; types::vector2 camera_offset( -114, 14 ); } // ---------------------------------------------------------------------------- CardCreatorApp::CardCreatorApp() { } //----------------------------------------------------------------------------- void LoadCSVFile( const std::string& csv_file, std::vector< std::map< std::string, std::string > >& result ) { std::vector< std::string > input; ceng::ReadFileToVector( csv_file, input ); if( input.empty() ) return; std::vector< std::string > labels = ceng::StringSplit( ",", input[0] ); result.resize( input.size() - 1 ); for( std::size_t i = 1; i < input.size(); ++i ) { std::vector< std::string > data = ceng::StringSplit( ",", input[i] ); for( std::size_t j = 0; j < data.size(); ++j ) { result[ i - 1 ][ labels[j] ] = data[j]; } } } //----------------------------------------------------------------------------- void CardCreatorApp::Init() { DefaultApplication::Init(); Poro()->GetGraphics()->SetFillColor( poro::GetFColor( 0.15f, 0.15f, 0.15f, 1.f ) ); ParseCards( "cards/list_of_files.txt" ); // test // LoadCSVFile( "data/nomoremeat.csv" ); // --- components ---- GComponents::Init(); SGF::EventManager* mEventManager = GComponents::eventManager; SGF::EntityManager* mEntityManager = GComponents::entityManager; // -- debug stuff --- mDebugLayer.reset( new DebugLayer ); mDebugLayer->SetManagers( mEventManager, mEntityManager ); // ----- sprite containers ---- mSpriteContainer = new as::Sprite; mCardContainer = new as::Sprite; mOverlay = new as::Sprite; // -- create card crafting --- mSpriteContainer->addChild( mCardContainer ); mSpriteContainer->addChild( mOverlay ); mSpriteContainer->SetScale( 1.0f, 1.0f ); // -- overlay sprite as::Sprite* overlay = as::LoadSprite( "data/templates/poker_overlay.png" ); mOverlay->addChild( overlay ); as::Sprite* new_card = new as::Sprite; mCardContainer->addChild( new_card ); GD.mSprite = new_card; } // ---------------------------------------------------------------------------- void CardCreatorApp::Update( float dt ) { UpdateGTweens( dt ); if( mDebugLayer.get() ) mDebugLayer->Update( dt ); if( Poro()->GetKeyboard()->IsKeyDown( SDLK_LEFT ) ) camera_offset.x++; if( Poro()->GetKeyboard()->IsKeyDown( SDLK_RIGHT ) ) camera_offset.x--; if( Poro()->GetKeyboard()->IsKeyDown( SDLK_UP ) ) camera_offset.y++; if( Poro()->GetKeyboard()->IsKeyDown( SDLK_DOWN ) ) camera_offset.y--; if( mSpriteContainer ) mSpriteContainer->Update( dt ); SGF::SystemManager::GetSingletonPtr()->Process( dt ); } // ---------------------------------------------------------------------------- void CardCreatorApp::Draw( poro::IGraphics* graphics ) { if( mDebugLayer.get() ) mDebugLayer->Draw( graphics ); if( mSpriteContainer ) as::DrawSprite( mSpriteContainer, graphics ); } // ---------------------------------------------------------------------------- types::vector2 TransformMouseForSprite( as::Sprite* sprite, const types::vector2& mouse_pos ) { using namespace as; std::vector< const DisplayObjectContainer* > parents; sprite->getParentTree( parents ); as::types::xform xform; for( int i = (int)parents.size() - 1; i > 0; --i ) { cassert( parents[ i ] ); const Sprite* parent = dynamic_cast< const Sprite* >( parents[ i ] ); if( parent ) xform = ceng::math::Mul( xform, parent->GetXForm() ); } // xform = ceng::math::Mul( xform, this->GetXForm() ); return ceng::math::MulT( xform, mouse_pos ); } void CardCreatorApp::MouseMove(const poro::types::vec2& p) { } void CardCreatorApp::MouseButtonDown(const poro::types::vec2& p, int button) { if( button == poro::Mouse::MOUSE_BUTTON_LEFT ) { types::vector2 mouse_pos = TransformMouseForSprite( mCardContainer, types::vector2( p ) ); std::vector< as::Sprite* > sprites = mCardContainer->FindSpritesAtPoint( mouse_pos ); std::cout << "sprites.size()" << sprites.size() << std::endl; /*SGF::Entity* e = mEntityManager->GetClosestEntity(types::vector2( p )); if ( e != NULL ) mDebugLayer->SetEntity(e); */ } } void CardCreatorApp::MouseButtonUp(const poro::types::vec2& pos, int button) { } //============================================================================= void CardCreatorApp::OnKeyDown( int key, poro::types::charset unicode ) { if( key == SDLK_0 ) mOverlay->SetAlpha( 0.f ); else if( key >= SDLK_1 && key <= SDLK_9 ) { float value = ( ( key - SDLK_1 ) + 1 ) / 10.f; mOverlay->SetAlpha( value ); } if( key == SDLK_SPACE ) DoAllTheCards(); // SaveTheCard( "output/test_card.png" ); } void CardCreatorApp::OnKeyUp( int key, poro::types::charset unicode ) { } //============================================================================= void CardCreatorApp::DoAllTheCards() { std::vector< std::map< std::string, std::string > > data_set; LoadCSVFile( "data/nomoremeat.csv", data_set ); GD.isCrafting = false; for( std::size_t i = 0; i < data_set.size(); ++i ) { std::map< std::string, std::string >::iterator j; for( j = data_set[i].begin(); j != data_set[i].end(); ++j ) { GD.SetData( j->first, j->second ); } // --- card data has been set // disable overlay, set color to white mOverlay->SetVisibility( 0 ); mOverlay->SetAlpha( 0 ); Poro()->GetGraphics()->SetFillColor( poro::GetFColor( 1, 1, 1, 1 ) ); UpdateStep(); // --- save the card std::string name = data_set[i]["name"]; if( name.empty() ) name = ceng::CastToString( i ); SaveTheCard( "output/" + name + ".png" ); // put the count and the name into something // --- } GD.isCrafting = true; Poro()->GetGraphics()->SetFillColor( poro::GetFColor( 0.15f, 0.15f, 0.15f, 1.f ) ); } void CardCreatorApp::SaveTheCard( const std::string& filename ) { Poro()->GetGraphics()->SaveScreenshot( filename, 0, 0, 825, 1125 ); } //============================================================================= void CardCreatorApp::UpdateStep() { for( int i = 0; i < 2; ++i ) { float dt = 1.f / 60.f; SetComponentRefresh( true ); SGF::SystemManager::GetSingletonPtr()->Process( dt ); Poro()->GetApplication()->Update( dt ); Poro()->GetGraphics()->BeginRendering(); Poro()->GetApplication()->Draw(Poro()->GetGraphics()); Poro()->GetGraphics()->EndRendering(); } } //============================================================================= <commit_msg>Page::Init(...) takes pixel_size and card_count_y as parameters<commit_after>#include "cardcreator_app.h" #include <set> #include <sdl.h> #include <utils/filesystem/filesystem.h> #include <game_utils/tween/tween_utils.h> #include "component_framework/EntityManager.h" #include "component_framework/EventManager.h" #include "component_framework/gcomponents.h" #include "component_framework/SystemManager.h" #include "component_framework/ComponentUpdator.h" #include "misc_utils/debug_layer.h" #include "misc_utils/config_ui.h" #include "misc_utils/simple_profiler.h" #include <utils/imagetoarray/imagetoarray.h> #include "global_data.h" //--------------------------------------------------------------------------------------- template< class T > inline void SWAP_RED_AND_BLUE( T& color ) { T red = 0; T blue = 0; red = 0x00ff0000 & color; blue = 0x000000ff & color; red = red >> 16; blue = blue << 16; color = ( color & 0xff00ff00 ) | red | blue; } struct Page { Page() { } void Init( int pixel_size_x, int pixel_size_y, int card_count_x, int card_count_y ) { card_count = 0; types::ivector2 pagesize( 2480, 3508 ); data.Resize( pagesize.x, pagesize.y ); data.SetEverythingTo( 0xFFFFFFFF ); size.Set( pixel_size_x, pixel_size_y ); border_buffer.Set( 2, 2 ); types::ivector2 start_pos =( pagesize - types::ivector2( card_count_x * ( size.x + border_buffer.x ), card_count_y * ( size.y + border_buffer.y ) ) ); start_pos.x *= 0.5f; start_pos.y *= 0.5f; types::ivector2 pos = start_pos; for( int y = 0; y < card_count_y; ++y ) { for( int x = 0; x < card_count_x; ++x ) { points.push_back( pos ); pos.x += size.x + border_buffer.x; } pos.x = start_pos.x; pos.y += size.y + border_buffer.y; } } void Clear() { card_count = 0; data.SetEverythingTo( 0xFFFFFFFF ); } ceng::CArray2D< Uint32 > data; int card_count; std::vector< types::ivector2 > points; types::ivector2 size; types::ivector2 border_buffer; void AddCardToPage( const ceng::CArray2D< Uint32 >& image ) { types::ivector2 image_pos = ( types::ivector2( image.GetWidth(), image.GetHeight() ) - size ) * 0.5f; types::ivector2 page_pos = points[ card_count ]; for( int y = 0; y < size.y + border_buffer.y; ++y ) { for( int x = 0; x < size.x + border_buffer.x; ++x ) { if( x < size.x && y < size.y ) { data.At( x + page_pos.x, y + page_pos.y ) = image.At( x + image_pos.x, y + image_pos.y ); SWAP_RED_AND_BLUE( data.At( x + page_pos.x, y + page_pos.y ) ); } else { data.At( x + page_pos.x, y + page_pos.y ) = 0xFFe8e8e8; } } } card_count++; } bool IsFull() { if( card_count >= (int)points.size() ) return true; else return false; } }; void LoadCSVFile( const std::string& csv_file, std::vector< std::map< std::string, std::string > >& result ); void ParseCards( const std::string& filename, const std::string& output_filename, const types::ivector2& pixel_size, const types::ivector2& card_page_count ) { std::vector< std::map< std::string, std::string > > values; LoadCSVFile( filename, values ); // void LoadImage( const std::string& filename, ceng::CArray2D< poro::types::Uint32 >& out_array2d, bool include_alpha ); Page p; p.Init( pixel_size.x, pixel_size.y, card_page_count.x, card_page_count.y ); int pagec = 0; for( std::size_t i = 0; i < values.size(); ++i ) { int count = ceng::CastFromString< int >(values[i]["count"]); std::string filename = values[i]["filename"]; if( filename.empty() ) continue; ceng::CArray2D< poro::types::Uint32 > image; LoadImage( filename, image, true ); for( int j = 0; j < count; ++j ) { p.AddCardToPage( image ); if( p.IsFull() ) { SaveImage( output_filename + ceng::CastToString( pagec ) + ".png", p.data ); pagec++; p.Clear(); } } } // last case SaveImage( output_filename + ceng::CastToString( pagec ) + ".png", p.data ); pagec++; p.Clear(); } //--------------------------------------------------------------------------------------- #define CONFIG_MARCHING_HOLES(list_) \ list_(bool, display_libtess2, true, NULL ) \ list_(bool, display_poly2tri, false, NULL ) \ list_(float, camera_zoom, 6.0f, MetaData( 1.f, 20.f ) ) \ list_(int, stat_fps_count, 0, NULL ) \ DEFINE_CONFIG_UI( ConfigMarchingHoles, CONFIG_MARCHING_HOLES ) namespace { ConfigMarchingHoles g_config; types::vector2 camera_offset( -114, 14 ); } // ---------------------------------------------------------------------------- CardCreatorApp::CardCreatorApp() { } //----------------------------------------------------------------------------- void LoadCSVFile( const std::string& csv_file, std::vector< std::map< std::string, std::string > >& result ) { std::vector< std::string > input; ceng::ReadFileToVector( csv_file, input ); if( input.empty() ) return; std::vector< std::string > labels = ceng::StringSplit( ",", input[0] ); result.resize( input.size() - 1 ); for( std::size_t i = 1; i < input.size(); ++i ) { std::vector< std::string > data = ceng::StringSplit( ",", input[i] ); for( std::size_t j = 0; j < data.size(); ++j ) { result[ i - 1 ][ labels[j] ] = data[j]; } } } //----------------------------------------------------------------------------- void CardCreatorApp::Init() { DefaultApplication::Init(); Poro()->GetGraphics()->SetFillColor( poro::GetFColor( 0.15f, 0.15f, 0.15f, 1.f ) ); // 550, 550 -> 4.6 cm // 590, 590 -> 5.0 cm ParseCards( "list_of_icons.txt", "output/icons_", types::ivector2( 220, 220 ), types::ivector2( 10, 14 ) ); // ParseCards( "transwormers_heads.txt", "output/transwormers_heads", types::ivector2( 590, 590 ), types::ivector2( 3, 5 ) ); // ParseCards( "transwormers_tiles.txt", "output/transwormers_tiles", types::ivector2( 550, 550 ), types::ivector2( 4, 6 ) ); // ParseCards( "space_cards.txt", "output/space_cards_", types::ivector2( 550, 550 ), types::ivector2( 4, 6 ) ); ParseCards( "empty_cards.txt", "output/empty_sheet_", types::ivector2( 709, 1007 ), types::ivector2( 3, 3 ) ); // ParseCards( "action_cards.txt", "output/action_cards_", types::ivector2( 550, 550 ), types::ivector2( 4, 6 ) ); // ParseCards( "cards/list_of_files.txt" ); Poro()->Exit(); return; // test // LoadCSVFile( "data/nomoremeat.csv" ); // --- components ---- GComponents::Init(); SGF::EventManager* mEventManager = GComponents::eventManager; SGF::EntityManager* mEntityManager = GComponents::entityManager; // -- debug stuff --- mDebugLayer.reset( new DebugLayer ); mDebugLayer->SetManagers( mEventManager, mEntityManager ); // ----- sprite containers ---- mSpriteContainer = new as::Sprite; mCardContainer = new as::Sprite; mOverlay = new as::Sprite; // -- create card crafting --- mSpriteContainer->addChild( mCardContainer ); mSpriteContainer->addChild( mOverlay ); mSpriteContainer->SetScale( 1.0f, 1.0f ); // -- overlay sprite as::Sprite* overlay = as::LoadSprite( "data/templates/poker_overlay.png" ); mOverlay->addChild( overlay ); as::Sprite* new_card = new as::Sprite; mCardContainer->addChild( new_card ); GD.mSprite = new_card; } // ---------------------------------------------------------------------------- void CardCreatorApp::Update( float dt ) { UpdateGTweens( dt ); if( mDebugLayer.get() ) mDebugLayer->Update( dt ); if( Poro()->GetKeyboard()->IsKeyDown( SDLK_LEFT ) ) camera_offset.x++; if( Poro()->GetKeyboard()->IsKeyDown( SDLK_RIGHT ) ) camera_offset.x--; if( Poro()->GetKeyboard()->IsKeyDown( SDLK_UP ) ) camera_offset.y++; if( Poro()->GetKeyboard()->IsKeyDown( SDLK_DOWN ) ) camera_offset.y--; if( mSpriteContainer ) mSpriteContainer->Update( dt ); SGF::SystemManager::GetSingletonPtr()->Process( dt ); } // ---------------------------------------------------------------------------- void CardCreatorApp::Draw( poro::IGraphics* graphics ) { if( mDebugLayer.get() ) mDebugLayer->Draw( graphics ); if( mSpriteContainer ) as::DrawSprite( mSpriteContainer, graphics ); } // ---------------------------------------------------------------------------- types::vector2 TransformMouseForSprite( as::Sprite* sprite, const types::vector2& mouse_pos ) { using namespace as; std::vector< const DisplayObjectContainer* > parents; sprite->getParentTree( parents ); as::types::xform xform; for( int i = (int)parents.size() - 1; i > 0; --i ) { cassert( parents[ i ] ); const Sprite* parent = dynamic_cast< const Sprite* >( parents[ i ] ); if( parent ) xform = ceng::math::Mul( xform, parent->GetXForm() ); } // xform = ceng::math::Mul( xform, this->GetXForm() ); return ceng::math::MulT( xform, mouse_pos ); } void CardCreatorApp::MouseMove(const poro::types::vec2& p) { } void CardCreatorApp::MouseButtonDown(const poro::types::vec2& p, int button) { if( button == poro::Mouse::MOUSE_BUTTON_LEFT ) { types::vector2 mouse_pos = TransformMouseForSprite( mCardContainer, types::vector2( p ) ); std::vector< as::Sprite* > sprites = mCardContainer->FindSpritesAtPoint( mouse_pos ); std::cout << "sprites.size()" << sprites.size() << std::endl; /*SGF::Entity* e = mEntityManager->GetClosestEntity(types::vector2( p )); if ( e != NULL ) mDebugLayer->SetEntity(e); */ } } void CardCreatorApp::MouseButtonUp(const poro::types::vec2& pos, int button) { } //============================================================================= void CardCreatorApp::OnKeyDown( int key, poro::types::charset unicode ) { if( key == SDLK_0 ) mOverlay->SetAlpha( 0.f ); else if( key >= SDLK_1 && key <= SDLK_9 ) { float value = ( ( key - SDLK_1 ) + 1 ) / 10.f; mOverlay->SetAlpha( value ); } if( key == SDLK_SPACE ) DoAllTheCards(); // SaveTheCard( "output/test_card.png" ); } void CardCreatorApp::OnKeyUp( int key, poro::types::charset unicode ) { } //============================================================================= void CardCreatorApp::DoAllTheCards() { std::vector< std::map< std::string, std::string > > data_set; LoadCSVFile( "data/nomoremeat.csv", data_set ); GD.isCrafting = false; for( std::size_t i = 0; i < data_set.size(); ++i ) { std::map< std::string, std::string >::iterator j; for( j = data_set[i].begin(); j != data_set[i].end(); ++j ) { GD.SetData( j->first, j->second ); } // --- card data has been set // disable overlay, set color to white mOverlay->SetVisibility( 0 ); mOverlay->SetAlpha( 0 ); Poro()->GetGraphics()->SetFillColor( poro::GetFColor( 1, 1, 1, 1 ) ); UpdateStep(); // --- save the card std::string name = data_set[i]["name"]; if( name.empty() ) name = ceng::CastToString( i ); SaveTheCard( "output/" + name + ".png" ); // put the count and the name into something // --- } GD.isCrafting = true; Poro()->GetGraphics()->SetFillColor( poro::GetFColor( 0.15f, 0.15f, 0.15f, 1.f ) ); } void CardCreatorApp::SaveTheCard( const std::string& filename ) { Poro()->GetGraphics()->SaveScreenshot( filename, 0, 0, 825, 1125 ); } //============================================================================= void CardCreatorApp::UpdateStep() { for( int i = 0; i < 2; ++i ) { float dt = 1.f / 60.f; SetComponentRefresh( true ); SGF::SystemManager::GetSingletonPtr()->Process( dt ); Poro()->GetApplication()->Update( dt ); Poro()->GetGraphics()->BeginRendering(); Poro()->GetApplication()->Draw(Poro()->GetGraphics()); Poro()->GetGraphics()->EndRendering(); } } //============================================================================= <|endoftext|>
<commit_before>/*- * Copyright (c) 2008 Michael Marner <michael@20papercups.net> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 system headers #include <stdlib.h> #include <string.h> #include <iostream> #include <fstream> #include <sstream> // include openGL headers #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <wcl/Exception.h> #include <wcl/camera/VirtualCamera.h> #include <wcl/camera/CameraFactory.h> using namespace std; using namespace wcl; Camera *cam; unsigned char* data; void usage() { printf("Usage: camera type [devicenode]\n" "\n" "eg: camera 1 /dev/video0\n" "\n" "Where type is:\n" " 1. UVC/Firewire\n" " 2. Virtual Camera\n" ); } /** * Initialise OpenGL */ GLvoid init() { glShadeModel(GL_SMOOTH); glClearColor(0,0,0,0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); data = new unsigned char[cam->getFormatBufferSize(Camera::RGB8)]; // create a texture for the image... glTexImage2D(GL_TEXTURE_2D, //target 0, //level of detail 3, //colour components cam->getActiveConfiguration().width, //width cam->getActiveConfiguration().height, //height 0, //border GL_RGB, //image format GL_UNSIGNED_BYTE, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); gluOrtho2D(0,1,0,1); glMatrixMode(GL_MODELVIEW); } /** * Constantly fetch a new image from the camera to display */ GLvoid idle() { glutPostRedisplay(); } /** * Display Loop. */ GLvoid display() { glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); const unsigned char* frame = cam->getFrame(Camera::RGB8); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cam->getActiveConfiguration().width, cam->getActiveConfiguration().height, GL_RGB, GL_UNSIGNED_BYTE, frame); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor3f(1,0,0); glBegin(GL_QUADS); glTexCoord2f(0,1); glVertex2f(0,0); glTexCoord2f(1,1); glVertex2f(1,0); glTexCoord2f(1,0); glVertex2f(1,1); glTexCoord2f(0,0); glVertex2f(0,1); glEnd(); glFlush(); glutSwapBuffers(); // print out any opengl errors to the console GLenum error = glGetError(); if (error != GL_NO_ERROR) { cout << gluErrorString(error) << endl; } } /** * This doesn't do what it is supposed to do! */ GLvoid reshape(int width, int height) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,1,0,1); glMatrixMode(GL_MODELVIEW); glViewport(0,0, (GLsizei)width, (GLsizei)height); } void keyboard(unsigned char key, int w, int h) { if(key==27) exit(EXIT_SUCCESS); } int main(int argc, char** argv) { if(argc < 2 ){ usage(); return 1; } try { // Display info about all cameras CameraFactory::printDetails(false); std::vector<Camera *> cameras = CameraFactory::getCameras(); if( cameras.size() == 0 ){ return 0; } cout << "Opening Camera... "; // Open the camera switch( atoi(argv[1])){ case 1: { if( argc < 3 ){ cout << "Using Camera factory" << endl; cam = CameraFactory::getCamera(); } else { cout << argv[2] <<endl; cam = CameraFactory::getCamera(argv[2]); } if (cam == NULL ){ std::cout << "No usable cameras found" << std::endl; exit(0); } } break; case 2: //Virtual Camera cam = new VirtualCamera(); break; default: usage(); return 1; } cout << "Done!" << endl; /* * Print out camera details */ cam->printDetails(); Camera::Configuration c; c.width = 640; cam->setConfiguration(cam->findConfiguration(c)); //set power frequency compensation to 50 Hz cam->setControlValue(Camera::POWER_FREQUENCY, 1); //cout << "about to grab frame, length is: " << cam.getBufferSize() << endl; // Create GLUT window glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(cam->getActiveConfiguration().width, cam->getActiveConfiguration().height); glutCreateWindow(argv[0]); init(); // register callbacks glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutIdleFunc(idle); // GO! glutMainLoop(); cout << "Deleting Cam" << endl; cam->shutdown(); delete cam; } catch (Exception &e) { cout << "Exception Occured: " << e.what() << endl; } return 0; } <commit_msg>example: Update to just find a camera and fall back to a virtual camera, indicate we're using 640x480<commit_after>/*- * Copyright (c) 2008 Michael Marner <michael@20papercups.net> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 system headers #include <stdlib.h> #include <string.h> #include <iostream> #include <fstream> #include <sstream> // include openGL headers #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <wcl/camera/CameraException.h> #include <wcl/camera/VirtualCamera.h> #include <wcl/camera/CameraFactory.h> #define WIDTH 640 using namespace std; using namespace wcl; Camera *cam; unsigned char* data; void usage() { printf("Usage: camera [devicenode]\n" "\n" "eg: camera /dev/video0\n" "\n" "If no device node is given the first available camera is used. If no physical camera exists, the virtual camera is used\n" ); } /** * Initialise OpenGL */ GLvoid init() { glShadeModel(GL_SMOOTH); glClearColor(0,0,0,0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); data = new unsigned char[cam->getFormatBufferSize(Camera::RGB8)]; // create a texture for the image... glTexImage2D(GL_TEXTURE_2D, //target 0, //level of detail 3, //colour components cam->getActiveConfiguration().width, //width cam->getActiveConfiguration().height, //height 0, //border GL_RGB, //image format GL_UNSIGNED_BYTE, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); gluOrtho2D(0,1,0,1); glMatrixMode(GL_MODELVIEW); } /** * Constantly fetch a new image from the camera to display */ GLvoid idle() { glutPostRedisplay(); } /** * Display Loop. */ GLvoid display() { glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); const unsigned char* frame = cam->getFrame(Camera::RGB8); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cam->getActiveConfiguration().width, cam->getActiveConfiguration().height, GL_RGB, GL_UNSIGNED_BYTE, frame); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor3f(1,0,0); glBegin(GL_QUADS); glTexCoord2f(0,1); glVertex2f(0,0); glTexCoord2f(1,1); glVertex2f(1,0); glTexCoord2f(1,0); glVertex2f(1,1); glTexCoord2f(0,0); glVertex2f(0,1); glEnd(); glFlush(); glutSwapBuffers(); // print out any opengl errors to the console GLenum error = glGetError(); if (error != GL_NO_ERROR) { cout << gluErrorString(error) << endl; } } /** * This doesn't do what it is supposed to do! */ GLvoid reshape(int width, int height) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,1,0,1); glMatrixMode(GL_MODELVIEW); glViewport(0,0, (GLsizei)width, (GLsizei)height); } void keyboard(unsigned char key, int w, int h) { if(key==27) exit(EXIT_SUCCESS); } int main(int argc, char** argv) { if(argc >= 2 && (strcmp(argv[1],"--help") == 0 || strcmp(argv[1],"-h" ) == 0)){ usage(); return 1; } try { if( argc == 2 ){ cout << "Attempting to use Camera specified:" << argv[1] <<endl; cam = CameraFactory::getCamera(argv[1]); } else { cout << "No Camera Specified, using CameraFactory to find the first camera..." << endl; std::vector<Camera *> cameras = CameraFactory::getCameras(); CameraFactory::printDetails(false); if( cameras.size() == 0 ){ cout << "No physical camera's found, using virtual camera" << endl; cam = new VirtualCamera(); } else { cam = CameraFactory::getCamera(); } } if (cam == NULL ){ std::cout << "No usable cameras found" << std::endl; exit(0); } /* * Print out camera details */ cam->printDetails(); cout << "Setting Camera to a width of " << WIDTH << " pixels" << endl; Camera::Configuration c; c.width = WIDTH; cam->setConfiguration(cam->findConfiguration(c)); //Set power frequency compensation to 50 Hz //this is noncritical so don't stop the program if it fails try { cam->setControlValue(Camera::POWER_FREQUENCY, 1); }catch(CameraException &e){} // Create GLUT window glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(cam->getActiveConfiguration().width, cam->getActiveConfiguration().height); glutCreateWindow(argv[0]); init(); // register callbacks glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutIdleFunc(idle); // GO! glutMainLoop(); cout << "Deleting Cam" << endl; cam->shutdown(); delete cam; } catch (Exception &e) { cout << "Exception Occured: " << e.what() << endl; } return 0; } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (C) 2015-2016 by Savoir-faire Linux * * Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "text.h" //Dring #include <media_const.h> #include "dbus/callmanager.h" #include "dbus/configurationmanager.h" //Ring #include <call.h> #include <callmodel.h> #include <account.h> #include <person.h> #include <contactmethod.h> #include <mime.h> #include <media/textrecording.h> #include <media/recordingmodel.h> #include <phonedirectorymodel.h> #include <private/call_p.h> #include <private/vcardutils.h> #include <private/textrecording_p.h> #include <private/imconversationmanagerprivate.h> #include <accountmodel.h> #include <personmodel.h> /* * Instant message have 3 major modes, "past", "in call" and "offline" * * Offline messages are currently implemented over the DHT and may eventually * be implemented over account registration (publish--subscribe) * * In call messages are the fastest as they have a communication channels of their * own. * * Past messages are local copy of past communication stored somewhere. * * All 3 sources have to be combined dynamically into a single stream per person. * * So chunks can come from all 3 sources for the same stream, including part that * are shared in a conference with multiple peers. */ class MediaTextPrivate { public: MediaTextPrivate(Media::Text* parent); //Attributes Media::TextRecording* m_pRecording; bool m_HasChecked; QHash<QString,bool> m_hMimeTypes; QStringList m_lMimeTypes; //Helper void updateMimeList(const QMap<QString,QString>& payloads); private: Media::Text* q_ptr; }; class ProfileChunk { public: //Helper static Person* addChunk( const QMap<QString,QString>& args, const QString& payload, ContactMethod *contactMethod); private: //Attributes QHash<int, QString> m_hParts { }; int m_PartsCount { 0 }; static QHash<QString, ProfileChunk*> m_hRequest; }; QHash<QString, ProfileChunk*> ProfileChunk::m_hRequest; IMConversationManagerPrivate::IMConversationManagerPrivate(QObject* parent) : QObject(parent) { CallManagerInterface& callManager = CallManager::instance(); ConfigurationManagerInterface& configurationManager = ConfigurationManager::instance(); connect(&configurationManager, &ConfigurationManagerInterface::incomingAccountMessage, this, &IMConversationManagerPrivate::newAccountMessage); connect(&configurationManager, &ConfigurationManagerInterface::accountMessageStatusChanged , this, &IMConversationManagerPrivate::accountMessageStatusChanged); connect(&callManager , &CallManagerInterface::incomingMessage , this, &IMConversationManagerPrivate::newMessage ); } IMConversationManagerPrivate& IMConversationManagerPrivate::instance() { static auto instance = new IMConversationManagerPrivate(nullptr); return *instance; } Person* ProfileChunk::addChunk(const QMap<QString, QString>& args, const QString& payload, ContactMethod *contactMethod) { const int total = args[ "of" ].toInt(); const int part = args[ "part" ].toInt(); const QString id = args[ "id" ]; auto c = m_hRequest[id]; if (!c) { c = new ProfileChunk(); c->m_PartsCount = total; m_hRequest[id] = c; } if (part < 1 and part > total) return nullptr; c->m_hParts[part] = payload; if (c->m_hParts.size() != c->m_PartsCount) return nullptr; QByteArray cv; for (int i=0; i < c->m_PartsCount; ++i) { cv += c->m_hParts[i+1]; } m_hRequest[id] = nullptr; delete c; return VCardUtils::mapToPersonFromReceivedProfile(contactMethod, cv); } ///Called when a new message is incoming void IMConversationManagerPrivate::newMessage(const QString& callId, const QString& from, const QMap<QString,QString>& message) { Q_UNUSED(from) auto call = CallModel::instance().getCall(callId); if (!call and !call->peerContactMethod()) { return; } static const int profileSize = QString(RingMimes::PROFILE_VCF).size(); //Intercept some messages early, those are intended for internal Ring usage QMapIterator<QString, QString> iter(message); while (iter.hasNext()) { iter.next(); if (iter.key().left(profileSize) == RingMimes::PROFILE_VCF) { const auto& args = VCardUtils::parseMimeAttributes(iter.key()); if (auto person = ProfileChunk::addChunk(args, iter.value(), call->peerContactMethod())) { PersonModel::instance().addPeerProfile(person); } return; } } Media::Text* media = call->firstMedia<Media::Text>(Media::Media::Direction::IN); if (!media) { media = call->d_ptr->mediaFactory<Media::Text>(Media::Media::Direction::IN); } media->recording()->setCall(call); media->recording()->d_ptr->insertNewMessage(message,call->peerContactMethod(),Media::Media::Direction::IN); media->d_ptr->updateMimeList(message); emit media->messageReceived(message); } void IMConversationManagerPrivate::newAccountMessage(const QString& accountId, const QString& from, const QMap<QString,QString>& payloads) { if (auto cm = PhoneDirectoryModel::instance().getNumber(from, AccountModel::instance().getById(accountId.toLatin1()))) { auto txtRecording = cm->textRecording(); txtRecording->d_ptr->insertNewMessage(payloads, cm, Media::Media::Direction::IN); } } void IMConversationManagerPrivate::accountMessageStatusChanged(const QString& accountId, uint64_t id, const QString& to, int status) { if (auto cm = PhoneDirectoryModel::instance().getNumber(to, AccountModel::instance().getById(accountId.toLatin1()))) { auto txtRecording = cm->textRecording(); txtRecording->d_ptr->accountMessageStatusChanged(id, static_cast<DRing::Account::MessageStates>(status)); } } MediaTextPrivate::MediaTextPrivate(Media::Text* parent) : q_ptr(parent),m_pRecording(nullptr),m_HasChecked(false) { } Media::Text::Text(Call* parent, const Media::Direction direction) : Media::Media(parent, direction), d_ptr(new MediaTextPrivate(this)) { Q_ASSERT(parent); } Media::Media::Type Media::Text::type() { return Media::Media::Type::TEXT; } Media::Text::~Text() { delete d_ptr; } Media::TextRecording* Media::Text::recording() const { const bool wasChecked = d_ptr->m_HasChecked; d_ptr->m_HasChecked = true; if ((!wasChecked) && !d_ptr->m_pRecording) { Text* other = call()->firstMedia<Text>(direction() == Media::Direction::OUT ? Media::Direction::IN : Media::Direction::OUT ); if (other && other->recording()) d_ptr->m_pRecording = other->recording(); } if ((!wasChecked) && !d_ptr->m_pRecording) { if (auto otherRecording = call()->peerContactMethod()->textRecording()) d_ptr->m_pRecording = otherRecording; else d_ptr->m_pRecording = RecordingModel::instance().createTextRecording(call()->peerContactMethod()); } return d_ptr->m_pRecording; } bool Media::Text::hasMimeType( const QString& mimeType ) const { return d_ptr->m_hMimeTypes.contains(mimeType); } QStringList Media::Text::mimeTypes() const { return d_ptr->m_lMimeTypes; } void MediaTextPrivate::updateMimeList(const QMap<QString,QString>& payloads) { const int prevSize = m_hMimeTypes.size(); QMapIterator<QString, QString> iter(payloads); while (iter.hasNext()) { iter.next(); // Mime types can have some arguments after ';' const QString mimeType = iter.key(); const int hasArgs = mimeType.indexOf(';'); const QString strippedMimeType = hasArgs != -1 ? mimeType.left(hasArgs) : mimeType; const int currentSize = m_hMimeTypes.size(); m_hMimeTypes[strippedMimeType] = true; if (currentSize != m_hMimeTypes.size()) m_lMimeTypes << strippedMimeType; } if (prevSize != m_hMimeTypes.size()) emit q_ptr->mimeTypesChanged(); } /** * Send a message to the peer. * * @param message A messages encoded in various alternate payloads * * The send a single messages. Just as e-mails, the message can be * encoded differently. The peer client will interpret the richest * payload it support and then fallback to lesser ones. * * Suggested payloads include: * * "text/plain" : The most common plain UTF-8 text * "text/enriched" : (RTF) The rich text format used by older applications (like WordPad and OS X TextEdit) * "text/html" : The format used by web browsers */ void Media::Text::send(const QMap<QString,QString>& message, const bool isMixed) { CallManagerInterface& callManager = CallManager::instance(); Q_NOREPLY callManager.sendTextMessage(call()->dringId(), message, isMixed); //Make sure the recording exist recording(); d_ptr->m_pRecording->setCall(call()); d_ptr->m_pRecording->d_ptr->insertNewMessage(message,call()->peerContactMethod(),Media::Direction::OUT); d_ptr->updateMimeList(message); emit messageSent(message); } #include <text.moc> <commit_msg>media/text: fix invalid reference<commit_after>/**************************************************************************** * Copyright (C) 2015-2016 by Savoir-faire Linux * * Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "text.h" //Dring #include <media_const.h> #include "dbus/callmanager.h" #include "dbus/configurationmanager.h" //Ring #include <call.h> #include <callmodel.h> #include <account.h> #include <person.h> #include <contactmethod.h> #include <mime.h> #include <media/textrecording.h> #include <media/recordingmodel.h> #include <phonedirectorymodel.h> #include <private/call_p.h> #include <private/vcardutils.h> #include <private/textrecording_p.h> #include <private/imconversationmanagerprivate.h> #include <accountmodel.h> #include <personmodel.h> /* * Instant message have 3 major modes, "past", "in call" and "offline" * * Offline messages are currently implemented over the DHT and may eventually * be implemented over account registration (publish--subscribe) * * In call messages are the fastest as they have a communication channels of their * own. * * Past messages are local copy of past communication stored somewhere. * * All 3 sources have to be combined dynamically into a single stream per person. * * So chunks can come from all 3 sources for the same stream, including part that * are shared in a conference with multiple peers. */ class MediaTextPrivate { public: MediaTextPrivate(Media::Text* parent); //Attributes Media::TextRecording* m_pRecording; bool m_HasChecked; QHash<QString,bool> m_hMimeTypes; QStringList m_lMimeTypes; //Helper void updateMimeList(const QMap<QString,QString>& payloads); private: Media::Text* q_ptr; }; class ProfileChunk { public: //Helper static Person* addChunk( const QMap<QString,QString>& args, const QString& payload, ContactMethod *contactMethod); private: //Attributes QHash<int, QString> m_hParts { }; int m_PartsCount { 0 }; static QHash<QString, ProfileChunk*> m_hRequest; }; QHash<QString, ProfileChunk*> ProfileChunk::m_hRequest; IMConversationManagerPrivate::IMConversationManagerPrivate(QObject* parent) : QObject(parent) { CallManagerInterface& callManager = CallManager::instance(); ConfigurationManagerInterface& configurationManager = ConfigurationManager::instance(); connect(&configurationManager, &ConfigurationManagerInterface::incomingAccountMessage, this, &IMConversationManagerPrivate::newAccountMessage); connect(&configurationManager, &ConfigurationManagerInterface::accountMessageStatusChanged , this, &IMConversationManagerPrivate::accountMessageStatusChanged); connect(&callManager , &CallManagerInterface::incomingMessage , this, &IMConversationManagerPrivate::newMessage ); } IMConversationManagerPrivate& IMConversationManagerPrivate::instance() { static auto instance = new IMConversationManagerPrivate(nullptr); return *instance; } Person* ProfileChunk::addChunk(const QMap<QString, QString>& args, const QString& payload, ContactMethod *contactMethod) { const int total = args[ "of" ].toInt(); const int part = args[ "part" ].toInt(); const QString id = args[ "id" ]; auto c = m_hRequest[id]; if (!c) { c = new ProfileChunk(); c->m_PartsCount = total; m_hRequest[id] = c; } if (part < 1 and part > total) return nullptr; c->m_hParts[part] = payload; if (c->m_hParts.size() != c->m_PartsCount) return nullptr; QByteArray cv; for (int i=0; i < c->m_PartsCount; ++i) { cv += c->m_hParts[i+1]; } m_hRequest[id] = nullptr; delete c; return VCardUtils::mapToPersonFromReceivedProfile(contactMethod, cv); } ///Called when a new message is incoming void IMConversationManagerPrivate::newMessage(const QString& callId, const QString& from, const QMap<QString,QString>& message) { Q_UNUSED(from) auto call = CallModel::instance().getCall(callId); if (!call and !call->peerContactMethod()) { return; } static const int profileSize = QString(RingMimes::PROFILE_VCF).size(); //Intercept some messages early, those are intended for internal Ring usage QMapIterator<QString, QString> iter(message); while (iter.hasNext()) { iter.next(); if (iter.key().left(profileSize) == RingMimes::PROFILE_VCF) { auto args = VCardUtils::parseMimeAttributes(iter.key()); if (auto person = ProfileChunk::addChunk(args, iter.value(), call->peerContactMethod())) { PersonModel::instance().addPeerProfile(person); } return; } } Media::Text* media = call->firstMedia<Media::Text>(Media::Media::Direction::IN); if (!media) { media = call->d_ptr->mediaFactory<Media::Text>(Media::Media::Direction::IN); } media->recording()->setCall(call); media->recording()->d_ptr->insertNewMessage(message,call->peerContactMethod(),Media::Media::Direction::IN); media->d_ptr->updateMimeList(message); emit media->messageReceived(message); } void IMConversationManagerPrivate::newAccountMessage(const QString& accountId, const QString& from, const QMap<QString,QString>& payloads) { if (auto cm = PhoneDirectoryModel::instance().getNumber(from, AccountModel::instance().getById(accountId.toLatin1()))) { auto txtRecording = cm->textRecording(); txtRecording->d_ptr->insertNewMessage(payloads, cm, Media::Media::Direction::IN); } } void IMConversationManagerPrivate::accountMessageStatusChanged(const QString& accountId, uint64_t id, const QString& to, int status) { if (auto cm = PhoneDirectoryModel::instance().getNumber(to, AccountModel::instance().getById(accountId.toLatin1()))) { auto txtRecording = cm->textRecording(); txtRecording->d_ptr->accountMessageStatusChanged(id, static_cast<DRing::Account::MessageStates>(status)); } } MediaTextPrivate::MediaTextPrivate(Media::Text* parent) : q_ptr(parent),m_pRecording(nullptr),m_HasChecked(false) { } Media::Text::Text(Call* parent, const Media::Direction direction) : Media::Media(parent, direction), d_ptr(new MediaTextPrivate(this)) { Q_ASSERT(parent); } Media::Media::Type Media::Text::type() { return Media::Media::Type::TEXT; } Media::Text::~Text() { delete d_ptr; } Media::TextRecording* Media::Text::recording() const { const bool wasChecked = d_ptr->m_HasChecked; d_ptr->m_HasChecked = true; if ((!wasChecked) && !d_ptr->m_pRecording) { Text* other = call()->firstMedia<Text>(direction() == Media::Direction::OUT ? Media::Direction::IN : Media::Direction::OUT ); if (other && other->recording()) d_ptr->m_pRecording = other->recording(); } if ((!wasChecked) && !d_ptr->m_pRecording) { if (auto otherRecording = call()->peerContactMethod()->textRecording()) d_ptr->m_pRecording = otherRecording; else d_ptr->m_pRecording = RecordingModel::instance().createTextRecording(call()->peerContactMethod()); } return d_ptr->m_pRecording; } bool Media::Text::hasMimeType( const QString& mimeType ) const { return d_ptr->m_hMimeTypes.contains(mimeType); } QStringList Media::Text::mimeTypes() const { return d_ptr->m_lMimeTypes; } void MediaTextPrivate::updateMimeList(const QMap<QString,QString>& payloads) { const int prevSize = m_hMimeTypes.size(); QMapIterator<QString, QString> iter(payloads); while (iter.hasNext()) { iter.next(); // Mime types can have some arguments after ';' const QString mimeType = iter.key(); const int hasArgs = mimeType.indexOf(';'); const QString strippedMimeType = hasArgs != -1 ? mimeType.left(hasArgs) : mimeType; const int currentSize = m_hMimeTypes.size(); m_hMimeTypes[strippedMimeType] = true; if (currentSize != m_hMimeTypes.size()) m_lMimeTypes << strippedMimeType; } if (prevSize != m_hMimeTypes.size()) emit q_ptr->mimeTypesChanged(); } /** * Send a message to the peer. * * @param message A messages encoded in various alternate payloads * * The send a single messages. Just as e-mails, the message can be * encoded differently. The peer client will interpret the richest * payload it support and then fallback to lesser ones. * * Suggested payloads include: * * "text/plain" : The most common plain UTF-8 text * "text/enriched" : (RTF) The rich text format used by older applications (like WordPad and OS X TextEdit) * "text/html" : The format used by web browsers */ void Media::Text::send(const QMap<QString,QString>& message, const bool isMixed) { CallManagerInterface& callManager = CallManager::instance(); Q_NOREPLY callManager.sendTextMessage(call()->dringId(), message, isMixed); //Make sure the recording exist recording(); d_ptr->m_pRecording->setCall(call()); d_ptr->m_pRecording->d_ptr->insertNewMessage(message,call()->peerContactMethod(),Media::Direction::OUT); d_ptr->updateMimeList(message); emit messageSent(message); } #include <text.moc> <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 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. * * Authors: Ron Dreslinski * Steve Reinhardt * Ali Saidi */ /** * @file * Declaration of a request, the overall memory request consisting of the parts of the request that are persistent throughout the transaction. */ #ifndef __MEM_REQUEST_HH__ #define __MEM_REQUEST_HH__ #include <cassert> #include "base/fast_alloc.hh" #include "base/flags.hh" #include "base/misc.hh" #include "base/types.hh" #include "sim/core.hh" class Request; typedef Request* RequestPtr; class Request : public FastAlloc { public: typedef uint32_t FlagsType; typedef ::Flags<FlagsType> Flags; /** ASI information for this request if it exists. */ static const FlagsType ASI_BITS = 0x000000FF; /** The request was an instruction fetch. */ static const FlagsType INST_FETCH = 0x00000100; /** The virtual address is also the physical address. */ static const FlagsType PHYSICAL = 0x00000200; /** The request is an ALPHA VPTE pal access (hw_ld). */ static const FlagsType VPTE = 0x00000400; /** Use the alternate mode bits in ALPHA. */ static const FlagsType ALTMODE = 0x00000800; /** The request is to an uncacheable address. */ static const FlagsType UNCACHEABLE = 0x00001000; /** This request is to a memory mapped register. */ static const FlagsType MMAPPED_IPR = 0x00002000; /** This request is a clear exclusive. */ static const FlagsType CLEAR_LL = 0x00004000; /** The request should not cause a memory access. */ static const FlagsType NO_ACCESS = 0x00080000; /** This request will lock or unlock the accessed memory. When used with * a load, the access locks the particular chunk of memory. When used * with a store, it unlocks. The rule is that locked accesses have to be * made up of a locked load, some operation on the data, and then a locked * store. */ static const FlagsType LOCKED = 0x00100000; /** The request is a Load locked/store conditional. */ static const FlagsType LLSC = 0x00200000; /** This request is for a memory swap. */ static const FlagsType MEM_SWAP = 0x00400000; static const FlagsType MEM_SWAP_COND = 0x00800000; /** The request is a prefetch. */ static const FlagsType PREFETCH = 0x01000000; /** The request should be prefetched into the exclusive state. */ static const FlagsType PF_EXCLUSIVE = 0x02000000; /** The request should be marked as LRU. */ static const FlagsType EVICT_NEXT = 0x04000000; /** These flags are *not* cleared when a Request object is reused (assigned a new address). */ static const FlagsType STICKY_FLAGS = INST_FETCH; private: typedef uint8_t PrivateFlagsType; typedef ::Flags<PrivateFlagsType> PrivateFlags; /** Whether or not the size is valid. */ static const PrivateFlagsType VALID_SIZE = 0x00000001; /** Whether or not paddr is valid (has been written yet). */ static const PrivateFlagsType VALID_PADDR = 0x00000002; /** Whether or not the vaddr & asid are valid. */ static const PrivateFlagsType VALID_VADDR = 0x00000004; /** Whether or not the pc is valid. */ static const PrivateFlagsType VALID_PC = 0x00000010; /** Whether or not the context ID is valid. */ static const PrivateFlagsType VALID_CONTEXT_ID = 0x00000020; static const PrivateFlagsType VALID_THREAD_ID = 0x00000040; /** Whether or not the sc result is valid. */ static const PrivateFlagsType VALID_EXTRA_DATA = 0x00000080; /** These flags are *not* cleared when a Request object is reused (assigned a new address). */ static const PrivateFlagsType STICKY_PRIVATE_FLAGS = VALID_CONTEXT_ID | VALID_THREAD_ID; private: /** * The physical address of the request. Valid only if validPaddr * is set. */ Addr _paddr; /** * The size of the request. This field must be set when vaddr or * paddr is written via setVirt() or setPhys(), so it is always * valid as long as one of the address fields is valid. */ int _size; /** Flag structure for the request. */ Flags _flags; /** Private flags for field validity checking. */ PrivateFlags privateFlags; /** * The time this request was started. Used to calculate * latencies. This field is set to curTick() any time paddr or vaddr * is written. */ Tick _time; /** The address space ID. */ int _asid; /** The virtual address of the request. */ Addr _vaddr; /** * Extra data for the request, such as the return value of * store conditional or the compare value for a CAS. */ uint64_t _extraData; /** The context ID (for statistics, typically). */ int _contextId; /** The thread ID (id within this CPU) */ int _threadId; /** program counter of initiating access; for tracing/debugging */ Addr _pc; public: /** Minimal constructor. No fields are initialized. * (Note that _flags and privateFlags are cleared by Flags * default constructor.) */ Request() {} /** * Constructor for physical (e.g. device) requests. Initializes * just physical address, size, flags, and timestamp (to curTick()). * These fields are adequate to perform a request. */ Request(Addr paddr, int size, Flags flags) { setPhys(paddr, size, flags); } Request(Addr paddr, int size, Flags flags, Tick time) { setPhys(paddr, size, flags, time); } Request(Addr paddr, int size, Flags flags, Tick time, Addr pc) { setPhys(paddr, size, flags, time); privateFlags.set(VALID_PC); _pc = pc; } Request(int asid, Addr vaddr, int size, Flags flags, Addr pc, int cid, ThreadID tid) { setVirt(asid, vaddr, size, flags, pc); setThreadContext(cid, tid); } ~Request() {} // for FastAlloc /** * Set up CPU and thread numbers. */ void setThreadContext(int context_id, ThreadID tid) { _contextId = context_id; _threadId = tid; privateFlags.set(VALID_CONTEXT_ID|VALID_THREAD_ID); } /** * Set up a physical (e.g. device) request in a previously * allocated Request object. */ void setPhys(Addr paddr, int size, Flags flags, Tick time) { assert(size >= 0); _paddr = paddr; _size = size; _time = time; _flags.clear(~STICKY_FLAGS); _flags.set(flags); privateFlags.clear(~STICKY_PRIVATE_FLAGS); privateFlags.set(VALID_PADDR|VALID_SIZE); } void setPhys(Addr paddr, int size, Flags flags) { setPhys(paddr, size, flags, curTick()); } /** * Set up a virtual (e.g., CPU) request in a previously * allocated Request object. */ void setVirt(int asid, Addr vaddr, int size, Flags flags, Addr pc) { assert(size >= 0); _asid = asid; _vaddr = vaddr; _size = size; _pc = pc; _time = curTick(); _flags.clear(~STICKY_FLAGS); _flags.set(flags); privateFlags.clear(~STICKY_PRIVATE_FLAGS); privateFlags.set(VALID_VADDR|VALID_SIZE|VALID_PC); } /** * Set just the physical address. This should only be used to * record the result of a translation, and thus the vaddr must be * valid before this method is called. Otherwise, use setPhys() * to guarantee that the size and flags are also set. */ void setPaddr(Addr paddr) { assert(privateFlags.isSet(VALID_VADDR)); _paddr = paddr; privateFlags.set(VALID_PADDR); } /** * Generate two requests as if this request had been split into two * pieces. The original request can't have been translated already. */ void splitOnVaddr(Addr split_addr, RequestPtr &req1, RequestPtr &req2) { assert(privateFlags.isSet(VALID_VADDR)); assert(privateFlags.noneSet(VALID_PADDR)); assert(split_addr > _vaddr && split_addr < _vaddr + _size); req1 = new Request; *req1 = *this; req2 = new Request; *req2 = *this; req1->_size = split_addr - _vaddr; req2->_vaddr = split_addr; req2->_size = _size - req1->_size; } /** * Accessor for paddr. */ bool hasPaddr() { return privateFlags.isSet(VALID_PADDR); } Addr getPaddr() { assert(privateFlags.isSet(VALID_PADDR)); return _paddr; } /** * Accessor for size. */ bool hasSize() { return privateFlags.isSet(VALID_SIZE); } int getSize() { assert(privateFlags.isSet(VALID_SIZE)); return _size; } /** Accessor for time. */ Tick time() const { assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR)); return _time; } void time(Tick time) { assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR)); _time = time; } /** Accessor for flags. */ Flags getFlags() { assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR)); return _flags; } /** Note that unlike other accessors, this function sets *specific flags* (ORs them in); it does not assign its argument to the _flags field. Thus this method should rightly be called setFlags() and not just flags(). */ void setFlags(Flags flags) { assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR)); _flags.set(flags); } /** Accessor function for vaddr.*/ Addr getVaddr() { assert(privateFlags.isSet(VALID_VADDR)); return _vaddr; } /** Accessor function for asid.*/ int getAsid() { assert(privateFlags.isSet(VALID_VADDR)); return _asid; } /** Accessor function for asi.*/ uint8_t getAsi() { assert(privateFlags.isSet(VALID_VADDR)); return _flags & ASI_BITS; } /** Accessor function to check if sc result is valid. */ bool extraDataValid() { return privateFlags.isSet(VALID_EXTRA_DATA); } /** Accessor function for store conditional return value.*/ uint64_t getExtraData() const { assert(privateFlags.isSet(VALID_EXTRA_DATA)); return _extraData; } /** Accessor function for store conditional return value.*/ void setExtraData(uint64_t extraData) { _extraData = extraData; privateFlags.set(VALID_EXTRA_DATA); } bool hasContextId() const { return privateFlags.isSet(VALID_CONTEXT_ID); } /** Accessor function for context ID.*/ int contextId() const { assert(privateFlags.isSet(VALID_CONTEXT_ID)); return _contextId; } /** Accessor function for thread ID. */ int threadId() const { assert(privateFlags.isSet(VALID_THREAD_ID)); return _threadId; } bool hasPC() const { return privateFlags.isSet(VALID_PC); } /** Accessor function for pc.*/ Addr getPC() const { assert(privateFlags.isSet(VALID_PC)); return _pc; } /** Accessor functions for flags. Note that these are for testing only; setting flags should be done via setFlags(). */ bool isUncacheable() const { return _flags.isSet(UNCACHEABLE); } bool isInstFetch() const { return _flags.isSet(INST_FETCH); } bool isPrefetch() const { return _flags.isSet(PREFETCH); } bool isLLSC() const { return _flags.isSet(LLSC); } bool isLocked() const { return _flags.isSet(LOCKED); } bool isSwap() const { return _flags.isSet(MEM_SWAP|MEM_SWAP_COND); } bool isCondSwap() const { return _flags.isSet(MEM_SWAP_COND); } bool isMmappedIpr() const { return _flags.isSet(MMAPPED_IPR); } bool isClearLL() const { return _flags.isSet(CLEAR_LL); } }; #endif // __MEM_REQUEST_HH__ <commit_msg>Mem: Allow ASID to be set after request is created.<commit_after>/* * Copyright (c) 2002-2005 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. * * Authors: Ron Dreslinski * Steve Reinhardt * Ali Saidi */ /** * @file * Declaration of a request, the overall memory request consisting of the parts of the request that are persistent throughout the transaction. */ #ifndef __MEM_REQUEST_HH__ #define __MEM_REQUEST_HH__ #include <cassert> #include "base/fast_alloc.hh" #include "base/flags.hh" #include "base/misc.hh" #include "base/types.hh" #include "sim/core.hh" class Request; typedef Request* RequestPtr; class Request : public FastAlloc { public: typedef uint32_t FlagsType; typedef ::Flags<FlagsType> Flags; /** ASI information for this request if it exists. */ static const FlagsType ASI_BITS = 0x000000FF; /** The request was an instruction fetch. */ static const FlagsType INST_FETCH = 0x00000100; /** The virtual address is also the physical address. */ static const FlagsType PHYSICAL = 0x00000200; /** The request is an ALPHA VPTE pal access (hw_ld). */ static const FlagsType VPTE = 0x00000400; /** Use the alternate mode bits in ALPHA. */ static const FlagsType ALTMODE = 0x00000800; /** The request is to an uncacheable address. */ static const FlagsType UNCACHEABLE = 0x00001000; /** This request is to a memory mapped register. */ static const FlagsType MMAPPED_IPR = 0x00002000; /** This request is a clear exclusive. */ static const FlagsType CLEAR_LL = 0x00004000; /** The request should not cause a memory access. */ static const FlagsType NO_ACCESS = 0x00080000; /** This request will lock or unlock the accessed memory. When used with * a load, the access locks the particular chunk of memory. When used * with a store, it unlocks. The rule is that locked accesses have to be * made up of a locked load, some operation on the data, and then a locked * store. */ static const FlagsType LOCKED = 0x00100000; /** The request is a Load locked/store conditional. */ static const FlagsType LLSC = 0x00200000; /** This request is for a memory swap. */ static const FlagsType MEM_SWAP = 0x00400000; static const FlagsType MEM_SWAP_COND = 0x00800000; /** The request is a prefetch. */ static const FlagsType PREFETCH = 0x01000000; /** The request should be prefetched into the exclusive state. */ static const FlagsType PF_EXCLUSIVE = 0x02000000; /** The request should be marked as LRU. */ static const FlagsType EVICT_NEXT = 0x04000000; /** These flags are *not* cleared when a Request object is reused (assigned a new address). */ static const FlagsType STICKY_FLAGS = INST_FETCH; private: typedef uint8_t PrivateFlagsType; typedef ::Flags<PrivateFlagsType> PrivateFlags; /** Whether or not the size is valid. */ static const PrivateFlagsType VALID_SIZE = 0x00000001; /** Whether or not paddr is valid (has been written yet). */ static const PrivateFlagsType VALID_PADDR = 0x00000002; /** Whether or not the vaddr & asid are valid. */ static const PrivateFlagsType VALID_VADDR = 0x00000004; /** Whether or not the pc is valid. */ static const PrivateFlagsType VALID_PC = 0x00000010; /** Whether or not the context ID is valid. */ static const PrivateFlagsType VALID_CONTEXT_ID = 0x00000020; static const PrivateFlagsType VALID_THREAD_ID = 0x00000040; /** Whether or not the sc result is valid. */ static const PrivateFlagsType VALID_EXTRA_DATA = 0x00000080; /** These flags are *not* cleared when a Request object is reused (assigned a new address). */ static const PrivateFlagsType STICKY_PRIVATE_FLAGS = VALID_CONTEXT_ID | VALID_THREAD_ID; private: /** * The physical address of the request. Valid only if validPaddr * is set. */ Addr _paddr; /** * The size of the request. This field must be set when vaddr or * paddr is written via setVirt() or setPhys(), so it is always * valid as long as one of the address fields is valid. */ int _size; /** Flag structure for the request. */ Flags _flags; /** Private flags for field validity checking. */ PrivateFlags privateFlags; /** * The time this request was started. Used to calculate * latencies. This field is set to curTick() any time paddr or vaddr * is written. */ Tick _time; /** The address space ID. */ int _asid; /** The virtual address of the request. */ Addr _vaddr; /** * Extra data for the request, such as the return value of * store conditional or the compare value for a CAS. */ uint64_t _extraData; /** The context ID (for statistics, typically). */ int _contextId; /** The thread ID (id within this CPU) */ int _threadId; /** program counter of initiating access; for tracing/debugging */ Addr _pc; public: /** Minimal constructor. No fields are initialized. * (Note that _flags and privateFlags are cleared by Flags * default constructor.) */ Request() {} /** * Constructor for physical (e.g. device) requests. Initializes * just physical address, size, flags, and timestamp (to curTick()). * These fields are adequate to perform a request. */ Request(Addr paddr, int size, Flags flags) { setPhys(paddr, size, flags); } Request(Addr paddr, int size, Flags flags, Tick time) { setPhys(paddr, size, flags, time); } Request(Addr paddr, int size, Flags flags, Tick time, Addr pc) { setPhys(paddr, size, flags, time); privateFlags.set(VALID_PC); _pc = pc; } Request(int asid, Addr vaddr, int size, Flags flags, Addr pc, int cid, ThreadID tid) { setVirt(asid, vaddr, size, flags, pc); setThreadContext(cid, tid); } ~Request() {} // for FastAlloc /** * Set up CPU and thread numbers. */ void setThreadContext(int context_id, ThreadID tid) { _contextId = context_id; _threadId = tid; privateFlags.set(VALID_CONTEXT_ID|VALID_THREAD_ID); } /** * Set up a physical (e.g. device) request in a previously * allocated Request object. */ void setPhys(Addr paddr, int size, Flags flags, Tick time) { assert(size >= 0); _paddr = paddr; _size = size; _time = time; _flags.clear(~STICKY_FLAGS); _flags.set(flags); privateFlags.clear(~STICKY_PRIVATE_FLAGS); privateFlags.set(VALID_PADDR|VALID_SIZE); } void setPhys(Addr paddr, int size, Flags flags) { setPhys(paddr, size, flags, curTick()); } /** * Set up a virtual (e.g., CPU) request in a previously * allocated Request object. */ void setVirt(int asid, Addr vaddr, int size, Flags flags, Addr pc) { assert(size >= 0); _asid = asid; _vaddr = vaddr; _size = size; _pc = pc; _time = curTick(); _flags.clear(~STICKY_FLAGS); _flags.set(flags); privateFlags.clear(~STICKY_PRIVATE_FLAGS); privateFlags.set(VALID_VADDR|VALID_SIZE|VALID_PC); } /** * Set just the physical address. This should only be used to * record the result of a translation, and thus the vaddr must be * valid before this method is called. Otherwise, use setPhys() * to guarantee that the size and flags are also set. */ void setPaddr(Addr paddr) { assert(privateFlags.isSet(VALID_VADDR)); _paddr = paddr; privateFlags.set(VALID_PADDR); } /** * Generate two requests as if this request had been split into two * pieces. The original request can't have been translated already. */ void splitOnVaddr(Addr split_addr, RequestPtr &req1, RequestPtr &req2) { assert(privateFlags.isSet(VALID_VADDR)); assert(privateFlags.noneSet(VALID_PADDR)); assert(split_addr > _vaddr && split_addr < _vaddr + _size); req1 = new Request; *req1 = *this; req2 = new Request; *req2 = *this; req1->_size = split_addr - _vaddr; req2->_vaddr = split_addr; req2->_size = _size - req1->_size; } /** * Accessor for paddr. */ bool hasPaddr() { return privateFlags.isSet(VALID_PADDR); } Addr getPaddr() { assert(privateFlags.isSet(VALID_PADDR)); return _paddr; } /** * Accessor for size. */ bool hasSize() { return privateFlags.isSet(VALID_SIZE); } int getSize() { assert(privateFlags.isSet(VALID_SIZE)); return _size; } /** Accessor for time. */ Tick time() const { assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR)); return _time; } void time(Tick time) { assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR)); _time = time; } /** Accessor for flags. */ Flags getFlags() { assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR)); return _flags; } /** Note that unlike other accessors, this function sets *specific flags* (ORs them in); it does not assign its argument to the _flags field. Thus this method should rightly be called setFlags() and not just flags(). */ void setFlags(Flags flags) { assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR)); _flags.set(flags); } /** Accessor function for vaddr.*/ Addr getVaddr() { assert(privateFlags.isSet(VALID_VADDR)); return _vaddr; } /** Accessor function for asid.*/ int getAsid() { assert(privateFlags.isSet(VALID_VADDR)); return _asid; } /** Accessor function for asid.*/ void setAsid(int asid) { _asid = asid; } /** Accessor function for asi.*/ uint8_t getAsi() { assert(privateFlags.isSet(VALID_VADDR)); return _flags & ASI_BITS; } /** Accessor function to check if sc result is valid. */ bool extraDataValid() { return privateFlags.isSet(VALID_EXTRA_DATA); } /** Accessor function for store conditional return value.*/ uint64_t getExtraData() const { assert(privateFlags.isSet(VALID_EXTRA_DATA)); return _extraData; } /** Accessor function for store conditional return value.*/ void setExtraData(uint64_t extraData) { _extraData = extraData; privateFlags.set(VALID_EXTRA_DATA); } bool hasContextId() const { return privateFlags.isSet(VALID_CONTEXT_ID); } /** Accessor function for context ID.*/ int contextId() const { assert(privateFlags.isSet(VALID_CONTEXT_ID)); return _contextId; } /** Accessor function for thread ID. */ int threadId() const { assert(privateFlags.isSet(VALID_THREAD_ID)); return _threadId; } bool hasPC() const { return privateFlags.isSet(VALID_PC); } /** Accessor function for pc.*/ Addr getPC() const { assert(privateFlags.isSet(VALID_PC)); return _pc; } /** Accessor functions for flags. Note that these are for testing only; setting flags should be done via setFlags(). */ bool isUncacheable() const { return _flags.isSet(UNCACHEABLE); } bool isInstFetch() const { return _flags.isSet(INST_FETCH); } bool isPrefetch() const { return _flags.isSet(PREFETCH); } bool isLLSC() const { return _flags.isSet(LLSC); } bool isLocked() const { return _flags.isSet(LOCKED); } bool isSwap() const { return _flags.isSet(MEM_SWAP|MEM_SWAP_COND); } bool isCondSwap() const { return _flags.isSet(MEM_SWAP_COND); } bool isMmappedIpr() const { return _flags.isSet(MMAPPED_IPR); } bool isClearLL() const { return _flags.isSet(CLEAR_LL); } }; #endif // __MEM_REQUEST_HH__ <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: metaOutput.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_WIN32) || defined(__CYGWIN__) #include <winsock2.h> #else #include <unistd.h> #endif #include "metaOutput.h" #include <itksys/SystemTools.hxx> #include "zlib/zlib.h" #if (METAIO_USE_NAMESPACE) namespace METAIO_NAMESPACE { #endif /** Constructor */ MetaOutput::MetaOutput() { m_MetaCommand = 0; m_CurrentVersion = "0.1"; } /** Destructor */ MetaOutput::~MetaOutput() { StreamVector::iterator itStream = m_StreamVector.begin(); while(itStream != m_StreamVector.end()) { itStream = m_StreamVector.erase(itStream); } } /** Add a field */ bool MetaOutput::AddField(METAIO_STL::string name, METAIO_STL::string description, TypeEnumType type, METAIO_STL::string value, METAIO_STL::string rangeMin, METAIO_STL::string rangeMax ) { Field field; field.name = name; field.description = description; field.value = value; field.type = type; field.rangeMin = rangeMin; field.rangeMax = rangeMax; m_FieldVector.push_back(field); return true; } /** Add a float field */ bool MetaOutput::AddFloatField(METAIO_STL::string name, METAIO_STL::string description, float value, METAIO_STL::string rangeMin, METAIO_STL::string rangeMax ) { char* val = new char[10]; sprintf(val,"%f",value); this->AddField(name,description,FLOAT,val,rangeMin,rangeMax); delete [] val; return true; } /** Add meta command */ void MetaOutput::SetMetaCommand(MetaCommand* metaCommand) { m_MetaCommand = metaCommand; m_MetaCommand->SetOption("GenerateMetaOutput","generateMetaOutput", false,"Generate MetaOutput"); m_MetaCommand->SetOption("GenerateXMLMetaOutput","oxml", false,"Generate XML MetaOutput to the console"); } /** Get the username */ METAIO_STL::string MetaOutput::GetUsername() { #if defined (_WIN32) || defined(__CYGWIN__) static char buf[1024]; DWORD size = sizeof(buf); buf[0] = '\0'; GetUserName( buf, &size); return buf; #else // not _WIN32 struct passwd *pw = getpwuid(getuid()); if ( pw == NULL ) { METAIO_STL::cout << "getpwuid() failed " << METAIO_STL::endl; } return pw->pw_name; #endif // not _WIN32 } METAIO_STL::string MetaOutput::GetHostname() { #if defined (_WIN32) || defined(__CYGWIN__) WSADATA WsaData; int err = WSAStartup (0x0101, &WsaData); // Init Winsock if(err!=0) { return ""; } #endif char nameBuffer[1024]; gethostname(nameBuffer, 1024); METAIO_STL::string hostName(nameBuffer); return hostName; } METAIO_STL::string MetaOutput::GetHostip() { #if defined (_WIN32) || defined(__CYGWIN__) WSADATA WsaData; int err = WSAStartup (0x0101, &WsaData); // Init Winsock if(err!=0) return ""; #endif struct hostent *phe = gethostbyname(GetHostname().c_str()); if (phe == 0) return ""; struct in_addr addr; char** address = phe->h_addr_list; int m_numaddrs = 0; while (*address) { m_numaddrs++; address++; } METAIO_STL::string m_ip = ""; if (m_numaddrs != 0) { memcpy(&addr, phe->h_addr_list[m_numaddrs-1], sizeof(struct in_addr)); m_ip = inet_ntoa(addr); } return m_ip; } /** Return the string representation of a type */ METAIO_STL::string MetaOutput::TypeToString(TypeEnumType type) { switch(type) { case INT: return "int"; case FLOAT: return "float"; case STRING: return "string"; case LIST: return "list"; case FLAG: return "flag"; case BOOL: return "boolean"; default: return "not defined"; } return "not defined"; } /** Private function to fill in the buffer */ METAIO_STL::string MetaOutput::GenerateXML(const char* filename) { METAIO_STL::string buffer; buffer = "<?xml version=\"1.0\"?>\n"; buffer += "<MetaOutputFile "; if(filename) { METAIO_STL::string filenamestr = filename; buffer += "name=\"" +filenamestr+"\""; } buffer += " version=\""+m_CurrentVersion+"\">\n"; buffer += "<Creation date=\"" + itksys::SystemTools::GetCurrentDateTime("%Y%m%d") + "\""; buffer += " time=\"" + itksys::SystemTools::GetCurrentDateTime("%H%M%S") + "\""; buffer += " hostname=\""+this->GetHostname() +"\""; buffer += " hostIP=\""+this->GetHostip() +"\""; buffer += " user=\"" + this->GetUsername() + "\"/>\n"; buffer += "<Executable name=\"" + m_MetaCommand->GetApplicationName() + "\""; buffer += " version=\"" + m_MetaCommand->GetVersion() + "\""; buffer += " author=\"" + m_MetaCommand->GetAuthor() + "\""; buffer += " description=\"" + m_MetaCommand->GetDescription() + "\"/>\n"; buffer += "<Inputs>\n"; const MetaCommand::OptionVector options = m_MetaCommand->GetParsedOptions(); MetaCommand::OptionVector::const_iterator itInput = options.begin(); while(itInput != options.end()) { if((*itInput).name == "GenerateMetaOutput") { itInput++; continue; } typedef METAIO_STL::vector<MetaCommand::Field> FieldVector; FieldVector::const_iterator itField = (*itInput).fields.begin(); while(itField != (*itInput).fields.end()) { if((*itInput).fields.size() == 1) { buffer += " <Input name=\"" + (*itInput).name +"\"";; } else { buffer += " <Input name=\"" + (*itInput).name + "." + (*itField).name +"\""; } buffer += " description=\"" + (*itInput).description + "\""; if((*itField).required) { buffer += " required=\"true\""; } buffer += " value=\"" + (*itField).value + "\""; buffer += " type=\"" + m_MetaCommand->TypeToString((*itField).type) + "\""; if((*itField).rangeMin != "") { buffer += " rangeMin=\"" + (*itField).rangeMin + "\""; } if((*itField).rangeMax != "") { buffer += " rangeMax=\"" + (*itField).rangeMax + "\""; } if((*itField).externaldata == MetaCommand::DATA_IN) { buffer += " externalData=\"in\""; } else if((*itField).externaldata == MetaCommand::DATA_OUT) { buffer += " externalData=\"out\""; } buffer += "/>\n"; itField++; } itInput++; } buffer += "</Inputs>\n"; // Output buffer += "<Outputs>\n"; FieldVector::const_iterator itOutput = m_FieldVector.begin(); while(itOutput != m_FieldVector.end()) { buffer += " <Output name=\""+ (*itOutput).name + "\""; buffer += " description=\""+ (*itOutput).description + "\""; buffer += " value=\""+ (*itOutput).value + "\""; buffer += " type=\""+ this->TypeToString((*itOutput).type) + "\""; itOutput++; } buffer += "/>\n"; buffer += "</Outputs>\n"; // CRC32 unsigned long crc = crc32(0L,(Bytef*)buffer.c_str(),buffer.size()); char * crcstring = new char[10]; sprintf(crcstring,"%ul",crc); // Compute the crc buffer += "<CRC32>"; buffer += crcstring; buffer += "</CRC32>\n"; buffer += "</MetaOutputFile>\n"; delete [] crcstring; return buffer; } /** Write the output to the connected streams */ void MetaOutput::Write() { if(m_MetaCommand && m_MetaCommand->GetOptionWasSet("GenerateXMLMetaOutput")) { METAIO_STL::cout << this->GenerateXML().c_str() << METAIO_STL::endl; } if(m_MetaCommand && !m_MetaCommand->GetOptionWasSet("GenerateMetaOutput")) { return; } StreamVector::iterator itStream = m_StreamVector.begin(); while(itStream != m_StreamVector.end()) { if(!(*itStream)->IsEnable()) { itStream++; continue; } (*itStream)->SetMetaOutput(this); if(!(*itStream)->Open()) { METAIO_STL::cout << "MetaOutput ERROR: cannot open stream" << METAIO_STL::endl; return; } FieldVector::const_iterator it = m_FieldVector.begin(); while(it != m_FieldVector.end()) { if(typeid(*(*itStream)) == typeid(MetaFileOutputStream)) { METAIO_STL::string filename = dynamic_cast<MetaFileOutputStream*>(*itStream)->GetFileName().c_str(); (*itStream)->Write(this->GenerateXML(filename.c_str()).c_str()); } else { (*itStream)->Write(this->GenerateXML().c_str()); } it++; } if(!(*itStream)->Close()) { METAIO_STL::cout << "MetaOutput ERROR: cannot close stream" << METAIO_STL::endl; return; } itStream++; } } /** Add a stream */ void MetaOutput::AddStream(const char* name,METAIO_STL::ostream & stdstream) { MetaOutputStream* stream = new MetaOutputStream; stream->SetName(name); stream->SetStdStream(&stdstream); m_StreamVector.push_back(stream); } void MetaOutput::AddStream(const char* name,MetaOutputStream * stream) { stream->SetName(name); m_StreamVector.push_back(stream); } /** Add a stream file. Helper function */ void MetaOutput::AddStreamFile(const char* name,const char* filename) { MetaFileOutputStream* stream = new MetaFileOutputStream(filename); this->AddStream(name,stream); } /** Enable a stream */ void MetaOutput::EnableStream(const char* name) { StreamVector::iterator itStream = m_StreamVector.begin(); while(itStream != m_StreamVector.end()) { if(!strcmp((*itStream)->GetName().c_str(),name)) { (*itStream)->Enable(); } itStream++; } } /** Disable a stream */ void MetaOutput::DisableStream(const char* name) { StreamVector::iterator itStream = m_StreamVector.begin(); while(itStream != m_StreamVector.end()) { if(!strcmp((*itStream)->GetName().c_str(),name)) { (*itStream)->Disable(); } itStream++; } } #if (METAIO_USE_NAMESPACE) }; #endif <commit_msg>COMP: Missing includes (reported by Kent Williams)<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: metaOutput.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_WIN32) || defined(__CYGWIN__) #include <winsock2.h> #else #include <unistd.h> #include <sys/types.h> #include <pwd.h> #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #endif #include "metaOutput.h" #include <itksys/SystemTools.hxx> #include "zlib/zlib.h" #if (METAIO_USE_NAMESPACE) namespace METAIO_NAMESPACE { #endif /** Constructor */ MetaOutput::MetaOutput() { m_MetaCommand = 0; m_CurrentVersion = "0.1"; } /** Destructor */ MetaOutput::~MetaOutput() { StreamVector::iterator itStream = m_StreamVector.begin(); while(itStream != m_StreamVector.end()) { itStream = m_StreamVector.erase(itStream); } } /** Add a field */ bool MetaOutput::AddField(METAIO_STL::string name, METAIO_STL::string description, TypeEnumType type, METAIO_STL::string value, METAIO_STL::string rangeMin, METAIO_STL::string rangeMax ) { Field field; field.name = name; field.description = description; field.value = value; field.type = type; field.rangeMin = rangeMin; field.rangeMax = rangeMax; m_FieldVector.push_back(field); return true; } /** Add a float field */ bool MetaOutput::AddFloatField(METAIO_STL::string name, METAIO_STL::string description, float value, METAIO_STL::string rangeMin, METAIO_STL::string rangeMax ) { char* val = new char[10]; sprintf(val,"%f",value); this->AddField(name,description,FLOAT,val,rangeMin,rangeMax); delete [] val; return true; } /** Add meta command */ void MetaOutput::SetMetaCommand(MetaCommand* metaCommand) { m_MetaCommand = metaCommand; m_MetaCommand->SetOption("GenerateMetaOutput","generateMetaOutput", false,"Generate MetaOutput"); m_MetaCommand->SetOption("GenerateXMLMetaOutput","oxml", false,"Generate XML MetaOutput to the console"); } /** Get the username */ METAIO_STL::string MetaOutput::GetUsername() { #if defined (_WIN32) || defined(__CYGWIN__) static char buf[1024]; DWORD size = sizeof(buf); buf[0] = '\0'; GetUserName( buf, &size); return buf; #else // not _WIN32 struct passwd *pw = getpwuid(getuid()); if ( pw == NULL ) { METAIO_STL::cout << "getpwuid() failed " << METAIO_STL::endl; } return pw->pw_name; #endif // not _WIN32 } METAIO_STL::string MetaOutput::GetHostname() { #if defined (_WIN32) || defined(__CYGWIN__) WSADATA WsaData; int err = WSAStartup (0x0101, &WsaData); // Init Winsock if(err!=0) { return ""; } #endif char nameBuffer[1024]; gethostname(nameBuffer, 1024); METAIO_STL::string hostName(nameBuffer); return hostName; } METAIO_STL::string MetaOutput::GetHostip() { #if defined (_WIN32) || defined(__CYGWIN__) WSADATA WsaData; int err = WSAStartup (0x0101, &WsaData); // Init Winsock if(err!=0) return ""; #endif struct hostent *phe = gethostbyname(GetHostname().c_str()); if (phe == 0) return ""; struct in_addr addr; char** address = phe->h_addr_list; int m_numaddrs = 0; while (*address) { m_numaddrs++; address++; } METAIO_STL::string m_ip = ""; if (m_numaddrs != 0) { memcpy(&addr, phe->h_addr_list[m_numaddrs-1], sizeof(struct in_addr)); m_ip = inet_ntoa(addr); } return m_ip; } /** Return the string representation of a type */ METAIO_STL::string MetaOutput::TypeToString(TypeEnumType type) { switch(type) { case INT: return "int"; case FLOAT: return "float"; case STRING: return "string"; case LIST: return "list"; case FLAG: return "flag"; case BOOL: return "boolean"; default: return "not defined"; } return "not defined"; } /** Private function to fill in the buffer */ METAIO_STL::string MetaOutput::GenerateXML(const char* filename) { METAIO_STL::string buffer; buffer = "<?xml version=\"1.0\"?>\n"; buffer += "<MetaOutputFile "; if(filename) { METAIO_STL::string filenamestr = filename; buffer += "name=\"" +filenamestr+"\""; } buffer += " version=\""+m_CurrentVersion+"\">\n"; buffer += "<Creation date=\"" + itksys::SystemTools::GetCurrentDateTime("%Y%m%d") + "\""; buffer += " time=\"" + itksys::SystemTools::GetCurrentDateTime("%H%M%S") + "\""; buffer += " hostname=\""+this->GetHostname() +"\""; buffer += " hostIP=\""+this->GetHostip() +"\""; buffer += " user=\"" + this->GetUsername() + "\"/>\n"; buffer += "<Executable name=\"" + m_MetaCommand->GetApplicationName() + "\""; buffer += " version=\"" + m_MetaCommand->GetVersion() + "\""; buffer += " author=\"" + m_MetaCommand->GetAuthor() + "\""; buffer += " description=\"" + m_MetaCommand->GetDescription() + "\"/>\n"; buffer += "<Inputs>\n"; const MetaCommand::OptionVector options = m_MetaCommand->GetParsedOptions(); MetaCommand::OptionVector::const_iterator itInput = options.begin(); while(itInput != options.end()) { if((*itInput).name == "GenerateMetaOutput") { itInput++; continue; } typedef METAIO_STL::vector<MetaCommand::Field> FieldVector; FieldVector::const_iterator itField = (*itInput).fields.begin(); while(itField != (*itInput).fields.end()) { if((*itInput).fields.size() == 1) { buffer += " <Input name=\"" + (*itInput).name +"\"";; } else { buffer += " <Input name=\"" + (*itInput).name + "." + (*itField).name +"\""; } buffer += " description=\"" + (*itInput).description + "\""; if((*itField).required) { buffer += " required=\"true\""; } buffer += " value=\"" + (*itField).value + "\""; buffer += " type=\"" + m_MetaCommand->TypeToString((*itField).type) + "\""; if((*itField).rangeMin != "") { buffer += " rangeMin=\"" + (*itField).rangeMin + "\""; } if((*itField).rangeMax != "") { buffer += " rangeMax=\"" + (*itField).rangeMax + "\""; } if((*itField).externaldata == MetaCommand::DATA_IN) { buffer += " externalData=\"in\""; } else if((*itField).externaldata == MetaCommand::DATA_OUT) { buffer += " externalData=\"out\""; } buffer += "/>\n"; itField++; } itInput++; } buffer += "</Inputs>\n"; // Output buffer += "<Outputs>\n"; FieldVector::const_iterator itOutput = m_FieldVector.begin(); while(itOutput != m_FieldVector.end()) { buffer += " <Output name=\""+ (*itOutput).name + "\""; buffer += " description=\""+ (*itOutput).description + "\""; buffer += " value=\""+ (*itOutput).value + "\""; buffer += " type=\""+ this->TypeToString((*itOutput).type) + "\""; itOutput++; } buffer += "/>\n"; buffer += "</Outputs>\n"; // CRC32 unsigned long crc = crc32(0L,(Bytef*)buffer.c_str(),buffer.size()); char * crcstring = new char[10]; sprintf(crcstring,"%ul",crc); // Compute the crc buffer += "<CRC32>"; buffer += crcstring; buffer += "</CRC32>\n"; buffer += "</MetaOutputFile>\n"; delete [] crcstring; return buffer; } /** Write the output to the connected streams */ void MetaOutput::Write() { if(m_MetaCommand && m_MetaCommand->GetOptionWasSet("GenerateXMLMetaOutput")) { METAIO_STL::cout << this->GenerateXML().c_str() << METAIO_STL::endl; } if(m_MetaCommand && !m_MetaCommand->GetOptionWasSet("GenerateMetaOutput")) { return; } StreamVector::iterator itStream = m_StreamVector.begin(); while(itStream != m_StreamVector.end()) { if(!(*itStream)->IsEnable()) { itStream++; continue; } (*itStream)->SetMetaOutput(this); if(!(*itStream)->Open()) { METAIO_STL::cout << "MetaOutput ERROR: cannot open stream" << METAIO_STL::endl; return; } FieldVector::const_iterator it = m_FieldVector.begin(); while(it != m_FieldVector.end()) { if(typeid(*(*itStream)) == typeid(MetaFileOutputStream)) { METAIO_STL::string filename = dynamic_cast<MetaFileOutputStream*>(*itStream)->GetFileName().c_str(); (*itStream)->Write(this->GenerateXML(filename.c_str()).c_str()); } else { (*itStream)->Write(this->GenerateXML().c_str()); } it++; } if(!(*itStream)->Close()) { METAIO_STL::cout << "MetaOutput ERROR: cannot close stream" << METAIO_STL::endl; return; } itStream++; } } /** Add a stream */ void MetaOutput::AddStream(const char* name,METAIO_STL::ostream & stdstream) { MetaOutputStream* stream = new MetaOutputStream; stream->SetName(name); stream->SetStdStream(&stdstream); m_StreamVector.push_back(stream); } void MetaOutput::AddStream(const char* name,MetaOutputStream * stream) { stream->SetName(name); m_StreamVector.push_back(stream); } /** Add a stream file. Helper function */ void MetaOutput::AddStreamFile(const char* name,const char* filename) { MetaFileOutputStream* stream = new MetaFileOutputStream(filename); this->AddStream(name,stream); } /** Enable a stream */ void MetaOutput::EnableStream(const char* name) { StreamVector::iterator itStream = m_StreamVector.begin(); while(itStream != m_StreamVector.end()) { if(!strcmp((*itStream)->GetName().c_str(),name)) { (*itStream)->Enable(); } itStream++; } } /** Disable a stream */ void MetaOutput::DisableStream(const char* name) { StreamVector::iterator itStream = m_StreamVector.begin(); while(itStream != m_StreamVector.end()) { if(!strcmp((*itStream)->GetName().c_str(),name)) { (*itStream)->Disable(); } itStream++; } } #if (METAIO_USE_NAMESPACE) }; #endif <|endoftext|>
<commit_before>// Copyright (c) 2014-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "hash.h" #include "uint256.h" #include <assert.h> #include <stdint.h> #include <string.h> #include <vector> #include <string> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> /** All alphanumeric characters except for "0", "I", "O", and "l" */ static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch) { // Skip leading spaces. while (*psz && isspace(*psz)) psz++; // Skip and count leading '1's. int zeroes = 0; while (*psz == '1') { zeroes++; psz++; } // Allocate enough space in big-endian base256 representation. std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up. // Process the characters. while (*psz && !isspace(*psz)) { // Decode base58 character const char* ch = strchr(pszBase58, *psz); if (ch == NULL) return false; // Apply "b256 = b256 * 58 + ch". int carry = ch - pszBase58; for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) { carry += 58 * (*it); *it = carry % 256; carry /= 256; } assert(carry == 0); psz++; } // Skip trailing spaces. while (isspace(*psz)) psz++; if (*psz != 0) return false; // Skip leading zeroes in b256. std::vector<unsigned char>::iterator it = b256.begin(); while (it != b256.end() && *it == 0) it++; // Copy result into output vector. vch.reserve(zeroes + (b256.end() - it)); vch.assign(zeroes, 0x00); while (it != b256.end()) vch.push_back(*(it++)); return true; } std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) { // Skip & count leading zeroes. int zeroes = 0; while (pbegin != pend && *pbegin == 0) { pbegin++; zeroes++; } // Allocate enough space in big-endian base58 representation. std::vector<unsigned char> b58((pend - pbegin) * 138 / 100 + 1); // log(256) / log(58), rounded up. // Process the bytes. while (pbegin != pend) { int carry = *pbegin; // Apply "b58 = b58 * 256 + ch". for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) { carry += 256 * (*it); *it = carry % 58; carry /= 58; } assert(carry == 0); pbegin++; } // Skip leading zeroes in base58 result. std::vector<unsigned char>::iterator it = b58.begin(); while (it != b58.end() && *it == 0) it++; // Translate the result into a string. std::string str; str.reserve(zeroes + (b58.end() - it)); str.assign(zeroes, '1'); while (it != b58.end()) str += pszBase58[*(it++)]; return str; } std::string EncodeBase58(const std::vector<unsigned char>& vch) { return EncodeBase58(&vch[0], &vch[0] + vch.size()); } bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58(str.c_str(), vchRet); } std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn) { // add 4-byte hash check to the end std::vector<unsigned char> vch(vchIn); uint256 hash = Hash(vch.begin(), vch.end()); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); return EncodeBase58(vch); } bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet) { if (!DecodeBase58(psz, vchRet) || (vchRet.size() < 4)) { vchRet.clear(); return false; } // re-calculate the checksum, insure it matches the included 4-byte checksum uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4); if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) { vchRet.clear(); return false; } vchRet.resize(vchRet.size() - 4); return true; } bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58Check(str.c_str(), vchRet); } CBase58Data::CBase58Data() { vchVersion.clear(); vchData.clear(); } void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize) { vchVersion = vchVersionIn; vchData.resize(nSize); if (!vchData.empty()) memcpy(&vchData[0], pdata, nSize); } void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend) { SetData(vchVersionIn, (void*)pbegin, pend - pbegin); } bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes) { std::vector<unsigned char> vchTemp; bool rc58 = DecodeBase58Check(psz, vchTemp); if ((!rc58) || (vchTemp.size() < nVersionBytes)) { vchData.clear(); vchVersion.clear(); return false; } vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes); vchData.resize(vchTemp.size() - nVersionBytes); if (!vchData.empty()) memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size()); memory_cleanse(&vchTemp[0], vchData.size()); return true; } bool CBase58Data::SetString(const std::string& str) { return SetString(str.c_str()); } std::string CBase58Data::ToString() const { std::vector<unsigned char> vch = vchVersion; vch.insert(vch.end(), vchData.begin(), vchData.end()); return EncodeBase58Check(vch); } int CBase58Data::CompareTo(const CBase58Data& b58) const { if (vchVersion < b58.vchVersion) return -1; if (vchVersion > b58.vchVersion) return 1; if (vchData < b58.vchData) return -1; if (vchData > b58.vchData) return 1; return 0; } namespace { class CBitcoinAddressVisitor : public boost::static_visitor<bool> { private: CBitcoinAddress* addr; public: CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {} bool operator()(const CKeyID& id) const { return addr->Set(id); } bool operator()(const CScriptID& id) const { return addr->Set(id); } bool operator()(const CNoDestination& no) const { return false; } }; } // anon namespace bool CBitcoinAddress::Set(const CKeyID& id) { SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20); return true; } bool CBitcoinAddress::Set(const CScriptID& id) { SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20); return true; } bool CBitcoinAddress::Set(const CTxDestination& dest) { return boost::apply_visitor(CBitcoinAddressVisitor(this), dest); } bool CBitcoinAddress::IsValid() const { return IsValid(Params()); } bool CBitcoinAddress::IsValid(const CChainParams& params) const { bool fCorrectSize = vchData.size() == 20; bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) || vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS); return fCorrectSize && fKnownVersion; } CTxDestination CBitcoinAddress::Get() const { if (!IsValid()) return CNoDestination(); uint160 id; memcpy(&id, &vchData[0], 20); if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return CKeyID(id); else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) return CScriptID(id); else return CNoDestination(); } bool CBitcoinAddress::GetKeyID(CKeyID& keyID) const { if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return false; uint160 id; memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } bool CBitcoinAddress::IsScript() const { return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS); } void CBitcoinSecret::SetKey(const CKey& vchSecret) { assert(vchSecret.IsValid()); SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size()); if (vchSecret.IsCompressed()) vchData.push_back(1); } CKey CBitcoinSecret::GetKey() { CKey ret; assert(vchData.size() >= 32); ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1); return ret; } bool CBitcoinSecret::IsValid() const { bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1); bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY); return fExpectedFormat && fCorrectVersion; } bool CBitcoinSecret::SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); } bool CBitcoinSecret::SetString(const std::string& strSecret) { return SetString(strSecret.c_str()); } <commit_msg>CBase58Data::SetString: cleanse the full vector<commit_after>// Copyright (c) 2014-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "hash.h" #include "uint256.h" #include <assert.h> #include <stdint.h> #include <string.h> #include <vector> #include <string> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> /** All alphanumeric characters except for "0", "I", "O", and "l" */ static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch) { // Skip leading spaces. while (*psz && isspace(*psz)) psz++; // Skip and count leading '1's. int zeroes = 0; while (*psz == '1') { zeroes++; psz++; } // Allocate enough space in big-endian base256 representation. std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up. // Process the characters. while (*psz && !isspace(*psz)) { // Decode base58 character const char* ch = strchr(pszBase58, *psz); if (ch == NULL) return false; // Apply "b256 = b256 * 58 + ch". int carry = ch - pszBase58; for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) { carry += 58 * (*it); *it = carry % 256; carry /= 256; } assert(carry == 0); psz++; } // Skip trailing spaces. while (isspace(*psz)) psz++; if (*psz != 0) return false; // Skip leading zeroes in b256. std::vector<unsigned char>::iterator it = b256.begin(); while (it != b256.end() && *it == 0) it++; // Copy result into output vector. vch.reserve(zeroes + (b256.end() - it)); vch.assign(zeroes, 0x00); while (it != b256.end()) vch.push_back(*(it++)); return true; } std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) { // Skip & count leading zeroes. int zeroes = 0; while (pbegin != pend && *pbegin == 0) { pbegin++; zeroes++; } // Allocate enough space in big-endian base58 representation. std::vector<unsigned char> b58((pend - pbegin) * 138 / 100 + 1); // log(256) / log(58), rounded up. // Process the bytes. while (pbegin != pend) { int carry = *pbegin; // Apply "b58 = b58 * 256 + ch". for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) { carry += 256 * (*it); *it = carry % 58; carry /= 58; } assert(carry == 0); pbegin++; } // Skip leading zeroes in base58 result. std::vector<unsigned char>::iterator it = b58.begin(); while (it != b58.end() && *it == 0) it++; // Translate the result into a string. std::string str; str.reserve(zeroes + (b58.end() - it)); str.assign(zeroes, '1'); while (it != b58.end()) str += pszBase58[*(it++)]; return str; } std::string EncodeBase58(const std::vector<unsigned char>& vch) { return EncodeBase58(&vch[0], &vch[0] + vch.size()); } bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58(str.c_str(), vchRet); } std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn) { // add 4-byte hash check to the end std::vector<unsigned char> vch(vchIn); uint256 hash = Hash(vch.begin(), vch.end()); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); return EncodeBase58(vch); } bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet) { if (!DecodeBase58(psz, vchRet) || (vchRet.size() < 4)) { vchRet.clear(); return false; } // re-calculate the checksum, insure it matches the included 4-byte checksum uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4); if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) { vchRet.clear(); return false; } vchRet.resize(vchRet.size() - 4); return true; } bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58Check(str.c_str(), vchRet); } CBase58Data::CBase58Data() { vchVersion.clear(); vchData.clear(); } void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize) { vchVersion = vchVersionIn; vchData.resize(nSize); if (!vchData.empty()) memcpy(&vchData[0], pdata, nSize); } void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend) { SetData(vchVersionIn, (void*)pbegin, pend - pbegin); } bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes) { std::vector<unsigned char> vchTemp; bool rc58 = DecodeBase58Check(psz, vchTemp); if ((!rc58) || (vchTemp.size() < nVersionBytes)) { vchData.clear(); vchVersion.clear(); return false; } vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes); vchData.resize(vchTemp.size() - nVersionBytes); if (!vchData.empty()) memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size()); memory_cleanse(&vchTemp[0], vchTemp.size()); return true; } bool CBase58Data::SetString(const std::string& str) { return SetString(str.c_str()); } std::string CBase58Data::ToString() const { std::vector<unsigned char> vch = vchVersion; vch.insert(vch.end(), vchData.begin(), vchData.end()); return EncodeBase58Check(vch); } int CBase58Data::CompareTo(const CBase58Data& b58) const { if (vchVersion < b58.vchVersion) return -1; if (vchVersion > b58.vchVersion) return 1; if (vchData < b58.vchData) return -1; if (vchData > b58.vchData) return 1; return 0; } namespace { class CBitcoinAddressVisitor : public boost::static_visitor<bool> { private: CBitcoinAddress* addr; public: CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {} bool operator()(const CKeyID& id) const { return addr->Set(id); } bool operator()(const CScriptID& id) const { return addr->Set(id); } bool operator()(const CNoDestination& no) const { return false; } }; } // anon namespace bool CBitcoinAddress::Set(const CKeyID& id) { SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20); return true; } bool CBitcoinAddress::Set(const CScriptID& id) { SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20); return true; } bool CBitcoinAddress::Set(const CTxDestination& dest) { return boost::apply_visitor(CBitcoinAddressVisitor(this), dest); } bool CBitcoinAddress::IsValid() const { return IsValid(Params()); } bool CBitcoinAddress::IsValid(const CChainParams& params) const { bool fCorrectSize = vchData.size() == 20; bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) || vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS); return fCorrectSize && fKnownVersion; } CTxDestination CBitcoinAddress::Get() const { if (!IsValid()) return CNoDestination(); uint160 id; memcpy(&id, &vchData[0], 20); if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return CKeyID(id); else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) return CScriptID(id); else return CNoDestination(); } bool CBitcoinAddress::GetKeyID(CKeyID& keyID) const { if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return false; uint160 id; memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } bool CBitcoinAddress::IsScript() const { return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS); } void CBitcoinSecret::SetKey(const CKey& vchSecret) { assert(vchSecret.IsValid()); SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size()); if (vchSecret.IsCompressed()) vchData.push_back(1); } CKey CBitcoinSecret::GetKey() { CKey ret; assert(vchData.size() >= 32); ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1); return ret; } bool CBitcoinSecret::IsValid() const { bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1); bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY); return fExpectedFormat && fCorrectVersion; } bool CBitcoinSecret::SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); } bool CBitcoinSecret::SetString(const std::string& strSecret) { return SetString(strSecret.c_str()); } <|endoftext|>
<commit_before>/* * Copyright (C) 2004 Steve Harris, Uwe Koloska * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <iostream> #include <vector> #include "lo/lo.h" using namespace std; int done = 0; struct member { int pid; char hostname[128]; }; vector<member> members; void error(int num, const char *m, const char *path); int ping_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data); int quit_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data); int main() { /* make address for multicast ip * pick a port number for you by passing NULL as the last argument */ lo_address t = lo_address_new("224.0.0.1", "7770"); // lo_server multi = lo_server_new_multicast("drone", "7771", error); /* start a new server on port 7770 */ lo_server_thread st = lo_server_thread_new("7770", error); /* add method that will match the path /foo/bar, with two numbers, coerced * to float and int */ lo_server_thread_add_method(st, "/ping", "fi", ping_handler, NULL); /* add method that will match the path /quit with no args */ lo_server_thread_add_method(st, "/quit", "", quit_handler, NULL); lo_server_thread_start(st); while (!done) { #ifdef WIN32 Sleep(1); #else usleep(1000000); #endif char hostname[128] = ""; gethostname(hostname, sizeof(hostname)); int pid = getpid(); cerr << "pid: " << pid << " || hostname : " << hostname << endl; lo_send(t, "/ping", "is", pid, hostname); // lo_send_from(t, st, now, "/foo/bar", "ff", 0.12345678f, 23.0f); } lo_server_thread_free(st); return 0; } void error(int num, const char *msg, const char *path) { printf("liblo server error %d in path %s: %s\n", num, path, msg); fflush(stdout); } /* catch any incoming messages and display them. returning 1 means that the * message has not been fully handled and the server should try other methods */ int ping_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data) { cerr << "PID: " << argv[0]->i << " || path : " << argv[1]->s << endl; /* example showing pulling the argument values out of the argv array */ printf("%s <- f:%f, i:%d\n\n", path, argv[0]->f, argv[1]->i); fflush(stdout); return 0; } int quit_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data) { done = 1; printf("quiting\n\n"); fflush(stdout); return 0; } /* vi:set ts=8 sts=4 sw=4: */ <commit_msg>Added time tag<commit_after>/* * Copyright (C) 2004 Steve Harris, Uwe Koloska * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <iostream> #include <vector> #include "lo/lo.h" using namespace std; int done = 0; struct member { int pid; char hostname[128]; lo_timetag timetag; }; vector<member> members; void error(int num, const char *m, const char *path); int ping_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data); int quit_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data); int main() { /* make address for multicast ip * pick a port number for you by passing NULL as the last argument */ lo_address t = lo_address_new("224.0.0.1", "7770"); // lo_server multi = lo_server_new_multicast("drone", "7771", error); /* start a new server on port 7770 */ lo_server_thread st = lo_server_thread_new_multicast("224.0.0.1", "7770", error); /* add method that will match the path /foo/bar, with two numbers, coerced * to float and int */ lo_server_thread_add_method(st, "/ping", "is", ping_handler, NULL); /* add method that will match the path /quit with no args */ lo_server_thread_add_method(st, "/quit", "", quit_handler, NULL); lo_server_thread_start(st); while (!done) { #ifdef WIN32 Sleep(1); #else usleep(1000000); #endif char hostname[128] = ""; gethostname(hostname, sizeof(hostname)); int pid = getpid(); // cerr << "pid: " << pid << " || hostname : " << hostname << endl; lo_send(t, "/ping", "is", pid, hostname); } lo_server_thread_free(st); return 0; } void error(int num, const char *msg, const char *path) { printf("liblo server error %d in path %s: %s\n", num, path, msg); fflush(stdout); } /* catch any incoming messages and display them. returning 1 means that the * message has not been fully handled and the server should try other methods */ int ping_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data) { member messageSender; messageSender.pid = argv[0]->i; strcpy(messageSender.hostname, (char *)argv[1]); lo_timetag_now(&messageSender.timetag); char *name = (char *)argv[1]; cerr << "PID: " << messageSender.pid << " || path : " << messageSender.hostname << " || timestamp : " << messageSender.timetag.sec << endl; fflush(stdout); return 0; } int quit_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data) { done = 1; printf("quiting\n\n"); fflush(stdout); return 0; } /* vi:set ts=8 sts=4 sw=4: */ <|endoftext|>
<commit_before>#ifndef VPP_ALGORITHMS_PYRLK_LK_HH_ # define VPP_ALGORITHMS_PYRLK_LK_HH_ # include <Eigen/Dense> # include <cfloat> namespace vpp { template <unsigned WS> struct lk_match_point_square_win { enum { window_size = WS }; template <typename F, typename GD> std::pair<vfloat2, float> operator()(vfloat2 p, vfloat2 tr_prediction, F A, F B, GD Ag, float min_ev_th, int max_interations, float convergence_delta); }; template <unsigned WS> struct oriented_lk_match_point_square_win { enum { window_size = WS }; template <typename F, typename GD> std::pair<vfloat2, float> operator()(vfloat2 p, vfloat2 tr_prediction, F A, F B, GD Ag, float min_ev_th, int max_interations, float convergence_delta, float max_step_norm, vfloat2 match_direction1, vfloat2 match_direction2); }; template <unsigned WS> template <typename F, typename GD> std::pair<vfloat2, float> lk_match_point_square_win<WS>::operator()(vfloat2 p, vfloat2 tr_prediction, F A, F B, GD Ag, float min_ev_th, int max_interations, float convergence_delta) { typedef typename F::value_type V; int ws = WS; int hws = ws/2; // Gradient matrix Eigen::Matrix2f G = Eigen::Matrix2f::Zero(); int cpt = 0; for(int r = -hws; r <= hws; r++) for(int c = -hws; c <= hws; c++) { vfloat2 n = p + vfloat2(r, c); if (A.has(n.cast<int>())) { Eigen::Matrix2f m; vfloat2 g = Ag.linear_interpolate(n); float gx = g[0]; float gy = g[1]; m << gx * gx, gx * gy, gx * gy, gy * gy; G += m; cpt++; } } // Check minimum eigenvalue. float min_ev = 99999.f; auto ev = G.eigenvalues(); for (int i = 0; i < ev.size(); i++) if (fabs(ev[i].real()) < min_ev) min_ev = fabs(ev[i].real()); if (min_ev < min_ev_th) return std::pair<vfloat2, float>(vfloat2(-1,-1), FLT_MAX); Eigen::Matrix2f G1 = G.inverse(); // Precompute gs and as. vfloat2 prediction_ = p + tr_prediction; vfloat2 v = prediction_; Eigen::Vector2f nk = Eigen::Vector2f::Ones(); vfloat2 gs[WS * WS]; typedef plus_promotion<V> S; S as[WS * WS]; { for(int i = 0, r = -hws; r <= hws; r++) { for(int c = -hws; c <= hws; c++) { vfloat2 n = p + vfloat2(r, c); if (Ag.has(n.cast<int>())) { gs[i] = Ag.linear_interpolate(n); as[i] = cast<S>(A.linear_interpolate(n)); } i++; } } } auto domain = B.domain() - border(hws + 1); // Gradient descent for (int k = 0; k <= max_interations && nk.norm() >= convergence_delta; k++) { Eigen::Vector2f bk = Eigen::Vector2f::Zero(); // Temporal difference. int i = 0; for(int r = -hws; r <= hws; r++) { for(int c = -hws; c <= hws; c++) { vfloat2 n2 = v + vfloat2(r, c); auto g = gs[i]; float dt = (cast<float>(as[i]) - cast<float>(B.linear_interpolate(n2))); bk += Eigen::Vector2f{g[0] * dt, g[1] * dt}; i++; } } nk = G1 * bk; // if (nk.norm() > 1) // { // nk.normalize(); // nk *= 1; // } v += vfloat2{nk[0], nk[1]}; if (!domain.has(v.cast<int>())) return std::pair<vfloat2, float>(vfloat2(0, 0), FLT_MAX); } // Compute matching error as the ssd. float avg = 0; float stddev = 0; for (int i = 0; i < WS * WS; i++) avg += cast<float>(as[i]); avg /= WS * WS; for (int i = 0; i < WS * WS; i++) stddev += std::abs(avg - cast<float>(as[i])); stddev /= WS * WS; float err = 0; for(int r = -hws; r <= hws; r++) for(int c = -hws; c <= hws; c++) { vfloat2 n2 = v + vfloat2(r, c); int i = (r+hws) * ws + (c+hws); { err += fabs(cast<float>(as[i] - cast<S>(B.linear_interpolate(n2)))); cpt++; } } return std::pair<vfloat2, float>(v - p, err / (cpt * stddev)); } template <unsigned WS> template <typename F, typename GD> std::pair<vfloat2, float> oriented_lk_match_point_square_win<WS>::operator()(vfloat2 p, vfloat2 tr_prediction, F A, F B, GD Ag, float min_ev_th, int max_interations, float convergence_delta, float max_step_norm, vfloat2 match_direction1, vfloat2 match_direction2) { typedef typename F::value_type V; int ws = WS; int hws = ws/2; int factor = 1; // Gradient matrix Eigen::Matrix2f G = Eigen::Matrix2f::Zero(); int cpt = 0; for(int r = -hws; r <= hws; r++) for(int c = -hws; c <= hws; c++) { vfloat2 n = p + vfloat2(r, c) * factor; if (A.has(n.cast<int>())) { Eigen::Matrix2f m; vfloat2 g = Ag.linear_interpolate(n); float gx = g[0]; float gy = g[1]; m << gx * gx, gx * gy, gx * gy, gy * gy; G += m; cpt++; } } // Check minimum eigenvalue. float min_ev = 99999.f; auto ev = G.eigenvalues(); for (int i = 0; i < ev.size(); i++) if (fabs(ev[i].real()) < min_ev) min_ev = fabs(ev[i].real()); if (min_ev < min_ev_th) return std::pair<vfloat2, float>(vfloat2(-1,-1), FLT_MAX); Eigen::Matrix2f G1 = G.inverse(); // Precompute gs and as. vfloat2 prediction_ = p + tr_prediction; vfloat2 v = prediction_; Eigen::Vector2f nk = Eigen::Vector2f::Ones(); vfloat2 mx = match_direction1; vfloat2 my{-mx[1], mx[0]}; vfloat2 gs[WS * WS]; typedef plus_promotion<V> S; S as[WS * WS]; { for(int i = 0, r = -hws; r <= hws; r++) { for(int c = -hws; c <= hws; c++) { vfloat2 n = p + (r * my + c * mx) * factor; if (Ag.has(n.cast<int>())) { gs[i] = Ag.linear_interpolate(n); as[i] = cast<S>(A.linear_interpolate(n)); } i++; } } } auto domain = B.domain() - border(3); mx = match_direction2; my = vfloat2{-mx[1], mx[0]}; // Gradient descent for (int k = 0; k < max_interations && nk.norm() >= convergence_delta; k++) { Eigen::Vector2f bk = Eigen::Vector2f::Zero(); // Temporal difference. int i = 0; for(int r = -hws; r <= hws; r++) { for(int c = -hws; c <= hws; c++) { vfloat2 n2 = v + (r * my + c * mx) * factor; { auto g = gs[i]; float dt = (cast<float>(as[i]) - cast<float>(B.linear_interpolate(n2))); bk += Eigen::Vector2f(g[0] * dt, g[1] * dt); } i++; } } nk = G1 * bk; if (nk.norm() > max_step_norm) { nk.normalize(); nk *= max_step_norm; } v += vfloat2{nk[0], nk[1]}; if (!domain.has(v.cast<int>())) return std::pair<vfloat2, float>(vfloat2(0, 0), FLT_MAX); } // Compute matching error as the ssd. float avg = 0; float stddev = 0; for (int i = 0; i < WS * WS; i++) avg += cast<float>(as[i]); avg /= WS * WS; for (int i = 0; i < WS * WS; i++) stddev += std::abs(avg - cast<float>(as[i])); stddev /= WS * WS; float err = 0; for(int r = -hws; r <= hws; r++) for(int c = -hws; c <= hws; c++) { vfloat2 n2 = v + (r * my + c * mx) * factor; int i = (r+hws) * ws + (c+hws); { err += fabs(cast<float>(as[i] - cast<S>(B.linear_interpolate(n2)))); cpt++; } } return std::pair<vfloat2, float>(v - p, err / (cpt * stddev)); } } #endif <commit_msg>Divide the gradient matrix before thresholding eivenvalues.<commit_after>#ifndef VPP_ALGORITHMS_PYRLK_LK_HH_ # define VPP_ALGORITHMS_PYRLK_LK_HH_ # include <Eigen/Dense> # include <cfloat> namespace vpp { template <unsigned WS> struct lk_match_point_square_win { enum { window_size = WS }; template <typename F, typename GD> std::pair<vfloat2, float> operator()(vfloat2 p, vfloat2 tr_prediction, F A, F B, GD Ag, float min_ev_th, int max_interations, float convergence_delta); }; template <unsigned WS> struct oriented_lk_match_point_square_win { enum { window_size = WS }; template <typename F, typename GD> std::pair<vfloat2, float> operator()(vfloat2 p, vfloat2 tr_prediction, F A, F B, GD Ag, float min_ev_th, int max_interations, float convergence_delta, float max_step_norm, vfloat2 match_direction1, vfloat2 match_direction2); }; template <unsigned WS> template <typename F, typename GD> std::pair<vfloat2, float> lk_match_point_square_win<WS>::operator()(vfloat2 p, vfloat2 tr_prediction, F A, F B, GD Ag, float min_ev_th, int max_interations, float convergence_delta) { typedef typename F::value_type V; int ws = WS; int hws = ws/2; // Gradient matrix Eigen::Matrix2f G = Eigen::Matrix2f::Zero(); int cpt = 0; for(int r = -hws; r <= hws; r++) for(int c = -hws; c <= hws; c++) { vfloat2 n = p + vfloat2(r, c); if (A.has(n.cast<int>())) { Eigen::Matrix2f m; vfloat2 g = Ag.linear_interpolate(n); float gx = g[0]; float gy = g[1]; m << gx * gx, gx * gy, gx * gy, gy * gy; G += m; cpt++; } } // Check minimum eigenvalue. float min_ev = 99999.f; auto ev = (G / cpt).eigenvalues(); for (int i = 0; i < ev.size(); i++) if (fabs(ev[i].real()) < min_ev) min_ev = fabs(ev[i].real()); if (min_ev < min_ev_th) return std::pair<vfloat2, float>(vfloat2(-1,-1), FLT_MAX); Eigen::Matrix2f G1 = G.inverse(); // Precompute gs and as. vfloat2 prediction_ = p + tr_prediction; vfloat2 v = prediction_; Eigen::Vector2f nk = Eigen::Vector2f::Ones(); vfloat2 gs[WS * WS]; typedef plus_promotion<V> S; S as[WS * WS]; { for(int i = 0, r = -hws; r <= hws; r++) { for(int c = -hws; c <= hws; c++) { vfloat2 n = p + vfloat2(r, c); if (Ag.has(n.cast<int>())) { gs[i] = Ag.linear_interpolate(n); as[i] = cast<S>(A.linear_interpolate(n)); } i++; } } } auto domain = B.domain();// - border(hws + 1); // Gradient descent for (int k = 0; k <= max_interations && nk.norm() >= convergence_delta; k++) { Eigen::Vector2f bk = Eigen::Vector2f::Zero(); // Temporal difference. int i = 0; for(int r = -hws; r <= hws; r++) { for(int c = -hws; c <= hws; c++) { vfloat2 n = p + vfloat2(r, c); if (Ag.has(n.cast<int>())) { vfloat2 n2 = v + vfloat2(r, c); auto g = gs[i]; float dt = (cast<float>(as[i]) - cast<float>(B.linear_interpolate(n2))); bk += Eigen::Vector2f{g[0] * dt, g[1] * dt}; } i++; } } nk = G1 * bk; // if (nk.norm() > 1) // { // nk.normalize(); // nk *= 1; // } v += vfloat2{nk[0], nk[1]}; if (!domain.has(v.cast<int>())) return std::pair<vfloat2, float>(vfloat2(0, 0), FLT_MAX); } // Compute matching error as the ssd. float avg = 0; float stddev = 0; for (int i = 0; i < WS * WS; i++) avg += cast<float>(as[i]); avg /= WS * WS; for (int i = 0; i < WS * WS; i++) stddev += std::abs(avg - cast<float>(as[i])); stddev /= WS * WS; float err = 0; for(int r = -hws; r <= hws; r++) for(int c = -hws; c <= hws; c++) { vfloat2 n2 = v + vfloat2(r, c); int i = (r+hws) * ws + (c+hws); { err += fabs(cast<float>(as[i] - cast<S>(B.linear_interpolate(n2)))); cpt++; } } return std::pair<vfloat2, float>(v - p, err / (cpt * stddev)); } template <unsigned WS> template <typename F, typename GD> std::pair<vfloat2, float> oriented_lk_match_point_square_win<WS>::operator()(vfloat2 p, vfloat2 tr_prediction, F A, F B, GD Ag, float min_ev_th, int max_interations, float convergence_delta, float max_step_norm, vfloat2 match_direction1, vfloat2 match_direction2) { typedef typename F::value_type V; int ws = WS; int hws = ws/2; int factor = 1; // Gradient matrix Eigen::Matrix2f G = Eigen::Matrix2f::Zero(); int cpt = 0; for(int r = -hws; r <= hws; r++) for(int c = -hws; c <= hws; c++) { vfloat2 n = p + vfloat2(r, c) * factor; if (A.has(n.cast<int>())) { Eigen::Matrix2f m; vfloat2 g = Ag.linear_interpolate(n); float gx = g[0]; float gy = g[1]; m << gx * gx, gx * gy, gx * gy, gy * gy; G += m; cpt++; } } // Check minimum eigenvalue. float min_ev = 99999.f; auto ev = G.eigenvalues(); for (int i = 0; i < ev.size(); i++) if (fabs(ev[i].real()) < min_ev) min_ev = fabs(ev[i].real()); if (min_ev < min_ev_th) return std::pair<vfloat2, float>(vfloat2(-1,-1), FLT_MAX); Eigen::Matrix2f G1 = G.inverse(); // Precompute gs and as. vfloat2 prediction_ = p + tr_prediction; vfloat2 v = prediction_; Eigen::Vector2f nk = Eigen::Vector2f::Ones(); vfloat2 mx = match_direction1; vfloat2 my{-mx[1], mx[0]}; vfloat2 gs[WS * WS]; typedef plus_promotion<V> S; S as[WS * WS]; { for(int i = 0, r = -hws; r <= hws; r++) { for(int c = -hws; c <= hws; c++) { vfloat2 n = p + (r * my + c * mx) * factor; if (Ag.has(n.cast<int>())) { gs[i] = Ag.linear_interpolate(n); as[i] = cast<S>(A.linear_interpolate(n)); } i++; } } } auto domain = B.domain() - border(3); mx = match_direction2; my = vfloat2{-mx[1], mx[0]}; // Gradient descent for (int k = 0; k < max_interations && nk.norm() >= convergence_delta; k++) { Eigen::Vector2f bk = Eigen::Vector2f::Zero(); // Temporal difference. int i = 0; for(int r = -hws; r <= hws; r++) { for(int c = -hws; c <= hws; c++) { vfloat2 n2 = v + (r * my + c * mx) * factor; { auto g = gs[i]; float dt = (cast<float>(as[i]) - cast<float>(B.linear_interpolate(n2))); bk += Eigen::Vector2f(g[0] * dt, g[1] * dt); } i++; } } nk = G1 * bk; if (nk.norm() > max_step_norm) { nk.normalize(); nk *= max_step_norm; } v += vfloat2{nk[0], nk[1]}; if (!domain.has(v.cast<int>())) return std::pair<vfloat2, float>(vfloat2(0, 0), FLT_MAX); } // Compute matching error as the ssd. float avg = 0; float stddev = 0; for (int i = 0; i < WS * WS; i++) avg += cast<float>(as[i]); avg /= WS * WS; for (int i = 0; i < WS * WS; i++) stddev += std::abs(avg - cast<float>(as[i])); stddev /= WS * WS; float err = 0; for(int r = -hws; r <= hws; r++) for(int c = -hws; c <= hws; c++) { vfloat2 n2 = v + (r * my + c * mx) * factor; int i = (r+hws) * ws + (c+hws); { err += fabs(cast<float>(as[i] - cast<S>(B.linear_interpolate(n2)))); cpt++; } } return std::pair<vfloat2, float>(v - p, err / (cpt * stddev)); } } #endif <|endoftext|>
<commit_before>/* * Copyright 2010 Martin Schreiber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CPHYSICS_COLLISION_IMPULSE_HPP #define CPHYSICS_COLLISION_IMPULSE_HPP #include "cPhysicsCollisionData.hpp" #include "worksheets_precompiler.hpp" /* * this class handles the change of object velocity (linear and angular) * by applying an impulse */ class CPhysicsCollisionImpulse { public: static inline void applyCollisionImpulse(CPhysicsCollisionData &c, double frame_elapsed_time) { #if WORKSHEET_6 #endif if ( (c.physics_object1->no_rotations_and_frictions && c.physics_object2->no_rotations_and_frictions) #if !WORKSHEET_6 || 1 #endif ) { #if WORKSHEET_3 //no friction or rotations, apply linear impulse //velocities in direction of collision normal float collision_velocity1 = (-c.collision_normal).dotProd(c.physics_object1->velocity); float collision_velocity2 = (-c.collision_normal).dotProd(c.physics_object2->velocity); float closing_velocity = (collision_velocity1 - collision_velocity2); float coefficient_of_restitution = (c.physics_object1->restitution_coefficient + c.physics_object2->restitution_coefficient)/2.0; c.physics_object1->velocity = -c.collision_normal*closing_velocity*(c.physics_object1->inv_mass/(c.physics_object1->inv_mass + c.physics_object2->inv_mass))*(-(1+coefficient_of_restitution)) + c.physics_object1->velocity; c.physics_object2->velocity = c.collision_normal*closing_velocity*(c.physics_object2->inv_mass/(c.physics_object1->inv_mass + c.physics_object2->inv_mass))*(-(1+coefficient_of_restitution)) + c.physics_object2->velocity; #endif } else if ((c.physics_object1->friction_disabled && c.physics_object2->friction_disabled) #if !WORKSHEET_7 || 1 #endif ) { #if WORKSHEET_6 #endif } else { #if WORKSHEET_7 #endif } // DAMPING TEST #if 0 c.physics_object1->velocity -= c.physics_object1->velocity*frame_elapsed_time*0.5; c.physics_object2->velocity -= c.physics_object2->velocity*frame_elapsed_time*0.5; c.physics_object1->angular_velocity -= c.physics_object1->angular_velocity*frame_elapsed_time*0.5; c.physics_object2->angular_velocity -= c.physics_object2->angular_velocity*frame_elapsed_time*0.5; #endif #if 0 if (c.physics_object1->velocity.getLength() < 0.5) c.physics_object1->velocity.setZero(); if (c.physics_object2->velocity.getLength() < 0.5) c.physics_object2->velocity.setZero(); if (c.physics_object1->angular_velocity.getLength() < 0.2) c.physics_object1->angular_velocity.setZero(); if (c.physics_object2->angular_velocity.getLength() < 0.2) c.physics_object2->angular_velocity.setZero(); #endif } }; #endif <commit_msg>Assertion for energy conservation<commit_after>/* * Copyright 2010 Martin Schreiber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CPHYSICS_COLLISION_IMPULSE_HPP #define CPHYSICS_COLLISION_IMPULSE_HPP #include "cPhysicsCollisionData.hpp" #include "worksheets_precompiler.hpp" /* * this class handles the change of object velocity (linear and angular) * by applying an impulse */ class CPhysicsCollisionImpulse { public: static inline void applyCollisionImpulse(CPhysicsCollisionData &c, double frame_elapsed_time) { #if WORKSHEET_6 #endif if ((c.physics_object1->no_rotations_and_frictions && c.physics_object2->no_rotations_and_frictions) #if !WORKSHEET_6 || 1 #endif ) { #if WORKSHEET_3 //no friction or rotations, apply linear impulse #ifdef DEBUG float eKin1 = 0; if (c.physics_object1->inv_mass > 0) { eKin1 += 0.5f / c.physics_object1->inv_mass * c.physics_object1->velocity.getLength2(); } if (c.physics_object2->inv_mass > 0) { eKin1 += 0.5f / c.physics_object2->inv_mass * c.physics_object2->velocity.getLength2(); } #endif //velocities in direction of collision normal float collision_velocity1 = (-c.collision_normal).dotProd(c.physics_object1->velocity); float collision_velocity2 = (-c.collision_normal).dotProd(c.physics_object2->velocity); float closing_velocity = (collision_velocity1 - collision_velocity2); float coefficient_of_restitution = (c.physics_object1->restitution_coefficient + c.physics_object2->restitution_coefficient)/2.0; c.physics_object1->velocity = -c.collision_normal*closing_velocity*(c.physics_object1->inv_mass/(c.physics_object1->inv_mass + c.physics_object2->inv_mass))*(-(1+coefficient_of_restitution)) + c.physics_object1->velocity; c.physics_object2->velocity = c.collision_normal*closing_velocity*(c.physics_object2->inv_mass/(c.physics_object1->inv_mass + c.physics_object2->inv_mass))*(-(1+coefficient_of_restitution)) + c.physics_object2->velocity; #ifdef DEBUG float energyLoss = 0.5f * (CMath<float>::pow(coefficient_of_restitution, 2) - 1) * CMath<float>::pow(collision_velocity1 - collision_velocity2, 2) / (c.physics_object1->inv_mass + c.physics_object2->inv_mass); float eKin2 = 0; if (c.physics_object1->inv_mass > 0) { eKin2 += 0.5f / c.physics_object1->inv_mass * c.physics_object1->velocity.getLength2(); } if (c.physics_object2->inv_mass > 0) { eKin2 += 0.5f / c.physics_object2->inv_mass * c.physics_object2->velocity.getLength2(); } // |(eKin2 - eKin1) / energyLoss| > 1/1000 -> Energy conservation problem if (fabs(fabs(eKin2 - eKin1) - fabs(energyLoss)) > (1.0f/1000) * fabs(energyLoss)) { std::cout << "ENERGY CONSERVATION ERROR" << std::endl; std::cout << "Lost energy should be " << energyLoss << "J but is " << (eKin2 - eKin1) << "J!" << std::endl; std::cout << "Difference: " << fabs(eKin2 - eKin1) - fabs(energyLoss) << "J" << std::endl; } #endif #endif } else if ((c.physics_object1->friction_disabled && c.physics_object2->friction_disabled) #if !WORKSHEET_7 || 1 #endif ) { #if WORKSHEET_6 #endif } else { #if WORKSHEET_7 #endif } // DAMPING TEST #if 0 c.physics_object1->velocity -= c.physics_object1->velocity*frame_elapsed_time*0.5; c.physics_object2->velocity -= c.physics_object2->velocity*frame_elapsed_time*0.5; c.physics_object1->angular_velocity -= c.physics_object1->angular_velocity*frame_elapsed_time*0.5; c.physics_object2->angular_velocity -= c.physics_object2->angular_velocity*frame_elapsed_time*0.5; #endif #if 0 if (c.physics_object1->velocity.getLength() < 0.5) c.physics_object1->velocity.setZero(); if (c.physics_object2->velocity.getLength() < 0.5) c.physics_object2->velocity.setZero(); if (c.physics_object1->angular_velocity.getLength() < 0.2) c.physics_object1->angular_velocity.setZero(); if (c.physics_object2->angular_velocity.getLength() < 0.2) c.physics_object2->angular_velocity.setZero(); #endif } }; #endif <|endoftext|>
<commit_before>#include "net/telnet.h" #include <arpa/telnet.h> namespace { std::string trim(std::string const& str) { // Find the first non-whitespace character auto first = std::find_if(std::begin(str), std::end(str), [](char const& c) { return !std::isspace(c); }); // Find the last non-whitespace character auto last = std::find_if(std::rbegin(str), std::rend(str), [](char const& c) { return !std::isspace(c); }); size_t first_pos = first != std::end(str) ? first - std::begin(str) : 0; size_t length = last != std::rend(str) ? (std::rend(str) - last) - first_pos : str.length(); return str.substr(first_pos, length); } } static constexpr std::size_t telnet_option_count = 256; struct rethinkmud::net::connections::telnet::telnet_info { // What we do, and don't do bool options[telnet_option_count] = { false }; // Options we have sent and are waiting for reply on bool sent_will[telnet_option_count] = { false }; bool sent_wont[telnet_option_count] = { false }; bool sent_do[telnet_option_count] = { false }; bool sent_dont[telnet_option_count] = { false }; }; void rethinkmud::net::connections::telnet::telnet_info_deleter::operator()(telnet_info* info) { delete info; } void rethinkmud::net::connections::telnet::start() { std::clog << "Starting telnet connection\n"; info_.reset(new telnet_info); tcp::start(); } void rethinkmud::net::connections::telnet::input(std::vector<char> data) { // Parse the input for telnet command sequence // Copy the non-telnet data to a new container // For now we assume that all sequences are complete std::string input = buffer_; buffer_ = ""; // Clear the saved buffer from last call for (auto i = std::begin(data); i != std::end(data); ++i) { if (static_cast<uint8_t>(*i) == IAC) { uint8_t command = static_cast<uint8_t>(*++i); // TODO: Handle all this switch (command) { case DO: case DONT: case WILL: case WONT: handle_option(command, *++i); break; case SB: break; case AYT: break; default: break; } } else input += *i; } if (input.empty()) return; std::istringstream iss{input}; std::string line; while (std::getline(iss, line)) { if (iss.eof()) { // Not a complete line at the end of the buffer, save the data for the next call to this function buffer_ = line; } else { // Trim leading and trailing white-space line = trim(line); if (line == "echo off") echo_off(); else if (line == "echo on") echo_on(); else write("You wrote: " + line + "\r\n"); // TODO: Add input line to queue } } } void rethinkmud::net::connections::telnet::send_option(uint8_t command, uint8_t option) { uint8_t const data[] = { IAC, command, option }; write(data, sizeof(data)); } void rethinkmud::net::connections::telnet::send_do(uint8_t option) { if (!info_->sent_do[option]) { send_option(DO, option); info_->sent_do[option] = true; } } void rethinkmud::net::connections::telnet::send_dont(uint8_t option) { if (!info_->sent_dont[option]) { send_option(DONT, option); info_->sent_dont[option] = true; } } void rethinkmud::net::connections::telnet::send_will(uint8_t option) { if (!info_->sent_will[option]) { send_option(WILL, option); info_->sent_will[option] = true; } } void rethinkmud::net::connections::telnet::send_wont(uint8_t option) { if (!info_->sent_wont[option]) { send_option(WONT, option); info_->sent_wont[option] = true; } } void rethinkmud::net::connections::telnet::echo_on() { send_wont(TELOPT_ECHO); send_do(TELOPT_ECHO); } void rethinkmud::net::connections::telnet::echo_off() { send_will(TELOPT_ECHO); send_dont(TELOPT_ECHO); } void rethinkmud::net::connections::telnet::handle_option(uint8_t command, uint8_t option) { // TODO: Handle all this switch (command) { case DO: if (info_->sent_will[option]) { } else if (info_->sent_wont[option]) { } else { send_wont(option); } break; case DONT: if (info_->sent_will[option]) { } else if (info_->sent_wont[option]) { } else { send_wont(option); } break; case WILL: if (info_->sent_do[option]) { } else if (info_->sent_dont[option]) { } else { send_dont(option); } break; case WONT: if (info_->sent_do[option]) { } else if (info_->sent_dont[option]) { } else { send_dont(option); } break; } } <commit_msg>Slight modification of the buffering<commit_after>#include "net/telnet.h" #include <arpa/telnet.h> namespace { std::string trim(std::string const& str) { // Find the first non-whitespace character auto first = std::find_if(std::begin(str), std::end(str), [](char const& c) { return !std::isspace(c); }); // Find the last non-whitespace character auto last = std::find_if(std::rbegin(str), std::rend(str), [](char const& c) { return !std::isspace(c); }); size_t first_pos = first != std::end(str) ? first - std::begin(str) : 0; size_t length = last != std::rend(str) ? (std::rend(str) - last) - first_pos : str.length(); return str.substr(first_pos, length); } } static constexpr std::size_t telnet_option_count = 256; struct rethinkmud::net::connections::telnet::telnet_info { // What we do, and don't do bool options[telnet_option_count] = { false }; // Options we have sent and are waiting for reply on bool sent_will[telnet_option_count] = { false }; bool sent_wont[telnet_option_count] = { false }; bool sent_do[telnet_option_count] = { false }; bool sent_dont[telnet_option_count] = { false }; }; void rethinkmud::net::connections::telnet::telnet_info_deleter::operator()(telnet_info* info) { delete info; } void rethinkmud::net::connections::telnet::start() { std::clog << "Starting telnet connection\n"; info_.reset(new telnet_info); tcp::start(); } void rethinkmud::net::connections::telnet::input(std::vector<char> data) { // Parse the input for telnet command sequence // Copy the non-telnet data to a new container // For now we assume that all sequences are complete std::string input; if (!buffer_.empty()) { input = buffer_; buffer_ = ""; // Clear the saved buffer from last call } for (auto i = std::begin(data); i != std::end(data); ++i) { if (static_cast<uint8_t>(*i) == IAC) { uint8_t command = static_cast<uint8_t>(*++i); // TODO: Handle all this switch (command) { case DO: case DONT: case WILL: case WONT: handle_option(command, *++i); break; case SB: break; case AYT: break; default: break; } } else input += *i; } if (input.empty()) return; std::istringstream iss{input}; std::string line; while (std::getline(iss, line)) { if (iss.eof()) { // Not a complete line at the end of the buffer, save the data for the next call to this function buffer_ = line; } else { // Trim leading and trailing white-space line = trim(line); if (line == "echo off") echo_off(); else if (line == "echo on") echo_on(); else write("You wrote: " + line + "\r\n"); // TODO: Add input line to queue } } } void rethinkmud::net::connections::telnet::send_option(uint8_t command, uint8_t option) { uint8_t const data[] = { IAC, command, option }; write(data, sizeof(data)); } void rethinkmud::net::connections::telnet::send_do(uint8_t option) { if (!info_->sent_do[option]) { send_option(DO, option); info_->sent_do[option] = true; } } void rethinkmud::net::connections::telnet::send_dont(uint8_t option) { if (!info_->sent_dont[option]) { send_option(DONT, option); info_->sent_dont[option] = true; } } void rethinkmud::net::connections::telnet::send_will(uint8_t option) { if (!info_->sent_will[option]) { send_option(WILL, option); info_->sent_will[option] = true; } } void rethinkmud::net::connections::telnet::send_wont(uint8_t option) { if (!info_->sent_wont[option]) { send_option(WONT, option); info_->sent_wont[option] = true; } } void rethinkmud::net::connections::telnet::echo_on() { send_wont(TELOPT_ECHO); send_do(TELOPT_ECHO); } void rethinkmud::net::connections::telnet::echo_off() { send_will(TELOPT_ECHO); send_dont(TELOPT_ECHO); } void rethinkmud::net::connections::telnet::handle_option(uint8_t command, uint8_t option) { // TODO: Handle all this switch (command) { case DO: if (info_->sent_will[option]) { } else if (info_->sent_wont[option]) { } else { send_wont(option); } break; case DONT: if (info_->sent_will[option]) { } else if (info_->sent_wont[option]) { } else { send_wont(option); } break; case WILL: if (info_->sent_do[option]) { } else if (info_->sent_dont[option]) { } else { send_dont(option); } break; case WONT: if (info_->sent_do[option]) { } else if (info_->sent_dont[option]) { } else { send_dont(option); } break; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2011, Nathan Rajlich <nathan@tootallnate.net> * * 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 <v8.h> #include <node.h> #include <node_buffer.h> #include <mpg123.h> using namespace v8; using namespace node; namespace nodelame { #define UNWRAP_MH \ HandleScope scope; \ Local<Object>wrapper = args[0]->ToObject(); \ mpg123_handle *mh = (mpg123_handle *)wrapper->GetPointerFromInternalField(0); /* Wrapper ObjectTemplate to hold `mpg123_handle` instances */ Persistent<ObjectTemplate> mhClass; Handle<Value> node_mpg123_init (const Arguments& args) { HandleScope scope; return scope.Close(Integer::New(mpg123_init())); } Handle<Value> node_mpg123_exit (const Arguments& args) { HandleScope scope; mpg123_exit(); return Undefined(); } void mh_weak_callback (Persistent<Value> wrapper, void *arg) { HandleScope scope; mpg123_handle *mh = (mpg123_handle *)arg; mpg123_delete(mh); wrapper.Dispose(); } Handle<Value> node_mpg123_new (const Arguments& args) { HandleScope scope; int error = 0; mpg123_handle *mh = mpg123_new(NULL, &error); Handle<Value> rtn; if (error == MPG123_OK) { Persistent<Object> o = Persistent<Object>::New(mhClass->NewInstance()); o->SetPointerInInternalField(0, mh); o.MakeWeak(mh, mh_weak_callback); rtn = o; } else { rtn = Integer::New(error); } return scope.Close(rtn); } Handle<Value> node_mpg123_current_decoder (const Arguments& args) { UNWRAP_MH; const char *decoder = mpg123_current_decoder(mh); return scope.Close(String::New(decoder)); } Handle<Value> node_mpg123_supported_decoders (const Arguments& args) { HandleScope scope; const char **decoders = mpg123_supported_decoders(); int i = 0; Handle<Array> rtn = Array::New(); while (*decoders != NULL) { rtn->Set(Integer::New(i++), String::New(*decoders)); decoders++; } return scope.Close(rtn); } Handle<Value> node_mpg123_decoders (const Arguments& args) { HandleScope scope; const char **decoders = mpg123_decoders(); int i = 0; Handle<Array> rtn = Array::New(); while (*decoders != NULL) { rtn->Set(Integer::New(i++), String::New(*decoders)); decoders++; } return scope.Close(rtn); } // TODO: Make async Handle<Value> node_mpg123_open_feed (const Arguments& args) { UNWRAP_MH; int ret = mpg123_open_feed(mh); return scope.Close(Integer::New(ret)); } // TODO: Make async Handle<Value> node_mpg123_decode (const Arguments& args) { UNWRAP_MH; // input MP3 data const unsigned char *input = (const unsigned char *)Buffer::Data(args[1]->ToObject()); size_t insize = args[2]->Int32Value(); // the output buffer Local<Object> outbuf = args[3]->ToObject(); int out_offset = args[4]->Int32Value(); unsigned char *output = (unsigned char *)(Buffer::Data(outbuf) + out_offset); size_t outsize = args[5]->Int32Value(); size_t size = 0; int ret = mpg123_decode(mh, input, insize, output, outsize, &size); Local<Object> rtn = Object::New(); rtn->Set(String::NewSymbol("ret"), Integer::New(ret)); rtn->Set(String::NewSymbol("size"), Integer::New(size)); return scope.Close(rtn); } void InitMPG123(Handle<Object> target) { HandleScope scope; mhClass = Persistent<ObjectTemplate>::New(ObjectTemplate::New()); mhClass->SetInternalFieldCount(1); #define CONST_INT(value) \ target->Set(String::NewSymbol(#value), Integer::New(value), \ static_cast<PropertyAttribute>(ReadOnly|DontDelete)); // mpg123_errors CONST_INT(MPG123_DONE); /**< Message: Track ended. Stop decoding. */ CONST_INT(MPG123_NEW_FORMAT); /**< Message: Output format will be different on next call. Note that some libmpg123 versions between 1.4.3 and 1.8.0 insist on you calling mpg123_getformat() after getting this message code. Newer verisons behave like advertised: You have the chance to call mpg123_getformat(), but you can also just continue decoding and get your data. */ CONST_INT(MPG123_NEED_MORE); /**< Message: For feed reader: "Feed me more!" (call mpg123_feed() or mpg123_decode() with some new input data). */ CONST_INT(MPG123_ERR); /**< Generic Error */ CONST_INT(MPG123_OK); /**< Success */ CONST_INT(MPG123_BAD_OUTFORMAT); /**< Unable to set up output format! */ CONST_INT(MPG123_BAD_CHANNEL); /**< Invalid channel number specified. */ CONST_INT(MPG123_BAD_RATE); /**< Invalid sample rate specified. */ CONST_INT(MPG123_ERR_16TO8TABLE); /**< Unable to allocate memory for 16 to 8 converter table! */ CONST_INT(MPG123_BAD_PARAM); /**< Bad parameter id! */ CONST_INT(MPG123_BAD_BUFFER); /**< Bad buffer given -- invalid pointer or too small size. */ CONST_INT(MPG123_OUT_OF_MEM); /**< Out of memory -- some malloc() failed. */ CONST_INT(MPG123_NOT_INITIALIZED); /**< You didn't initialize the library! */ CONST_INT(MPG123_BAD_DECODER); /**< Invalid decoder choice. */ CONST_INT(MPG123_BAD_HANDLE); /**< Invalid mpg123 handle. */ CONST_INT(MPG123_NO_BUFFERS); /**< Unable to initialize frame buffers (out of memory?). */ CONST_INT(MPG123_BAD_RVA); /**< Invalid RVA mode. */ CONST_INT(MPG123_NO_GAPLESS); /**< This build doesn't support gapless decoding. */ CONST_INT(MPG123_NO_SPACE); /**< Not enough buffer space. */ CONST_INT(MPG123_BAD_TYPES); /**< Incompatible numeric data types. */ CONST_INT(MPG123_BAD_BAND); /**< Bad equalizer band. */ CONST_INT(MPG123_ERR_NULL); /**< Null pointer given where valid storage address needed. */ CONST_INT(MPG123_ERR_READER); /**< Error reading the stream. */ CONST_INT(MPG123_NO_SEEK_FROM_END);/**< Cannot seek from end (end is not known). */ CONST_INT(MPG123_BAD_WHENCE); /**< Invalid 'whence' for seek function.*/ CONST_INT(MPG123_NO_TIMEOUT); /**< Build does not support stream timeouts. */ CONST_INT(MPG123_BAD_FILE); /**< File access error. */ CONST_INT(MPG123_NO_SEEK); /**< Seek not supported by stream. */ CONST_INT(MPG123_NO_READER); /**< No stream opened. */ CONST_INT(MPG123_BAD_PARS); /**< Bad parameter handle. */ CONST_INT(MPG123_BAD_INDEX_PAR); /**< Bad parameters to mpg123_index() and mpg123_set_index() */ CONST_INT(MPG123_OUT_OF_SYNC); /**< Lost track in bytestream and did not try to resync. */ CONST_INT(MPG123_RESYNC_FAIL); /**< Resync failed to find valid MPEG data. */ CONST_INT(MPG123_NO_8BIT); /**< No 8bit encoding possible. */ CONST_INT(MPG123_BAD_ALIGN); /**< Stack aligmnent error */ CONST_INT(MPG123_NULL_BUFFER); /**< NULL input buffer with non-zero size... */ CONST_INT(MPG123_NO_RELSEEK); /**< Relative seek not possible (screwed up file offset) */ CONST_INT(MPG123_NULL_POINTER); /**< You gave a null pointer somewhere where you shouldn't have. */ CONST_INT(MPG123_BAD_KEY); /**< Bad key value given. */ CONST_INT(MPG123_NO_INDEX); /**< No frame index in this build. */ CONST_INT(MPG123_INDEX_FAIL); /**< Something with frame index went wrong. */ CONST_INT(MPG123_BAD_DECODER_SETUP); /**< Something prevents a proper decoder setup */ CONST_INT(MPG123_MISSING_FEATURE); /**< This feature has not been built into libmpg123. */ CONST_INT(MPG123_BAD_VALUE); /**< A bad value has been given, somewhere. */ CONST_INT(MPG123_LSEEK_FAILED); /**< Low-level seek failed. */ CONST_INT(MPG123_BAD_CUSTOM_IO); /**< Custom I/O not prepared. */ CONST_INT(MPG123_LFS_OVERFLOW); /**< Offset value overflow during translation of large file API calls -- your client program cannot handle that large file. */ /* mpg123_channelcount */ CONST_INT(MPG123_MONO); CONST_INT(MPG123_STEREO); // mpg123_channels CONST_INT(MPG123_LEFT); CONST_INT(MPG123_RIGHT); CONST_INT(MPG123_LR); CONST_INT(MPG123_ID3); CONST_INT(MPG123_NEW_ID3); CONST_INT(MPG123_ICY); CONST_INT(MPG123_NEW_ICY); NODE_SET_METHOD(target, "mpg123_init", node_mpg123_init); NODE_SET_METHOD(target, "mpg123_exit", node_mpg123_exit); NODE_SET_METHOD(target, "mpg123_new", node_mpg123_new); NODE_SET_METHOD(target, "mpg123_decoders", node_mpg123_decoders); NODE_SET_METHOD(target, "mpg123_current_decoder", node_mpg123_current_decoder); NODE_SET_METHOD(target, "mpg123_supported_decoders", node_mpg123_supported_decoders); NODE_SET_METHOD(target, "mpg123_open_feed", node_mpg123_open_feed); NODE_SET_METHOD(target, "mpg123_decode", node_mpg123_decode); } } // nodelame namespace <commit_msg>Add a couple TODOs.<commit_after>/* * Copyright (c) 2011, Nathan Rajlich <nathan@tootallnate.net> * * 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 <v8.h> #include <node.h> #include <node_buffer.h> #include <mpg123.h> using namespace v8; using namespace node; namespace nodelame { #define UNWRAP_MH \ HandleScope scope; \ Local<Object>wrapper = args[0]->ToObject(); \ mpg123_handle *mh = (mpg123_handle *)wrapper->GetPointerFromInternalField(0); /* Wrapper ObjectTemplate to hold `mpg123_handle` instances */ Persistent<ObjectTemplate> mhClass; Handle<Value> node_mpg123_init (const Arguments& args) { HandleScope scope; return scope.Close(Integer::New(mpg123_init())); } Handle<Value> node_mpg123_exit (const Arguments& args) { HandleScope scope; mpg123_exit(); return Undefined(); } void mh_weak_callback (Persistent<Value> wrapper, void *arg) { HandleScope scope; mpg123_handle *mh = (mpg123_handle *)arg; mpg123_delete(mh); wrapper.Dispose(); } // TODO: Make async Handle<Value> node_mpg123_new (const Arguments& args) { HandleScope scope; // TODO: Accept an input decoder String int error = 0; mpg123_handle *mh = mpg123_new(NULL, &error); Handle<Value> rtn; if (error == MPG123_OK) { Persistent<Object> o = Persistent<Object>::New(mhClass->NewInstance()); o->SetPointerInInternalField(0, mh); o.MakeWeak(mh, mh_weak_callback); rtn = o; } else { rtn = Integer::New(error); } return scope.Close(rtn); } Handle<Value> node_mpg123_current_decoder (const Arguments& args) { UNWRAP_MH; const char *decoder = mpg123_current_decoder(mh); return scope.Close(String::New(decoder)); } Handle<Value> node_mpg123_supported_decoders (const Arguments& args) { HandleScope scope; const char **decoders = mpg123_supported_decoders(); int i = 0; Handle<Array> rtn = Array::New(); while (*decoders != NULL) { rtn->Set(Integer::New(i++), String::New(*decoders)); decoders++; } return scope.Close(rtn); } Handle<Value> node_mpg123_decoders (const Arguments& args) { HandleScope scope; const char **decoders = mpg123_decoders(); int i = 0; Handle<Array> rtn = Array::New(); while (*decoders != NULL) { rtn->Set(Integer::New(i++), String::New(*decoders)); decoders++; } return scope.Close(rtn); } // TODO: Make async Handle<Value> node_mpg123_open_feed (const Arguments& args) { UNWRAP_MH; int ret = mpg123_open_feed(mh); return scope.Close(Integer::New(ret)); } // TODO: Make async Handle<Value> node_mpg123_decode (const Arguments& args) { UNWRAP_MH; // input MP3 data const unsigned char *input = (const unsigned char *)Buffer::Data(args[1]->ToObject()); size_t insize = args[2]->Int32Value(); // the output buffer Local<Object> outbuf = args[3]->ToObject(); int out_offset = args[4]->Int32Value(); unsigned char *output = (unsigned char *)(Buffer::Data(outbuf) + out_offset); size_t outsize = args[5]->Int32Value(); size_t size = 0; int ret = mpg123_decode(mh, input, insize, output, outsize, &size); Local<Object> rtn = Object::New(); rtn->Set(String::NewSymbol("ret"), Integer::New(ret)); rtn->Set(String::NewSymbol("size"), Integer::New(size)); return scope.Close(rtn); } void InitMPG123(Handle<Object> target) { HandleScope scope; mhClass = Persistent<ObjectTemplate>::New(ObjectTemplate::New()); mhClass->SetInternalFieldCount(1); #define CONST_INT(value) \ target->Set(String::NewSymbol(#value), Integer::New(value), \ static_cast<PropertyAttribute>(ReadOnly|DontDelete)); // mpg123_errors CONST_INT(MPG123_DONE); /**< Message: Track ended. Stop decoding. */ CONST_INT(MPG123_NEW_FORMAT); /**< Message: Output format will be different on next call. Note that some libmpg123 versions between 1.4.3 and 1.8.0 insist on you calling mpg123_getformat() after getting this message code. Newer verisons behave like advertised: You have the chance to call mpg123_getformat(), but you can also just continue decoding and get your data. */ CONST_INT(MPG123_NEED_MORE); /**< Message: For feed reader: "Feed me more!" (call mpg123_feed() or mpg123_decode() with some new input data). */ CONST_INT(MPG123_ERR); /**< Generic Error */ CONST_INT(MPG123_OK); /**< Success */ CONST_INT(MPG123_BAD_OUTFORMAT); /**< Unable to set up output format! */ CONST_INT(MPG123_BAD_CHANNEL); /**< Invalid channel number specified. */ CONST_INT(MPG123_BAD_RATE); /**< Invalid sample rate specified. */ CONST_INT(MPG123_ERR_16TO8TABLE); /**< Unable to allocate memory for 16 to 8 converter table! */ CONST_INT(MPG123_BAD_PARAM); /**< Bad parameter id! */ CONST_INT(MPG123_BAD_BUFFER); /**< Bad buffer given -- invalid pointer or too small size. */ CONST_INT(MPG123_OUT_OF_MEM); /**< Out of memory -- some malloc() failed. */ CONST_INT(MPG123_NOT_INITIALIZED); /**< You didn't initialize the library! */ CONST_INT(MPG123_BAD_DECODER); /**< Invalid decoder choice. */ CONST_INT(MPG123_BAD_HANDLE); /**< Invalid mpg123 handle. */ CONST_INT(MPG123_NO_BUFFERS); /**< Unable to initialize frame buffers (out of memory?). */ CONST_INT(MPG123_BAD_RVA); /**< Invalid RVA mode. */ CONST_INT(MPG123_NO_GAPLESS); /**< This build doesn't support gapless decoding. */ CONST_INT(MPG123_NO_SPACE); /**< Not enough buffer space. */ CONST_INT(MPG123_BAD_TYPES); /**< Incompatible numeric data types. */ CONST_INT(MPG123_BAD_BAND); /**< Bad equalizer band. */ CONST_INT(MPG123_ERR_NULL); /**< Null pointer given where valid storage address needed. */ CONST_INT(MPG123_ERR_READER); /**< Error reading the stream. */ CONST_INT(MPG123_NO_SEEK_FROM_END);/**< Cannot seek from end (end is not known). */ CONST_INT(MPG123_BAD_WHENCE); /**< Invalid 'whence' for seek function.*/ CONST_INT(MPG123_NO_TIMEOUT); /**< Build does not support stream timeouts. */ CONST_INT(MPG123_BAD_FILE); /**< File access error. */ CONST_INT(MPG123_NO_SEEK); /**< Seek not supported by stream. */ CONST_INT(MPG123_NO_READER); /**< No stream opened. */ CONST_INT(MPG123_BAD_PARS); /**< Bad parameter handle. */ CONST_INT(MPG123_BAD_INDEX_PAR); /**< Bad parameters to mpg123_index() and mpg123_set_index() */ CONST_INT(MPG123_OUT_OF_SYNC); /**< Lost track in bytestream and did not try to resync. */ CONST_INT(MPG123_RESYNC_FAIL); /**< Resync failed to find valid MPEG data. */ CONST_INT(MPG123_NO_8BIT); /**< No 8bit encoding possible. */ CONST_INT(MPG123_BAD_ALIGN); /**< Stack aligmnent error */ CONST_INT(MPG123_NULL_BUFFER); /**< NULL input buffer with non-zero size... */ CONST_INT(MPG123_NO_RELSEEK); /**< Relative seek not possible (screwed up file offset) */ CONST_INT(MPG123_NULL_POINTER); /**< You gave a null pointer somewhere where you shouldn't have. */ CONST_INT(MPG123_BAD_KEY); /**< Bad key value given. */ CONST_INT(MPG123_NO_INDEX); /**< No frame index in this build. */ CONST_INT(MPG123_INDEX_FAIL); /**< Something with frame index went wrong. */ CONST_INT(MPG123_BAD_DECODER_SETUP); /**< Something prevents a proper decoder setup */ CONST_INT(MPG123_MISSING_FEATURE); /**< This feature has not been built into libmpg123. */ CONST_INT(MPG123_BAD_VALUE); /**< A bad value has been given, somewhere. */ CONST_INT(MPG123_LSEEK_FAILED); /**< Low-level seek failed. */ CONST_INT(MPG123_BAD_CUSTOM_IO); /**< Custom I/O not prepared. */ CONST_INT(MPG123_LFS_OVERFLOW); /**< Offset value overflow during translation of large file API calls -- your client program cannot handle that large file. */ /* mpg123_channelcount */ CONST_INT(MPG123_MONO); CONST_INT(MPG123_STEREO); // mpg123_channels CONST_INT(MPG123_LEFT); CONST_INT(MPG123_RIGHT); CONST_INT(MPG123_LR); CONST_INT(MPG123_ID3); CONST_INT(MPG123_NEW_ID3); CONST_INT(MPG123_ICY); CONST_INT(MPG123_NEW_ICY); NODE_SET_METHOD(target, "mpg123_init", node_mpg123_init); NODE_SET_METHOD(target, "mpg123_exit", node_mpg123_exit); NODE_SET_METHOD(target, "mpg123_new", node_mpg123_new); NODE_SET_METHOD(target, "mpg123_decoders", node_mpg123_decoders); NODE_SET_METHOD(target, "mpg123_current_decoder", node_mpg123_current_decoder); NODE_SET_METHOD(target, "mpg123_supported_decoders", node_mpg123_supported_decoders); NODE_SET_METHOD(target, "mpg123_open_feed", node_mpg123_open_feed); NODE_SET_METHOD(target, "mpg123_decode", node_mpg123_decode); } } // nodelame namespace <|endoftext|>
<commit_before>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file object/list-class.cc ** \brief Creation of the URBI object list. */ #include <libport/bind.hh> #include <libport/foreach.hh> #include <libport/lexical-cast.hh> #include <libport/finally.hh> #include <libport/ufloat.hh> #include <kernel/userver.hh> #include <object/cxx-helper.hh> #include <object/symbols.hh> #include <urbi/object/code.hh> #include <urbi/object/float.hh> #include <urbi/object/list.hh> #include <urbi/object/object.hh> #include <runner/raise.hh> #include <runner/runner.hh> #include <runner/interpreter.hh> namespace urbi { namespace object { List::List() { proto_add(proto ? proto : Object::proto); } List::List(const value_type& value) : content_(value) { proto_add(List::proto); } List::List(const rList& model) : content_(model->content_) { proto_add(List::proto); } const List::value_type& List::value_get() const { return content_; } List::value_type& List::value_get() { return content_; } #define CHECK_NON_EMPTY(Name) \ do { \ if (content_.empty()) \ RAISE("cannot be applied onto empty list"); \ } while (0) rList List::tail() { CHECK_NON_EMPTY(tail); value_type res = content_; libport::pop_front(res); return new List(res); } bool List::as_bool() const { return !empty(); } bool List::empty() const { return content_.empty(); } List::size_type List::index(const rFloat& idx) const { int i = idx->to_int("invalid index: %s"); if (i < 0) i += content_.size(); if (i < 0 || content_.size() <= static_cast<size_type>(i)) RAISE("invalid index: " + string_cast(idx->value_get())); return static_cast<size_type>(i); } rObject List::operator[](const rFloat& idx) { return content_[index(idx)]; } rObject List::set(const rFloat& idx, const rObject& val) { return content_[index(idx)] = val; } rFloat List::size() { return new Float(content_.size()); } rList List::remove_by_id(const rObject& elt) { value_type::iterator it = content_.begin(); while (it != content_.end()) if (*it == elt) it = content_.erase(it); else ++it; return this; } rList List::operator+=(const rList& rhs) { // Copy the list to make a += a work value_type other = rhs->value_get(); foreach (const rObject& o, other) content_.push_back(o); return this; } rList List::operator+(const rList& rhs) { rList res = new List(this); *res += rhs; return res; } rList List::operator*(unsigned int times) { List::value_type res; unsigned int s = content_.size(); for (unsigned int i = 0; i < times; ++i) for (unsigned int j = 0; j < s; ++j) res.push_back(content_[j]); return new List(res); } /// Binary predicates used to sort lists. static bool compareListItems (const rObject& a, const rObject& b) { return a->call(SYMBOL(LT), b)->as_bool(); } static bool compareListItemsLambda (const rObject& f, const rObject& l, const rObject& a, const rObject& b) { rExecutable fun = f.unsafe_cast<Executable>(); if (!fun) { type_check<Code>(f); unreached(); } objects_type args; args << l; args << a; args << b; return (*fun)(args)->as_bool(); } List::value_type List::sort() { value_type s(content_); std::sort(s.begin(), s.end(), boost::bind(compareListItems, _1, _2)); return s; } List::value_type List::sort(rObject f) { value_type s(content_); std::sort(s.begin(), s.end(), boost::bind(compareListItemsLambda, f, this, _1, _2)); return s; } void List::each_common(const rObject& f, bool yielding) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); // Beware of iterations that modify the list in place: make a // copy. bool must_yield = false; foreach (const rObject& o, value_type(content_)) { if (must_yield) r.yield(); must_yield = yielding; objects_type args; args.push_back(f); args.push_back(o); r.apply(f, SYMBOL(each), args); } } void List::each(const rObject& f) { each_common(f, true); } void List::each_pipe(const rObject& f) { each_common(f, false); } void List::each_and(const rObject& f) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); // Beware of iterations that modify the list in place: make a // copy. value_type l(content_); sched::Job::Collector collector(&r, l.size()); foreach (const rObject& o, l) { object::objects_type args; args.push_back(o); sched::rJob job = new runner::Interpreter(dynamic_cast<runner::Interpreter&>(r), f, SYMBOL(each_AMPERSAND), args); r.register_child(job, children); job->start_job(); } try { r.yield_until_terminated(collector); } catch (const sched::ChildException& ce) { ce.rethrow_child_exception(); } } rList List::insertFront(const rObject& o) { libport::push_front(content_, o); return this; } #define BOUNCE(Name, Bounce, Ret, Arg, Check) \ IF(Ret, rObject, rList) \ List::Name(WHEN(Arg, const rObject& arg)) \ { \ WHEN(Check, CHECK_NON_EMPTY(Name)); \ WHEN(Ret, return) content_.Bounce(WHEN(Arg, arg)); \ return this; \ } BOUNCE(back, back, true, false, true ); BOUNCE(clear, clear, false, false, false); BOUNCE(front, front, true, false, true ); BOUNCE(insertBack, push_back, false, true, false); #undef BOUNCE rList List::insert(const rFloat& idx, const rObject& elt) { size_type i = index(idx); value_type::iterator b = content_.begin(); while(i--) ++b; content_.insert(b, elt); return this; } // FIXME: Really looks like String::join, we should find a means to // factor both. std::string List::asString() const { std::string res = "["; bool tail = false; foreach (const rObject& o, content_) { if (tail++) res += ", "; res += o->call(SYMBOL(asPrintable))->as<String>()->value_get(); } res += "]"; return res; } rObject List::removeBack() { CHECK_NON_EMPTY(pop_back); rObject res = content_.back(); content_.pop_back(); return res; } rObject List::removeFront() { CHECK_NON_EMPTY(pop_front); rObject res = content_.front(); libport::pop_front(content_); return res; } rList List::reverse() { value_type res; rforeach (const rObject& obj, content_) res.push_back(obj); return new List(res); } OVERLOAD_2(sort_bouncer, 1, (List::value_type (List::*) ()) &List::sort, (List::value_type (List::*) (rObject f)) &List::sort) void List::initialize(CxxObject::Binder<List>& bind) { #define DECLARE(Name, Function) \ bind(SYMBOL(Name), &List::Function) DECLARE(asBool, as_bool ); DECLARE(asString, asString ); DECLARE(back, back ); DECLARE(clear, clear ); DECLARE(each, each ); DECLARE(each_AMPERSAND, each_and ); DECLARE(each_PIPE, each_pipe ); DECLARE(empty, empty ); DECLARE(front, front ); DECLARE(SBL_SBR, operator[] ); DECLARE(SBL_SBR_EQ, set ); DECLARE(PLUS, operator+ ); DECLARE(PLUS_EQ, operator+= ); DECLARE(insert, insert ); DECLARE(insertBack, insertBack ); DECLARE(insertFront, insertFront ); DECLARE(removeBack, removeBack ); DECLARE(removeFront, removeFront ); DECLARE(removeById, remove_by_id ); DECLARE(reverse, reverse ); DECLARE(size, size ); DECLARE(STAR, operator* ); DECLARE(tail, tail ); #undef DECLARE bind(SYMBOL(sort), &sort_bouncer ); } URBI_CXX_OBJECT_REGISTER(List) {} } // namespace object } <commit_msg>Typo.<commit_after>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file object/list-class.cc ** \brief Creation of the URBI object list. */ #include <libport/bind.hh> #include <libport/foreach.hh> #include <libport/lexical-cast.hh> #include <libport/finally.hh> #include <libport/ufloat.hh> #include <kernel/userver.hh> #include <object/cxx-helper.hh> #include <object/symbols.hh> #include <urbi/object/code.hh> #include <urbi/object/float.hh> #include <urbi/object/list.hh> #include <urbi/object/object.hh> #include <runner/raise.hh> #include <runner/runner.hh> #include <runner/interpreter.hh> namespace urbi { namespace object { List::List() { proto_add(proto ? proto : Object::proto); } List::List(const value_type& value) : content_(value) { proto_add(List::proto); } List::List(const rList& model) : content_(model->content_) { proto_add(List::proto); } const List::value_type& List::value_get() const { return content_; } List::value_type& List::value_get() { return content_; } #define CHECK_NON_EMPTY(Name) \ do { \ if (content_.empty()) \ RAISE("cannot be applied onto empty list"); \ } while (0) rList List::tail() { CHECK_NON_EMPTY(tail); value_type res = content_; libport::pop_front(res); return new List(res); } bool List::as_bool() const { return !empty(); } bool List::empty() const { return content_.empty(); } List::size_type List::index(const rFloat& idx) const { int i = idx->to_int("invalid index: %s"); if (i < 0) i += content_.size(); if (i < 0 || content_.size() <= static_cast<size_type>(i)) RAISE("invalid index: " + string_cast(idx->value_get())); return static_cast<size_type>(i); } rObject List::operator[](const rFloat& idx) { return content_[index(idx)]; } rObject List::set(const rFloat& idx, const rObject& val) { return content_[index(idx)] = val; } rFloat List::size() { return new Float(content_.size()); } rList List::remove_by_id(const rObject& elt) { value_type::iterator it = content_.begin(); while (it != content_.end()) if (*it == elt) it = content_.erase(it); else ++it; return this; } rList List::operator+=(const rList& rhs) { // Copy the list to make a += a work value_type other = rhs->value_get(); foreach (const rObject& o, other) content_.push_back(o); return this; } rList List::operator+(const rList& rhs) { rList res = new List(this); *res += rhs; return res; } rList List::operator*(unsigned int times) { List::value_type res; unsigned int s = content_.size(); for (unsigned int i = 0; i < times; ++i) for (unsigned int j = 0; j < s; ++j) res.push_back(content_[j]); return new List(res); } /// Binary predicates used to sort lists. static bool compareListItems (const rObject& a, const rObject& b) { return a->call(SYMBOL(LT), b)->as_bool(); } static bool compareListItemsLambda (const rObject& f, const rObject& l, const rObject& a, const rObject& b) { rExecutable fun = f.unsafe_cast<Executable>(); if (!fun) { type_check<Code>(f); unreached(); } objects_type args; args << l; args << a; args << b; return (*fun)(args)->as_bool(); } List::value_type List::sort() { value_type s(content_); std::sort(s.begin(), s.end(), boost::bind(compareListItems, _1, _2)); return s; } List::value_type List::sort(rObject f) { value_type s(content_); std::sort(s.begin(), s.end(), boost::bind(compareListItemsLambda, f, this, _1, _2)); return s; } void List::each_common(const rObject& f, bool yielding) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); // Beware of iterations that modify the list in place: make a // copy. bool must_yield = false; foreach (const rObject& o, value_type(content_)) { if (must_yield) r.yield(); must_yield = yielding; objects_type args; args.push_back(f); args.push_back(o); r.apply(f, SYMBOL(each), args); } } void List::each(const rObject& f) { each_common(f, true); } void List::each_pipe(const rObject& f) { each_common(f, false); } void List::each_and(const rObject& f) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); // Beware of iterations that modify the list in place: make a // copy. value_type l(content_); sched::Job::Collector collector(&r, l.size()); foreach (const rObject& o, l) { object::objects_type args; args.push_back(o); sched::rJob job = new runner::Interpreter(dynamic_cast<runner::Interpreter&>(r), f, SYMBOL(each_AMPERSAND), args); r.register_child(job, collector); job->start_job(); } try { r.yield_until_terminated(collector); } catch (const sched::ChildException& ce) { ce.rethrow_child_exception(); } } rList List::insertFront(const rObject& o) { libport::push_front(content_, o); return this; } #define BOUNCE(Name, Bounce, Ret, Arg, Check) \ IF(Ret, rObject, rList) \ List::Name(WHEN(Arg, const rObject& arg)) \ { \ WHEN(Check, CHECK_NON_EMPTY(Name)); \ WHEN(Ret, return) content_.Bounce(WHEN(Arg, arg)); \ return this; \ } BOUNCE(back, back, true, false, true ); BOUNCE(clear, clear, false, false, false); BOUNCE(front, front, true, false, true ); BOUNCE(insertBack, push_back, false, true, false); #undef BOUNCE rList List::insert(const rFloat& idx, const rObject& elt) { size_type i = index(idx); value_type::iterator b = content_.begin(); while(i--) ++b; content_.insert(b, elt); return this; } // FIXME: Really looks like String::join, we should find a means to // factor both. std::string List::asString() const { std::string res = "["; bool tail = false; foreach (const rObject& o, content_) { if (tail++) res += ", "; res += o->call(SYMBOL(asPrintable))->as<String>()->value_get(); } res += "]"; return res; } rObject List::removeBack() { CHECK_NON_EMPTY(pop_back); rObject res = content_.back(); content_.pop_back(); return res; } rObject List::removeFront() { CHECK_NON_EMPTY(pop_front); rObject res = content_.front(); libport::pop_front(content_); return res; } rList List::reverse() { value_type res; rforeach (const rObject& obj, content_) res.push_back(obj); return new List(res); } OVERLOAD_2(sort_bouncer, 1, (List::value_type (List::*) ()) &List::sort, (List::value_type (List::*) (rObject f)) &List::sort) void List::initialize(CxxObject::Binder<List>& bind) { #define DECLARE(Name, Function) \ bind(SYMBOL(Name), &List::Function) DECLARE(asBool, as_bool ); DECLARE(asString, asString ); DECLARE(back, back ); DECLARE(clear, clear ); DECLARE(each, each ); DECLARE(each_AMPERSAND, each_and ); DECLARE(each_PIPE, each_pipe ); DECLARE(empty, empty ); DECLARE(front, front ); DECLARE(SBL_SBR, operator[] ); DECLARE(SBL_SBR_EQ, set ); DECLARE(PLUS, operator+ ); DECLARE(PLUS_EQ, operator+= ); DECLARE(insert, insert ); DECLARE(insertBack, insertBack ); DECLARE(insertFront, insertFront ); DECLARE(removeBack, removeBack ); DECLARE(removeFront, removeFront ); DECLARE(removeById, remove_by_id ); DECLARE(reverse, reverse ); DECLARE(size, size ); DECLARE(STAR, operator* ); DECLARE(tail, tail ); #undef DECLARE bind(SYMBOL(sort), &sort_bouncer ); } URBI_CXX_OBJECT_REGISTER(List) {} } // namespace object } <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #include <miopen/rnn.hpp> #include <miopen/env.hpp> #include <miopen/util.hpp> #include <miopen/float_equal.hpp> #include <vector> #include <numeric> #include <miopengemm/gemm.hpp> namespace miopen { MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_DIRECT) struct AutoEnableProfiling { AutoEnableProfiling(Handle& x) : h(x) { prev_state = h.IsProfilingEnabled(); h.EnableProfiling(); } ~AutoEnableProfiling() { h.EnableProfiling(prev_state); h.ResetKernelTime(); } private: Handle& h; bool prev_state; }; void RNNDescriptor::RNNForwardTraining(Handle& handle, const int seqLen, // const TensorDescriptor& xDesc, ConstData_t x, // const TensorDescriptor& hxDesc, ConstData_t hx, // const TensorDescriptor& cxDesc, ConstData_t cx, // const TensorDescriptor& wDesc, ConstData_t w, // const TensorDescriptor& yDesc, Data_t y, // const TensorDescriptor& hyDesc, Data_t hy, // const TensorDescriptor& cyDesc, Data_t cy, Data_t workSpace, size_t workSpaceSize, Data_t reserveSpace, size_t reserveSpaceSize, const std::vector<int> &in_n, const int in_h, const int hy_d, const int hy_n, const int hy_h, const int out_h) const {/* if (x == nullptr || w == nullptr || y == nullptr) { MIOPEN_THROW(miopenStatusBadParm); } if (xDesc.GetSize() != yDesc.GetSize() || xDesc.GetSize() != wDesc.GetSize()) { MIOPEN_THROW(miopenStatusBadParm); } if (xDesc.GetType() != yDesc.GetType() || xDesc.GetType() != wDesc.GetType()) { MIOPEN_THROW(miopenStatusBadParm); } */ // int in_n, in_c, in_h, in_w; // std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths()); // int out_h, out_w; // std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths()); /* if (workSpace == nullptr || workSpaceSize < ForwardGetWorkSpaceSize(handle, wDesc, xDesc, yDesc) || reserveSpaceSize < ForwardGetReserveSpaceSize(handle, wDesc, xDesc, yDesc)) { MIOPEN_THROW("Workspace is required"); } */ // miopenRNNMode_t mode; // int seqLength; // int layer; // int bidir; // int bias; int batch_n = std::accumulate(in_n.begin(), in_n.end(), 0); bool bidirection = (bidir != 0); bool biased = (bias != 0); int numlayer = layer; int bacc, baccbi; int bi = bidirection ? 2 : 1; int wei_len = (bi * (in_h + hy_h + out_h) + (numlayer - 1) * bi * (bi + 1) * hy_h) * hy_h; if (biased) { wei_len += (bi * 2 + (numlayer - 1) * bi * (bi + 1)) * hy_h + bi * out_h; } int wei_shift_bias = ((in_h + hy_h + out_h) * bi + (bi * hy_h + hy_h) * bi * (numlayer - 1)) * hy_h; int in_stride = in_h; int hy_stride = hy_h * bi; int out_stride = out_h; int wei_stride = hy_h * bi; if (mode == miopenRNNRELU || mode == miopenRNNTANH) { // std::string network_config; #if MIOPEN_USE_MIOPENGEMM // CreateGemmGeometryConvFwd(xDesc, wDesc, yDesc, false, network_config); // GemmGeometry gg = GetGemmGeometry("miopenConvolutionFwdAlgoGEMM", network_config); /* float time_0 = 0; float t1 = 0; for (int i = 0; i < in_n; i++) { int out_offset = i * wei_n * out_h * out_w; if (wei_h != 1 || wei_w != 1 || v != 1 || u != 1) { size_t in_offset = i * in_c * in_h * in_w; Im2ColGPU(handle, xDesc.GetElementSize(), x, in_offset, in_c, in_h, in_w, wei_h, wei_w, out_h, out_w, pad_h, pad_w, v, u, dilation_h, dilation_w, workSpace); if (handle.IsProfilingEnabled()) t1 = handle.GetKernelTime(); gg.RunGemm(handle, workSpace, w, y, 0, 0, out_offset); // Update times for both the kernels if (handle.IsProfilingEnabled()) { if (i == in_n - 1) handle.AccumKernelTime(t1 + time_0); else handle.AccumKernelTime(t1); time_0 += handle.GetKernelTime(); } } else if (wei_h == 1 && wei_w == 1 && v == 1 && u == 1) { int in_offset = i * in_c * in_h * in_w; gg.RunGemm(handle, x, w, y, in_offset, 0, out_offset); if (handle.IsProfilingEnabled()) { if (i == in_n - 1) handle.AccumKernelTime(time_0); time_0 += handle.GetKernelTime(); } } } */ printf("rnn gpu \n"); auto confirm = [](cl_int clstat) { if (clstat != CL_SUCCESS) { std::stringstream ss; ss << "OpenCL error status : " << clstat; throw std::runtime_error(ss.str()); } }; cl_int clstat; size_t platform_id = 0; cl_uint num_platforms; clGetPlatformIDs(0, nullptr, &num_platforms); std::vector<cl_platform_id> platforms(num_platforms); clstat = clGetPlatformIDs(num_platforms, platforms.data(), nullptr); confirm(clstat); cl_platform_id platform = platforms[platform_id]; size_t device_id = 0; cl_uint num_devices; clstat = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 0, nullptr, &num_devices); std::vector<cl_device_id> devices(num_devices); clstat = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, num_devices, devices.data(), nullptr); cl_device_id device = devices[device_id]; cl_context context = clCreateContext(nullptr, 1, &device, nullptr, nullptr, &clstat); cl_queue_properties properties = 0; // CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE; #if (CL_VERSION_2_0 == 1) std::vector<cl_queue_properties> props = { CL_QUEUE_PROPERTIES, properties, 0 }; cl_command_queue Q = clCreateCommandQueueWithProperties(context, device, props.data(), &clstat); #else cl_command_queue Q = clCreateCommandQueue(context, device, properties, &clstat); #endif for (int li = 0; li < numlayer; li++) { int hid_shift = li * batch_n * hy_h * bi; int hx_shift = li * bi * in_n[0] * hy_h; // from input if (li == 0) { MIOpenGEMM::gemm0<float>(true, false, false, hy_h, hy_h, in_h, 1, w, 0, wei_stride, x, 0, in_stride, 1, y, hid_shift, hy_stride, &Q, 0, nullptr, nullptr); } clFinish(Q); } #else MIOPEN_THROW("GEMM is not supported"); #endif } else if (mode == miopenLSTM) { printf("lstm gpu \n"); } else if (mode == miopenGRU) { printf("gru gpu \n"); } }; void RNNDescriptor::RNNBackwardData(Handle& handle, const int seqLen, const TensorDescriptor& yDesc, ConstData_t y, const TensorDescriptor& dyDesc, ConstData_t dy, const TensorDescriptor& dhyDesc, ConstData_t dhy, const TensorDescriptor& dcyDesc, ConstData_t dcy, const TensorDescriptor& wDesc, ConstData_t w, const TensorDescriptor& hxDesc, ConstData_t hx, const TensorDescriptor& cxDesc, ConstData_t cx, const TensorDescriptor& dxDesc, Data_t dx, const TensorDescriptor& dhxDesc, Data_t dhx, const TensorDescriptor& dcxDesc, Data_t dcx, Data_t workSpace, size_t workSpaceSize, ConstData_t reserveSpace, size_t reserveSpaceSize) const { /* if (dx == nullptr || w == nullptr || dy == nullptr) { MIOPEN_THROW(miopenStatusBadParm); } if (dyDesc.GetSize() != dxDesc.GetSize() || dyDesc.GetSize() != wDesc.GetSize()) { MIOPEN_THROW(miopenStatusBadParm); } if (dyDesc.GetType() != dxDesc.GetType() || dyDesc.GetType() != wDesc.GetType()) { MIOPEN_THROW(miopenStatusBadParm); } */ int in_n, in_c, in_h, in_w; // std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths()); int wei_n, wei_h, wei_w; // std::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths()); int out_h, out_w; // std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths()); }; void RNNDescriptor::RNNBackwardWeights(Handle& handle, const int seqLen, const TensorDescriptor& xDesc, ConstData_t x, const TensorDescriptor& hxDesc, ConstData_t hx, const TensorDescriptor& dyDesc, ConstData_t dy, ConstData_t workSpace, size_t workSpaceSize, const TensorDescriptor& dwDesc, Data_t dw, ConstData_t reserveSpace, size_t reserveSpaceSize) const { int in_n, in_c, in_h, in_w; // std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths()); int wei_n, wei_h, wei_w; // std::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths()); int out_h, out_w; // std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths()); }; } // namespace miopen <commit_msg>rnn fwd.......<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #include <miopen/rnn.hpp> #include <miopen/env.hpp> #include <miopen/util.hpp> #include <miopen/float_equal.hpp> #include <vector> #include <numeric> #include <miopengemm/gemm.hpp> namespace miopen { MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_DIRECT) struct AutoEnableProfiling { AutoEnableProfiling(Handle& x) : h(x) { prev_state = h.IsProfilingEnabled(); h.EnableProfiling(); } ~AutoEnableProfiling() { h.EnableProfiling(prev_state); h.ResetKernelTime(); } private: Handle& h; bool prev_state; }; void RNNDescriptor::RNNForwardTraining(Handle& handle, const int seqLen, // const TensorDescriptor& xDesc, ConstData_t x, // const TensorDescriptor& hxDesc, ConstData_t hx, // const TensorDescriptor& cxDesc, ConstData_t cx, // const TensorDescriptor& wDesc, ConstData_t w, // const TensorDescriptor& yDesc, Data_t y, // const TensorDescriptor& hyDesc, Data_t hy, // const TensorDescriptor& cyDesc, Data_t cy, Data_t workSpace, size_t workSpaceSize, Data_t reserveSpace, size_t reserveSpaceSize, const std::vector<int> &in_n, const int in_h, const int hy_d, const int hy_n, const int hy_h, const int out_h) const {/* if (x == nullptr || w == nullptr || y == nullptr) { MIOPEN_THROW(miopenStatusBadParm); } if (xDesc.GetSize() != yDesc.GetSize() || xDesc.GetSize() != wDesc.GetSize()) { MIOPEN_THROW(miopenStatusBadParm); } if (xDesc.GetType() != yDesc.GetType() || xDesc.GetType() != wDesc.GetType()) { MIOPEN_THROW(miopenStatusBadParm); } */ // int in_n, in_c, in_h, in_w; // std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths()); // int out_h, out_w; // std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths()); /* if (workSpace == nullptr || workSpaceSize < ForwardGetWorkSpaceSize(handle, wDesc, xDesc, yDesc) || reserveSpaceSize < ForwardGetReserveSpaceSize(handle, wDesc, xDesc, yDesc)) { MIOPEN_THROW("Workspace is required"); } */ // miopenRNNMode_t mode; // int seqLength; // int layer; // int bidir; // int bias; int batch_n = std::accumulate(in_n.begin(), in_n.end(), 0); bool bidirection = (bidir != 0); bool biased = (bias != 0); int numlayer = layer; int bacc, baccbi; int bi = bidirection ? 2 : 1; int wei_len = (bi * (in_h + hy_h + out_h) + (numlayer - 1) * bi * (bi + 1) * hy_h) * hy_h; if (biased) { wei_len += (bi * 2 + (numlayer - 1) * bi * (bi + 1)) * hy_h + bi * out_h; } int wei_shift_bias = ((in_h + hy_h + out_h) * bi + (bi * hy_h + hy_h) * bi * (numlayer - 1)) * hy_h; int in_stride = in_h; int hy_stride = hy_h * bi; int out_stride = out_h; int wei_stride = hy_h * bi; if (mode == miopenRNNRELU || mode == miopenRNNTANH) { // std::string network_config; #if MIOPEN_USE_MIOPENGEMM // CreateGemmGeometryConvFwd(xDesc, wDesc, yDesc, false, network_config); // GemmGeometry gg = GetGemmGeometry("miopenConvolutionFwdAlgoGEMM", network_config); /* float time_0 = 0; float t1 = 0; for (int i = 0; i < in_n; i++) { int out_offset = i * wei_n * out_h * out_w; if (wei_h != 1 || wei_w != 1 || v != 1 || u != 1) { size_t in_offset = i * in_c * in_h * in_w; Im2ColGPU(handle, xDesc.GetElementSize(), x, in_offset, in_c, in_h, in_w, wei_h, wei_w, out_h, out_w, pad_h, pad_w, v, u, dilation_h, dilation_w, workSpace); if (handle.IsProfilingEnabled()) t1 = handle.GetKernelTime(); gg.RunGemm(handle, workSpace, w, y, 0, 0, out_offset); // Update times for both the kernels if (handle.IsProfilingEnabled()) { if (i == in_n - 1) handle.AccumKernelTime(t1 + time_0); else handle.AccumKernelTime(t1); time_0 += handle.GetKernelTime(); } } else if (wei_h == 1 && wei_w == 1 && v == 1 && u == 1) { int in_offset = i * in_c * in_h * in_w; gg.RunGemm(handle, x, w, y, in_offset, 0, out_offset); if (handle.IsProfilingEnabled()) { if (i == in_n - 1) handle.AccumKernelTime(time_0); time_0 += handle.GetKernelTime(); } } } */ printf("rnn gpu \n"); auto confirm = [](cl_int clstat) { if (clstat != CL_SUCCESS) { std::stringstream ss; ss << "OpenCL error status : " << clstat; throw std::runtime_error(ss.str()); } }; cl_int clstat; size_t platform_id = 0; cl_uint num_platforms; clGetPlatformIDs(0, nullptr, &num_platforms); std::vector<cl_platform_id> platforms(num_platforms); clstat = clGetPlatformIDs(num_platforms, platforms.data(), nullptr); confirm(clstat); cl_platform_id platform = platforms[platform_id]; size_t device_id = 0; cl_uint num_devices; clstat = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 0, nullptr, &num_devices); std::vector<cl_device_id> devices(num_devices); clstat = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, num_devices, devices.data(), nullptr); cl_device_id device = devices[device_id]; cl_context context = clCreateContext(nullptr, 1, &device, nullptr, nullptr, &clstat); cl_queue_properties properties = 0; // CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE; #if (CL_VERSION_2_0 == 1) std::vector<cl_queue_properties> props = { CL_QUEUE_PROPERTIES, properties, 0 }; cl_command_queue Q = clCreateCommandQueueWithProperties(context, device, props.data(), &clstat); #else cl_command_queue Q = clCreateCommandQueue(context, device, properties, &clstat); #endif for (int li = 0; li < numlayer; li++) { int hid_shift = li * batch_n * hy_h * bi; int hx_shift = li * bi * in_n[0] * hy_h; // from input if (li == 0) { MIOpenGEMM::gemm0<float>(false, false, false, batch_n, hy_h, in_h, 1, x, 0, in_stride, w, 0, wei_stride, 1, reserveSpace, hid_shift, hy_stride, &Q, 0, nullptr, nullptr); } clFinish(Q); } #else MIOPEN_THROW("GEMM is not supported"); #endif } else if (mode == miopenLSTM) { printf("lstm gpu \n"); } else if (mode == miopenGRU) { printf("gru gpu \n"); } }; void RNNDescriptor::RNNBackwardData(Handle& handle, const int seqLen, const TensorDescriptor& yDesc, ConstData_t y, const TensorDescriptor& dyDesc, ConstData_t dy, const TensorDescriptor& dhyDesc, ConstData_t dhy, const TensorDescriptor& dcyDesc, ConstData_t dcy, const TensorDescriptor& wDesc, ConstData_t w, const TensorDescriptor& hxDesc, ConstData_t hx, const TensorDescriptor& cxDesc, ConstData_t cx, const TensorDescriptor& dxDesc, Data_t dx, const TensorDescriptor& dhxDesc, Data_t dhx, const TensorDescriptor& dcxDesc, Data_t dcx, Data_t workSpace, size_t workSpaceSize, ConstData_t reserveSpace, size_t reserveSpaceSize) const { /* if (dx == nullptr || w == nullptr || dy == nullptr) { MIOPEN_THROW(miopenStatusBadParm); } if (dyDesc.GetSize() != dxDesc.GetSize() || dyDesc.GetSize() != wDesc.GetSize()) { MIOPEN_THROW(miopenStatusBadParm); } if (dyDesc.GetType() != dxDesc.GetType() || dyDesc.GetType() != wDesc.GetType()) { MIOPEN_THROW(miopenStatusBadParm); } */ int in_n, in_c, in_h, in_w; // std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths()); int wei_n, wei_h, wei_w; // std::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths()); int out_h, out_w; // std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths()); }; void RNNDescriptor::RNNBackwardWeights(Handle& handle, const int seqLen, const TensorDescriptor& xDesc, ConstData_t x, const TensorDescriptor& hxDesc, ConstData_t hx, const TensorDescriptor& dyDesc, ConstData_t dy, ConstData_t workSpace, size_t workSpaceSize, const TensorDescriptor& dwDesc, Data_t dw, ConstData_t reserveSpace, size_t reserveSpaceSize) const { int in_n, in_c, in_h, in_w; // std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths()); int wei_n, wei_h, wei_w; // std::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths()); int out_h, out_w; // std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths()); }; } // namespace miopen <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "bouncer.h" #include <vespa/storageapi/message/state.h> #include <vespa/storageapi/message/persistence.h> #include <vespa/config/subscription/configuri.h> #include <vespa/config/common/exceptions.h> #include <sstream> #include <vespa/log/log.h> LOG_SETUP(".bouncer"); namespace storage { Bouncer::Bouncer(StorageComponentRegister& compReg, const config::ConfigUri & configUri) : StorageLink("Bouncer"), _config(new vespa::config::content::core::StorBouncerConfig()), _component(compReg, "bouncer"), _lock(), _nodeState("s:i"), _clusterState(&lib::State::UP), _configFetcher(configUri.getContext()) { _component.getStateUpdater().addStateListener(*this); // Register for config. Normally not critical, so catching config // exception allowing program to continue if missing/faulty config. try{ if (!configUri.empty()) { _configFetcher.subscribe<vespa::config::content::core::StorBouncerConfig>(configUri.getConfigId(), this); _configFetcher.start(); } else { LOG(info, "No config id specified. Using defaults rather than " "config"); } } catch (config::InvalidConfigException& e) { LOG(info, "Bouncer failed to load config '%s'. This " "is not critical since it has sensible defaults: %s", configUri.getConfigId().c_str(), e.what()); } } Bouncer::~Bouncer() { closeNextLink(); LOG(debug, "Deleting link %s.", toString().c_str()); } void Bouncer::print(std::ostream& out, bool verbose, const std::string& indent) const { (void) verbose; (void) indent; out << "Bouncer(" << _nodeState << ")"; } void Bouncer::onClose() { _configFetcher.close(); _component.getStateUpdater().removeStateListener(*this); } void Bouncer::configure(std::unique_ptr<vespa::config::content::core::StorBouncerConfig> config) { validateConfig(*config); vespalib::LockGuard lock(_lock); _config = std::move(config); } void Bouncer::validateConfig( const vespa::config::content::core::StorBouncerConfig& newConfig) const { if (newConfig.feedRejectionPriorityThreshold != -1) { if (newConfig.feedRejectionPriorityThreshold > std::numeric_limits<api::StorageMessage::Priority>::max()) { throw config::InvalidConfigException( "feed_rejection_priority_threshold config value exceeds " "maximum allowed value"); } if (newConfig.feedRejectionPriorityThreshold < std::numeric_limits<api::StorageMessage::Priority>::min()) { throw config::InvalidConfigException( "feed_rejection_priority_threshold config value lower than " "minimum allowed value"); } } } void Bouncer::abortCommandForUnavailableNode(api::StorageMessage& msg, const lib::State& state) { // If we're not up or retired, fail due to this nodes state. std::shared_ptr<api::StorageReply> reply( static_cast<api::StorageCommand&>(msg).makeReply().release()); std::ostringstream ost; ost << "We don't allow command of type " << msg.getType() << " when node is in state " << state.toString(true) << "."; reply->setResult(api::ReturnCode(api::ReturnCode::ABORTED, ost.str())); sendUp(reply); } void Bouncer::abortCommandWithTooHighClockSkew(api::StorageMessage& msg, int maxClockSkewInSeconds) { std::shared_ptr<api::StorageReply> reply( static_cast<api::StorageCommand&>(msg).makeReply().release()); std::ostringstream ost; ost << "Message " << msg.getType() << " is more than " << maxClockSkewInSeconds << " seconds in the future."; reply->setResult(api::ReturnCode(api::ReturnCode::ABORTED, ost.str())); sendUp(reply); } void Bouncer::abortCommandDueToClusterDown(api::StorageMessage& msg) { std::shared_ptr<api::StorageReply> reply( static_cast<api::StorageCommand&>(msg).makeReply().release()); std::ostringstream ost; ost << "We don't allow external load while cluster is in state " << _clusterState->toString(true) << "."; reply->setResult(api::ReturnCode(api::ReturnCode::ABORTED, ost.str())); sendUp(reply); } bool Bouncer::clusterIsUp() const { return (*_clusterState == lib::State::UP); } uint64_t Bouncer::extractMutationTimestampIfAny(const api::StorageMessage& msg) { switch (msg.getType().getId()) { case api::MessageType::PUT_ID: return static_cast<const api::PutCommand&>(msg).getTimestamp(); case api::MessageType::REMOVE_ID: return static_cast<const api::RemoveCommand&>(msg).getTimestamp(); case api::MessageType::UPDATE_ID: return static_cast<const api::UpdateCommand&>(msg).getTimestamp(); default: return 0; } } bool Bouncer::isExternalLoad(const api::MessageType& type) const noexcept { switch (type.getId()) { case api::MessageType::PUT_ID: case api::MessageType::REMOVE_ID: case api::MessageType::UPDATE_ID: case api::MessageType::GET_ID: case api::MessageType::VISITOR_CREATE_ID: case api::MessageType::MULTIOPERATION_ID: case api::MessageType::STATBUCKET_ID: return true; default: return false; } } bool Bouncer::isExternalWriteOperation(const api::MessageType& type) const noexcept { switch (type.getId()) { case api::MessageType::PUT_ID: case api::MessageType::REMOVE_ID: case api::MessageType::UPDATE_ID: case api::MessageType::MULTIOPERATION_ID: return true; default: return false; } } void Bouncer::rejectDueToInsufficientPriority( api::StorageMessage& msg, api::StorageMessage::Priority feedPriorityLowerBound) { std::shared_ptr<api::StorageReply> reply( static_cast<api::StorageCommand&>(msg).makeReply().release()); std::ostringstream ost; ost << "Operation priority (" << int(msg.getPriority()) << ") is lower than currently configured threshold (" << int(feedPriorityLowerBound) << ") -- note that lower numbers " "mean a higher priority. This usually means your application " "has been reconfigured to deal with a transient upgrade or " "load event"; reply->setResult(api::ReturnCode(api::ReturnCode::REJECTED, ost.str())); sendUp(reply); } bool Bouncer::onDown(const std::shared_ptr<api::StorageMessage>& msg) { const api::MessageType& type(msg->getType()); // All replies can come in. if (type.isReply()) return false; switch (type.getId()) { case api::MessageType::SETNODESTATE_ID: case api::MessageType::GETNODESTATE_ID: case api::MessageType::SETSYSTEMSTATE_ID: case api::MessageType::NOTIFYBUCKETCHANGE_ID: // state commands are always ok return false; default: break; } const lib::State* state; int maxClockSkewInSeconds; bool isInAvailableState; bool abortLoadWhenClusterDown; int feedPriorityLowerBound; { vespalib::LockGuard lock(_lock); state = &_nodeState.getState(); maxClockSkewInSeconds = _config->maxClockSkewSeconds; abortLoadWhenClusterDown = _config->stopExternalLoadWhenClusterDown; isInAvailableState = state->oneOf( _config->stopAllLoadWhenNodestateNotIn.c_str()); feedPriorityLowerBound = _config->feedRejectionPriorityThreshold; } // Special case for messages storage nodes are expected to get during // initializing. Request bucket info will be queued so storage can // answer them at the moment they are done initializing if (*state == lib::State::INITIALIZING && type.getId() == api::MessageType::REQUESTBUCKETINFO_ID) { return false; } if (!isInAvailableState) { abortCommandForUnavailableNode(*msg, *state); return true; } // Allow all internal load to go through at this point if (!isExternalLoad(type)) { return false; } if (priorityRejectionIsEnabled(feedPriorityLowerBound) && isExternalWriteOperation(type) && (msg->getPriority() > feedPriorityLowerBound)) { rejectDueToInsufficientPriority(*msg, feedPriorityLowerBound); return true; } uint64_t timestamp = extractMutationTimestampIfAny(*msg); if (timestamp != 0) { timestamp /= 1000000; uint64_t currentTime = _component.getClock().getTimeInSeconds().getTime(); if (timestamp > currentTime + maxClockSkewInSeconds) { abortCommandWithTooHighClockSkew(*msg, maxClockSkewInSeconds); return true; } } // If cluster state is not up, fail external load if (abortLoadWhenClusterDown && !clusterIsUp()) { abortCommandDueToClusterDown(*msg); return true; } return false; } void Bouncer::handleNewState() { vespalib::LockGuard lock(_lock); _nodeState = *_component.getStateUpdater().getReportedNodeState(); _clusterState = &_component.getStateUpdater().getSystemState() ->getClusterState(); if (_config->useWantedStateIfPossible) { // If current node state is more strict than our own reported state, // set node state to our current state lib::NodeState currState = _component.getStateUpdater().getSystemState() ->getNodeState(lib::Node(_component.getNodeType(), _component.getIndex())); if (_nodeState.getState().maySetWantedStateForThisNodeState( currState.getState())) { _nodeState = currState; } } } } // storage <commit_msg>Log warning when aborting operation due to clock skew<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "bouncer.h" #include <vespa/storageapi/message/state.h> #include <vespa/storageapi/message/persistence.h> #include <vespa/config/subscription/configuri.h> #include <vespa/config/common/exceptions.h> #include <sstream> #include <vespa/log/log.h> #include <vespa/log/bufferedlogger.h> LOG_SETUP(".bouncer"); namespace storage { Bouncer::Bouncer(StorageComponentRegister& compReg, const config::ConfigUri & configUri) : StorageLink("Bouncer"), _config(new vespa::config::content::core::StorBouncerConfig()), _component(compReg, "bouncer"), _lock(), _nodeState("s:i"), _clusterState(&lib::State::UP), _configFetcher(configUri.getContext()) { _component.getStateUpdater().addStateListener(*this); // Register for config. Normally not critical, so catching config // exception allowing program to continue if missing/faulty config. try{ if (!configUri.empty()) { _configFetcher.subscribe<vespa::config::content::core::StorBouncerConfig>(configUri.getConfigId(), this); _configFetcher.start(); } else { LOG(info, "No config id specified. Using defaults rather than " "config"); } } catch (config::InvalidConfigException& e) { LOG(info, "Bouncer failed to load config '%s'. This " "is not critical since it has sensible defaults: %s", configUri.getConfigId().c_str(), e.what()); } } Bouncer::~Bouncer() { closeNextLink(); LOG(debug, "Deleting link %s.", toString().c_str()); } void Bouncer::print(std::ostream& out, bool verbose, const std::string& indent) const { (void) verbose; (void) indent; out << "Bouncer(" << _nodeState << ")"; } void Bouncer::onClose() { _configFetcher.close(); _component.getStateUpdater().removeStateListener(*this); } void Bouncer::configure(std::unique_ptr<vespa::config::content::core::StorBouncerConfig> config) { validateConfig(*config); vespalib::LockGuard lock(_lock); _config = std::move(config); } void Bouncer::validateConfig( const vespa::config::content::core::StorBouncerConfig& newConfig) const { if (newConfig.feedRejectionPriorityThreshold != -1) { if (newConfig.feedRejectionPriorityThreshold > std::numeric_limits<api::StorageMessage::Priority>::max()) { throw config::InvalidConfigException( "feed_rejection_priority_threshold config value exceeds " "maximum allowed value"); } if (newConfig.feedRejectionPriorityThreshold < std::numeric_limits<api::StorageMessage::Priority>::min()) { throw config::InvalidConfigException( "feed_rejection_priority_threshold config value lower than " "minimum allowed value"); } } } void Bouncer::abortCommandForUnavailableNode(api::StorageMessage& msg, const lib::State& state) { // If we're not up or retired, fail due to this nodes state. std::shared_ptr<api::StorageReply> reply( static_cast<api::StorageCommand&>(msg).makeReply().release()); std::ostringstream ost; ost << "We don't allow command of type " << msg.getType() << " when node is in state " << state.toString(true) << "."; reply->setResult(api::ReturnCode(api::ReturnCode::ABORTED, ost.str())); sendUp(reply); } void Bouncer::abortCommandWithTooHighClockSkew(api::StorageMessage& msg, int maxClockSkewInSeconds) { auto& as_cmd = dynamic_cast<api::StorageCommand&>(msg); std::ostringstream ost; ost << "Message " << msg.getType() << " is more than " << maxClockSkewInSeconds << " seconds in the future."; LOGBP(warning, "Aborting operation from distributor %u: %s", as_cmd.getSourceIndex(), ost.str().c_str()); std::shared_ptr<api::StorageReply> reply(as_cmd.makeReply().release()); reply->setResult(api::ReturnCode(api::ReturnCode::ABORTED, ost.str())); sendUp(reply); } void Bouncer::abortCommandDueToClusterDown(api::StorageMessage& msg) { std::shared_ptr<api::StorageReply> reply( static_cast<api::StorageCommand&>(msg).makeReply().release()); std::ostringstream ost; ost << "We don't allow external load while cluster is in state " << _clusterState->toString(true) << "."; reply->setResult(api::ReturnCode(api::ReturnCode::ABORTED, ost.str())); sendUp(reply); } bool Bouncer::clusterIsUp() const { return (*_clusterState == lib::State::UP); } uint64_t Bouncer::extractMutationTimestampIfAny(const api::StorageMessage& msg) { switch (msg.getType().getId()) { case api::MessageType::PUT_ID: return static_cast<const api::PutCommand&>(msg).getTimestamp(); case api::MessageType::REMOVE_ID: return static_cast<const api::RemoveCommand&>(msg).getTimestamp(); case api::MessageType::UPDATE_ID: return static_cast<const api::UpdateCommand&>(msg).getTimestamp(); default: return 0; } } bool Bouncer::isExternalLoad(const api::MessageType& type) const noexcept { switch (type.getId()) { case api::MessageType::PUT_ID: case api::MessageType::REMOVE_ID: case api::MessageType::UPDATE_ID: case api::MessageType::GET_ID: case api::MessageType::VISITOR_CREATE_ID: case api::MessageType::MULTIOPERATION_ID: case api::MessageType::STATBUCKET_ID: return true; default: return false; } } bool Bouncer::isExternalWriteOperation(const api::MessageType& type) const noexcept { switch (type.getId()) { case api::MessageType::PUT_ID: case api::MessageType::REMOVE_ID: case api::MessageType::UPDATE_ID: case api::MessageType::MULTIOPERATION_ID: return true; default: return false; } } void Bouncer::rejectDueToInsufficientPriority( api::StorageMessage& msg, api::StorageMessage::Priority feedPriorityLowerBound) { std::shared_ptr<api::StorageReply> reply( static_cast<api::StorageCommand&>(msg).makeReply().release()); std::ostringstream ost; ost << "Operation priority (" << int(msg.getPriority()) << ") is lower than currently configured threshold (" << int(feedPriorityLowerBound) << ") -- note that lower numbers " "mean a higher priority. This usually means your application " "has been reconfigured to deal with a transient upgrade or " "load event"; reply->setResult(api::ReturnCode(api::ReturnCode::REJECTED, ost.str())); sendUp(reply); } bool Bouncer::onDown(const std::shared_ptr<api::StorageMessage>& msg) { const api::MessageType& type(msg->getType()); // All replies can come in. if (type.isReply()) return false; switch (type.getId()) { case api::MessageType::SETNODESTATE_ID: case api::MessageType::GETNODESTATE_ID: case api::MessageType::SETSYSTEMSTATE_ID: case api::MessageType::NOTIFYBUCKETCHANGE_ID: // state commands are always ok return false; default: break; } const lib::State* state; int maxClockSkewInSeconds; bool isInAvailableState; bool abortLoadWhenClusterDown; int feedPriorityLowerBound; { vespalib::LockGuard lock(_lock); state = &_nodeState.getState(); maxClockSkewInSeconds = _config->maxClockSkewSeconds; abortLoadWhenClusterDown = _config->stopExternalLoadWhenClusterDown; isInAvailableState = state->oneOf( _config->stopAllLoadWhenNodestateNotIn.c_str()); feedPriorityLowerBound = _config->feedRejectionPriorityThreshold; } // Special case for messages storage nodes are expected to get during // initializing. Request bucket info will be queued so storage can // answer them at the moment they are done initializing if (*state == lib::State::INITIALIZING && type.getId() == api::MessageType::REQUESTBUCKETINFO_ID) { return false; } if (!isInAvailableState) { abortCommandForUnavailableNode(*msg, *state); return true; } // Allow all internal load to go through at this point if (!isExternalLoad(type)) { return false; } if (priorityRejectionIsEnabled(feedPriorityLowerBound) && isExternalWriteOperation(type) && (msg->getPriority() > feedPriorityLowerBound)) { rejectDueToInsufficientPriority(*msg, feedPriorityLowerBound); return true; } uint64_t timestamp = extractMutationTimestampIfAny(*msg); if (timestamp != 0) { timestamp /= 1000000; uint64_t currentTime = _component.getClock().getTimeInSeconds().getTime(); if (timestamp > currentTime + maxClockSkewInSeconds) { abortCommandWithTooHighClockSkew(*msg, maxClockSkewInSeconds); return true; } } // If cluster state is not up, fail external load if (abortLoadWhenClusterDown && !clusterIsUp()) { abortCommandDueToClusterDown(*msg); return true; } return false; } void Bouncer::handleNewState() { vespalib::LockGuard lock(_lock); _nodeState = *_component.getStateUpdater().getReportedNodeState(); _clusterState = &_component.getStateUpdater().getSystemState() ->getClusterState(); if (_config->useWantedStateIfPossible) { // If current node state is more strict than our own reported state, // set node state to our current state lib::NodeState currState = _component.getStateUpdater().getSystemState() ->getNodeState(lib::Node(_component.getNodeType(), _component.getIndex())); if (_nodeState.getState().maySetWantedStateForThisNodeState( currState.getState())) { _nodeState = currState; } } } } // storage <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: queue.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: mhu $ $Date: 2001-05-14 11:51:46 $ * * 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 _SALHELPER_QUEUE_HXX_ #define _SALHELPER_QUEUE_HXX_ #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _OSL_SEMAPHOR_HXX_ #include <osl/semaphor.hxx> #endif #ifndef __LIST__ #include <list> #endif namespace salhelper { //---------------------------------------------------------------------------- #ifndef SALHELPER_COPYCTOR_API #define SALHELPER_COPYCTOR_API(C) C (const C&); C& operator= (const C&) #endif //---------------------------------------------------------------------------- template<class element_type> class QueueBase : protected std::list<element_type> { /** Representation. */ osl::Mutex m_aMutex; /** Not implemented. */ SALHELPER_COPYCTOR_API(QueueBase<element_type>); public: inline QueueBase() {} inline ~QueueBase() { erase (begin(), end()); } inline void put (const element_type& element) { osl::MutexGuard aGuard (m_aMutex); push_back (element); } inline element_type get() { element_type element; osl::MutexGuard aGuard (m_aMutex); if (!empty()) { element = front(); pop_front(); } return (element); } }; //---------------------------------------------------------------------------- template<class element_type> class Queue : protected QueueBase<element_type> { /** Representation. */ osl::Semaphore m_aNotEmpty; /** Not implemented. */ SALHELPER_COPYCTOR_API(Queue<element_type>); public: inline Queue() : m_aNotEmpty (0) {} inline ~Queue() {} inline void put (const element_type& element) { QueueBase<element_type>::put (element); m_aNotEmpty.release(); } inline element_type get() { element_type element; m_aNotEmpty.acquire(); element = QueueBase<element_type>::get(); return (element); } }; //---------------------------------------------------------------------------- template<class element_type> class BoundedQueue : protected Queue<element_type> { /** Representation. */ osl::Semaphore m_aNotFull; /** Not implemented. */ SALHELPER_COPYCTOR_API(BoundedQueue<element_type>); public: inline BoundedQueue (sal_uInt32 capacity) : m_aNotFull (capacity) { OSL_POSTCOND(capacity, "BoundedQueue:BoundedQueue(): no capacity"); } inline ~BoundedQueue() {} inline void put (const element_type& element) { m_aNotFull.acquire(); Queue<element_type>::put (element); } inline element_type get() { element_type element; element = Queue<element_type>::get(); m_aNotFull.release(); return (element); } }; //---------------------------------------------------------------------------- } // namespace salhelper #endif /* !_SALHELPER_QUEUE_HXX_ */ <commit_msg>INTEGRATION: CWS sb31 (1.1.130); FILE MERGED 2005/06/10 13:51:39 sb 1.1.130.1: Resolved ambiguity.<commit_after>/************************************************************************* * * $RCSfile: queue.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2005-06-17 10:13: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 _SALHELPER_QUEUE_HXX_ #define _SALHELPER_QUEUE_HXX_ #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _OSL_SEMAPHOR_HXX_ #include <osl/semaphor.hxx> #endif #ifndef __LIST__ #include <list> #endif namespace salhelper { //---------------------------------------------------------------------------- #ifndef SALHELPER_COPYCTOR_API #define SALHELPER_COPYCTOR_API(C) C (const C&); C& operator= (const C&) #endif //---------------------------------------------------------------------------- template<class element_type> class QueueBase : protected std::list<element_type> { /** Representation. */ osl::Mutex m_aMutex; /** Not implemented. */ SALHELPER_COPYCTOR_API(QueueBase<element_type>); public: inline QueueBase() {} inline ~QueueBase() { erase (begin(), end()); } inline void put (const element_type& element) { osl::MutexGuard aGuard (m_aMutex); push_back (element); } inline element_type get() { element_type element; osl::MutexGuard aGuard (m_aMutex); if (!empty()) { element = front(); pop_front(); } return (element); } }; //---------------------------------------------------------------------------- template<class element_type> class Queue : protected QueueBase<element_type> { /** Representation. */ osl::Semaphore m_aNotEmpty; /** Not implemented. */ SALHELPER_COPYCTOR_API(Queue<element_type>); public: inline Queue() : m_aNotEmpty (static_cast< sal_uInt32 >(0)) {} inline ~Queue() {} inline void put (const element_type& element) { QueueBase<element_type>::put (element); m_aNotEmpty.release(); } inline element_type get() { element_type element; m_aNotEmpty.acquire(); element = QueueBase<element_type>::get(); return (element); } }; //---------------------------------------------------------------------------- template<class element_type> class BoundedQueue : protected Queue<element_type> { /** Representation. */ osl::Semaphore m_aNotFull; /** Not implemented. */ SALHELPER_COPYCTOR_API(BoundedQueue<element_type>); public: inline BoundedQueue (sal_uInt32 capacity) : m_aNotFull (capacity) { OSL_POSTCOND(capacity, "BoundedQueue:BoundedQueue(): no capacity"); } inline ~BoundedQueue() {} inline void put (const element_type& element) { m_aNotFull.acquire(); Queue<element_type>::put (element); } inline element_type get() { element_type element; element = Queue<element_type>::get(); m_aNotFull.release(); return (element); } }; //---------------------------------------------------------------------------- } // namespace salhelper #endif /* !_SALHELPER_QUEUE_HXX_ */ <|endoftext|>
<commit_before> /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ascharanchoredobjectposition.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2007-09-27 08:53:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _ASCHARANCHOREDOBJECTPOSITION_HXX #define _ASCHARANCHOREDOBJECTPOSITION_HXX #ifndef _ANCHOREDOBJECTPOSITION_HXX #include <anchoredobjectposition.hxx> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _SWRECT_HXX #include <swrect.hxx> #endif class SwTxtFrm; class SwFmtVertOrient; namespace objectpositioning { // flags for positioning algorithm of as-character-anchored objects typedef sal_uInt8 AsCharFlags; #define AS_CHAR_NOFLAG 0 #define AS_CHAR_QUICK 1 #define AS_CHAR_ULSPACE 2 #define AS_CHAR_INIT 4 #define AS_CHAR_ROTATE 8 #define AS_CHAR_REVERSE 16 #define AS_CHAR_BIDI 32 class SwAsCharAnchoredObjectPosition : public SwAnchoredObjectPosition { private: // data to calculate object position // proposed anchor position, starting point for the calculation // of the object position const Point& mrProposedAnchorPos; // flags that influences the calculation of the anchor position // AS_CHAR_QUICK : quick formatting - calculated position not set at object // AS_CHAR_ULSPACE : consider upper/lower spacing - adjustment of anchor position // AS_CHAR_INIT : initial calculation // AS_CHAR_ROTATE : object is rotated by 90 degrees // AS_CHAR_REVERSE : object is reversed (rotated by 270 degrees) // AS_CHAR_BIDI : object belongs to a BIDI-multi-portion const AsCharFlags mnFlags; // needed line values for the different alignments. const SwTwips mnLineAscent; const SwTwips mnLineDescent; const SwTwips mnLineAscentInclObjs; const SwTwips mnLineDescentInclObjs; // calculated data for object position Point maAnchorPos; SwTwips mnRelPos; SwRect maObjBoundRect; // line alignment relative to line height; gives feedback for line formatting // 0 - no line alignment, 1 - at top, 2 - at center, 3 - at bottom sal_uInt8 mnLineAlignment; // method to cast <SwAnchoredObjectPosition::GetAnchorFrm()> const SwTxtFrm& GetAnchorTxtFrm() const; /** determine the relative position to base line for object position @author OD @param _ObjBoundHeight height including corresponding spacing of the object, for which the Y-position has to be calculated. @param _rVert given vertical positioning and alignment @return relative position to the base line */ SwTwips _GetRelPosToBase( const SwTwips _nObjBoundHeight, const SwFmtVertOrient& _rVert ); // ********************************************************************* public: /** construtor; provided object to be positioned and needed data for calculation of the object position OD 28.10.2003 #110978# @param _rDrawObj input parameter - object, that is be positioned. @param _rProposedAnchorPos proposed anchor position; starting point for the calculation of the anchor position @param _nFlags flags that influences the calculation of the anchor position AS_CHAR_QUICK : quick formatting - calculated position not set at object AS_CHAR_ULSPACE : consider upper/lower spacing - adjustment of anchor position AS_CHAR_INIT : initial calculation AS_CHAR_ROTATE : object is rotated by 90 degrees AS_CHAR_REVERSE : object is reversed (rotated by 270 degrees) AS_CHAR_BIDI : object belongs to a BIDI-multi-portion @param _nLineAscent, _nLineDescent, _nLineAscentInclObjs, _nLineDescentInclObjs - needed line values for the different alignments. @author OD */ SwAsCharAnchoredObjectPosition( SdrObject& _rDrawObj, const Point& _rProposedAnchorPos, const AsCharFlags _nFlags, const SwTwips _nLineAscent, const SwTwips _nLineDescent, const SwTwips _nLineAscentInclObjs, const SwTwips _nLineDescentInclObjs ); virtual ~SwAsCharAnchoredObjectPosition(); /** calculate position for object position members <maAnchorPos>, <mnRelPos>, <maObjBoundRect> and <mnLineAlignment> are calculated. calculated position is set at the given object. @author OD */ virtual void CalcPosition(); /** calculated anchored position for object position type AS_CHAR @author OD */ Point GetAnchorPos() const; /** calculated relative position to base line for object position type AS_CHAR @author OD */ SwTwips GetRelPosY() const; /** determined object rectangle including spacing for object position type AS_CHAR @author OD */ SwRect GetObjBoundRectInclSpacing() const; /** determined line alignment relative to line height @author OD */ sal_uInt8 GetLineAlignment() const; }; } // namespace objectpositioning #endif <commit_msg>INTEGRATION: CWS changefileheader (1.6.242); FILE MERGED 2008/04/01 15:57:09 thb 1.6.242.3: #i85898# Stripping all external header guards 2008/04/01 12:54:08 thb 1.6.242.2: #i85898# Stripping all external header guards 2008/03/31 16:54:12 rt 1.6.242.1: #i87441# Change license header to LPGL v3.<commit_after> /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ascharanchoredobjectposition.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _ASCHARANCHOREDOBJECTPOSITION_HXX #define _ASCHARANCHOREDOBJECTPOSITION_HXX #include <anchoredobjectposition.hxx> #include <sal/types.h> #include <swtypes.hxx> #include <swrect.hxx> class SwTxtFrm; class SwFmtVertOrient; namespace objectpositioning { // flags for positioning algorithm of as-character-anchored objects typedef sal_uInt8 AsCharFlags; #define AS_CHAR_NOFLAG 0 #define AS_CHAR_QUICK 1 #define AS_CHAR_ULSPACE 2 #define AS_CHAR_INIT 4 #define AS_CHAR_ROTATE 8 #define AS_CHAR_REVERSE 16 #define AS_CHAR_BIDI 32 class SwAsCharAnchoredObjectPosition : public SwAnchoredObjectPosition { private: // data to calculate object position // proposed anchor position, starting point for the calculation // of the object position const Point& mrProposedAnchorPos; // flags that influences the calculation of the anchor position // AS_CHAR_QUICK : quick formatting - calculated position not set at object // AS_CHAR_ULSPACE : consider upper/lower spacing - adjustment of anchor position // AS_CHAR_INIT : initial calculation // AS_CHAR_ROTATE : object is rotated by 90 degrees // AS_CHAR_REVERSE : object is reversed (rotated by 270 degrees) // AS_CHAR_BIDI : object belongs to a BIDI-multi-portion const AsCharFlags mnFlags; // needed line values for the different alignments. const SwTwips mnLineAscent; const SwTwips mnLineDescent; const SwTwips mnLineAscentInclObjs; const SwTwips mnLineDescentInclObjs; // calculated data for object position Point maAnchorPos; SwTwips mnRelPos; SwRect maObjBoundRect; // line alignment relative to line height; gives feedback for line formatting // 0 - no line alignment, 1 - at top, 2 - at center, 3 - at bottom sal_uInt8 mnLineAlignment; // method to cast <SwAnchoredObjectPosition::GetAnchorFrm()> const SwTxtFrm& GetAnchorTxtFrm() const; /** determine the relative position to base line for object position @author OD @param _ObjBoundHeight height including corresponding spacing of the object, for which the Y-position has to be calculated. @param _rVert given vertical positioning and alignment @return relative position to the base line */ SwTwips _GetRelPosToBase( const SwTwips _nObjBoundHeight, const SwFmtVertOrient& _rVert ); // ********************************************************************* public: /** construtor; provided object to be positioned and needed data for calculation of the object position OD 28.10.2003 #110978# @param _rDrawObj input parameter - object, that is be positioned. @param _rProposedAnchorPos proposed anchor position; starting point for the calculation of the anchor position @param _nFlags flags that influences the calculation of the anchor position AS_CHAR_QUICK : quick formatting - calculated position not set at object AS_CHAR_ULSPACE : consider upper/lower spacing - adjustment of anchor position AS_CHAR_INIT : initial calculation AS_CHAR_ROTATE : object is rotated by 90 degrees AS_CHAR_REVERSE : object is reversed (rotated by 270 degrees) AS_CHAR_BIDI : object belongs to a BIDI-multi-portion @param _nLineAscent, _nLineDescent, _nLineAscentInclObjs, _nLineDescentInclObjs - needed line values for the different alignments. @author OD */ SwAsCharAnchoredObjectPosition( SdrObject& _rDrawObj, const Point& _rProposedAnchorPos, const AsCharFlags _nFlags, const SwTwips _nLineAscent, const SwTwips _nLineDescent, const SwTwips _nLineAscentInclObjs, const SwTwips _nLineDescentInclObjs ); virtual ~SwAsCharAnchoredObjectPosition(); /** calculate position for object position members <maAnchorPos>, <mnRelPos>, <maObjBoundRect> and <mnLineAlignment> are calculated. calculated position is set at the given object. @author OD */ virtual void CalcPosition(); /** calculated anchored position for object position type AS_CHAR @author OD */ Point GetAnchorPos() const; /** calculated relative position to base line for object position type AS_CHAR @author OD */ SwTwips GetRelPosY() const; /** determined object rectangle including spacing for object position type AS_CHAR @author OD */ SwRect GetObjBoundRectInclSpacing() const; /** determined line alignment relative to line height @author OD */ sal_uInt8 GetLineAlignment() const; }; } // namespace objectpositioning #endif <|endoftext|>
<commit_before>// Fill out your copyright notice in the Description page of Project Settings. #include "AttackOnPotato.h" #include "AttackOnPotatoCharacter.h" #include "Runtime/CoreUObject/Public/UObject/ConstructorHelpers.h" #include "Runtime/Engine/Classes/Components/DecalComponent.h" #include "Kismet/HeadMountedDisplayFunctionLibrary.h" #include "Pickup.h" // Sets default values AAttackOnPotatoCharacter::AAttackOnPotatoCharacter() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; // Set size for player capsule GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); // Don't rotate character to camera direction bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = true; // Rotate character to moving direction GetCharacterMovement()->RotationRate = FRotator(0.f, 640.f, 0.f); GetCharacterMovement()->bConstrainToPlane = true; GetCharacterMovement()->bSnapToPlaneAtStart = true; // Create a camera boom... CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->bAbsoluteRotation = true; // Don't want arm to rotate when character does CameraBoom->TargetArmLength = 800.f; CameraBoom->RelativeRotation = FRotator(-60.f, 0.f, 0.f); CameraBoom->bDoCollisionTest = false; // Don't want to pull camera in when it collides with level // Create a camera... TopDownCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("TopDownCamera")); TopDownCameraComponent->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); TopDownCameraComponent->bUsePawnControlRotation = false; // Camera does not rotate relative to arm // Create a decal in the world to show the cursor's location CursorToWorld = CreateDefaultSubobject<UDecalComponent>("CursorToWorld"); CursorToWorld->SetupAttachment(RootComponent); static ConstructorHelpers::FObjectFinder<UMaterial> DecalMaterialAsset(TEXT("Material'/Game/AttackOnPotato/Materials/M_Cursor_Decal.M_Cursor_Decal'")); if (DecalMaterialAsset.Succeeded()) { CursorToWorld->SetDecalMaterial(DecalMaterialAsset.Object); } CursorToWorld->DecalSize = FVector(16.0f, 32.0f, 32.0f); CursorToWorld->SetRelativeRotation(FRotator(90.0f, 0.0f, 0.0f).Quaternion()); // Create Collection Shere CollectionSphere = CreateDefaultSubobject<USphereComponent>(TEXT("CollectionSphere")); CollectionSphere->SetSphereRadius(200.0f); //Set Collection sphere for on overlap CollectionSphere->OnComponentBeginOverlap.AddDynamic(this, &AAttackOnPotatoCharacter::OnOverlap); CollectionSphere->SetupAttachment(RootComponent); // Activate ticking in order to update the cursor every frame. PrimaryActorTick.bCanEverTick = true; PrimaryActorTick.bStartWithTickEnabled = true; fSpeedBoostDuration = 0.0f; //Time until speed boost ends iNormalSpeed = 600.0f; iHealth = 10; iMaxHealth = 10; } // Called every frame void AAttackOnPotatoCharacter::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); if (CursorToWorld != nullptr) { if (UHeadMountedDisplayFunctionLibrary::IsHeadMountedDisplayEnabled()) { if (UWorld* World = GetWorld()) { FHitResult HitResult; FCollisionQueryParams Params; FVector StartLocation = TopDownCameraComponent->GetComponentLocation(); FVector EndLocation = TopDownCameraComponent->GetComponentRotation().Vector() * 2000.0f; Params.AddIgnoredActor(this); World->LineTraceSingleByChannel(HitResult, StartLocation, EndLocation, ECC_Visibility, Params); FQuat SurfaceRotation = HitResult.ImpactNormal.ToOrientationRotator().Quaternion(); CursorToWorld->SetWorldLocationAndRotation(HitResult.Location, SurfaceRotation); } } else if (APlayerController* PC = Cast<APlayerController>(GetController())) { FHitResult TraceHitResult; PC->GetHitResultUnderCursor(ECC_Visibility, true, TraceHitResult); FVector CursorFV = TraceHitResult.ImpactNormal; FRotator CursorR = CursorFV.Rotation(); CursorToWorld->SetWorldLocation(TraceHitResult.Location); CursorToWorld->SetWorldRotation(CursorR); } } } //Player will collect pickups within collection sphere void AAttackOnPotatoCharacter::CollectPickups() { //Get All overlapping actors and store into array TArray<AActor*> CollectedActors; CollectionSphere->GetOverlappingActors(CollectedActors); //Iterate through array (Foreach actor to collect) for (int32 iCollected = 0; iCollected < CollectedActors.Num(); ++iCollected) { //Cast actor to APickup APickup* const TestPickup = Cast<APickup>(CollectedActors[iCollected]); //If Cast successful //If Pickup valid and active if (TestPickup && !TestPickup->IsPendingKill() && TestPickup->IsActive()) { TestPickup->Collect(); //Call the Collect function //Deactivate pickup TestPickup->SetActive(false); //Prevent spam collections } } } void AAttackOnPotatoCharacter::OnOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { if (OtherActor->IsA(APickup::StaticClass())) { APickup* pickup = Cast<APickup>(OtherActor); pickup->Collect(); //Collect Pickup } } void AAttackOnPotatoCharacter::setHealth(int newHealth) { iHealth = newHealth; } void AAttackOnPotatoCharacter::addHealth(int health) { if ((iHealth + health) > iMaxHealth) { iHealth = iMaxHealth; } iHealth += health; } void AAttackOnPotatoCharacter::setMaxHealth(int newMaxHealth) { iMaxHealth = newMaxHealth; } void AAttackOnPotatoCharacter::setSpeed(int newSpeed) { iSpeed = newSpeed; GetCharacterMovement()->MaxWalkSpeed = newSpeed; } void AAttackOnPotatoCharacter::boostSpeed(int newSpeed, float duration) { GetCharacterMovement()->MaxWalkSpeed = newSpeed; fSpeedBoostDuration = duration; //Timer to end speed boost GetWorldTimerManager().SetTimer(SpeedBoostTimer, this, &AAttackOnPotatoCharacter::endSpeedBoost, fSpeedBoostDuration, false); } void AAttackOnPotatoCharacter::setMaxSpeed(int newSpeed) { iMaxSpeed = newSpeed; } void AAttackOnPotatoCharacter::endSpeedBoost() { GetCharacterMovement()->MaxWalkSpeed = iNormalSpeed; }<commit_msg>Fixed Decal<commit_after>// Fill out your copyright notice in the Description page of Project Settings. #include "AttackOnPotato.h" #include "AttackOnPotatoCharacter.h" #include "Runtime/CoreUObject/Public/UObject/ConstructorHelpers.h" #include "Runtime/Engine/Classes/Components/DecalComponent.h" #include "Kismet/HeadMountedDisplayFunctionLibrary.h" #include "Pickup.h" // Sets default values AAttackOnPotatoCharacter::AAttackOnPotatoCharacter() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; // Set size for player capsule GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); // Don't rotate character to camera direction bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = true; // Rotate character to moving direction GetCharacterMovement()->RotationRate = FRotator(0.f, 640.f, 0.f); GetCharacterMovement()->bConstrainToPlane = true; GetCharacterMovement()->bSnapToPlaneAtStart = true; // Create a camera boom... CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->bAbsoluteRotation = true; // Don't want arm to rotate when character does CameraBoom->TargetArmLength = 800.f; CameraBoom->RelativeRotation = FRotator(-60.f, 0.f, 0.f); CameraBoom->bDoCollisionTest = false; // Don't want to pull camera in when it collides with level // Create a camera... TopDownCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("TopDownCamera")); TopDownCameraComponent->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); TopDownCameraComponent->bUsePawnControlRotation = false; // Camera does not rotate relative to arm // Create a decal in the world to show the cursor's location CursorToWorld = CreateDefaultSubobject<UDecalComponent>("CursorToWorld"); CursorToWorld->SetupAttachment(RootComponent); static ConstructorHelpers::FObjectFinder<UMaterial> DecalMaterialAsset(TEXT("Material'/Game/AttackOnPotato/Textures/Materials/M_Cursor_Decal.M_Cursor_Decal'")); if (DecalMaterialAsset.Succeeded()) { CursorToWorld->SetDecalMaterial(DecalMaterialAsset.Object); } CursorToWorld->DecalSize = FVector(16.0f, 32.0f, 32.0f); CursorToWorld->SetRelativeRotation(FRotator(90.0f, 0.0f, 0.0f).Quaternion()); // Create Collection Shere CollectionSphere = CreateDefaultSubobject<USphereComponent>(TEXT("CollectionSphere")); CollectionSphere->SetSphereRadius(200.0f); //Set Collection sphere for on overlap CollectionSphere->OnComponentBeginOverlap.AddDynamic(this, &AAttackOnPotatoCharacter::OnOverlap); CollectionSphere->SetupAttachment(RootComponent); // Activate ticking in order to update the cursor every frame. PrimaryActorTick.bCanEverTick = true; PrimaryActorTick.bStartWithTickEnabled = true; fSpeedBoostDuration = 0.0f; //Time until speed boost ends iNormalSpeed = 600.0f; iHealth = 10; iMaxHealth = 10; } // Called every frame void AAttackOnPotatoCharacter::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); if (CursorToWorld != nullptr) { if (UHeadMountedDisplayFunctionLibrary::IsHeadMountedDisplayEnabled()) { if (UWorld* World = GetWorld()) { FHitResult HitResult; FCollisionQueryParams Params; FVector StartLocation = TopDownCameraComponent->GetComponentLocation(); FVector EndLocation = TopDownCameraComponent->GetComponentRotation().Vector() * 2000.0f; Params.AddIgnoredActor(this); World->LineTraceSingleByChannel(HitResult, StartLocation, EndLocation, ECC_Visibility, Params); FQuat SurfaceRotation = HitResult.ImpactNormal.ToOrientationRotator().Quaternion(); CursorToWorld->SetWorldLocationAndRotation(HitResult.Location, SurfaceRotation); } } else if (APlayerController* PC = Cast<APlayerController>(GetController())) { FHitResult TraceHitResult; PC->GetHitResultUnderCursor(ECC_Visibility, true, TraceHitResult); FVector CursorFV = TraceHitResult.ImpactNormal; FRotator CursorR = CursorFV.Rotation(); CursorToWorld->SetWorldLocation(TraceHitResult.Location); CursorToWorld->SetWorldRotation(CursorR); } } } //Player will collect pickups within collection sphere void AAttackOnPotatoCharacter::CollectPickups() { //Get All overlapping actors and store into array TArray<AActor*> CollectedActors; CollectionSphere->GetOverlappingActors(CollectedActors); //Iterate through array (Foreach actor to collect) for (int32 iCollected = 0; iCollected < CollectedActors.Num(); ++iCollected) { //Cast actor to APickup APickup* const TestPickup = Cast<APickup>(CollectedActors[iCollected]); //If Cast successful //If Pickup valid and active if (TestPickup && !TestPickup->IsPendingKill() && TestPickup->IsActive()) { TestPickup->Collect(); //Call the Collect function //Deactivate pickup TestPickup->SetActive(false); //Prevent spam collections } } } void AAttackOnPotatoCharacter::OnOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { if (OtherActor->IsA(APickup::StaticClass())) { APickup* pickup = Cast<APickup>(OtherActor); pickup->Collect(); //Collect Pickup } } void AAttackOnPotatoCharacter::setHealth(int newHealth) { iHealth = newHealth; } void AAttackOnPotatoCharacter::addHealth(int health) { if ((iHealth + health) > iMaxHealth) { iHealth = iMaxHealth; } iHealth += health; } void AAttackOnPotatoCharacter::setMaxHealth(int newMaxHealth) { iMaxHealth = newMaxHealth; } void AAttackOnPotatoCharacter::setSpeed(int newSpeed) { iSpeed = newSpeed; GetCharacterMovement()->MaxWalkSpeed = newSpeed; } void AAttackOnPotatoCharacter::boostSpeed(int newSpeed, float duration) { GetCharacterMovement()->MaxWalkSpeed = newSpeed; fSpeedBoostDuration = duration; //Timer to end speed boost GetWorldTimerManager().SetTimer(SpeedBoostTimer, this, &AAttackOnPotatoCharacter::endSpeedBoost, fSpeedBoostDuration, false); } void AAttackOnPotatoCharacter::setMaxSpeed(int newSpeed) { iMaxSpeed = newSpeed; } void AAttackOnPotatoCharacter::endSpeedBoost() { GetCharacterMovement()->MaxWalkSpeed = iNormalSpeed; }<|endoftext|>
<commit_before>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QITYPE_DETAILS_TYPE_HXX_ #define _QITYPE_DETAILS_TYPE_HXX_ #include <qi/types.hpp> #include <cstring> #include <map> #include <vector> #include <list> #include <qitype/details/bindtype.hxx> #include <boost/mpl/for_each.hpp> #include <boost/mpl/transform_view.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/type_traits/add_pointer.hpp> #include <boost/function_types/parameter_types.hpp> #include <boost/function_types/result_type.hpp> #include <boost/function_types/function_type.hpp> #include <boost/function_types/is_member_pointer.hpp> /* This file contains the default-provided Type specialisations * */ namespace qi { // void template<> class TypeImpl<void>: public Type { public: const TypeInfo& info() { static TypeInfo result = TypeInfo(typeid(void)); return result; } void* initializeStorage(void*) { return 0;} void* ptrFromStorage(void** ) { return 0;} void* clone(void*) { return 0;} void destroy(void* ptr) {} Kind kind() const { return Void;} }; //reference template<typename T> class TypeImpl<T&> : public TypeImpl<T> {}; //any template<> class TypeImpl<boost::any>: public TypeDynamic { public: std::pair<GenericValuePtr, bool> get(void* storage) { qiLogVerbose("qitype.impl") << "get on boost::any not implemented"; return std::make_pair(GenericValuePtr(), false); }; void set(void** storage, GenericValuePtr source) { qiLogVerbose("qitype.impl") << "set on boost::any not implemented"; } typedef DefaultTypeImplMethods<boost::any> Methods; _QI_BOUNCE_TYPE_METHODS(Methods); }; } namespace qi { namespace detail { template<typename T> inline Type* typeOfBackend() { Type* result = getType(typeid(T)); if (!result) { static Type* defaultResult = 0; // Is this realy a problem? if (!defaultResult) qiLogDebug("qitype.typeof") << "typeOf request for unregistered type " << typeid(T).name(); if (!defaultResult) defaultResult = new TypeImpl<T>(); result = defaultResult; } return result; } template<typename T> struct TypeOfAdapter { typedef T type; }; template<typename T> struct TypeOfAdapter<T&> { typedef typename TypeOfAdapter<T>::type type; }; template<typename T> struct TypeOfAdapter<const T> { typedef typename TypeOfAdapter<T>::type type; }; template<typename T> struct TypeOfAdapter<T*> { typedef typename boost::add_pointer<typename boost::remove_const<typename TypeOfAdapter<T>::type>::type>::type type; }; } template<typename T> Type* typeOf() { return detail::typeOfBackend<typename detail::TypeOfAdapter<T>::type>(); } inline Type::Kind Type::kind() const { return Unknown; } namespace detail { struct signature_function_arg_apply { signature_function_arg_apply(std::string* val) : val(*val) {} template<typename T> void operator()(T *x) { val += qi::typeOf<T>()->signature(); } std::string &val; }; template<typename T> struct RawFunctionSignature { static std::string makeSigreturn() { typedef typename boost::function_types::result_type<T>::type ResultType; return typeOf<ResultType>()->signature(); } static std::string makeSignature() { std::string signature; signature += '('; typedef typename boost::function_types::parameter_types<T>::type ArgsType; boost::mpl::for_each< boost::mpl::transform_view<ArgsType, boost::add_pointer< boost::remove_const< boost::remove_reference<boost::mpl::_1> > > > > (qi::detail::signature_function_arg_apply(&signature)); signature += ')'; return signature; } }; template<typename R, typename F, typename B> struct RawFunctionSignature<boost::_bi::bind_t<R, F, B> > { static std::string makeSigreturn() { typedef typename qi::boost_bind_result_type<boost::_bi::bind_t<R, F, B> >::type ResultType; return typeOf<ResultType>()->signature(); } static std::string makeSignature() { std::string signature; signature += '('; typedef typename qi::boost_bind_parameter_types<boost::_bi::bind_t<R, F, B> >::type ArgsType; boost::mpl::for_each< boost::mpl::transform_view<ArgsType, boost::add_pointer< boost::remove_const< boost::remove_reference<boost::mpl::_1> > > > > (qi::detail::signature_function_arg_apply(&signature)); signature += ')'; return signature; } }; template<typename T> struct MemberFunctionSignature { static std::string makeSigreturn() { typedef typename boost::function_types::result_type<T>::type ResultType; return typeOf<ResultType>()->signature(); } static std::string makeSignature() { // Reconstruct the boost::bind(instance, _1, _2...) signature typedef typename boost::function_types::result_type<T>::type RetType; typedef typename boost::function_types::parameter_types<T>::type MemArgsType; typedef typename boost::mpl::pop_front< MemArgsType >::type ArgsType; typedef typename boost::mpl::push_front<ArgsType, RetType>::type EffectiveType; typedef typename boost::function_types::function_type<EffectiveType>::type type; return RawFunctionSignature<type>::makeSignature(); } }; template<typename T> struct FunctionSignature { typedef typename boost::mpl::if_< typename boost::function_types::is_member_pointer<T>, MemberFunctionSignature<T>, RawFunctionSignature<T> >::type Backend; static std::string signature() { static std::string result = Backend::makeSignature(); return result; } static std::string sigreturn() { static std::string result = Backend::makeSigreturn(); return result; } }; template<typename T> struct FunctionSignature<boost::function<T> > : public FunctionSignature<T> {}; template<typename T> inline std::string functionArgumentsSignature() { static bool done = false; static std::string sigs; if (!done) { sigs += '('; typedef typename boost::function_types::parameter_types<T>::type ArgsType; boost::mpl::for_each< boost::mpl::transform_view<ArgsType, boost::add_pointer< boost::remove_const< boost::remove_reference<boost::mpl::_1> > > > > (qi::detail::signature_function_arg_apply(&sigs)); sigs += ')'; done = true; } return sigs; } // Bouncer to DefaultAccess or DirectAccess based on type size template<typename T> class TypeImplMethodsBySize { public: typedef typename boost::mpl::if_c< sizeof(T) <= sizeof(void*), DefaultTypeImplMethods<T, TypeByValue<T> >, DefaultTypeImplMethods<T, TypeByPointer<T> > >::type type; }; } } #endif // _QITYPE_DETAILS_TYPE_HXX_ <commit_msg>Fix compiler warning with qiLog<commit_after>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QITYPE_DETAILS_TYPE_HXX_ #define _QITYPE_DETAILS_TYPE_HXX_ #include <qi/types.hpp> #include <cstring> #include <map> #include <vector> #include <list> #include <qitype/details/bindtype.hxx> #include <boost/mpl/for_each.hpp> #include <boost/mpl/transform_view.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/type_traits/add_pointer.hpp> #include <boost/function_types/parameter_types.hpp> #include <boost/function_types/result_type.hpp> #include <boost/function_types/function_type.hpp> #include <boost/function_types/is_member_pointer.hpp> /* This file contains the default-provided Type specialisations * */ namespace qi { // void template<> class TypeImpl<void>: public Type { public: const TypeInfo& info() { static TypeInfo result = TypeInfo(typeid(void)); return result; } void* initializeStorage(void*) { return 0;} void* ptrFromStorage(void** ) { return 0;} void* clone(void*) { return 0;} void destroy(void* ptr) {} Kind kind() const { return Void;} }; //reference template<typename T> class TypeImpl<T&> : public TypeImpl<T> {}; //any template<> class TypeImpl<boost::any>: public TypeDynamic { public: std::pair<GenericValuePtr, bool> get(void* storage) { qiLogVerbose("qitype.impl") << "get on boost::any not implemented"; return std::make_pair(GenericValuePtr(), false); }; void set(void** storage, GenericValuePtr source) { qiLogVerbose("qitype.impl") << "set on boost::any not implemented"; } typedef DefaultTypeImplMethods<boost::any> Methods; _QI_BOUNCE_TYPE_METHODS(Methods); }; } namespace qi { namespace detail { template<typename T> inline Type* typeOfBackend() { Type* result = getType(typeid(T)); if (!result) { static Type* defaultResult = 0; // Is this realy a problem? if (!defaultResult) { qiLogDebug("qitype.typeof") << "typeOf request for unregistered type " << typeid(T).name(); } if (!defaultResult) defaultResult = new TypeImpl<T>(); result = defaultResult; } return result; } template<typename T> struct TypeOfAdapter { typedef T type; }; template<typename T> struct TypeOfAdapter<T&> { typedef typename TypeOfAdapter<T>::type type; }; template<typename T> struct TypeOfAdapter<const T> { typedef typename TypeOfAdapter<T>::type type; }; template<typename T> struct TypeOfAdapter<T*> { typedef typename boost::add_pointer<typename boost::remove_const<typename TypeOfAdapter<T>::type>::type>::type type; }; } template<typename T> Type* typeOf() { return detail::typeOfBackend<typename detail::TypeOfAdapter<T>::type>(); } inline Type::Kind Type::kind() const { return Unknown; } namespace detail { struct signature_function_arg_apply { signature_function_arg_apply(std::string* val) : val(*val) {} template<typename T> void operator()(T *x) { val += qi::typeOf<T>()->signature(); } std::string &val; }; template<typename T> struct RawFunctionSignature { static std::string makeSigreturn() { typedef typename boost::function_types::result_type<T>::type ResultType; return typeOf<ResultType>()->signature(); } static std::string makeSignature() { std::string signature; signature += '('; typedef typename boost::function_types::parameter_types<T>::type ArgsType; boost::mpl::for_each< boost::mpl::transform_view<ArgsType, boost::add_pointer< boost::remove_const< boost::remove_reference<boost::mpl::_1> > > > > (qi::detail::signature_function_arg_apply(&signature)); signature += ')'; return signature; } }; template<typename R, typename F, typename B> struct RawFunctionSignature<boost::_bi::bind_t<R, F, B> > { static std::string makeSigreturn() { typedef typename qi::boost_bind_result_type<boost::_bi::bind_t<R, F, B> >::type ResultType; return typeOf<ResultType>()->signature(); } static std::string makeSignature() { std::string signature; signature += '('; typedef typename qi::boost_bind_parameter_types<boost::_bi::bind_t<R, F, B> >::type ArgsType; boost::mpl::for_each< boost::mpl::transform_view<ArgsType, boost::add_pointer< boost::remove_const< boost::remove_reference<boost::mpl::_1> > > > > (qi::detail::signature_function_arg_apply(&signature)); signature += ')'; return signature; } }; template<typename T> struct MemberFunctionSignature { static std::string makeSigreturn() { typedef typename boost::function_types::result_type<T>::type ResultType; return typeOf<ResultType>()->signature(); } static std::string makeSignature() { // Reconstruct the boost::bind(instance, _1, _2...) signature typedef typename boost::function_types::result_type<T>::type RetType; typedef typename boost::function_types::parameter_types<T>::type MemArgsType; typedef typename boost::mpl::pop_front< MemArgsType >::type ArgsType; typedef typename boost::mpl::push_front<ArgsType, RetType>::type EffectiveType; typedef typename boost::function_types::function_type<EffectiveType>::type type; return RawFunctionSignature<type>::makeSignature(); } }; template<typename T> struct FunctionSignature { typedef typename boost::mpl::if_< typename boost::function_types::is_member_pointer<T>, MemberFunctionSignature<T>, RawFunctionSignature<T> >::type Backend; static std::string signature() { static std::string result = Backend::makeSignature(); return result; } static std::string sigreturn() { static std::string result = Backend::makeSigreturn(); return result; } }; template<typename T> struct FunctionSignature<boost::function<T> > : public FunctionSignature<T> {}; template<typename T> inline std::string functionArgumentsSignature() { static bool done = false; static std::string sigs; if (!done) { sigs += '('; typedef typename boost::function_types::parameter_types<T>::type ArgsType; boost::mpl::for_each< boost::mpl::transform_view<ArgsType, boost::add_pointer< boost::remove_const< boost::remove_reference<boost::mpl::_1> > > > > (qi::detail::signature_function_arg_apply(&sigs)); sigs += ')'; done = true; } return sigs; } // Bouncer to DefaultAccess or DirectAccess based on type size template<typename T> class TypeImplMethodsBySize { public: typedef typename boost::mpl::if_c< sizeof(T) <= sizeof(void*), DefaultTypeImplMethods<T, TypeByValue<T> >, DefaultTypeImplMethods<T, TypeByPointer<T> > >::type type; }; } } #endif // _QITYPE_DETAILS_TYPE_HXX_ <|endoftext|>
<commit_before> // Includes. #include "App/Lua/LuaNodeScript.h" #include "App/Logger.h" // Selene. #include <selene.h> // STD. #include <string> #include <sstream> #include <iostream> namespace { void logError(std::string message) { Logger::instance().logError(message); } void logMessage(std::string message) { Logger::instance().logMessage(message); } } class InputList { public: InputList() {} InputList(const std::vector<std::string>& inputs) : inputs_(inputs) { } int count() { return (int)inputs_.size(); } const std::string& getString(int i) { return inputs_.at(i); } float getFloat(int i) { return std::stof(inputs_.at(i)); } private: std::vector<std::string> inputs_; }; class SeleneHelper { public: SeleneHelper() {} sel::State& state() { return state_; } private: sel::State state_{true}; }; LuaNodeScript::LuaNodeScript(const std::string &fileName) : script_file_(fileName) , selene_(new SeleneHelper) { reload(); } LuaNodeScript::~LuaNodeScript() { delete selene_; } std::string LuaNodeScript::name() const { return selene_->state()["name"]; } int LuaNodeScript::numInputs() const { return selene_->state()["num_inputs"]; } int LuaNodeScript::numOutputs() const { return selene_->state()["num_outputs"]; } std::vector<std::string> LuaNodeScript::inputTypes() const { return stringVectorFromLuaTable("input_types"); } std::vector<std::string> LuaNodeScript::outputTypes() const { return stringVectorFromLuaTable("output_types"); } std::vector<std::string> LuaNodeScript::requiredParameters() const { return stringVectorFromLuaTable("required_parameters"); } bool LuaNodeScript::validateParameter(const std::string &name, const std::string &value) const { return selene_->state()["validateParameter"](name, value); } std::string LuaNodeScript::evaluateAtOutput(const std::vector<std::string> &inputs, int outputIndex) const { InputList list(inputs); // Register the instance "list" instead of the class. selene_->state()["ndn_inputs"].SetObj(list, "count", &InputList::count, "string", &InputList::getString, "float", &InputList::getFloat); return selene_->state()["evaluateForOutput"](outputIndex); } bool LuaNodeScript::reload() { bool ok = selene_->state().Load(script_file_); if (!ok) { Logger::instance().logError(selene_->state().errorMessage()); } else { selene_->state()["ndnLogError"] = &logError; selene_->state()["ndnLogMessage"] = &logMessage; } return ok; } bool LuaNodeScript::isValid(const std::string& fileName) { sel::State state; if (!state.Load(fileName)) { Logger::instance().logError(state.errorMessage()); return false; } std::vector<std::string> required_vars; required_vars.push_back("name"); required_vars.push_back("num_inputs"); required_vars.push_back("num_outputs"); required_vars.push_back("input_types"); required_vars.push_back("output_types"); required_vars.push_back("evaluateForOutput"); for (size_t i = 0; i < required_vars.size(); ++i) { std::string var = required_vars[i]; if ( state.CheckNil(var) ) { std::ostringstream stream; stream << "\"" << var << "\" variable not found."; Logger::instance().logError(stream.str()); return false; } } return true; } std::vector<std::string> LuaNodeScript::stringVectorFromLuaTable(const char *varName) const { std::vector<std::string> result; sel::Selector table = selene_->state()[varName]; int i = 1; std::string type = table[i]; while (!type.empty()) { result.push_back(type); std::string next_type = table[++i]; type = next_type; } return result; } <commit_msg>Lua does not cope well with const std::string.<commit_after> // Includes. #include "App/Lua/LuaNodeScript.h" #include "App/Logger.h" // Selene. #include <selene.h> // STD. #include <string> #include <sstream> #include <iostream> namespace { void logError(std::string message) { Logger::instance().logError(message); } void logMessage(std::string message) { Logger::instance().logMessage(message); } } class InputList { public: InputList() {} InputList(const std::vector<std::string>& inputs) : inputs_(inputs) { } int count() { return (int)inputs_.size(); } std::string getString(int i) { return inputs_.at(i); } float getFloat(int i) { return std::stof(inputs_.at(i)); } private: std::vector<std::string> inputs_; }; class SeleneHelper { public: SeleneHelper() {} sel::State& state() { return state_; } private: sel::State state_{true}; }; LuaNodeScript::LuaNodeScript(const std::string &fileName) : script_file_(fileName) , selene_(new SeleneHelper) { reload(); } LuaNodeScript::~LuaNodeScript() { delete selene_; } std::string LuaNodeScript::name() const { return selene_->state()["name"]; } int LuaNodeScript::numInputs() const { return selene_->state()["num_inputs"]; } int LuaNodeScript::numOutputs() const { return selene_->state()["num_outputs"]; } std::vector<std::string> LuaNodeScript::inputTypes() const { return stringVectorFromLuaTable("input_types"); } std::vector<std::string> LuaNodeScript::outputTypes() const { return stringVectorFromLuaTable("output_types"); } std::vector<std::string> LuaNodeScript::requiredParameters() const { return stringVectorFromLuaTable("required_parameters"); } bool LuaNodeScript::validateParameter(const std::string &name, const std::string &value) const { return selene_->state()["validateParameter"](name, value); } std::string LuaNodeScript::evaluateAtOutput(const std::vector<std::string> &inputs, int outputIndex) const { InputList list(inputs); // Register the instance "list" instead of the class. selene_->state()["ndn_inputs"].SetObj(list, "count", &InputList::count, "string", &InputList::getString, "float", &InputList::getFloat); return selene_->state()["evaluateForOutput"](outputIndex); } bool LuaNodeScript::reload() { bool ok = selene_->state().Load(script_file_); if (!ok) { Logger::instance().logError(selene_->state().errorMessage()); } else { selene_->state()["ndnLogError"] = &logError; selene_->state()["ndnLogMessage"] = &logMessage; } return ok; } bool LuaNodeScript::isValid(const std::string& fileName) { sel::State state; if (!state.Load(fileName)) { Logger::instance().logError(state.errorMessage()); return false; } std::vector<std::string> required_vars; required_vars.push_back("name"); required_vars.push_back("num_inputs"); required_vars.push_back("num_outputs"); required_vars.push_back("input_types"); required_vars.push_back("output_types"); required_vars.push_back("evaluateForOutput"); for (size_t i = 0; i < required_vars.size(); ++i) { std::string var = required_vars[i]; if ( state.CheckNil(var) ) { std::ostringstream stream; stream << "\"" << var << "\" variable not found."; Logger::instance().logError(stream.str()); return false; } } return true; } std::vector<std::string> LuaNodeScript::stringVectorFromLuaTable(const char *varName) const { std::vector<std::string> result; sel::Selector table = selene_->state()[varName]; int i = 1; std::string type = table[i]; while (!type.empty()) { result.push_back(type); std::string next_type = table[++i]; type = next_type; } return result; } <|endoftext|>
<commit_before>/*! * Copyright (C) 2014 Nomovok Ltd. All rights reserved. * Contact: info@nomovok.com * * This file may be used under the terms of the GNU Lesser * General Public License version 2.1 as published by the Free Software * Foundation and appearing in the file LICENSE.LGPL included in the * packaging of this file. Please review the following information to * ensure the GNU Lesser General Public License version 2.1 requirements * will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. * * In addition, as a special exception, copyright holders * give you certain additional rights. These rights are described in * the Digia Qt LGPL Exception version 1.1, included in the file * LGPL_EXCEPTION.txt in this package. */ #include <QQmlEngine> #include <QMap> #include <QDir> #include <QQmlComponent> #include <private/qv4isel_moth_p.h> #include <private/qobject_p.h> #include <private/qqmlcompiler_p.h> #include <private/qqmlcomponent_p.h> #include <private/qv4compileddata_p.h> #include "qmcloader.h" #include "qmcfile.h" #include "qmcunit.h" #include "qmctypeunit.h" static int DEPENDENCY_MAX_RECURSION_DEPTH = 10; /* This takes care when the user calls Qt.createComponent in javascript to load * the .qmc in place of creating a component from the .qml */ static QQmlComponent *loadCallback(QQmlEngine *engine, QUrl url) { QmcLoader loader(engine); QString qmcfile = url.toString().replace("file://", "").replace(".qml", ".qmc"); return loader.loadComponent(qmcfile); } class QmcLoaderPrivate : public QObjectPrivate { Q_DECLARE_PUBLIC(QmcLoader) public: QmcLoaderPrivate(QQmlEngine *engine); virtual ~QmcLoaderPrivate(); QQmlEngine *engine; QList<QQmlError> errors; QmcTypeUnit* unit; QMap<QString, QmcUnit *> dependencies; bool loadDependenciesAutomatically; int dependencyRecursionDepth; }; QmcLoaderPrivate::QmcLoaderPrivate(QQmlEngine *engine) : engine(engine), unit(NULL), loadDependenciesAutomatically(true), dependencyRecursionDepth(0) { } QmcLoaderPrivate::~QmcLoaderPrivate() { if (unit) unit->release(); foreach (QmcUnit *unit, dependencies) { unit->blob->release(); } dependencies.clear(); } QmcLoader::QmcLoader(QQmlEngine *engine, QObject *parent) : QObject(*(new QmcLoaderPrivate(engine)), parent) { } QQmlComponent *QmcLoader::loadComponent(const QString &file) { Q_D(QmcLoader); if (QQmlFile::isBundle(file)) { // Untested at this point. QUrl url(file); QQmlBundleData *bundle = QQmlEnginePrivate::get(d->engine)->typeLoader.getBundle(url.host()); if (!bundle) { QQmlError error; error.setDescription("Could not load bundle"); error.setUrl(url); appendError(error); return NULL; } QString fileName = url.path().mid(1); const QQmlBundle::FileEntry *entry = bundle->find(fileName); if (!entry) { QQmlError error; error.setDescription("Could not find file in bundle"); error.setUrl(QUrl(fileName)); appendError(error); return NULL; } QByteArray contents(entry->contents(), entry->fileSize()); QDataStream in(contents); QQmlComponent *ret = loadComponent(in, createLoadedUrl(file)); bundle->release(); return ret; } // This loads files and from bundles embedded in the application. QUrl url(file); QString fileName = QQmlFile::urlToLocalFileOrQrc(url); QFile f(fileName); if (!f.open(QFile::ReadOnly)) { QQmlError error; error.setDescription("Could not open file for reading"); error.setUrl(QUrl(file)); appendError(error); return NULL; } QDataStream in(&f); QQmlComponent *ret = loadComponent(in, createLoadedUrl(file)); f.close(); return ret; } QQmlComponent *QmcLoader::loadComponent(QDataStream &stream, const QUrl &loadedUrl) { clearError(); Q_D(QmcLoader); d->engine->setLoadCallback(loadCallback); // TBD: check validity of all read values QmcUnit *unit = QmcUnit::loadUnit(stream, d->engine, this, loadedUrl); if (!unit) { QQmlError error; error.setDescription("Error parsing / loading"); error.setUrl(loadedUrl); appendError(error); return NULL; } // replace with loaded url cause we aren't always loading from the same // directories as we compiled unit->url = loadedUrl; unit->urlString = loadedUrl.toString(); if (unit->type != QMC_QML) { QQmlError error; error.setDescription("Cannot have Script unit as main unit"); error.setUrl(loadedUrl); appendError(error); unit->blob->release(); return NULL; } QmcTypeUnit *typeUnit = (QmcTypeUnit *)unit->blob; // add to engine if (!typeUnit->link()) { appendErrors(unit->errors); unit->blob->release(); return NULL; } // create QQmlComponent and attach QQmlCompiledData into it QQmlComponent *component = typeUnit->createComponent(); if (!component) { QQmlError error; error.setDescription("Error creating QQmlComponent"); error.setUrl(unit->url); appendError(error); unit->blob->release(); return NULL; } // TBD: where to put unit d->unit = typeUnit; d->unit->addref(); return component; } void QmcLoader::setLoadDependenciesAutomatically(bool load) { Q_D(QmcLoader); d->loadDependenciesAutomatically = load; } bool QmcLoader::isLoadDependenciesAutomatically() const { const Q_D(QmcLoader); return d->loadDependenciesAutomatically; } QUrl QmcLoader::createLoadedUrl(const QString &file) { QString urlStr; if (file.startsWith(":/")) urlStr = "qrc:"; else if(file.startsWith("/")) urlStr = "file://"; else{ QDir dd; urlStr = "file://" + dd.absolutePath() + "/"; } urlStr.append(file); return QUrl(urlStr); } QString QmcLoader::getBaseUrl(const QUrl &url) { QString path = url.path(); QUrl newUrl(url); int lastSlash = path.lastIndexOf('/'); if (lastSlash != -1) { path = path.left(lastSlash + 1); newUrl.setPath(path); } else { newUrl.setPath(""); } return newUrl.toString(); } QmcUnit *QmcLoader::getUnit(const QString &url) { Q_D(QmcLoader); QString precompiled = precompiledUrl(url); if (!d->dependencies.contains(precompiled)) { if (d->loadDependenciesAutomatically) { // try to load it if (d->dependencyRecursionDepth >= DEPENDENCY_MAX_RECURSION_DEPTH) { QQmlError error; error.setDescription("Could not load dependency, too deep recursion"); error.setUrl(url); appendError(error); return NULL; } d->dependencyRecursionDepth++; QmcUnit *unit = doloadDependency(precompiled); d->dependencyRecursionDepth--; return unit; } else return NULL; } return d->dependencies[precompiled]; } QString QmcLoader::precompiledUrl(const QString &url) { QString urlString = url; if (url.endsWith(".js")) urlString.append("c"); else if (url.endsWith(".qml")) urlString[urlString.length() - 1] = 'c'; return urlString; } QmcScriptUnit *QmcLoader::getScript(const QString &url, const QUrl &loaderUrl) { QString newUrl; if(url.startsWith("file:")){ newUrl = url; }else{ newUrl = getBaseUrl(loaderUrl); newUrl.append(url); } QmcUnit *unit = getUnit(newUrl); if (!unit) return NULL; if (unit->type != QMC_JS) return NULL; unit->blob->addref(); return (QmcScriptUnit *)unit->blob; } QmcUnit *QmcLoader::getType(const QString &name, const QUrl &loaderUrl) { qDebug() << "Getting type name = " << name << "loaderUrl =" << loaderUrl; QString newUrl; if(name.startsWith("file://")){ newUrl = name; newUrl.append(".qml"); }else{ newUrl = getBaseUrl(loaderUrl); newUrl.append(name); newUrl.append(".qml"); } QmcUnit *unit = getUnit(newUrl); if (!unit) return NULL; if (unit->type != QMC_QML) return NULL; unit->blob->addref(); return unit; } bool QmcLoader::loadDependency(QDataStream &stream, const QUrl &loadedUrl) { clearError(); QmcUnit *unit = doloadDependency(stream, loadedUrl); unit->blob->release(); return true; } bool QmcLoader::loadDependency(const QString &file) { clearError(); QUrl url(file); QString fileName = QQmlFile::urlToLocalFileOrQrc(url); QFile f(fileName); if (!f.open(QFile::ReadOnly)) { QQmlError error; error.setDescription("Could not open file for reading"); error.setUrl(url); appendError(error); return NULL; } QDataStream in(&f); QmcUnit *unit = doloadDependency(in, createLoadedUrl(file)); unit->blob->release(); f.close(); return true; } QmcUnit *QmcLoader::doloadDependency(const QString &url) { QString file = QQmlFile::urlToLocalFileOrQrc(url); QFile f(file); if (!f.open(QFile::ReadOnly)) { QQmlError error; error.setDescription("Could not open file for reading: " + f.errorString()); qWarning() << "Could not open file for reading" << file; error.setUrl(QUrl(file)); qDebug() << "Cannot open" << file; appendError(error); return NULL; } QDataStream in(&f); const QUrl loadAs = createLoadedUrl(file); qDebug() << "Loading dependency" << url << "as" << loadAs; QmcUnit *unit = doloadDependency(in, loadAs); f.close(); return unit; } QmcUnit *QmcLoader::doloadDependency(QDataStream &stream, const QUrl &loadedUrl) { Q_D(QmcLoader); QmcUnit *unit = QmcUnit::loadUnit(stream, d->engine, this, loadedUrl); if (!unit) { QQmlError error; error.setDescription("Error loading"); appendError(error); return NULL; } // add to dependencies d->dependencies[unit->loadedUrl.toString()] = unit; unit->blob->addref(); return unit; } const QList<QQmlError>& QmcLoader::errors() const { const Q_D(QmcLoader); return d->errors; } void QmcLoader::clearError() { Q_D(QmcLoader); d->errors.clear(); } void QmcLoader::appendError(QQmlError error) { Q_D(QmcLoader); d->errors.append(error); } void QmcLoader::appendErrors(const QList<QQmlError> &errors) { Q_D(QmcLoader); d->errors.append(errors); } <commit_msg>Pass QmcLoader handle for loader callback to use<commit_after>/*! * Copyright (C) 2014 Nomovok Ltd. All rights reserved. * Contact: info@nomovok.com * * This file may be used under the terms of the GNU Lesser * General Public License version 2.1 as published by the Free Software * Foundation and appearing in the file LICENSE.LGPL included in the * packaging of this file. Please review the following information to * ensure the GNU Lesser General Public License version 2.1 requirements * will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. * * In addition, as a special exception, copyright holders * give you certain additional rights. These rights are described in * the Digia Qt LGPL Exception version 1.1, included in the file * LGPL_EXCEPTION.txt in this package. */ #include <QQmlEngine> #include <QMap> #include <QDir> #include <QQmlComponent> #include <private/qv4isel_moth_p.h> #include <private/qobject_p.h> #include <private/qqmlcompiler_p.h> #include <private/qqmlcomponent_p.h> #include <private/qv4compileddata_p.h> #include "qmcloader.h" #include "qmcfile.h" #include "qmcunit.h" #include "qmctypeunit.h" static int DEPENDENCY_MAX_RECURSION_DEPTH = 10; /* This takes care when the user calls Qt.createComponent in javascript to load * the .qmc in place of creating a component from the .qml */ static QQmlComponent *loadCallback(QQmlEngine *engine, QUrl url, void *data) { QmcLoader *loader = static_cast<QmcLoader*>(data); QString qmcfile = url.toString().replace("file://", "").replace(".qml", ".qmc"); return loader->loadComponent(qmcfile); } class QmcLoaderPrivate : public QObjectPrivate { Q_DECLARE_PUBLIC(QmcLoader) public: QmcLoaderPrivate(QQmlEngine *engine); virtual ~QmcLoaderPrivate(); QQmlEngine *engine; QList<QQmlError> errors; QmcTypeUnit* unit; QMap<QString, QmcUnit *> dependencies; bool loadDependenciesAutomatically; int dependencyRecursionDepth; }; QmcLoaderPrivate::QmcLoaderPrivate(QQmlEngine *engine) : engine(engine), unit(NULL), loadDependenciesAutomatically(true), dependencyRecursionDepth(0) { } QmcLoaderPrivate::~QmcLoaderPrivate() { if (unit) unit->release(); foreach (QmcUnit *unit, dependencies) { unit->blob->release(); } dependencies.clear(); } QmcLoader::QmcLoader(QQmlEngine *engine, QObject *parent) : QObject(*(new QmcLoaderPrivate(engine)), parent) { } QQmlComponent *QmcLoader::loadComponent(const QString &file) { Q_D(QmcLoader); if (QQmlFile::isBundle(file)) { // Untested at this point. QUrl url(file); QQmlBundleData *bundle = QQmlEnginePrivate::get(d->engine)->typeLoader.getBundle(url.host()); if (!bundle) { QQmlError error; error.setDescription("Could not load bundle"); error.setUrl(url); appendError(error); return NULL; } QString fileName = url.path().mid(1); const QQmlBundle::FileEntry *entry = bundle->find(fileName); if (!entry) { QQmlError error; error.setDescription("Could not find file in bundle"); error.setUrl(QUrl(fileName)); appendError(error); return NULL; } QByteArray contents(entry->contents(), entry->fileSize()); QDataStream in(contents); QQmlComponent *ret = loadComponent(in, createLoadedUrl(file)); bundle->release(); return ret; } // This loads files and from bundles embedded in the application. QUrl url(file); QString fileName = QQmlFile::urlToLocalFileOrQrc(url); QFile f(fileName); if (!f.open(QFile::ReadOnly)) { QQmlError error; error.setDescription("Could not open file for reading"); error.setUrl(QUrl(file)); appendError(error); return NULL; } QDataStream in(&f); QQmlComponent *ret = loadComponent(in, createLoadedUrl(file)); f.close(); return ret; } QQmlComponent *QmcLoader::loadComponent(QDataStream &stream, const QUrl &loadedUrl) { clearError(); Q_D(QmcLoader); d->engine->setLoadCallback(loadCallback, this); // TBD: check validity of all read values QmcUnit *unit = QmcUnit::loadUnit(stream, d->engine, this, loadedUrl); if (!unit) { QQmlError error; error.setDescription("Error parsing / loading"); error.setUrl(loadedUrl); appendError(error); return NULL; } // replace with loaded url cause we aren't always loading from the same // directories as we compiled unit->url = loadedUrl; unit->urlString = loadedUrl.toString(); if (unit->type != QMC_QML) { QQmlError error; error.setDescription("Cannot have Script unit as main unit"); error.setUrl(loadedUrl); appendError(error); unit->blob->release(); return NULL; } QmcTypeUnit *typeUnit = (QmcTypeUnit *)unit->blob; // add to engine if (!typeUnit->link()) { appendErrors(unit->errors); unit->blob->release(); return NULL; } // create QQmlComponent and attach QQmlCompiledData into it QQmlComponent *component = typeUnit->createComponent(); if (!component) { QQmlError error; error.setDescription("Error creating QQmlComponent"); error.setUrl(unit->url); appendError(error); unit->blob->release(); return NULL; } // TBD: where to put unit d->unit = typeUnit; d->unit->addref(); return component; } void QmcLoader::setLoadDependenciesAutomatically(bool load) { Q_D(QmcLoader); d->loadDependenciesAutomatically = load; } bool QmcLoader::isLoadDependenciesAutomatically() const { const Q_D(QmcLoader); return d->loadDependenciesAutomatically; } QUrl QmcLoader::createLoadedUrl(const QString &file) { QString urlStr; if (file.startsWith(":/")) urlStr = "qrc:"; else if(file.startsWith("/")) urlStr = "file://"; else{ QDir dd; urlStr = "file://" + dd.absolutePath() + "/"; } urlStr.append(file); return QUrl(urlStr); } QString QmcLoader::getBaseUrl(const QUrl &url) { QString path = url.path(); QUrl newUrl(url); int lastSlash = path.lastIndexOf('/'); if (lastSlash != -1) { path = path.left(lastSlash + 1); newUrl.setPath(path); } else { newUrl.setPath(""); } return newUrl.toString(); } QmcUnit *QmcLoader::getUnit(const QString &url) { Q_D(QmcLoader); QString precompiled = precompiledUrl(url); if (!d->dependencies.contains(precompiled)) { if (d->loadDependenciesAutomatically) { // try to load it if (d->dependencyRecursionDepth >= DEPENDENCY_MAX_RECURSION_DEPTH) { QQmlError error; error.setDescription("Could not load dependency, too deep recursion"); error.setUrl(url); appendError(error); return NULL; } d->dependencyRecursionDepth++; QmcUnit *unit = doloadDependency(precompiled); d->dependencyRecursionDepth--; return unit; } else return NULL; } return d->dependencies[precompiled]; } QString QmcLoader::precompiledUrl(const QString &url) { QString urlString = url; if (url.endsWith(".js")) urlString.append("c"); else if (url.endsWith(".qml")) urlString[urlString.length() - 1] = 'c'; return urlString; } QmcScriptUnit *QmcLoader::getScript(const QString &url, const QUrl &loaderUrl) { QString newUrl; if(url.startsWith("file:")){ newUrl = url; }else{ newUrl = getBaseUrl(loaderUrl); newUrl.append(url); } QmcUnit *unit = getUnit(newUrl); if (!unit) return NULL; if (unit->type != QMC_JS) return NULL; unit->blob->addref(); return (QmcScriptUnit *)unit->blob; } QmcUnit *QmcLoader::getType(const QString &name, const QUrl &loaderUrl) { qDebug() << "Getting type name = " << name << "loaderUrl =" << loaderUrl; QString newUrl; if(name.startsWith("file://")){ newUrl = name; newUrl.append(".qml"); }else{ newUrl = getBaseUrl(loaderUrl); newUrl.append(name); newUrl.append(".qml"); } QmcUnit *unit = getUnit(newUrl); if (!unit) return NULL; if (unit->type != QMC_QML) return NULL; unit->blob->addref(); return unit; } bool QmcLoader::loadDependency(QDataStream &stream, const QUrl &loadedUrl) { clearError(); QmcUnit *unit = doloadDependency(stream, loadedUrl); unit->blob->release(); return true; } bool QmcLoader::loadDependency(const QString &file) { clearError(); QUrl url(file); QString fileName = QQmlFile::urlToLocalFileOrQrc(url); QFile f(fileName); if (!f.open(QFile::ReadOnly)) { QQmlError error; error.setDescription("Could not open file for reading"); error.setUrl(url); appendError(error); return NULL; } QDataStream in(&f); QmcUnit *unit = doloadDependency(in, createLoadedUrl(file)); unit->blob->release(); f.close(); return true; } QmcUnit *QmcLoader::doloadDependency(const QString &url) { QString file = QQmlFile::urlToLocalFileOrQrc(url); QFile f(file); if (!f.open(QFile::ReadOnly)) { QQmlError error; error.setDescription("Could not open file for reading: " + f.errorString()); qWarning() << "Could not open file for reading" << file; error.setUrl(QUrl(file)); qDebug() << "Cannot open" << file; appendError(error); return NULL; } QDataStream in(&f); const QUrl loadAs = createLoadedUrl(file); qDebug() << "Loading dependency" << url << "as" << loadAs; QmcUnit *unit = doloadDependency(in, loadAs); f.close(); return unit; } QmcUnit *QmcLoader::doloadDependency(QDataStream &stream, const QUrl &loadedUrl) { Q_D(QmcLoader); QmcUnit *unit = QmcUnit::loadUnit(stream, d->engine, this, loadedUrl); if (!unit) { QQmlError error; error.setDescription("Error loading"); appendError(error); return NULL; } // add to dependencies d->dependencies[unit->loadedUrl.toString()] = unit; unit->blob->addref(); return unit; } const QList<QQmlError>& QmcLoader::errors() const { const Q_D(QmcLoader); return d->errors; } void QmcLoader::clearError() { Q_D(QmcLoader); d->errors.clear(); } void QmcLoader::appendError(QQmlError error) { Q_D(QmcLoader); d->errors.append(error); } void QmcLoader::appendErrors(const QList<QQmlError> &errors) { Q_D(QmcLoader); d->errors.append(errors); } <|endoftext|>
<commit_before>/* This file is part of KAddressBook. Copyright (c) 2002 Mike Pilone <mpilone@slac.com> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qlayout.h> #include <qpopupmenu.h> #include <kabc/addressbook.h> #include <kabc/distributionlistdialog.h> #include <kconfig.h> #include <kdebug.h> #include <klocale.h> #include <kxmlguifactory.h> #include <kxmlguiclient.h> #include "core.h" #include "searchmanager.h" #include "kaddressbookview.h" KAddressBookView::KAddressBookView( KAB::Core *core, QWidget *parent, const char *name ) : QWidget( parent, name ), mCore( core ), mFieldList() { initGUI(); connect( SearchManager::self(), SIGNAL( contactsUpdated() ), this, SLOT( updateView() ) ); } KAddressBookView::~KAddressBookView() { kdDebug(5720) << "KAddressBookView::~KAddressBookView: destroying - " << name() << endl; } void KAddressBookView::readConfig( KConfig *config ) { mFieldList = KABC::Field::restoreFields( config, "KABCFields" ); if ( mFieldList.isEmpty() ) mFieldList = KABC::Field::defaultFields(); mDefaultFilterType = (DefaultFilterType)config->readNumEntry( "DefaultFilterType", 1 ); mDefaultFilterName = config->readEntry( "DefaultFilterName" ); } void KAddressBookView::writeConfig( KConfig* ) { // Most of writing the config is handled by the ConfigureViewDialog } QString KAddressBookView::selectedEmails() { bool first = true; QString emailAddrs; QStringList uidList = selectedUids(); KABC::Addressee addr; QString email; QStringList::Iterator it; for ( it = uidList.begin(); it != uidList.end(); ++it ) { addr = mCore->addressBook()->findByUid( *it ); if ( !addr.isEmpty() ) { QString m = QString::null; if ( addr.emails().count() > 1 ) m = KABC::EmailSelector::getEmail( addr.emails(), addr.preferredEmail(), this ); email = addr.fullEmail( m ); if ( !first ) emailAddrs += ", "; else first = false; emailAddrs += email; } } return emailAddrs; } KABC::Addressee::List KAddressBookView::addressees() { KABC::Addressee::List addresseeList; KABC::Addressee::List contacts = SearchManager::self()->contacts(); KABC::Addressee::List::Iterator it; for ( it = contacts.begin(); it != contacts.end(); ++it ) { if ( mFilter.filterAddressee( *it ) ) addresseeList.append( *it ); } return addresseeList; } void KAddressBookView::initGUI() { // Create the layout QVBoxLayout *layout = new QVBoxLayout( this ); // Add the view widget mViewWidget = new QWidget( this ); layout->addWidget( mViewWidget ); } KABC::Field::List KAddressBookView::fields() const { return mFieldList; } void KAddressBookView::setFilter( const Filter &filter ) { mFilter = filter; } KAddressBookView::DefaultFilterType KAddressBookView::defaultFilterType() const { return mDefaultFilterType; } const QString &KAddressBookView::defaultFilterName() const { return mDefaultFilterName; } KAB::Core *KAddressBookView::core() const { return mCore; } void KAddressBookView::popup( const QPoint &point ) { if ( !mCore->guiClient() ) { kdWarning() << "No GUI client set!" << endl; return; } QPopupMenu *menu = static_cast<QPopupMenu*>( mCore->guiClient()->factory()->container( "RMBPopup", mCore->guiClient() ) ); if ( menu ) menu->popup( point ); } QWidget *KAddressBookView::viewWidget() { return mViewWidget; } void KAddressBookView::updateView() { refresh(); } ViewConfigureWidget *ViewFactory::configureWidget( KABC::AddressBook *ab, QWidget *parent, const char *name ) { return new ViewConfigureWidget( ab, parent, name ); } #include "kaddressbookview.moc" <commit_msg>Select a contact after a reload.<commit_after>/* This file is part of KAddressBook. Copyright (c) 2002 Mike Pilone <mpilone@slac.com> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qlayout.h> #include <qpopupmenu.h> #include <kabc/addressbook.h> #include <kabc/distributionlistdialog.h> #include <kconfig.h> #include <kdebug.h> #include <klocale.h> #include <kxmlguifactory.h> #include <kxmlguiclient.h> #include "core.h" #include "searchmanager.h" #include "kaddressbookview.h" KAddressBookView::KAddressBookView( KAB::Core *core, QWidget *parent, const char *name ) : QWidget( parent, name ), mCore( core ), mFieldList() { initGUI(); connect( SearchManager::self(), SIGNAL( contactsUpdated() ), this, SLOT( updateView() ) ); } KAddressBookView::~KAddressBookView() { kdDebug(5720) << "KAddressBookView::~KAddressBookView: destroying - " << name() << endl; } void KAddressBookView::readConfig( KConfig *config ) { mFieldList = KABC::Field::restoreFields( config, "KABCFields" ); if ( mFieldList.isEmpty() ) mFieldList = KABC::Field::defaultFields(); mDefaultFilterType = (DefaultFilterType)config->readNumEntry( "DefaultFilterType", 1 ); mDefaultFilterName = config->readEntry( "DefaultFilterName" ); } void KAddressBookView::writeConfig( KConfig* ) { // Most of writing the config is handled by the ConfigureViewDialog } QString KAddressBookView::selectedEmails() { bool first = true; QString emailAddrs; QStringList uidList = selectedUids(); KABC::Addressee addr; QString email; QStringList::Iterator it; for ( it = uidList.begin(); it != uidList.end(); ++it ) { addr = mCore->addressBook()->findByUid( *it ); if ( !addr.isEmpty() ) { QString m = QString::null; if ( addr.emails().count() > 1 ) m = KABC::EmailSelector::getEmail( addr.emails(), addr.preferredEmail(), this ); email = addr.fullEmail( m ); if ( !first ) emailAddrs += ", "; else first = false; emailAddrs += email; } } return emailAddrs; } KABC::Addressee::List KAddressBookView::addressees() { KABC::Addressee::List addresseeList; KABC::Addressee::List contacts = SearchManager::self()->contacts(); KABC::Addressee::List::Iterator it; for ( it = contacts.begin(); it != contacts.end(); ++it ) { if ( mFilter.filterAddressee( *it ) ) addresseeList.append( *it ); } return addresseeList; } void KAddressBookView::initGUI() { // Create the layout QVBoxLayout *layout = new QVBoxLayout( this ); // Add the view widget mViewWidget = new QWidget( this ); layout->addWidget( mViewWidget ); } KABC::Field::List KAddressBookView::fields() const { return mFieldList; } void KAddressBookView::setFilter( const Filter &filter ) { mFilter = filter; } KAddressBookView::DefaultFilterType KAddressBookView::defaultFilterType() const { return mDefaultFilterType; } const QString &KAddressBookView::defaultFilterName() const { return mDefaultFilterName; } KAB::Core *KAddressBookView::core() const { return mCore; } void KAddressBookView::popup( const QPoint &point ) { if ( !mCore->guiClient() ) { kdWarning() << "No GUI client set!" << endl; return; } QPopupMenu *menu = static_cast<QPopupMenu*>( mCore->guiClient()->factory()->container( "RMBPopup", mCore->guiClient() ) ); if ( menu ) menu->popup( point ); } QWidget *KAddressBookView::viewWidget() { return mViewWidget; } void KAddressBookView::updateView() { refresh(); KABC::Addressee::List contacts = SearchManager::self()->contacts(); if ( contacts.count() > 0 ) setSelected( contacts.first().uid(), true ); else { setSelected( QString::null, false ); emit selected( QString::null ); } } ViewConfigureWidget *ViewFactory::configureWidget( KABC::AddressBook *ab, QWidget *parent, const char *name ) { return new ViewConfigureWidget( ab, parent, name ); } #include "kaddressbookview.moc" <|endoftext|>
<commit_before>#include "node-syslog.h" using namespace v8; using namespace node; #define NODE_LESS_THAN_5 (!(NODE_VERSION_AT_LEAST(0, 5, 4))) #define NODE_LESS_THAN_6 (!(NODE_VERSION_AT_LEAST(0, 6, 0))) Persistent<FunctionTemplate> Syslog::constructor_template; bool Syslog::connected_ = false; char Syslog::name[1024]; void Syslog::Initialize ( Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(); constructor_template = Persistent<FunctionTemplate>::New(t); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); constructor_template->SetClassName(String::NewSymbol("Syslog")); NODE_SET_METHOD(constructor_template, "init", Syslog::init); NODE_SET_METHOD(constructor_template, "log", Syslog::log); NODE_SET_METHOD(constructor_template, "setMask", Syslog::setMask); NODE_SET_METHOD(constructor_template, "close", Syslog::destroy); target->Set(String::NewSymbol("Syslog"), constructor_template->GetFunction()); } Handle<Value> Syslog::init ( const Arguments& args) { HandleScope scope; if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(Exception::Error( String::New("Must give daemonname string as argument"))); } if (args.Length() < 3 ) { return ThrowException(Exception::Error( String::New("Must have atleast 3 params as argument"))); } if(connected_) close(); //open syslog args[0]->ToString()->WriteAscii((char*) &name); int options = args[1]->ToInt32()->Value(); int facility = args[2]->ToInt32()->Value(); open( options , facility ); return Undefined(); } struct log_request { Persistent<Function> cb; char *msg; uint32_t log_level; }; #if !NODE_LESS_THAN_6 static void UV_AfterLog(uv_work_t *req) { #else static int EIO_AfterLog( eio_req *req) { #endif HandleScope scope; struct log_request *log_req = (struct log_request *)(req->data); log_req->cb.Dispose(); // is this necessary? free(log_req->msg); free(log_req); delete req; #if NODE_LESS_THAN_6 ev_unref(EV_DEFAULT_UC); #endif #if NODE_LESS_THAN_5 return 0; #endif } #if !NODE_LESS_THAN_6 static void UV_Log(uv_work_t *req) { #elif !NODE_LESS_THAN_5 static void EIO_Log(eio_req *req) { #else static int EIO_Log(eio_req *req) { #endif struct log_request *log_req = (struct log_request *)(req->data); char *msg = log_req->msg; syslog(log_req->log_level, "%s", msg); #if NODE_LESS_THAN_6 req->result = 0; #endif #if NODE_LESS_THAN_5 return 0; #else return; #endif } Handle<Value> Syslog::log ( const Arguments& args) { HandleScope scope; Local<Function> cb = Local<Function>::Cast(args[3]); struct log_request * log_req = (struct log_request *) calloc(1, sizeof(struct log_request)); if(!log_req) { V8::LowMemoryNotification(); return ThrowException(Exception::Error( String::New("Could not allocate enought memory"))); } if(!connected_) return ThrowException(Exception::Error( String::New("init method has to be called befor syslog"))); String::AsciiValue msg(args[1]); uint32_t log_level = args[0]->Int32Value(); log_req->cb = Persistent<Function>::New(cb); log_req->msg = strdup(*msg); log_req->log_level = log_level; #if NODE_LESS_THAN_6 eio_custom(EIO_Log, EIO_PRI_DEFAULT, EIO_AfterLog, log_req); ev_ref(EV_DEFAULT_UC); #else uv_work_t *work_req = new uv_work_t(); work_req->data = log_req; uv_queue_work(uv_default_loop(), work_req, UV_Log, UV_AfterLog); #endif return Undefined(); } Handle<Value> Syslog::destroy ( const Arguments& args) { HandleScope scope; close(); return Undefined(); } void Syslog::open ( int option, int facility) { openlog( name, option, facility ); connected_ = true; } Handle<Value> Syslog::setMask ( const Arguments& args) { bool upTo = false; int mask, value; if (args.Length() < 1) { return ThrowException(Exception::Error(String::New("You must provide an mask"))); } if (!args[0]->IsNumber()) { return ThrowException(Exception::Error(String::New("First parameter (mask) should be numeric"))); } if (args.Length() == 2 && !args[1]->IsBoolean()) { return ThrowException(Exception::Error(String::New("Second parameter (upTo) should be boolean"))); } if (args.Length() == 2 && args[1]->IsBoolean()) { upTo = true; } value = args[0]->Int32Value(); if(upTo) { mask = LOG_UPTO(value); } else { mask = LOG_MASK(value); } return Integer::New( setlogmask(mask) ); } void Syslog::close () { if(connected_) { closelog(); connected_ = false; } } extern "C" void init (Handle<Object> target) { HandleScope scope; Syslog::Initialize(target); } <commit_msg>cleanup return values<commit_after>#include "node-syslog.h" using namespace v8; using namespace node; #define NODE_LESS_THAN_5 (!(NODE_VERSION_AT_LEAST(0, 5, 4))) #define NODE_LESS_THAN_6 (!(NODE_VERSION_AT_LEAST(0, 6, 0))) Persistent<FunctionTemplate> Syslog::constructor_template; bool Syslog::connected_ = false; char Syslog::name[1024]; void Syslog::Initialize ( Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(); constructor_template = Persistent<FunctionTemplate>::New(t); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); constructor_template->SetClassName(String::NewSymbol("Syslog")); NODE_SET_METHOD(constructor_template, "init", Syslog::init); NODE_SET_METHOD(constructor_template, "log", Syslog::log); NODE_SET_METHOD(constructor_template, "setMask", Syslog::setMask); NODE_SET_METHOD(constructor_template, "close", Syslog::destroy); target->Set(String::NewSymbol("Syslog"), constructor_template->GetFunction()); } Handle<Value> Syslog::init ( const Arguments& args) { HandleScope scope; if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(Exception::Error( String::New("Must give daemonname string as argument"))); } if (args.Length() < 3 ) { return ThrowException(Exception::Error( String::New("Must have atleast 3 params as argument"))); } if(connected_) close(); //open syslog args[0]->ToString()->WriteAscii((char*) &name); int options = args[1]->ToInt32()->Value(); int facility = args[2]->ToInt32()->Value(); open( options , facility ); return scope.Close(Undefined()); } struct log_request { Persistent<Function> cb; char *msg; uint32_t log_level; }; #if !NODE_LESS_THAN_6 static void UV_AfterLog(uv_work_t *req) { #else static int EIO_AfterLog( eio_req *req) { #endif HandleScope scope; struct log_request *log_req = (struct log_request *)(req->data); log_req->cb.Dispose(); // is this necessary? free(log_req->msg); free(log_req); delete req; #if NODE_LESS_THAN_6 ev_unref(EV_DEFAULT_UC); #endif #if NODE_LESS_THAN_5 return 0; #endif } #if !NODE_LESS_THAN_6 static void UV_Log(uv_work_t *req) { #elif !NODE_LESS_THAN_5 static void EIO_Log(eio_req *req) { #else static int EIO_Log(eio_req *req) { #endif struct log_request *log_req = (struct log_request *)(req->data); char *msg = log_req->msg; syslog(log_req->log_level, "%s", msg); #if NODE_LESS_THAN_6 req->result = 0; #endif #if NODE_LESS_THAN_5 return 0; #else return; #endif } Handle<Value> Syslog::log ( const Arguments& args) { HandleScope scope; Local<Function> cb = Local<Function>::Cast(args[3]); struct log_request * log_req = (struct log_request *) calloc(1, sizeof(struct log_request)); if(!log_req) { V8::LowMemoryNotification(); return ThrowException(Exception::Error( String::New("Could not allocate enought memory"))); } if(!connected_) return ThrowException(Exception::Error( String::New("init method has to be called befor syslog"))); String::AsciiValue msg(args[1]); uint32_t log_level = args[0]->Int32Value(); log_req->cb = Persistent<Function>::New(cb); log_req->msg = strdup(*msg); log_req->log_level = log_level; #if NODE_LESS_THAN_6 eio_custom(EIO_Log, EIO_PRI_DEFAULT, EIO_AfterLog, log_req); ev_ref(EV_DEFAULT_UC); #else uv_work_t *work_req = new uv_work_t(); work_req->data = log_req; uv_queue_work(uv_default_loop(), work_req, UV_Log, UV_AfterLog); #endif return scope.Close(Undefined()); } Handle<Value> Syslog::destroy ( const Arguments& args) { HandleScope scope; close(); return scope.Close(Undefined()); } void Syslog::open ( int option, int facility) { openlog( name, option, facility ); connected_ = true; } Handle<Value> Syslog::setMask ( const Arguments& args) { bool upTo = false; int mask, value; HandleScope scope; if (args.Length() < 1) { return ThrowException(Exception::Error(String::New("You must provide an mask"))); } if (!args[0]->IsNumber()) { return ThrowException(Exception::Error(String::New("First parameter (mask) should be numeric"))); } if (args.Length() == 2 && !args[1]->IsBoolean()) { return ThrowException(Exception::Error(String::New("Second parameter (upTo) should be boolean"))); } if (args.Length() == 2 && args[1]->IsBoolean()) { upTo = true; } value = args[0]->Int32Value(); if(upTo) { mask = LOG_UPTO(value); } else { mask = LOG_MASK(value); } return scope.Close(Integer::New( setlogmask(mask) )); } void Syslog::close () { if(connected_) { closelog(); connected_ = false; } } extern "C" void init (Handle<Object> target) { HandleScope scope; Syslog::Initialize(target); } <|endoftext|>
<commit_before>#include <rtti/metadefine.h> #include <iostream> using namespace std::literals; namespace test { void greeting(char const *message) { std::cout << "Hello, " << message << std::endl; } class Point2D { DECLARE_CLASSINFO public: Point2D() : m_x(0), m_y(0) { } Point2D(int x, int y) : m_x(x), m_y(y) { } void extend(int scale) { m_x *= scale; m_y *= scale; } int getArea() const { return m_x * m_y; } int getX() const { return m_x; } void setX(int value) { m_x = value; } int& y() { return m_y; } int const& y() const { return m_y; } private: int m_x; int m_y; }; } // namespace test // Reflection for test namespace. // RTTI_REGISTER defines static global object that runs before main. // You can of course use ordinary method instead. RTTI_REGISTER { rtti::global_define() ._namespace("test"sv) ._method("greeting"sv, &test::greeting) ._class<test::Point2D>("Point2D") ._constructor<int, int>() ._method("extend", &test::Point2D::extend) ._method("getArea", &test::Point2D::getArea) ._property("X"sv, &test::Point2D::getX, &test::Point2D::setX) ._method<int& (test::Point2D::*)()>("ref_Y", &test::Point2D::y) ._method<int const& (test::Point2D::*)() const>("const_ref_Y", &test::Point2D::y) ._end() ._end() ; } int main(int, char**) { // Get the global meta data repository. auto *ns_global = rtti::MetaNamespace::global(); // Get the meta method for global function "greeting". auto *mm_greeting = ns_global->getNamespace("test"sv)->getMethod("greeting"sv); // Invoke the global function. mm_greeting->invoke("World!"); // Now let's use the class Point2D via reflection system. auto *mc_point = ns_global->getNamespace("test"sv)->getClass("Point2D"sv); { // Create an instance of Point2D to be used by meta functions. test::Point2D point(5, 8); // Get the meta property for "x". auto *mp_x = mc_point->getProperty("X"sv); // Get the value of "x". The result is a rtti::variant. x_value contains a copy of point.x! auto x_value = mp_x->get(&point); // Print the value. We use "to" method to convert a rtti::variant to relevant C++ type. std::cout << "point.x is " << x_value.to<int>() << " (should be 5)" << std::endl; // Get the meta method for "y". auto *mm_y = mc_point->getMethod("const_ref_Y"); // Get the value of "y". The result is a rtti::variant. y_value contains a const reference to point.y! auto y_value = mm_y->invoke(&point); // Print the value. We use "to" method to convert a rtti::variant to relevant C++ type. std::cout << "point.y is " << y_value.to<int>() << " (should be 8)" << std::endl; // Get the meta method for "extend". auto *mm_extend = mc_point->getMethod("extend"sv); // Invoke Point2D::extend. mm_extend->invoke(&point, 2); // Since x property returns a copy we need to get the value again to reflect changes! x_value = mp_x->get(&point); std::cout << "After extend, point.x is " << x_value.to<int>() << " (should be 10)" << std::endl; // But y method returns reference! No need to get value again! std::cout << "After extend, point.y is " << y_value.to<int>() << " (should be 16)" << std::endl; // Get the meta method for "getArea". auto *mm_area = mc_point->getMethod("getArea"sv); // Invoke Point::getArea, and obtain the return value (rtti::variant). auto v_area = mm_area->invoke(&point); // Print the return value. std::cout << "The area is " << v_area.to<int>() << " (should be 160)" << std::endl; } { // Invoke default constructor of Point2D class auto v_point = mc_point->defaultConstructor()->invoke(); // Extract reference from rtti::variant auto &point = v_point.ref<test::Point2D>(); // Convenient way to get property instead of: // auto *mp_x = mc_point->getProperty("X"sv); // auto x_value = mp_x->get(v_point); auto x_value = v_point.get_property("X"sv); // Convenient way to invoke a method instead of: // auto *mm_y = mc_point->getMethod("const_ref_Y"); // auto y_value = mm_y->invoke(v_point); auto y_value = v_point.invoke("const_ref_Y"sv); std::cout << "default_constructor -- point.x is " << x_value.to<int>() << " (should be 0), point.y is " << y_value.to<int>() << " (should be 0)" << std::endl; std::cout << "extracted reference -- point.x is " << point.getX() << " (should be 0), point.y is " << point.y() << " (should be 0)" << std::endl; } { // Invoke constructor with arguments auto v_point = mc_point->getConstructor<int, int>()->invoke(3, 8); // Extract reference from rtti::variant auto &point = v_point.ref<test::Point2D>(); // Get values auto x_value = v_point.get_property("X"sv); auto y_value = v_point.invoke("const_ref_Y"sv); std::cout << "constructor -- point.x is " << x_value.to<int>() << " (should be 3), point.y is " << y_value.to<int>() << " (should be 8)" << std::endl; std::cout << "extracted reference -- point.x is " << point.getX() << " (should be 3), point.y is " << point.y() << " (should be 8)" << std::endl; // Get area auto v_area = v_point.invoke("getArea"sv); std::cout << "The area is " << v_area.to<int>() << " (should be 24)" << std::endl; // Scale 3 times v_point.invoke("extend", 3); // Print values x_value = v_point.get_property("X"sv); std::cout << "After extend, point.x is " << x_value.to<int>() << " (should be 9), point.y is " << y_value.to<int>() << " (should be 24)" << std::endl; // Get area v_area = v_point.invoke("getArea"sv); std::cout << "The area is " << v_area.to<int>() << " (should be 216)" << std::endl; } return EXIT_SUCCESS; } <commit_msg>Delete empty line<commit_after>#include <rtti/metadefine.h> #include <iostream> using namespace std::literals; namespace test { void greeting(char const *message) { std::cout << "Hello, " << message << std::endl; } class Point2D { DECLARE_CLASSINFO public: Point2D() : m_x(0), m_y(0) { } Point2D(int x, int y) : m_x(x), m_y(y) { } void extend(int scale) { m_x *= scale; m_y *= scale; } int getArea() const { return m_x * m_y; } int getX() const { return m_x; } void setX(int value) { m_x = value; } int& y() { return m_y; } int const& y() const { return m_y; } private: int m_x; int m_y; }; } // namespace test // Reflection for test namespace. // RTTI_REGISTER defines static global object that runs before main. // You can of course use ordinary method instead. RTTI_REGISTER { rtti::global_define() ._namespace("test"sv) ._method("greeting"sv, &test::greeting) ._class<test::Point2D>("Point2D") ._constructor<int, int>() ._method("extend", &test::Point2D::extend) ._method("getArea", &test::Point2D::getArea) ._property("X"sv, &test::Point2D::getX, &test::Point2D::setX) ._method<int& (test::Point2D::*)()>("ref_Y", &test::Point2D::y) ._method<int const& (test::Point2D::*)() const>("const_ref_Y", &test::Point2D::y) ._end() ._end() ; } int main(int, char**) { // Get the global meta data repository. auto *ns_global = rtti::MetaNamespace::global(); // Get the meta method for global function "greeting". auto *mm_greeting = ns_global->getNamespace("test"sv)->getMethod("greeting"sv); // Invoke the global function. mm_greeting->invoke("World!"); // Now let's use the class Point2D via reflection system. auto *mc_point = ns_global->getNamespace("test"sv)->getClass("Point2D"sv); { // Create an instance of Point2D to be used by meta functions. test::Point2D point(5, 8); // Get the meta property for "x". auto *mp_x = mc_point->getProperty("X"sv); // Get the value of "x". The result is a rtti::variant. x_value contains a copy of point.x! auto x_value = mp_x->get(&point); // Print the value. We use "to" method to convert a rtti::variant to relevant C++ type. std::cout << "point.x is " << x_value.to<int>() << " (should be 5)" << std::endl; // Get the meta method for "y". auto *mm_y = mc_point->getMethod("const_ref_Y"); // Get the value of "y". The result is a rtti::variant. y_value contains a const reference to point.y! auto y_value = mm_y->invoke(&point); // Print the value. We use "to" method to convert a rtti::variant to relevant C++ type. std::cout << "point.y is " << y_value.to<int>() << " (should be 8)" << std::endl; // Get the meta method for "extend". auto *mm_extend = mc_point->getMethod("extend"sv); // Invoke Point2D::extend. mm_extend->invoke(&point, 2); // Since x property returns a copy we need to get the value again to reflect changes! x_value = mp_x->get(&point); std::cout << "After extend, point.x is " << x_value.to<int>() << " (should be 10)" << std::endl; // But y method returns reference! No need to get value again! std::cout << "After extend, point.y is " << y_value.to<int>() << " (should be 16)" << std::endl; // Get the meta method for "getArea". auto *mm_area = mc_point->getMethod("getArea"sv); // Invoke Point::getArea, and obtain the return value (rtti::variant). auto v_area = mm_area->invoke(&point); // Print the return value. std::cout << "The area is " << v_area.to<int>() << " (should be 160)" << std::endl; } { // Invoke default constructor of Point2D class auto v_point = mc_point->defaultConstructor()->invoke(); // Extract reference from rtti::variant auto &point = v_point.ref<test::Point2D>(); // Convenient way to get property instead of: // auto *mp_x = mc_point->getProperty("X"sv); // auto x_value = mp_x->get(v_point); auto x_value = v_point.get_property("X"sv); // Convenient way to invoke a method instead of: // auto *mm_y = mc_point->getMethod("const_ref_Y"); // auto y_value = mm_y->invoke(v_point); auto y_value = v_point.invoke("const_ref_Y"sv); std::cout << "default_constructor -- point.x is " << x_value.to<int>() << " (should be 0), point.y is " << y_value.to<int>() << " (should be 0)" << std::endl; std::cout << "extracted reference -- point.x is " << point.getX() << " (should be 0), point.y is " << point.y() << " (should be 0)" << std::endl; } { // Invoke constructor with arguments auto v_point = mc_point->getConstructor<int, int>()->invoke(3, 8); // Extract reference from rtti::variant auto &point = v_point.ref<test::Point2D>(); // Get values auto x_value = v_point.get_property("X"sv); auto y_value = v_point.invoke("const_ref_Y"sv); std::cout << "constructor -- point.x is " << x_value.to<int>() << " (should be 3), point.y is " << y_value.to<int>() << " (should be 8)" << std::endl; std::cout << "extracted reference -- point.x is " << point.getX() << " (should be 3), point.y is " << point.y() << " (should be 8)" << std::endl; // Get area auto v_area = v_point.invoke("getArea"sv); std::cout << "The area is " << v_area.to<int>() << " (should be 24)" << std::endl; // Scale 3 times v_point.invoke("extend", 3); // Print values x_value = v_point.get_property("X"sv); std::cout << "After extend, point.x is " << x_value.to<int>() << " (should be 9), point.y is " << y_value.to<int>() << " (should be 24)" << std::endl; // Get area v_area = v_point.invoke("getArea"sv); std::cout << "The area is " << v_area.to<int>() << " (should be 216)" << std::endl; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include <gtest/gtest.h> #include <logging.h> #include "json_document.h" #include "pack.h" #include "receiver/reactor.h" #include "util/pointer.h" #include "util/string.h" #include "util_concurrency.h" using namespace receiver; // NOLINT class MockedReactor : public Reactor { public: MockedReactor(int fdin, int fdout) : Reactor(fdin, fdout) {} }; class T_Reactor : public ::testing::Test { protected: T_Reactor() : ready_(1, 1) {} virtual void SetUp() { ASSERT_NE(pipe(to_reactor_), -1); ASSERT_NE(pipe(from_reactor_), -1); ASSERT_EQ(pthread_create(&thread_, NULL, T_Reactor::ReactorFunction, static_cast<void*>(this)), 0); ASSERT_EQ(ready_.Dequeue(), true); } virtual void TearDown() { ASSERT_EQ(pthread_join(thread_, NULL), 0); close(to_reactor_[1]); close(from_reactor_[0]); } static void* ReactorFunction(void* data) { T_Reactor* ctx = static_cast<T_Reactor*>(data); ctx->ready_.Enqueue(true); MockedReactor reactor(ctx->to_reactor_[0], ctx->from_reactor_[1]); reactor.run(); close(ctx->to_reactor_[0]); close(ctx->from_reactor_[1]); return NULL; } FifoChannel<bool> ready_; pthread_t thread_; int to_reactor_[2]; int from_reactor_[2]; }; TEST_F(T_Reactor, kEcho_kQuit) { ASSERT_TRUE(Reactor::WriteRequest(to_reactor_[1], Reactor::kEcho, "Hey")); std::string reply; ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); ASSERT_EQ(reply, "Hey"); ASSERT_TRUE(Reactor::WriteRequest(to_reactor_[1], Reactor::kQuit, "")); ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); ASSERT_EQ(reply, "ok"); } TEST_F(T_Reactor, kGenerateToken_kQuit) { const std::string req_data = "{\"key_id\":\"some_key\",\"path\":\"some_path\",\"max_lease_time\":10}"; ASSERT_TRUE( Reactor::WriteRequest(to_reactor_[1], Reactor::kGenerateToken, req_data)); std::string reply; ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); UniquePtr<JsonDocument> json_reply(JsonDocument::Create(reply)); ASSERT_TRUE(json_reply.IsValid()); // Send kQuit request ASSERT_TRUE(Reactor::WriteRequest(to_reactor_[1], Reactor::kQuit, "")); reply.clear(); ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); ASSERT_EQ(reply, "ok"); } TEST_F(T_Reactor, FullCycle) { const std::string key_id = "some_key"; const std::string path = "some_path"; const std::string req_data = "{\"key_id\":\"" + key_id + "\",\"path\":\"" + path + "\",\"max_lease_time\":10}"; // Generate token ASSERT_TRUE( Reactor::WriteRequest(to_reactor_[1], Reactor::kGenerateToken, req_data)); std::string reply; ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); std::string token, public_id, secret; { UniquePtr<JsonDocument> json_reply(JsonDocument::Create(reply)); ASSERT_TRUE(json_reply.IsValid()); // Extract the token, public_id and secret from the reply const JSON* token_json = JsonDocument::SearchInObject(json_reply->root(), "token", JSON_STRING); ASSERT_TRUE(token_json); token = token_json->string_value; const JSON* public_id_json = JsonDocument::SearchInObject(json_reply->root(), "id", JSON_STRING); ASSERT_TRUE(public_id_json); public_id = public_id_json->string_value; const JSON* secret_json = JsonDocument::SearchInObject(json_reply->root(), "secret", JSON_STRING); ASSERT_TRUE(secret_json); secret = secret_json->string_value; } // Get the public_id from the token ASSERT_TRUE( Reactor::WriteRequest(to_reactor_[1], Reactor::kGetTokenId, token)); reply.clear(); ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); { UniquePtr<JsonDocument> json_reply(JsonDocument::Create(reply)); ASSERT_TRUE(json_reply.IsValid()); // Extract the token, public_id and secret from the reply const JSON* id_json = JsonDocument::SearchInObject(json_reply->root(), "id", JSON_STRING); ASSERT_TRUE(id_json); ASSERT_EQ(id_json->string_value, public_id); } // Check the token validity json_string_input request_terms; request_terms.push_back(std::make_pair("token", &token[0])); request_terms.push_back(std::make_pair("secret", &secret[0])); std::string request; ASSERT_TRUE(ToJsonString(request_terms, &request)); ASSERT_TRUE( Reactor::WriteRequest(to_reactor_[1], Reactor::kCheckToken, request)); reply.clear(); ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); { UniquePtr<JsonDocument> json_reply(JsonDocument::Create(reply)); ASSERT_TRUE(json_reply.IsValid()); // Extract the token, public_id and secret from the reply const JSON* path_json = JsonDocument::SearchInObject(json_reply->root(), "path", JSON_STRING); ASSERT_TRUE(path_json); ASSERT_EQ(path_json->string_value, path); } // Submit a payload { // Prepare an object pack and send it through the pipe ObjectPack pack; ObjectPack::BucketHandle hd = pack.NewBucket(); std::vector<uint8_t> buffer(4096, 0); ObjectPack::AddToBucket(&buffer[0], 4096, hd); shash::Any buffer_hash(shash::kSha1); shash::HashMem(&buffer[0], buffer.size(), &buffer_hash); ASSERT_TRUE(pack.CommitBucket(ObjectPack::kCas, buffer_hash, hd)); ObjectPackProducer serializer(&pack); shash::Any digest(shash::kSha1); serializer.GetDigest(&digest); const std::string request = "{\"path\":\"some_path\",\"digest\":\"" + Base64(digest.ToString(false)) + "\",\"header_size\":" + StringifyInt(serializer.GetHeaderSize()) + "}"; std::vector<unsigned char> payload(0); std::vector<unsigned char> buf(4096); unsigned nbytes = 0; do { nbytes = serializer.ProduceNext(buf.size(), &buf[0]); std::copy(buf.begin(), buf.begin() + nbytes, std::back_inserter(payload)); } while (nbytes > 0); ASSERT_TRUE(Reactor::WriteRequest(to_reactor_[1], Reactor::kSubmitPayload, request)); int nb = write(to_reactor_[1], &payload[0], payload.size()); ASSERT_EQ(static_cast<size_t>(nb), payload.size()); std::string reply; ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); } // Send kQuit request ASSERT_TRUE(Reactor::WriteRequest(to_reactor_[1], Reactor::kQuit, "")); reply.clear(); ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); ASSERT_EQ(reply, "ok"); } <commit_msg>Using mocked PayloadProcessor object in t_reactor.cc<commit_after>/** * This file is part of the CernVM File System. */ #include <gtest/gtest.h> #include <logging.h> #include "json_document.h" #include "pack.h" #include "receiver/payload_processor.h" #include "receiver/reactor.h" #include "util/pointer.h" #include "util/string.h" #include "util_concurrency.h" using namespace receiver; // NOLINT class MockedPayloadProcessor : public PayloadProcessor { public: MockedPayloadProcessor() {} protected: virtual int WriteFile(int /*fd*/, const void* const /*buf*/, size_t buf_size) { // NO OP return buf_size; } }; class MockedReactor : public Reactor { public: MockedReactor(int fdin, int fdout) : Reactor(fdin, fdout) {} protected: PayloadProcessor* MakePayloadProcessor() { return new MockedPayloadProcessor(); } }; class T_Reactor : public ::testing::Test { protected: T_Reactor() : ready_(1, 1) {} virtual void SetUp() { ASSERT_NE(pipe(to_reactor_), -1); ASSERT_NE(pipe(from_reactor_), -1); ASSERT_EQ(pthread_create(&thread_, NULL, T_Reactor::ReactorFunction, static_cast<void*>(this)), 0); ASSERT_EQ(ready_.Dequeue(), true); } virtual void TearDown() { ASSERT_EQ(pthread_join(thread_, NULL), 0); close(to_reactor_[1]); close(from_reactor_[0]); } static void* ReactorFunction(void* data) { T_Reactor* ctx = static_cast<T_Reactor*>(data); ctx->ready_.Enqueue(true); MockedReactor reactor(ctx->to_reactor_[0], ctx->from_reactor_[1]); reactor.run(); close(ctx->to_reactor_[0]); close(ctx->from_reactor_[1]); return NULL; } FifoChannel<bool> ready_; pthread_t thread_; int to_reactor_[2]; int from_reactor_[2]; }; TEST_F(T_Reactor, kEcho_kQuit) { ASSERT_TRUE(Reactor::WriteRequest(to_reactor_[1], Reactor::kEcho, "Hey")); std::string reply; ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); ASSERT_EQ(reply, "Hey"); ASSERT_TRUE(Reactor::WriteRequest(to_reactor_[1], Reactor::kQuit, "")); ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); ASSERT_EQ(reply, "ok"); } TEST_F(T_Reactor, kGenerateToken_kQuit) { const std::string req_data = "{\"key_id\":\"some_key\",\"path\":\"some_path\",\"max_lease_time\":10}"; ASSERT_TRUE( Reactor::WriteRequest(to_reactor_[1], Reactor::kGenerateToken, req_data)); std::string reply; ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); UniquePtr<JsonDocument> json_reply(JsonDocument::Create(reply)); ASSERT_TRUE(json_reply.IsValid()); // Send kQuit request ASSERT_TRUE(Reactor::WriteRequest(to_reactor_[1], Reactor::kQuit, "")); reply.clear(); ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); ASSERT_EQ(reply, "ok"); } TEST_F(T_Reactor, FullCycle) { const std::string key_id = "some_key"; const std::string path = "some_path"; const std::string req_data = "{\"key_id\":\"" + key_id + "\",\"path\":\"" + path + "\",\"max_lease_time\":10}"; // Generate token ASSERT_TRUE( Reactor::WriteRequest(to_reactor_[1], Reactor::kGenerateToken, req_data)); std::string reply; ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); std::string token, public_id, secret; { UniquePtr<JsonDocument> json_reply(JsonDocument::Create(reply)); ASSERT_TRUE(json_reply.IsValid()); // Extract the token, public_id and secret from the reply const JSON* token_json = JsonDocument::SearchInObject(json_reply->root(), "token", JSON_STRING); ASSERT_TRUE(token_json); token = token_json->string_value; const JSON* public_id_json = JsonDocument::SearchInObject(json_reply->root(), "id", JSON_STRING); ASSERT_TRUE(public_id_json); public_id = public_id_json->string_value; const JSON* secret_json = JsonDocument::SearchInObject(json_reply->root(), "secret", JSON_STRING); ASSERT_TRUE(secret_json); secret = secret_json->string_value; } // Get the public_id from the token ASSERT_TRUE( Reactor::WriteRequest(to_reactor_[1], Reactor::kGetTokenId, token)); reply.clear(); ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); { UniquePtr<JsonDocument> json_reply(JsonDocument::Create(reply)); ASSERT_TRUE(json_reply.IsValid()); // Extract the token, public_id and secret from the reply const JSON* id_json = JsonDocument::SearchInObject(json_reply->root(), "id", JSON_STRING); ASSERT_TRUE(id_json); ASSERT_EQ(id_json->string_value, public_id); } // Check the token validity json_string_input request_terms; request_terms.push_back(std::make_pair("token", &token[0])); request_terms.push_back(std::make_pair("secret", &secret[0])); std::string request; ASSERT_TRUE(ToJsonString(request_terms, &request)); ASSERT_TRUE( Reactor::WriteRequest(to_reactor_[1], Reactor::kCheckToken, request)); reply.clear(); ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); { UniquePtr<JsonDocument> json_reply(JsonDocument::Create(reply)); ASSERT_TRUE(json_reply.IsValid()); // Extract the token, public_id and secret from the reply const JSON* path_json = JsonDocument::SearchInObject(json_reply->root(), "path", JSON_STRING); ASSERT_TRUE(path_json); ASSERT_EQ(path_json->string_value, path); } // Submit a payload { // Prepare an object pack and send it through the pipe ObjectPack pack; ObjectPack::BucketHandle hd = pack.NewBucket(); std::vector<uint8_t> buffer(4096, 0); ObjectPack::AddToBucket(&buffer[0], 4096, hd); shash::Any buffer_hash(shash::kSha1); shash::HashMem(&buffer[0], buffer.size(), &buffer_hash); ASSERT_TRUE(pack.CommitBucket(ObjectPack::kCas, buffer_hash, hd)); ObjectPackProducer serializer(&pack); shash::Any digest(shash::kSha1); serializer.GetDigest(&digest); const std::string request = "{\"path\":\"some_path\",\"digest\":\"" + Base64(digest.ToString(false)) + "\",\"header_size\":" + StringifyInt(serializer.GetHeaderSize()) + "}"; std::vector<unsigned char> payload(0); std::vector<unsigned char> buf(4096); unsigned nbytes = 0; do { nbytes = serializer.ProduceNext(buf.size(), &buf[0]); std::copy(buf.begin(), buf.begin() + nbytes, std::back_inserter(payload)); } while (nbytes > 0); ASSERT_TRUE(Reactor::WriteRequest(to_reactor_[1], Reactor::kSubmitPayload, request)); int nb = write(to_reactor_[1], &payload[0], payload.size()); ASSERT_EQ(static_cast<size_t>(nb), payload.size()); std::string reply; ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); } // Send kQuit request ASSERT_TRUE(Reactor::WriteRequest(to_reactor_[1], Reactor::kQuit, "")); reply.clear(); ASSERT_TRUE(Reactor::ReadReply(from_reactor_[0], &reply)); ASSERT_EQ(reply, "ok"); } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "DeclarationVisitor.h" #include "ExpressionVisitor.h" #include "StatementVisitor.h" #include "ElementVisitor.h" #include "OOModel/src/declarations/Project.h" #include "OOModel/src/declarations/Module.h" #include "OOModel/src/declarations/Class.h" #include "OOModel/src/declarations/Declaration.h" #include "OOModel/src/declarations/Method.h" #include "OOModel/src/declarations/NameImport.h" #include "OOModel/src/declarations/VariableDeclaration.h" #include "OOModel/src/declarations/ExplicitTemplateInstantiation.h" #include "OOModel/src/declarations/TypeAlias.h" #include "Export/src/tree/SourceDir.h" #include "Export/src/tree/SourceFile.h" #include "Export/src/tree/CompositeFragment.h" #include "Export/src/tree/TextFragment.h" using namespace Export; using namespace OOModel; namespace CppExport { SourceFragment* DeclarationVisitor::visit(Declaration* declaration) { if (auto castDeclaration = DCast<Method>(declaration)) return visit(castDeclaration); if (auto castDeclaration = DCast<Class>(declaration)) return visit(castDeclaration); if (auto castDeclaration = DCast<VariableDeclaration>(declaration)) return visit(castDeclaration); if (auto castDeclaration = DCast<TypeAlias>(declaration)) return visit(castDeclaration); notAllowed(declaration); // TODO: handle comments auto fragment = new CompositeFragment(declaration); *fragment << "Invalid Declaration"; return fragment; } SourceDir* DeclarationVisitor::visitProject(Project* project, SourceDir* parent) { auto projectDir = parent ? &parent->subDir(project->name()) : new SourceDir(nullptr, "src"); for (auto node : *project->projects()) visitProject(node, projectDir); for (auto node : *project->modules()) visitModule(node, projectDir); for (auto node : *project->classes()) visitTopLevelClass(node, projectDir); notAllowed(project->methods()); notAllowed(project->fields()); return projectDir; } SourceDir* DeclarationVisitor::visitModule(Module* module, SourceDir* parent) { Q_ASSERT(parent); auto moduleDir = &parent->subDir(module->name()); for (auto node : *module->modules()) visitModule(node, moduleDir); for (auto node : *module->classes()) visitTopLevelClass(node, moduleDir); notAllowed(module->methods()); notAllowed(module->fields()); return moduleDir; } SourceFile* DeclarationVisitor::visitTopLevelClass(Class* classs, SourceDir* parent) { Q_ASSERT(parent); auto classFile = &parent->file(classs->name() + ".cpp"); auto fragment = classFile->append(new CompositeFragment(classs, "sections")); auto imports = fragment->append(new CompositeFragment(classs, "vertical")); for (auto node : *classs->subDeclarations()) { if (auto ni = DCast<NameImport>(node)) *imports << visit(ni); else notAllowed(node); } *fragment << visit(classs); return classFile; } SourceFragment* DeclarationVisitor::visitTopLevelClass(Class* classs) { if (!headerVisitor()) return visit(classs); auto fragment = new CompositeFragment(classs, "spacedSections"); *fragment << visit(classs); auto filter = [](Method* method) { return !method->typeArguments()->isEmpty(); }; *fragment << list(classs->methods(), DeclarationVisitor(SOURCE_VISITOR), "spacedSections", filter); return fragment; } SourceFragment* DeclarationVisitor::visit(Class* classs) { auto fragment = new CompositeFragment(classs); if (!headerVisitor()) { //TODO auto sections = fragment->append( new CompositeFragment(classs, "sections")); *sections << list(classs->enumerators(), ElementVisitor(data()), "enumerators"); *sections << list(classs->classes(), this, "sections"); auto filter = [](Method* method) { return method->typeArguments()->isEmpty(); }; *sections << list(classs->methods(), this, "spacedSections", filter); *sections << list(classs->fields(), this, "vertical"); } else { if (!classs->typeArguments()->isEmpty()) *fragment << list(classs->typeArguments(), ElementVisitor(data()), "templateArgsList"); *fragment << printAnnotationsAndModifiers(classs); if (Class::ConstructKind::Class == classs->constructKind()) *fragment << "class "; else if (Class::ConstructKind::Struct == classs->constructKind()) *fragment << "struct "; else if (Class::ConstructKind::Enum == classs->constructKind()) *fragment << "enum "; else notAllowed(classs); if (auto namespaceModule = classs->firstAncestorOfType<Module>()) *fragment << namespaceModule->name().toUpper() + "_API "; *fragment << classs->nameNode(); if (!classs->baseClasses()->isEmpty()) // TODO: inheritance modifiers like private, virtual... (not only public) *fragment << list(classs->baseClasses(), ExpressionVisitor(data()), "baseClasses"); notAllowed(classs->friends()); auto sections = fragment->append( new CompositeFragment(classs, "bodySections")); if (classs->enumerators()->size() > 0) error(classs->enumerators(), "Enum unhandled"); // TODO auto publicSection = new CompositeFragment(classs, "accessorSections"); auto publicFilter = [](Declaration* declaration) { return declaration->modifiers()->isSet(Modifier::Public); }; bool hasPublicSection = addMemberDeclarations(classs, publicSection, publicFilter); if (hasPublicSection) { *sections << "public:"; sections->append(publicSection); } auto protectedSection = new CompositeFragment(classs, "accessorSections"); auto protectedFilter = [](Declaration* declaration) { return declaration->modifiers()->isSet(Modifier::Protected); }; bool hasProtectedSection = addMemberDeclarations(classs, protectedSection, protectedFilter); if (hasProtectedSection) { if (hasPublicSection) *sections << "\n"; // add newline between two accessor sections *sections << "protected:"; sections->append(protectedSection); } auto privateSection = new CompositeFragment(classs, "accessorSections"); auto privateFilter = [](Declaration* declaration) { return !declaration->modifiers()->isSet(Modifier::Public) && !declaration->modifiers()->isSet(Modifier::Protected); }; bool hasPrivateSection = addMemberDeclarations(classs, privateSection, privateFilter); if (hasPrivateSection) { if (hasPublicSection || hasProtectedSection) *sections << "\n"; // add newline between two accessor sections *sections << "private:"; sections->append(privateSection); } *fragment << ";"; } return fragment; } template<typename Predicate> bool DeclarationVisitor::addMemberDeclarations(Class* classs, CompositeFragment* section, Predicate filter) { auto subDeclarations = list(classs->subDeclarations(), this, "sections", filter); auto fields = list(classs->fields(), this, "vertical", filter); auto classes = list(classs->classes(), this, "sections", filter); auto methods = list(classs->methods(), this, "sections", filter); *section << subDeclarations << fields << classes << methods; return !subDeclarations->fragments().empty() || !fields->fragments().empty() || !classes->fragments().empty() || !methods->fragments().empty(); } SourceFragment* DeclarationVisitor::visit(Method* method) { auto fragment = new CompositeFragment(method); if (!method->typeArguments()->isEmpty()) *fragment << list(method->typeArguments(), ElementVisitor(data()), "templateArgsList"); if (headerVisitor()) *fragment << printAnnotationsAndModifiers(method); if (method->results()->size() > 1) error(method->results(), "Cannot have more than one return value in C++"); if (method->methodKind() != Method::MethodKind::Constructor && method->methodKind() != Method::MethodKind::Destructor) { if (!method->results()->isEmpty()) *fragment << expression(method->results()->at(0)->typeExpression()) << " "; else *fragment << "void "; } if (!headerVisitor()) if (auto parentClass = method->firstAncestorOfType<Class>()) *fragment << parentClass->name() << "::"; if (method->methodKind() == Method::MethodKind::Destructor && !method->name().startsWith("~")) *fragment << "~"; *fragment << method->nameNode(); *fragment << list(method->arguments(), ElementVisitor(data()), "argsList"); if (method->modifiers()->isSet(Modifier::Const)) *fragment << " " << new TextFragment(method->modifiers(), "const"); if (!headerVisitor()) if (!method->memberInitializers()->isEmpty()) *fragment << " : " << list(method->memberInitializers(), ElementVisitor(data())); if (!method->throws()->isEmpty()) { *fragment << " throw ("; *fragment << list(method->throws(), ExpressionVisitor(data()), "comma"); *fragment << ")"; } if (headerVisitor()) { if (method->modifiers()->isSet(Modifier::Override)) *fragment << " " << new TextFragment(method->modifiers(), "override"); *fragment << ";"; } else *fragment << list(method->items(), StatementVisitor(data()), "body"); notAllowed(method->subDeclarations()); notAllowed(method->memberInitializers()); return fragment; } SourceFragment* DeclarationVisitor::visit(VariableDeclaration* variableDeclaration) { auto fragment = new CompositeFragment(variableDeclaration); if (headerVisitor()) { *fragment << printAnnotationsAndModifiers(variableDeclaration); *fragment << expression(variableDeclaration->typeExpression()) << " " << variableDeclaration->nameNode(); if (variableDeclaration->initialValue()) *fragment << " = " << expression(variableDeclaration->initialValue()); if (!DCast<Expression>(variableDeclaration->parent())) *fragment << ";"; } else { bool isField = DCast<Field>(variableDeclaration); if (!isField || variableDeclaration->modifiers()->isSet(Modifier::Static)) { *fragment << printAnnotationsAndModifiers(variableDeclaration); *fragment << expression(variableDeclaration->typeExpression()) << " "; if (isField) if (auto parentClass = variableDeclaration->firstAncestorOfType<Class>()) *fragment << parentClass->name() << "::"; *fragment << variableDeclaration->nameNode(); if (variableDeclaration->initialValue()) *fragment << " = " << expression(variableDeclaration->initialValue()); if (!DCast<Expression>(variableDeclaration->parent())) *fragment << ";"; } } return fragment; } SourceFragment* DeclarationVisitor::printAnnotationsAndModifiers(Declaration* declaration) { auto fragment = new CompositeFragment(declaration, "vertical"); if (!declaration->annotations()->isEmpty()) // avoid an extra new line if there are no annotations *fragment << list(declaration->annotations(), StatementVisitor(data()), "vertical"); auto header = fragment->append(new CompositeFragment(declaration, "space")); if (declaration->modifiers()->isSet(Modifier::Static)) *header << new TextFragment(declaration->modifiers(), "static"); if (declaration->modifiers()->isSet(Modifier::Final)) *header << new TextFragment(declaration->modifiers(), "final"); if (declaration->modifiers()->isSet(Modifier::Abstract)) *header << new TextFragment(declaration->modifiers(), "abstract"); if (declaration->modifiers()->isSet(Modifier::Virtual)) *header << new TextFragment(declaration->modifiers(), "virtual"); if (declaration->modifiers()->isSet(Modifier::Inline)) *header << new TextFragment(declaration->modifiers(), "inline"); return fragment; } SourceFragment* DeclarationVisitor::visit(NameImport* nameImport) { auto fragment = new CompositeFragment(nameImport); notAllowed(nameImport->annotations()); *fragment << "import " << expression(nameImport->importedName()); if (nameImport->importAll()) *fragment << ".*"; *fragment << ";"; return fragment; } SourceFragment* DeclarationVisitor::visit(ExplicitTemplateInstantiation* eti) { notAllowed(eti); return new TextFragment(eti); } SourceFragment* DeclarationVisitor::visit(TypeAlias* typeAlias) { auto fragment = new CompositeFragment(typeAlias); *fragment << "using " << typeAlias->nameNode() << " = " << expression(typeAlias->typeExpression()) << ";"; return fragment; } } <commit_msg>export method declaration comments<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "DeclarationVisitor.h" #include "ExpressionVisitor.h" #include "StatementVisitor.h" #include "ElementVisitor.h" #include "OOModel/src/declarations/Project.h" #include "OOModel/src/declarations/Module.h" #include "OOModel/src/declarations/Class.h" #include "OOModel/src/declarations/Declaration.h" #include "OOModel/src/declarations/Method.h" #include "OOModel/src/declarations/NameImport.h" #include "OOModel/src/declarations/VariableDeclaration.h" #include "OOModel/src/declarations/ExplicitTemplateInstantiation.h" #include "OOModel/src/declarations/TypeAlias.h" #include "Export/src/tree/SourceDir.h" #include "Export/src/tree/SourceFile.h" #include "Export/src/tree/CompositeFragment.h" #include "Export/src/tree/TextFragment.h" #include "Comments/src/nodes/CommentNode.h" using namespace Export; using namespace OOModel; namespace CppExport { SourceFragment* DeclarationVisitor::visit(Declaration* declaration) { if (auto castDeclaration = DCast<Method>(declaration)) return visit(castDeclaration); if (auto castDeclaration = DCast<Class>(declaration)) return visit(castDeclaration); if (auto castDeclaration = DCast<VariableDeclaration>(declaration)) return visit(castDeclaration); if (auto castDeclaration = DCast<TypeAlias>(declaration)) return visit(castDeclaration); notAllowed(declaration); // TODO: handle comments auto fragment = new CompositeFragment(declaration); *fragment << "Invalid Declaration"; return fragment; } SourceDir* DeclarationVisitor::visitProject(Project* project, SourceDir* parent) { auto projectDir = parent ? &parent->subDir(project->name()) : new SourceDir(nullptr, "src"); for (auto node : *project->projects()) visitProject(node, projectDir); for (auto node : *project->modules()) visitModule(node, projectDir); for (auto node : *project->classes()) visitTopLevelClass(node, projectDir); notAllowed(project->methods()); notAllowed(project->fields()); return projectDir; } SourceDir* DeclarationVisitor::visitModule(Module* module, SourceDir* parent) { Q_ASSERT(parent); auto moduleDir = &parent->subDir(module->name()); for (auto node : *module->modules()) visitModule(node, moduleDir); for (auto node : *module->classes()) visitTopLevelClass(node, moduleDir); notAllowed(module->methods()); notAllowed(module->fields()); return moduleDir; } SourceFile* DeclarationVisitor::visitTopLevelClass(Class* classs, SourceDir* parent) { Q_ASSERT(parent); auto classFile = &parent->file(classs->name() + ".cpp"); auto fragment = classFile->append(new CompositeFragment(classs, "sections")); auto imports = fragment->append(new CompositeFragment(classs, "vertical")); for (auto node : *classs->subDeclarations()) { if (auto ni = DCast<NameImport>(node)) *imports << visit(ni); else notAllowed(node); } *fragment << visit(classs); return classFile; } SourceFragment* DeclarationVisitor::visitTopLevelClass(Class* classs) { if (!headerVisitor()) return visit(classs); auto fragment = new CompositeFragment(classs, "spacedSections"); *fragment << visit(classs); auto filter = [](Method* method) { return !method->typeArguments()->isEmpty(); }; *fragment << list(classs->methods(), DeclarationVisitor(SOURCE_VISITOR), "spacedSections", filter); return fragment; } SourceFragment* DeclarationVisitor::visit(Class* classs) { auto fragment = new CompositeFragment(classs); if (!headerVisitor()) { //TODO auto sections = fragment->append( new CompositeFragment(classs, "sections")); *sections << list(classs->enumerators(), ElementVisitor(data()), "enumerators"); *sections << list(classs->classes(), this, "sections"); auto filter = [](Method* method) { return method->typeArguments()->isEmpty(); }; *sections << list(classs->methods(), this, "spacedSections", filter); *sections << list(classs->fields(), this, "vertical"); } else { if (!classs->typeArguments()->isEmpty()) *fragment << list(classs->typeArguments(), ElementVisitor(data()), "templateArgsList"); *fragment << printAnnotationsAndModifiers(classs); if (Class::ConstructKind::Class == classs->constructKind()) *fragment << "class "; else if (Class::ConstructKind::Struct == classs->constructKind()) *fragment << "struct "; else if (Class::ConstructKind::Enum == classs->constructKind()) *fragment << "enum "; else notAllowed(classs); if (auto namespaceModule = classs->firstAncestorOfType<Module>()) *fragment << namespaceModule->name().toUpper() + "_API "; *fragment << classs->nameNode(); if (!classs->baseClasses()->isEmpty()) // TODO: inheritance modifiers like private, virtual... (not only public) *fragment << list(classs->baseClasses(), ExpressionVisitor(data()), "baseClasses"); notAllowed(classs->friends()); auto sections = fragment->append( new CompositeFragment(classs, "bodySections")); if (classs->enumerators()->size() > 0) error(classs->enumerators(), "Enum unhandled"); // TODO auto publicSection = new CompositeFragment(classs, "accessorSections"); auto publicFilter = [](Declaration* declaration) { return declaration->modifiers()->isSet(Modifier::Public); }; bool hasPublicSection = addMemberDeclarations(classs, publicSection, publicFilter); if (hasPublicSection) { *sections << "public:"; sections->append(publicSection); } auto protectedSection = new CompositeFragment(classs, "accessorSections"); auto protectedFilter = [](Declaration* declaration) { return declaration->modifiers()->isSet(Modifier::Protected); }; bool hasProtectedSection = addMemberDeclarations(classs, protectedSection, protectedFilter); if (hasProtectedSection) { if (hasPublicSection) *sections << "\n"; // add newline between two accessor sections *sections << "protected:"; sections->append(protectedSection); } auto privateSection = new CompositeFragment(classs, "accessorSections"); auto privateFilter = [](Declaration* declaration) { return !declaration->modifiers()->isSet(Modifier::Public) && !declaration->modifiers()->isSet(Modifier::Protected); }; bool hasPrivateSection = addMemberDeclarations(classs, privateSection, privateFilter); if (hasPrivateSection) { if (hasPublicSection || hasProtectedSection) *sections << "\n"; // add newline between two accessor sections *sections << "private:"; sections->append(privateSection); } *fragment << ";"; } return fragment; } template<typename Predicate> bool DeclarationVisitor::addMemberDeclarations(Class* classs, CompositeFragment* section, Predicate filter) { auto subDeclarations = list(classs->subDeclarations(), this, "sections", filter); auto fields = list(classs->fields(), this, "vertical", filter); auto classes = list(classs->classes(), this, "sections", filter); auto methods = list(classs->methods(), this, "sections", filter); *section << subDeclarations << fields << classes << methods; return !subDeclarations->fragments().empty() || !fields->fragments().empty() || !classes->fragments().empty() || !methods->fragments().empty(); } SourceFragment* DeclarationVisitor::visit(Method* method) { auto fragment = new CompositeFragment(method); if (headerVisitor()) if (auto comment = DCast<Comments::CommentNode>(method->comment())) for (auto line : *(comment->lines())) *fragment << line->get() << "\n"; if (!method->typeArguments()->isEmpty()) *fragment << list(method->typeArguments(), ElementVisitor(data()), "templateArgsList"); if (headerVisitor()) *fragment << printAnnotationsAndModifiers(method); if (method->results()->size() > 1) error(method->results(), "Cannot have more than one return value in C++"); if (method->methodKind() != Method::MethodKind::Constructor && method->methodKind() != Method::MethodKind::Destructor) { if (!method->results()->isEmpty()) *fragment << expression(method->results()->at(0)->typeExpression()) << " "; else *fragment << "void "; } if (!headerVisitor()) if (auto parentClass = method->firstAncestorOfType<Class>()) *fragment << parentClass->name() << "::"; if (method->methodKind() == Method::MethodKind::Destructor && !method->name().startsWith("~")) *fragment << "~"; *fragment << method->nameNode(); *fragment << list(method->arguments(), ElementVisitor(data()), "argsList"); if (method->modifiers()->isSet(Modifier::Const)) *fragment << " " << new TextFragment(method->modifiers(), "const"); if (!headerVisitor()) if (!method->memberInitializers()->isEmpty()) *fragment << " : " << list(method->memberInitializers(), ElementVisitor(data())); if (!method->throws()->isEmpty()) { *fragment << " throw ("; *fragment << list(method->throws(), ExpressionVisitor(data()), "comma"); *fragment << ")"; } if (headerVisitor()) { if (method->modifiers()->isSet(Modifier::Override)) *fragment << " " << new TextFragment(method->modifiers(), "override"); *fragment << ";"; } else *fragment << list(method->items(), StatementVisitor(data()), "body"); notAllowed(method->subDeclarations()); notAllowed(method->memberInitializers()); return fragment; } SourceFragment* DeclarationVisitor::visit(VariableDeclaration* variableDeclaration) { auto fragment = new CompositeFragment(variableDeclaration); if (headerVisitor()) { *fragment << printAnnotationsAndModifiers(variableDeclaration); *fragment << expression(variableDeclaration->typeExpression()) << " " << variableDeclaration->nameNode(); if (variableDeclaration->initialValue()) *fragment << " = " << expression(variableDeclaration->initialValue()); if (!DCast<Expression>(variableDeclaration->parent())) *fragment << ";"; } else { bool isField = DCast<Field>(variableDeclaration); if (!isField || variableDeclaration->modifiers()->isSet(Modifier::Static)) { *fragment << printAnnotationsAndModifiers(variableDeclaration); *fragment << expression(variableDeclaration->typeExpression()) << " "; if (isField) if (auto parentClass = variableDeclaration->firstAncestorOfType<Class>()) *fragment << parentClass->name() << "::"; *fragment << variableDeclaration->nameNode(); if (variableDeclaration->initialValue()) *fragment << " = " << expression(variableDeclaration->initialValue()); if (!DCast<Expression>(variableDeclaration->parent())) *fragment << ";"; } } return fragment; } SourceFragment* DeclarationVisitor::printAnnotationsAndModifiers(Declaration* declaration) { auto fragment = new CompositeFragment(declaration, "vertical"); if (!declaration->annotations()->isEmpty()) // avoid an extra new line if there are no annotations *fragment << list(declaration->annotations(), StatementVisitor(data()), "vertical"); auto header = fragment->append(new CompositeFragment(declaration, "space")); if (declaration->modifiers()->isSet(Modifier::Static)) *header << new TextFragment(declaration->modifiers(), "static"); if (declaration->modifiers()->isSet(Modifier::Final)) *header << new TextFragment(declaration->modifiers(), "final"); if (declaration->modifiers()->isSet(Modifier::Abstract)) *header << new TextFragment(declaration->modifiers(), "abstract"); if (declaration->modifiers()->isSet(Modifier::Virtual)) *header << new TextFragment(declaration->modifiers(), "virtual"); if (declaration->modifiers()->isSet(Modifier::Inline)) *header << new TextFragment(declaration->modifiers(), "inline"); return fragment; } SourceFragment* DeclarationVisitor::visit(NameImport* nameImport) { auto fragment = new CompositeFragment(nameImport); notAllowed(nameImport->annotations()); *fragment << "import " << expression(nameImport->importedName()); if (nameImport->importAll()) *fragment << ".*"; *fragment << ";"; return fragment; } SourceFragment* DeclarationVisitor::visit(ExplicitTemplateInstantiation* eti) { notAllowed(eti); return new TextFragment(eti); } SourceFragment* DeclarationVisitor::visit(TypeAlias* typeAlias) { auto fragment = new CompositeFragment(typeAlias); *fragment << "using " << typeAlias->nameNode() << " = " << expression(typeAlias->typeExpression()) << ";"; return fragment; } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // Unit Test for Loki // // Copyright Terje Sletteb and Pavel Vozenilek 2002. // // Permission to use, copy, modify, and distribute this software for any // purpose is hereby granted without fee, provided that this copyright and // permissions notice appear in all copies and derivatives. // // This software is provided "as is" without express or implied warranty. // // Last update: October 12, 2002 /////////////////////////////////////////////////////////////////////////////// #ifdef __INTEL_COMPILER # pragma warning(disable: 111 193 304 383 444 488 981 1418) #elif defined(_MSC_VER) && !defined(__MWERKS__) # pragma warning(disable: 4018 4097 4100 4213 4290 4512 4514 4700 4702 4710 4786 4800) #endif // Some platforms might have difficulty with this // Need to ifdef around those cases. // TODO SGB #include "UnitTest.h" // static variable defintion, do not remove Test::tests_type Test::tests; // Merely comment out any of the following headers to // prevent thier execution during the test. // // A pluggable-factory-like method is used to // auto-register the test, so all that is needed // is the header inclusion to execute the correspond // unit test. #include "TypelistTest.h" #include "TypeManipTest.h" #include "TypeTraitsTest.h" #include "SmallObjectTest.h" #include "SingletonTest.h" #include "SmartPtrTest.h" #include "FactoryTest.h" #include "AbstractFactoryTest.h" #include "AssocVectorTest.h" #include "FunctorTest.h" #include "DataGeneratorsTest.h" /* * AP - All Pass * FC - Fails to Compile * ? - Unknown/Not Tested/Not Recorded * * TypelistTest TypeManipTest TypeTraitsTest SmallObjectTest SingletonTest * gcc 2.95.3 ? ? ? ? ? * gcc 3.2 AP AP AP AP P (Only SingleThreaded) * MSVC 6.0 P AP FC FC AP * MSVC 7.0 AP Conversion FC AP P (Only SingleThreaded) ? * Intel 5.0 AP AP AP FC FC * Intel 6.0 AP AP AP FC P (Only SingleThreaded) * Intel 7.0 AP AP AP FC P (Only SingleThreaded) * BCC 5.5 ? ? ? ? ? * BCC 5.6 ? ? ? ? ? * CW 6.0 ? ? ? ? ? * * SmartPtrTest FactoryTest AbstractFactoryTest AssocVectorTest FunctorTest * gcc 2.95.3 ? ? ? ? ? * gcc 3.2 FC AP AP FC AP * MSVC 6.0 FC AP FC FC FC * MSVC 7.0 FC AP AP FC AP * Intel 5.0 FC FC FC FC FC * Intel 6.0 FC AP AP FC FC * Intel 7.0 FC AP AP FC FC * BCC 5.5 ? ? ? ? ? * CW 6.0 ? ? ? ? ? * * DataGeneratorsTest * gcc 2.95.3 ? * gcc 3.2 AP * MSVC 6.0 FC * MSVC 7.0 AP * Intel 5.0 FC * Intel 6.0 AP * Intel 7.0 AP * BCC 5.5 ? * BCC 5.6 ? * CW 6.0 ? */ int main() { int result = Test::run("Loki Unit Test"); #if defined(__BORLANDC__) || defined(__GNUC__) || defined(_MSC_VER) system("pause"); // Stop console window from closing if run from IDE. #endif return result; } <commit_msg>Updated test results: gcc 3.2 pass them all (MT excepted)<commit_after>/////////////////////////////////////////////////////////////////////////////// // Unit Test for Loki // // Copyright Terje Sletteb and Pavel Vozenilek 2002. // // Permission to use, copy, modify, and distribute this software for any // purpose is hereby granted without fee, provided that this copyright and // permissions notice appear in all copies and derivatives. // // This software is provided "as is" without express or implied warranty. // // Last update: October 12, 2002 /////////////////////////////////////////////////////////////////////////////// #ifdef __INTEL_COMPILER # pragma warning(disable: 111 193 304 383 444 488 981 1418) #elif defined(_MSC_VER) && !defined(__MWERKS__) # pragma warning(disable: 4018 4097 4100 4213 4290 4512 4514 4700 4702 4710 4786 4800) #endif // Some platforms might have difficulty with this // Need to ifdef around those cases. // TODO SGB #include "UnitTest.h" // static variable defintion, do not remove Test::tests_type Test::tests; // Merely comment out any of the following headers to // prevent thier execution during the test. // // A pluggable-factory-like method is used to // auto-register the test, so all that is needed // is the header inclusion to execute the correspond // unit test. #include "TypelistTest.h" #include "TypeManipTest.h" #include "TypeTraitsTest.h" #include "SmallObjectTest.h" #include "SingletonTest.h" #include "SmartPtrTest.h" #include "FactoryTest.h" #include "AbstractFactoryTest.h" #include "AssocVectorTest.h" #include "FunctorTest.h" #include "DataGeneratorsTest.h" /* * AP - All Pass * FC - Fails to Compile * ? - Unknown/Not Tested/Not Recorded * * TypelistTest TypeManipTest TypeTraitsTest SmallObjectTest SingletonTest * gcc 2.95.3 ? ? ? ? ? * gcc 3.2 AP AP AP AP P (Only SingleThreaded) * MSVC 6.0 P AP FC FC AP * MSVC 7.0 AP Conversion FC AP P (Only SingleThreaded) ? * Intel 5.0 AP AP AP FC FC * Intel 6.0 AP AP AP FC P (Only SingleThreaded) * Intel 7.0 AP AP AP FC P (Only SingleThreaded) * BCC 5.5 ? ? ? ? ? * BCC 5.6 ? ? ? ? ? * CW 6.0 ? ? ? ? ? * * SmartPtrTest FactoryTest AbstractFactoryTest AssocVectorTest FunctorTest * gcc 2.95.3 ? ? ? ? ? * gcc 3.2 AP AP AP AP AP * MSVC 6.0 FC AP FC FC FC * MSVC 7.0 FC AP AP FC AP * Intel 5.0 FC FC FC FC FC * Intel 6.0 FC AP AP FC FC * Intel 7.0 FC AP AP FC FC * BCC 5.5 ? ? ? ? ? * CW 6.0 ? ? ? ? ? * * DataGeneratorsTest * gcc 2.95.3 ? * gcc 3.2 AP * MSVC 6.0 FC * MSVC 7.0 AP * Intel 5.0 FC * Intel 6.0 AP * Intel 7.0 AP * BCC 5.5 ? * BCC 5.6 ? * CW 6.0 ? */ int main() { int result = Test::run("Loki Unit Test"); #if defined(__BORLANDC__) || defined(__GNUC__) || defined(_MSC_VER) system("pause"); // Stop console window from closing if run from IDE. #endif return result; } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ */ #include <sensor_msgs/PointCloud2.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/console/print.h> #include <pcl/console/parse.h> #include <pcl/console/time.h> #include <pcl/kdtree/kdtree_flann.h> using namespace pcl; using namespace pcl::io; using namespace pcl::console; std::string default_correspondence_type = "index"; void printHelp (int argc, char **argv) { print_error ("Syntax is: %s source.pcd target.pcd output_intensity.pcd <options>\n", argv[0]); print_info (" where options are:\n"); print_info (" -correspondence X = the way of selecting the corresponding pair in the target cloud for the current point in the source cloud\n"); print_info (" options are: index = points with identical indices are paired together. Note: both clouds need to have the same number of points\n"); print_info (" nn = source point is paired with its nearest neighbor in the target cloud\n"); print_info (" nnplane = source point is paired with its projection on the plane determined by the nearest neighbor in the target cloud. Note: target cloud needs to contain normals\n"); print_info (" (default: "); print_value ("%s", default_correspondence_type.c_str ()); print_info (")\n"); } bool loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud) { TicToc tt; print_highlight ("Loading "); print_value ("%s ", filename.c_str ()); tt.tic (); if (loadPCDFile (filename, cloud) < 0) return (false); print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n"); print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ()); return (true); } void compute (const sensor_msgs::PointCloud2::ConstPtr &cloud_source, const sensor_msgs::PointCloud2::ConstPtr &cloud_target, sensor_msgs::PointCloud2 &output, std::string correspondence_type) { // Estimate TicToc tt; tt.tic (); PointCloud<PointXYZ>::Ptr xyz_source (new PointCloud<PointXYZ> ()); fromROSMsg (*cloud_source, *xyz_source); PointCloud<PointXYZ>::Ptr xyz_target (new PointCloud<PointXYZ> ()); fromROSMsg (*cloud_target, *xyz_target); PointCloud<PointXYZI>::Ptr output_xyzi (new PointCloud<PointXYZI> ()); output_xyzi->points.resize (xyz_source->points.size ()); output_xyzi->height = cloud_source->height; output_xyzi->width = cloud_source->width; float rmse = 0.0f; if (correspondence_type == "index") { print_highlight (stderr, "Computing using the equal indices correspondence heuristic.\n"); if (xyz_source->points.size () != xyz_target->points.size ()) { print_error ("Source and target clouds do not have the same number of points.\n"); return; } for (size_t point_i = 0; point_i < xyz_source->points.size (); ++point_i) { if (!pcl_isfinite (xyz_source->points[point_i].x) || !pcl_isfinite (xyz_source->points[point_i].y) || !pcl_isfinite (xyz_source->points[point_i].z)) continue; if (!pcl_isfinite (xyz_target->points[point_i].x) || !pcl_isfinite (xyz_target->points[point_i].y) || !pcl_isfinite (xyz_target->points[point_i].z)) continue; float dist = squaredEuclideanDistance (xyz_source->points[point_i], xyz_target->points[point_i]); rmse += dist; output_xyzi->points[point_i].x = xyz_source->points[point_i].x; output_xyzi->points[point_i].y = xyz_source->points[point_i].y; output_xyzi->points[point_i].z = xyz_source->points[point_i].z; output_xyzi->points[point_i].intensity = dist; } rmse = sqrt (rmse / xyz_source->points.size ()); } else if (correspondence_type == "nn") { print_highlight (stderr, "Computing using the nearest neighbor correspondence heuristic.\n"); KdTreeFLANN<PointXYZ>::Ptr tree (new KdTreeFLANN<PointXYZ> ()); tree->setInputCloud (xyz_target); for (size_t point_i = 0; point_i < xyz_source->points.size (); ++ point_i) { if (!pcl_isfinite (xyz_source->points[point_i].x) || !pcl_isfinite (xyz_source->points[point_i].y) || !pcl_isfinite (xyz_source->points[point_i].z)) continue; std::vector<int> nn_indices (1); std::vector<float> nn_distances (1); if (!tree->nearestKSearch (point_i, 1, nn_indices, nn_distances)) continue; size_t point_nn_i = nn_indices.front(); float dist = squaredEuclideanDistance (xyz_source->points[point_i], xyz_target->points[point_nn_i]); rmse += dist; output_xyzi->points[point_i].x = xyz_source->points[point_i].x; output_xyzi->points[point_i].y = xyz_source->points[point_i].y; output_xyzi->points[point_i].z = xyz_source->points[point_i].z; output_xyzi->points[point_i].intensity = dist; } rmse = sqrt (rmse / xyz_source->points.size ()); } else if (correspondence_type == "nnplane") { print_highlight (stderr, "Computing using the nearest neighbor plane projection correspondence heuristic.\n"); PointCloud<Normal>::Ptr normals_target (new PointCloud<Normal> ()); fromROSMsg (*cloud_target, *normals_target); KdTreeFLANN<PointXYZ>::Ptr tree (new KdTreeFLANN<PointXYZ> ()); tree->setInputCloud (xyz_target); for (size_t point_i = 0; point_i < xyz_source->points.size (); ++ point_i) { if (!pcl_isfinite (xyz_source->points[point_i].x) || !pcl_isfinite (xyz_source->points[point_i].y) || !pcl_isfinite (xyz_source->points[point_i].z)) continue; std::vector<int> nn_indices (1); std::vector<float> nn_distances (1); if (!tree->nearestKSearch (point_i, 1, nn_indices, nn_distances)) continue; size_t point_nn_i = nn_indices.front(); Eigen::Vector3f normal_target = normals_target->points[point_nn_i].getNormalVector3fMap (), point_source = xyz_source->points[point_i].getVector3fMap (), point_target = xyz_target->points[point_nn_i].getVector3fMap (); float dist = normal_target.dot (point_source - point_target); rmse += dist * dist; output_xyzi->points[point_i].x = xyz_source->points[point_i].x; output_xyzi->points[point_i].y = xyz_source->points[point_i].y; output_xyzi->points[point_i].z = xyz_source->points[point_i].z; output_xyzi->points[point_i].intensity = dist * dist; } rmse = sqrt (rmse / xyz_source->points.size ()); } else { print_error ("Unrecognized correspondence type. Check legal arguments by using the -h option\n"); return; } toROSMsg (*output_xyzi, output); print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms]\n"); print_highlight ("RMSE Error: %f\n", rmse); } void saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output) { TicToc tt; tt.tic (); print_highlight ("Saving "); print_value ("%s ", filename.c_str ()); pcl::io::savePCDFile (filename, output); print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", output.width * output.height); print_info (" points]\n"); } /* ---[ */ int main (int argc, char** argv) { print_info ("Compute the differences between two point clouds and visualizing them as an output intensity cloud. For more information, use: %s -h\n", argv[0]); if (argc < 4) { printHelp (argc, argv); return (-1); } // Parse the command line arguments for .pcd files std::vector<int> p_file_indices; p_file_indices = parse_file_extension_argument (argc, argv, ".pcd"); if (p_file_indices.size () != 3) { print_error ("Need two input PCD files and one output PCD file to continue.\n"); return (-1); } // Command line parsing std::string correspondence_type = default_correspondence_type; parse_argument (argc, argv, "-correspondence", correspondence_type); // Load the first file sensor_msgs::PointCloud2::Ptr cloud_source (new sensor_msgs::PointCloud2 ()); if (!loadCloud (argv[p_file_indices[0]], *cloud_source)) return (-1); // Load the second file sensor_msgs::PointCloud2::Ptr cloud_target (new sensor_msgs::PointCloud2 ()); if (!loadCloud (argv[p_file_indices[1]], *cloud_target)) return (-1); sensor_msgs::PointCloud2 output; // Perform the feature estimation compute (cloud_source, cloud_target, output, correspondence_type); // Output the third file saveCloud (argv[p_file_indices[2]], output); } <commit_msg>tools/compute_cloud_error bug fix<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ */ #include <sensor_msgs/PointCloud2.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/console/print.h> #include <pcl/console/parse.h> #include <pcl/console/time.h> #include <pcl/kdtree/kdtree_flann.h> using namespace pcl; using namespace pcl::io; using namespace pcl::console; std::string default_correspondence_type = "index"; void printHelp (int argc, char **argv) { print_error ("Syntax is: %s source.pcd target.pcd output_intensity.pcd <options>\n", argv[0]); print_info (" where options are:\n"); print_info (" -correspondence X = the way of selecting the corresponding pair in the target cloud for the current point in the source cloud\n"); print_info (" options are: index = points with identical indices are paired together. Note: both clouds need to have the same number of points\n"); print_info (" nn = source point is paired with its nearest neighbor in the target cloud\n"); print_info (" nnplane = source point is paired with its projection on the plane determined by the nearest neighbor in the target cloud. Note: target cloud needs to contain normals\n"); print_info (" (default: "); print_value ("%s", default_correspondence_type.c_str ()); print_info (")\n"); } bool loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud) { TicToc tt; // print_highlight ("Loading "); print_value ("%s ", filename.c_str ()); tt.tic (); if (loadPCDFile (filename, cloud) < 0) return (false); // print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n"); // print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ()); return (true); } void compute (const sensor_msgs::PointCloud2::ConstPtr &cloud_source, const sensor_msgs::PointCloud2::ConstPtr &cloud_target, sensor_msgs::PointCloud2 &output, std::string correspondence_type) { // Estimate TicToc tt; tt.tic (); PointCloud<PointXYZ>::Ptr xyz_source (new PointCloud<PointXYZ> ()); fromROSMsg (*cloud_source, *xyz_source); PointCloud<PointXYZ>::Ptr xyz_target (new PointCloud<PointXYZ> ()); fromROSMsg (*cloud_target, *xyz_target); PointCloud<PointXYZI>::Ptr output_xyzi (new PointCloud<PointXYZI> ()); output_xyzi->points.resize (xyz_source->points.size ()); output_xyzi->height = cloud_source->height; output_xyzi->width = cloud_source->width; float rmse = 0.0f; if (correspondence_type == "index") { // print_highlight (stderr, "Computing using the equal indices correspondence heuristic.\n"); if (xyz_source->points.size () != xyz_target->points.size ()) { print_error ("Source and target clouds do not have the same number of points.\n"); return; } for (size_t point_i = 0; point_i < xyz_source->points.size (); ++point_i) { if (!pcl_isfinite (xyz_source->points[point_i].x) || !pcl_isfinite (xyz_source->points[point_i].y) || !pcl_isfinite (xyz_source->points[point_i].z)) continue; if (!pcl_isfinite (xyz_target->points[point_i].x) || !pcl_isfinite (xyz_target->points[point_i].y) || !pcl_isfinite (xyz_target->points[point_i].z)) continue; float dist = squaredEuclideanDistance (xyz_source->points[point_i], xyz_target->points[point_i]); rmse += dist; output_xyzi->points[point_i].x = xyz_source->points[point_i].x; output_xyzi->points[point_i].y = xyz_source->points[point_i].y; output_xyzi->points[point_i].z = xyz_source->points[point_i].z; output_xyzi->points[point_i].intensity = dist; } rmse = sqrt (rmse / xyz_source->points.size ()); } else if (correspondence_type == "nn") { // print_highlight (stderr, "Computing using the nearest neighbor correspondence heuristic.\n"); KdTreeFLANN<PointXYZ>::Ptr tree (new KdTreeFLANN<PointXYZ> ()); tree->setInputCloud (xyz_target); for (size_t point_i = 0; point_i < xyz_source->points.size (); ++ point_i) { if (!pcl_isfinite (xyz_source->points[point_i].x) || !pcl_isfinite (xyz_source->points[point_i].y) || !pcl_isfinite (xyz_source->points[point_i].z)) continue; std::vector<int> nn_indices (1); std::vector<float> nn_distances (1); if (!tree->nearestKSearch (xyz_source->points[point_i], 1, nn_indices, nn_distances)) continue; size_t point_nn_i = nn_indices.front(); float dist = squaredEuclideanDistance (xyz_source->points[point_i], xyz_target->points[point_nn_i]); rmse += dist; output_xyzi->points[point_i].x = xyz_source->points[point_i].x; output_xyzi->points[point_i].y = xyz_source->points[point_i].y; output_xyzi->points[point_i].z = xyz_source->points[point_i].z; output_xyzi->points[point_i].intensity = dist; } rmse = sqrt (rmse / xyz_source->points.size ()); } else if (correspondence_type == "nnplane") { // print_highlight (stderr, "Computing using the nearest neighbor plane projection correspondence heuristic.\n"); PointCloud<Normal>::Ptr normals_target (new PointCloud<Normal> ()); fromROSMsg (*cloud_target, *normals_target); KdTreeFLANN<PointXYZ>::Ptr tree (new KdTreeFLANN<PointXYZ> ()); tree->setInputCloud (xyz_target); for (size_t point_i = 0; point_i < xyz_source->points.size (); ++ point_i) { if (!pcl_isfinite (xyz_source->points[point_i].x) || !pcl_isfinite (xyz_source->points[point_i].y) || !pcl_isfinite (xyz_source->points[point_i].z)) continue; std::vector<int> nn_indices (1); std::vector<float> nn_distances (1); if (!tree->nearestKSearch (xyz_source->points[point_i], 1, nn_indices, nn_distances)) continue; size_t point_nn_i = nn_indices.front(); Eigen::Vector3f normal_target = normals_target->points[point_nn_i].getNormalVector3fMap (), point_source = xyz_source->points[point_i].getVector3fMap (), point_target = xyz_target->points[point_nn_i].getVector3fMap (); float dist = normal_target.dot (point_source - point_target); rmse += dist * dist; output_xyzi->points[point_i].x = xyz_source->points[point_i].x; output_xyzi->points[point_i].y = xyz_source->points[point_i].y; output_xyzi->points[point_i].z = xyz_source->points[point_i].z; output_xyzi->points[point_i].intensity = dist * dist; } rmse = sqrt (rmse / xyz_source->points.size ()); } else { // print_error ("Unrecognized correspondence type. Check legal arguments by using the -h option\n"); return; } toROSMsg (*output_xyzi, output); // print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds]\n"); print_highlight ("RMSE Error: %f\n", rmse); } void saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output) { TicToc tt; tt.tic (); // print_highlight ("Saving "); print_value ("%s ", filename.c_str ()); pcl::io::savePCDFile (filename, output); // print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", output.width * output.height); print_info (" points]\n"); } /* ---[ */ int main (int argc, char** argv) { // print_info ("Compute the differences between two point clouds and visualizing them as an output intensity cloud. For more information, use: %s -h\n", argv[0]); if (argc < 4) { printHelp (argc, argv); return (-1); } // Parse the command line arguments for .pcd files std::vector<int> p_file_indices; p_file_indices = parse_file_extension_argument (argc, argv, ".pcd"); if (p_file_indices.size () != 3) { print_error ("Need two input PCD files and one output PCD file to continue.\n"); return (-1); } // Command line parsing std::string correspondence_type = default_correspondence_type; parse_argument (argc, argv, "-correspondence", correspondence_type); // Load the first file sensor_msgs::PointCloud2::Ptr cloud_source (new sensor_msgs::PointCloud2 ()); if (!loadCloud (argv[p_file_indices[0]], *cloud_source)) return (-1); // Load the second file sensor_msgs::PointCloud2::Ptr cloud_target (new sensor_msgs::PointCloud2 ()); if (!loadCloud (argv[p_file_indices[1]], *cloud_target)) return (-1); sensor_msgs::PointCloud2 output; // Perform the feature estimation compute (cloud_source, cloud_target, output, correspondence_type); // Output the third file saveCloud (argv[p_file_indices[2]], output); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: scuiimoptdlg.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:48:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SCUI_IMOPTDLG_HXX #define SCUI_IMOPTDLG_HXX #include "imoptdlg.hxx" //=================================================================== class ScDelimiterTable; class ScImportOptionsDlg : public ModalDialog { public: ScImportOptionsDlg( Window* pParent, BOOL bAscii = TRUE, const ScImportOptions* pOptions = NULL, const String* pStrTitle = NULL, BOOL bMultiByte = FALSE, BOOL bOnlyDbtoolsEncodings = FALSE, BOOL bImport = TRUE ); ~ScImportOptionsDlg(); void GetImportOptions( ScImportOptions& rOptions ) const; private: FixedLine aFlFieldOpt; FixedText aFtFont; SvxTextEncodingBox aLbFont; FixedText aFtFieldSep; ComboBox aEdFieldSep; FixedText aFtTextSep; ComboBox aEdTextSep; CheckBox aCbFixed; OKButton aBtnOk; CancelButton aBtnCancel; HelpButton aBtnHelp; ScDelimiterTable* pFieldSepTab; ScDelimiterTable* pTextSepTab; private: USHORT GetCodeFromCombo( const ComboBox& rEd ) const; DECL_LINK( FixedWidthHdl, CheckBox* ); DECL_LINK( DoubleClickHdl, ListBox* ); }; #endif <commit_msg>INTEGRATION: CWS dr46 (1.4.106); FILE MERGED 2006/02/16 13:06:20 er 1.4.106.1: #i4925# CSV export with option 'save as shown'<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: scuiimoptdlg.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-03-22 12:11:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SCUI_IMOPTDLG_HXX #define SCUI_IMOPTDLG_HXX #include "imoptdlg.hxx" //=================================================================== class ScDelimiterTable; class ScImportOptionsDlg : public ModalDialog { public: ScImportOptionsDlg( Window* pParent, BOOL bAscii = TRUE, const ScImportOptions* pOptions = NULL, const String* pStrTitle = NULL, BOOL bMultiByte = FALSE, BOOL bOnlyDbtoolsEncodings = FALSE, BOOL bImport = TRUE ); ~ScImportOptionsDlg(); void GetImportOptions( ScImportOptions& rOptions ) const; private: FixedLine aFlFieldOpt; FixedText aFtFont; SvxTextEncodingBox aLbFont; FixedText aFtFieldSep; ComboBox aEdFieldSep; FixedText aFtTextSep; ComboBox aEdTextSep; CheckBox aCbFixed; OKButton aBtnOk; CancelButton aBtnCancel; HelpButton aBtnHelp; CheckBox aCbShown; ScDelimiterTable* pFieldSepTab; ScDelimiterTable* pTextSepTab; private: USHORT GetCodeFromCombo( const ComboBox& rEd ) const; DECL_LINK( FixedWidthHdl, CheckBox* ); DECL_LINK( DoubleClickHdl, ListBox* ); }; #endif <|endoftext|>
<commit_before>#include "FAST/Data/Image.hpp" #include "FAST/Streamers/ImageFileStreamer.hpp" #include "FAST/Algorithms/UltrasoundVesselDetection/UltrasoundVesselDetection.hpp" #include "FAST/Algorithms/UltrasoundVesselDetection/VesselCrossSection.hpp" #include "FAST/Exporters/ImageExporter.hpp" #include "FAST/Algorithms/ImageCropper/ImageCropper.hpp" #include "boost/filesystem.hpp" using namespace fast; inline std::string currentDateTime() { time_t now = time(0); struct tm tstruct; char buf[80]; tstruct = *localtime(&now); // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime // for more information about date/time format strftime(buf, sizeof(buf), "%Y-%m-%d-%H%M%S", &tstruct); return buf; } int main() { std::string storageDir = "/home/smistad/vessel_detection_dataset3/"; boost::filesystem::create_directories(storageDir); // Set up stream std::vector<std::string> recordings = { "/home/smistad/AssistantTestData/1/US-Acq_03_20150608T103739/Acquisition/US-Acq_03_20150608T103739_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/1/US-Acq_04_20150608T103837/Acquisition/US-Acq_04_20150608T103837_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/1/US-Acq_07_20150608T104148/Acquisition/US-Acq_07_20150608T104148_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/1/US-Acq_08_20150608T104238/Acquisition/US-Acq_08_20150608T104238_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/0/US-Acq_03_20150608T102144/Acquisition/US-Acq_03_20150608T102144_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/0/US-Acq_04_20150608T102242/Acquisition/US-Acq_04_20150608T102242_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/0/US-Acq_07_20150608T102703/Acquisition/US-Acq_07_20150608T102703_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/0/US-Acq_08_20150608T102854/Acquisition/US-Acq_08_20150608T102854_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/2/US-Acq_03_20150608T104805/Acquisition/US-Acq_03_20150608T104805_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/2/US-Acq_04_20150608T104910/Acquisition/US-Acq_04_20150608T104910_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/2/US-Acq_07_20150608T105549/Acquisition/US-Acq_07_20150608T105549_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/2/US-Acq_08_20150608T105649/Acquisition/US-Acq_08_20150608T105649_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/3/US-Acq_03_20150608T113646/Acquisition/US-Acq_03_20150608T113646_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/3/US-Acq_04_20150608T113750/Acquisition/US-Acq_04_20150608T113750_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/3/US-Acq_07_20150608T114115/Acquisition/US-Acq_07_20150608T114115_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/3/US-Acq_08_20150608T114217/Acquisition/US-Acq_08_20150608T114217_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/4/US-Acq_03_20150608T112610/Acquisition/US-Acq_03_20150608T112610_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/4/US-Acq_04_20150608T112656/Acquisition/US-Acq_04_20150608T112656_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/4/US-Acq_08_20150608T113129/Acquisition/US-Acq_08_20150608T113129_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/4/US-Acq_09_20150608T113245/Acquisition/US-Acq_09_20150608T113245_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/5/US-Acq_03_20150608T111610/Acquisition/US-Acq_03_20150608T111610_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/5/US-Acq_04_20150608T111701/Acquisition/US-Acq_04_20150608T111701_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/5/US-Acq_07_20150608T111940/Acquisition/US-Acq_07_20150608T111940_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/6/0/US-2D_#.mhd", "/home/smistad/AssistantTestData/6/1/US-2D_#.mhd", "/home/smistad/AssistantTestData/6/2/US-2D_#.mhd", "/home/smistad/AssistantTestData/6/3/US-2D_#.mhd", "/home/smistad/AssistantTestData/6/4/US-2D_#.mhd", "/home/smistad/AssistantTestData/7/0/US-2D_#.mhd", "/home/smistad/AssistantTestData/7/1/US-2D_#.mhd", "/home/smistad/AssistantTestData/7/2/US-2D_#.mhd", "/home/smistad/AssistantTestData/7/3/US-2D_#.mhd", "/home/smistad/AssistantTestData/8/0/US-2D_#.mhd", "/home/smistad/AssistantTestData/8/1/US-2D_#.mhd", "/home/smistad/AssistantTestData/8/2/US-2D_#.mhd", "/home/smistad/AssistantTestData/8/3/US-2D_#.mhd", "/home/smistad/AssistantTestData/9/0/US-2D_#.mhd", "/home/smistad/AssistantTestData/9/1/US-2D_#.mhd", "/home/smistad/AssistantTestData/9/2/US-2D_#.mhd", "/home/smistad/AssistantTestData/9/3/US-2D_#.mhd", "/home/smistad/AssistantTestData/10/0/US-2D_#.mhd", "/home/smistad/AssistantTestData/10/1/US-2D_#.mhd", "/home/smistad/AssistantTestData/10/2/US-2D_#.mhd", "/home/smistad/AssistantTestData/10/3/US-2D_#.mhd", "/home/smistad/AssistantTestData/11/0/US-2D_#.mhd", "/home/smistad/AssistantTestData/11/1/US-2D_#.mhd", "/home/smistad/AssistantTestData/11/2/US-2D_#.mhd", "/home/smistad/AssistantTestData/11/3/US-2D_#.mhd", "/home/smistad/AssistantTestData/12/0/US-2D_#.mhd", "/home/smistad/AssistantTestData/12/1/US-2D_#.mhd", "/home/smistad/AssistantTestData/12/2/US-2D_#.mhd", "/home/smistad/AssistantTestData/12/3/US-2D_#.mhd" }; for(int i = 0; i < recordings.size(); ++i) { ImageFileStreamer::pointer streamer = ImageFileStreamer::New(); streamer->setStreamingMode(STREAMING_MODE_PROCESS_ALL_FRAMES); streamer->setStepSize(10); streamer->setFilenameFormat(recordings[i]); streamer->update(); DynamicData::pointer images = streamer->getOutputData<Image>(); //int j = i / 4; // Group 4 sequences into each folder //std::string targetDir = storageDir + boost::lexical_cast<std::string>(j) + "/"; //boost::filesystem::create_directories(targetDir); std::string targetDir = storageDir; UltrasoundVesselDetection::pointer dummy = UltrasoundVesselDetection::New(); // Store ROIs as PNGs to disk int counter = 0; UltrasoundVesselDetection::pointer detector = UltrasoundVesselDetection::New(); while(!images->hasReachedEnd()) { Image::pointer image = images->getNextFrame(dummy); Vector3ui imageSize = image->getSize(); Vector3f spacing = image->getSpacing(); detector->setInputData(image); detector->update(); std::vector<VesselCrossSection::pointer> crossSections = detector->getCrossSections(); std::cout << "Found " << crossSections.size() << " cross sections" << std::endl; // For each detected black ellipse for(VesselCrossSection::pointer crossSection : crossSections) { VesselCrossSectionAccess::pointer access = crossSection->getAccess(ACCESS_READ); Vector2f imageCenter = access->getImageCenterPosition(); // Radius in pixels const float majorRadius = access->getMajorRadius(); const float minorRadius = access->getMinorRadius(); const int frameSize = std::max((int)round(majorRadius), 50); // Nr if pixels to include around vessel Vector2i offset( round(imageCenter.x() - majorRadius) - frameSize, round(imageCenter.y() - minorRadius) - frameSize ); int size2 = 2*majorRadius + 2*frameSize; Vector2i size( size2, size2 ); ImageCropper::pointer cropper = ImageCropper::New(); cropper->setInputData(image); cropper->allowOutOfBoundsCropping(true); cropper->setOffset(offset); cropper->setSize(size); ImageExporter::pointer exporter = ImageExporter::New(); std::string filename = currentDateTime() + "-" + boost::lexical_cast<std::string>(counter) + ".png"; exporter->setFilename(targetDir + filename); exporter->setInputConnection(cropper->getOutputPort()); exporter->update(); counter++; } } } } <commit_msg>Put region proposals in subfolders<commit_after>#include "FAST/Data/Image.hpp" #include "FAST/Streamers/ImageFileStreamer.hpp" #include "FAST/Algorithms/UltrasoundVesselDetection/UltrasoundVesselDetection.hpp" #include "FAST/Algorithms/UltrasoundVesselDetection/VesselCrossSection.hpp" #include "FAST/Exporters/ImageExporter.hpp" #include "FAST/Algorithms/ImageCropper/ImageCropper.hpp" #include "boost/filesystem.hpp" using namespace fast; inline std::string currentDateTime() { time_t now = time(0); struct tm tstruct; char buf[80]; tstruct = *localtime(&now); // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime // for more information about date/time format strftime(buf, sizeof(buf), "%Y-%m-%d-%H%M%S", &tstruct); return buf; } int main() { std::string storageDir = "/home/smistad/vessel_detection_dataset3/"; boost::filesystem::create_directories(storageDir); // Set up stream std::vector<std::string> recordings = { "/home/smistad/AssistantTestData/1/US-Acq_03_20150608T103739/Acquisition/US-Acq_03_20150608T103739_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/1/US-Acq_04_20150608T103837/Acquisition/US-Acq_04_20150608T103837_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/1/US-Acq_07_20150608T104148/Acquisition/US-Acq_07_20150608T104148_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/1/US-Acq_08_20150608T104238/Acquisition/US-Acq_08_20150608T104238_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/0/US-Acq_03_20150608T102144/Acquisition/US-Acq_03_20150608T102144_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/0/US-Acq_04_20150608T102242/Acquisition/US-Acq_04_20150608T102242_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/0/US-Acq_07_20150608T102703/Acquisition/US-Acq_07_20150608T102703_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/0/US-Acq_08_20150608T102854/Acquisition/US-Acq_08_20150608T102854_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/2/US-Acq_03_20150608T104805/Acquisition/US-Acq_03_20150608T104805_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/2/US-Acq_04_20150608T104910/Acquisition/US-Acq_04_20150608T104910_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/2/US-Acq_07_20150608T105549/Acquisition/US-Acq_07_20150608T105549_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/2/US-Acq_08_20150608T105649/Acquisition/US-Acq_08_20150608T105649_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/3/US-Acq_03_20150608T113646/Acquisition/US-Acq_03_20150608T113646_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/3/US-Acq_04_20150608T113750/Acquisition/US-Acq_04_20150608T113750_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/3/US-Acq_07_20150608T114115/Acquisition/US-Acq_07_20150608T114115_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/3/US-Acq_08_20150608T114217/Acquisition/US-Acq_08_20150608T114217_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/4/US-Acq_03_20150608T112610/Acquisition/US-Acq_03_20150608T112610_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/4/US-Acq_04_20150608T112656/Acquisition/US-Acq_04_20150608T112656_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/4/US-Acq_08_20150608T113129/Acquisition/US-Acq_08_20150608T113129_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/4/US-Acq_09_20150608T113245/Acquisition/US-Acq_09_20150608T113245_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/5/US-Acq_03_20150608T111610/Acquisition/US-Acq_03_20150608T111610_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/5/US-Acq_04_20150608T111701/Acquisition/US-Acq_04_20150608T111701_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/5/US-Acq_07_20150608T111940/Acquisition/US-Acq_07_20150608T111940_Image_Transducer_#.mhd", "/home/smistad/AssistantTestData/6/0/US-2D_#.mhd", "/home/smistad/AssistantTestData/6/1/US-2D_#.mhd", "/home/smistad/AssistantTestData/6/2/US-2D_#.mhd", "/home/smistad/AssistantTestData/6/3/US-2D_#.mhd", "/home/smistad/AssistantTestData/6/4/US-2D_#.mhd", "/home/smistad/AssistantTestData/7/0/US-2D_#.mhd", "/home/smistad/AssistantTestData/7/1/US-2D_#.mhd", "/home/smistad/AssistantTestData/7/2/US-2D_#.mhd", "/home/smistad/AssistantTestData/7/3/US-2D_#.mhd", "/home/smistad/AssistantTestData/8/0/US-2D_#.mhd", "/home/smistad/AssistantTestData/8/1/US-2D_#.mhd", "/home/smistad/AssistantTestData/8/2/US-2D_#.mhd", "/home/smistad/AssistantTestData/8/3/US-2D_#.mhd", "/home/smistad/AssistantTestData/9/0/US-2D_#.mhd", "/home/smistad/AssistantTestData/9/1/US-2D_#.mhd", "/home/smistad/AssistantTestData/9/2/US-2D_#.mhd", "/home/smistad/AssistantTestData/9/3/US-2D_#.mhd", "/home/smistad/AssistantTestData/10/0/US-2D_#.mhd", "/home/smistad/AssistantTestData/10/1/US-2D_#.mhd", "/home/smistad/AssistantTestData/10/2/US-2D_#.mhd", "/home/smistad/AssistantTestData/10/3/US-2D_#.mhd", "/home/smistad/AssistantTestData/11/0/US-2D_#.mhd", "/home/smistad/AssistantTestData/11/1/US-2D_#.mhd", "/home/smistad/AssistantTestData/11/2/US-2D_#.mhd", "/home/smistad/AssistantTestData/11/3/US-2D_#.mhd", "/home/smistad/AssistantTestData/12/0/US-2D_#.mhd", "/home/smistad/AssistantTestData/12/1/US-2D_#.mhd", "/home/smistad/AssistantTestData/12/2/US-2D_#.mhd", "/home/smistad/AssistantTestData/12/3/US-2D_#.mhd" }; for(int i = 0; i < recordings.size(); ++i) { ImageFileStreamer::pointer streamer = ImageFileStreamer::New(); streamer->setStreamingMode(STREAMING_MODE_PROCESS_ALL_FRAMES); streamer->setStepSize(10); streamer->setFilenameFormat(recordings[i]); streamer->update(); DynamicData::pointer images = streamer->getOutputData<Image>(); // Put in subfolders int j = i / 4; // Group 4 sequences into each folder std::string targetDir = storageDir + boost::lexical_cast<std::string>(j) + "/"; boost::filesystem::create_directories(targetDir); UltrasoundVesselDetection::pointer dummy = UltrasoundVesselDetection::New(); // Store ROIs as PNGs to disk int counter = 0; UltrasoundVesselDetection::pointer detector = UltrasoundVesselDetection::New(); while(!images->hasReachedEnd()) { Image::pointer image = images->getNextFrame(dummy); Vector3ui imageSize = image->getSize(); Vector3f spacing = image->getSpacing(); detector->setInputData(image); detector->update(); std::vector<VesselCrossSection::pointer> crossSections = detector->getCrossSections(); std::cout << "Found " << crossSections.size() << " cross sections" << std::endl; // For each detected black ellipse for(VesselCrossSection::pointer crossSection : crossSections) { VesselCrossSectionAccess::pointer access = crossSection->getAccess(ACCESS_READ); Vector2f imageCenter = access->getImageCenterPosition(); // Radius in pixels const float majorRadius = access->getMajorRadius(); const float minorRadius = access->getMinorRadius(); const int frameSize = std::max((int)round(majorRadius), 50); // Nr if pixels to include around vessel Vector2i offset( round(imageCenter.x() - majorRadius) - frameSize, round(imageCenter.y() - minorRadius) - frameSize ); int size2 = 2*majorRadius + 2*frameSize; Vector2i size( size2, size2 ); ImageCropper::pointer cropper = ImageCropper::New(); cropper->setInputData(image); cropper->allowOutOfBoundsCropping(true); cropper->setOffset(offset); cropper->setSize(size); ImageExporter::pointer exporter = ImageExporter::New(); std::string filename = currentDateTime() + "-" + boost::lexical_cast<std::string>(counter) + ".png"; exporter->setFilename(targetDir + filename); exporter->setInputConnection(cropper->getOutputPort()); exporter->update(); counter++; } } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: highred.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: rt $ $Date: 2007-04-26 09:53:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // System - Includes --------------------------------------------------------- // INCLUDE ------------------------------------------------------------------- #include "global.hxx" #include "reffact.hxx" #include "document.hxx" #include "docsh.hxx" #include "scresid.hxx" #include "globstr.hrc" #include "highred.hrc" #include "highred.hxx" #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #include <sfx2/app.hxx> // defines ------------------------------------------------------------------- #define ABS_SREF SCA_VALID \ | SCA_COL_ABSOLUTE | SCA_ROW_ABSOLUTE | SCA_TAB_ABSOLUTE #define ABS_DREF ABS_SREF \ | SCA_COL2_ABSOLUTE | SCA_ROW2_ABSOLUTE | SCA_TAB2_ABSOLUTE #define ABS_SREF3D ABS_SREF | SCA_TAB_3D #define ABS_DREF3D ABS_DREF | SCA_TAB_3D #define ERRORBOX(s) ErrorBox(this,WinBits(WB_OK|WB_DEF_OK),s).Execute(); inline void EnableDisable( Window& rWin, BOOL bEnable ) { if (bEnable) rWin.Enable(); else rWin.Disable(); } //============================================================================ // class ScHighlightChgDlg //---------------------------------------------------------------------------- ScHighlightChgDlg::ScHighlightChgDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, ScViewData* ptrViewData) : ScAnyRefDlg ( pB, pCW, pParent, RID_SCDLG_HIGHLIGHT_CHANGES ), // aHighlightBox ( this, ScResId( CB_HIGHLIGHT)), aFlFilter ( this, ScResId( FL_FILTER)), aFilterCtr ( this), aCbAccept ( this, ScResId( CB_HIGHLIGHT_ACCEPT)), aCbReject ( this, ScResId( CB_HIGHLIGHT_REJECT)), aOkButton ( this, ScResId( BTN_OK ) ), aCancelButton ( this, ScResId( BTN_CANCEL ) ), aHelpButton ( this, ScResId( BTN_HELP ) ), aEdAssign ( this, ScResId( ED_ASSIGN ) ), aRbAssign ( this, ScResId( RB_ASSIGN ), &aEdAssign ), // pViewData ( ptrViewData ), pDoc ( ptrViewData->GetDocument() ), aLocalRangeName ( *(pDoc->GetRangeName()) ) { FreeResource(); Point aFlFilterPt( aFlFilter.GetPosPixel() ); aFlFilterPt.Y() += aFlFilter.GetSizePixel().Height(); aFilterCtr.SetPosPixel( aFlFilterPt ); MinSize=aFilterCtr.GetSizePixel(); MinSize.Height()+=2; MinSize.Width()+=2; aOkButton.SetClickHdl(LINK( this, ScHighlightChgDlg, OKBtnHdl)); aHighlightBox.SetClickHdl(LINK( this, ScHighlightChgDlg, HighLightHandle )); aFilterCtr.SetRefHdl(LINK( this, ScHighlightChgDlg, RefHandle )); aFilterCtr.HideRange(FALSE); aFilterCtr.Show(); SetDispatcherLock( TRUE ); //SFX_APPWINDOW->Disable(FALSE); Init(); } ScHighlightChgDlg::~ScHighlightChgDlg() { SetDispatcherLock( FALSE ); //SFX_APPWINDOW->Enable(); } void __EXPORT ScHighlightChgDlg::Init() { String aAreaStr; ScRange aRange; DBG_ASSERT( pViewData && pDoc, "ViewData oder Document nicht gefunden!" ); ScChangeTrack* pChanges=pDoc->GetChangeTrack(); if(pChanges!=NULL) { aChangeViewSet.SetTheAuthorToShow(pChanges->GetUser()); aFilterCtr.ClearAuthors(); StrCollection aUserColl=pChanges->GetUserCollection(); for(USHORT i=0;i<aUserColl.GetCount();i++) aFilterCtr.InsertAuthor(aUserColl[i]->GetString()); } ScChangeViewSettings* pViewSettings=pDoc->GetChangeViewSettings(); if(pViewSettings!=NULL) aChangeViewSet=*pViewSettings; aHighlightBox.Check(aChangeViewSet.ShowChanges()); aFilterCtr.CheckDate(aChangeViewSet.HasDate()); aFilterCtr.SetFirstDate(aChangeViewSet.GetTheFirstDateTime()); aFilterCtr.SetFirstTime(aChangeViewSet.GetTheFirstDateTime()); aFilterCtr.SetLastDate(aChangeViewSet.GetTheLastDateTime()); aFilterCtr.SetLastTime(aChangeViewSet.GetTheLastDateTime()); aFilterCtr.SetDateMode((USHORT)aChangeViewSet.GetTheDateMode()); aFilterCtr.CheckAuthor(aChangeViewSet.HasAuthor()); aFilterCtr.CheckComment(aChangeViewSet.HasComment()); aFilterCtr.SetComment(aChangeViewSet.GetTheComment()); aCbAccept.Check(aChangeViewSet.IsShowAccepted()); aCbReject.Check(aChangeViewSet.IsShowRejected()); String aString=aChangeViewSet.GetTheAuthorToShow(); if(aString.Len()!=0) { aFilterCtr.SelectAuthor(aString); } else { aFilterCtr.SelectedAuthorPos(0); } aFilterCtr.CheckRange(aChangeViewSet.HasRange()); ScRange* pRangeEntry=aChangeViewSet.GetTheRangeList().GetObject(0); if(pRangeEntry!=NULL) { String aRefStr; pRangeEntry->Format( aRefStr, ABS_DREF3D, pDoc ); aFilterCtr.SetRange(aRefStr); } aFilterCtr.Enable(TRUE,TRUE); HighLightHandle(&aHighlightBox); } //---------------------------------------------------------------------------- // Uebergabe eines mit der Maus selektierten Tabellenbereiches, der dann als // neue Selektion im Referenz-Edit angezeigt wird. void ScHighlightChgDlg::SetReference( const ScRange& rRef, ScDocument* pDocP ) { if ( aEdAssign.IsVisible() ) { if ( rRef.aStart != rRef.aEnd ) RefInputStart(&aEdAssign); String aRefStr; rRef.Format( aRefStr, ABS_DREF3D, pDocP ); aEdAssign.SetRefString( aRefStr ); aFilterCtr.SetRange(aRefStr); } } //---------------------------------------------------------------------------- BOOL __EXPORT ScHighlightChgDlg::Close() { return DoClose( ScHighlightChgDlgWrapper::GetChildWindowId() ); } void ScHighlightChgDlg::RefInputDone( BOOL bForced) { ScAnyRefDlg::RefInputDone(bForced); if(bForced || !aRbAssign.IsVisible()) { aFilterCtr.SetRange(aEdAssign.GetText()); aFilterCtr.SetFocusToRange(); aEdAssign.Hide(); aRbAssign.Hide(); } } void ScHighlightChgDlg::SetActive() { /* if(pTPFilter!=NULL) { aAcceptChgCtr.GetFilterPage()->SetFocusToRange(); aEdAssign.Hide(); aRbAssign.Hide(); SFX_APPWINDOW->Enable(); SetDispatcherLock( FALSE ); } //RefInputDone(); */ } BOOL ScHighlightChgDlg::IsRefInputMode() const { return aEdAssign.IsVisible(); } IMPL_LINK( ScHighlightChgDlg, HighLightHandle, CheckBox*, pCb ) { if(pCb!=NULL) { if(aHighlightBox.IsChecked()) { aFilterCtr.Enable(TRUE,TRUE); aCbAccept.Enable(); aCbReject.Enable(); } else { aFilterCtr.Disable(TRUE); aCbAccept.Disable(); aCbReject.Disable(); } } return 0; } IMPL_LINK( ScHighlightChgDlg, RefHandle, SvxTPFilter*, pRef ) { if(pRef!=NULL) { SetDispatcherLock( TRUE ); //SFX_APPWINDOW->Disable(FALSE); aEdAssign.Show(); aRbAssign.Show(); aEdAssign.SetText(aFilterCtr.GetRange()); ScAnyRefDlg::RefInputStart(&aEdAssign,&aRbAssign); } return 0; } IMPL_LINK( ScHighlightChgDlg, OKBtnHdl, PushButton*, pOKBtn ) { if ( pOKBtn == &aOkButton) { aChangeViewSet.SetShowChanges(aHighlightBox.IsChecked()); aChangeViewSet.SetHasDate(aFilterCtr.IsDate()); ScChgsDateMode eMode = (ScChgsDateMode) aFilterCtr.GetDateMode(); aChangeViewSet.SetTheDateMode( eMode ); Date aFirstDate( aFilterCtr.GetFirstDate() ); Time aFirstTime( aFilterCtr.GetFirstTime() ); Date aLastDate( aFilterCtr.GetLastDate() ); Time aLastTime( aFilterCtr.GetLastTime() ); aChangeViewSet.SetTheFirstDateTime( DateTime( aFirstDate, aFirstTime ) ); aChangeViewSet.SetTheLastDateTime( DateTime( aLastDate, aLastTime ) ); aChangeViewSet.SetHasAuthor(aFilterCtr.IsAuthor()); aChangeViewSet.SetTheAuthorToShow(aFilterCtr.GetSelectedAuthor()); aChangeViewSet.SetHasRange(aFilterCtr.IsRange()); aChangeViewSet.SetShowAccepted(aCbAccept.IsChecked()); aChangeViewSet.SetShowRejected(aCbReject.IsChecked()); aChangeViewSet.SetHasComment(aFilterCtr.IsComment()); aChangeViewSet.SetTheComment(aFilterCtr.GetComment()); ScRangeList aLocalRangeList; aLocalRangeList.Parse(aFilterCtr.GetRange(), pDoc); aChangeViewSet.SetTheRangeList(aLocalRangeList); aChangeViewSet.AdjustDateMode( *pDoc ); pDoc->SetChangeViewSettings(aChangeViewSet); pViewData->GetDocShell()->PostPaintGridAll(); Close(); } return 0; } <commit_msg>INTEGRATION: CWS changefileheader (1.12.300); FILE MERGED 2008/04/01 15:31:09 thb 1.12.300.2: #i85898# Stripping all external header guards 2008/03/31 17:16:05 rt 1.12.300.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: highred.cxx,v $ * $Revision: 1.13 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // System - Includes --------------------------------------------------------- // INCLUDE ------------------------------------------------------------------- #include "global.hxx" #include "reffact.hxx" #include "document.hxx" #include "docsh.hxx" #include "scresid.hxx" #include "globstr.hrc" #include "highred.hrc" #include "highred.hxx" #include <vcl/msgbox.hxx> #include <sfx2/app.hxx> // defines ------------------------------------------------------------------- #define ABS_SREF SCA_VALID \ | SCA_COL_ABSOLUTE | SCA_ROW_ABSOLUTE | SCA_TAB_ABSOLUTE #define ABS_DREF ABS_SREF \ | SCA_COL2_ABSOLUTE | SCA_ROW2_ABSOLUTE | SCA_TAB2_ABSOLUTE #define ABS_SREF3D ABS_SREF | SCA_TAB_3D #define ABS_DREF3D ABS_DREF | SCA_TAB_3D #define ERRORBOX(s) ErrorBox(this,WinBits(WB_OK|WB_DEF_OK),s).Execute(); inline void EnableDisable( Window& rWin, BOOL bEnable ) { if (bEnable) rWin.Enable(); else rWin.Disable(); } //============================================================================ // class ScHighlightChgDlg //---------------------------------------------------------------------------- ScHighlightChgDlg::ScHighlightChgDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, ScViewData* ptrViewData) : ScAnyRefDlg ( pB, pCW, pParent, RID_SCDLG_HIGHLIGHT_CHANGES ), // aHighlightBox ( this, ScResId( CB_HIGHLIGHT)), aFlFilter ( this, ScResId( FL_FILTER)), aFilterCtr ( this), aCbAccept ( this, ScResId( CB_HIGHLIGHT_ACCEPT)), aCbReject ( this, ScResId( CB_HIGHLIGHT_REJECT)), aOkButton ( this, ScResId( BTN_OK ) ), aCancelButton ( this, ScResId( BTN_CANCEL ) ), aHelpButton ( this, ScResId( BTN_HELP ) ), aEdAssign ( this, ScResId( ED_ASSIGN ) ), aRbAssign ( this, ScResId( RB_ASSIGN ), &aEdAssign ), // pViewData ( ptrViewData ), pDoc ( ptrViewData->GetDocument() ), aLocalRangeName ( *(pDoc->GetRangeName()) ) { FreeResource(); Point aFlFilterPt( aFlFilter.GetPosPixel() ); aFlFilterPt.Y() += aFlFilter.GetSizePixel().Height(); aFilterCtr.SetPosPixel( aFlFilterPt ); MinSize=aFilterCtr.GetSizePixel(); MinSize.Height()+=2; MinSize.Width()+=2; aOkButton.SetClickHdl(LINK( this, ScHighlightChgDlg, OKBtnHdl)); aHighlightBox.SetClickHdl(LINK( this, ScHighlightChgDlg, HighLightHandle )); aFilterCtr.SetRefHdl(LINK( this, ScHighlightChgDlg, RefHandle )); aFilterCtr.HideRange(FALSE); aFilterCtr.Show(); SetDispatcherLock( TRUE ); //SFX_APPWINDOW->Disable(FALSE); Init(); } ScHighlightChgDlg::~ScHighlightChgDlg() { SetDispatcherLock( FALSE ); //SFX_APPWINDOW->Enable(); } void __EXPORT ScHighlightChgDlg::Init() { String aAreaStr; ScRange aRange; DBG_ASSERT( pViewData && pDoc, "ViewData oder Document nicht gefunden!" ); ScChangeTrack* pChanges=pDoc->GetChangeTrack(); if(pChanges!=NULL) { aChangeViewSet.SetTheAuthorToShow(pChanges->GetUser()); aFilterCtr.ClearAuthors(); StrCollection aUserColl=pChanges->GetUserCollection(); for(USHORT i=0;i<aUserColl.GetCount();i++) aFilterCtr.InsertAuthor(aUserColl[i]->GetString()); } ScChangeViewSettings* pViewSettings=pDoc->GetChangeViewSettings(); if(pViewSettings!=NULL) aChangeViewSet=*pViewSettings; aHighlightBox.Check(aChangeViewSet.ShowChanges()); aFilterCtr.CheckDate(aChangeViewSet.HasDate()); aFilterCtr.SetFirstDate(aChangeViewSet.GetTheFirstDateTime()); aFilterCtr.SetFirstTime(aChangeViewSet.GetTheFirstDateTime()); aFilterCtr.SetLastDate(aChangeViewSet.GetTheLastDateTime()); aFilterCtr.SetLastTime(aChangeViewSet.GetTheLastDateTime()); aFilterCtr.SetDateMode((USHORT)aChangeViewSet.GetTheDateMode()); aFilterCtr.CheckAuthor(aChangeViewSet.HasAuthor()); aFilterCtr.CheckComment(aChangeViewSet.HasComment()); aFilterCtr.SetComment(aChangeViewSet.GetTheComment()); aCbAccept.Check(aChangeViewSet.IsShowAccepted()); aCbReject.Check(aChangeViewSet.IsShowRejected()); String aString=aChangeViewSet.GetTheAuthorToShow(); if(aString.Len()!=0) { aFilterCtr.SelectAuthor(aString); } else { aFilterCtr.SelectedAuthorPos(0); } aFilterCtr.CheckRange(aChangeViewSet.HasRange()); ScRange* pRangeEntry=aChangeViewSet.GetTheRangeList().GetObject(0); if(pRangeEntry!=NULL) { String aRefStr; pRangeEntry->Format( aRefStr, ABS_DREF3D, pDoc ); aFilterCtr.SetRange(aRefStr); } aFilterCtr.Enable(TRUE,TRUE); HighLightHandle(&aHighlightBox); } //---------------------------------------------------------------------------- // Uebergabe eines mit der Maus selektierten Tabellenbereiches, der dann als // neue Selektion im Referenz-Edit angezeigt wird. void ScHighlightChgDlg::SetReference( const ScRange& rRef, ScDocument* pDocP ) { if ( aEdAssign.IsVisible() ) { if ( rRef.aStart != rRef.aEnd ) RefInputStart(&aEdAssign); String aRefStr; rRef.Format( aRefStr, ABS_DREF3D, pDocP ); aEdAssign.SetRefString( aRefStr ); aFilterCtr.SetRange(aRefStr); } } //---------------------------------------------------------------------------- BOOL __EXPORT ScHighlightChgDlg::Close() { return DoClose( ScHighlightChgDlgWrapper::GetChildWindowId() ); } void ScHighlightChgDlg::RefInputDone( BOOL bForced) { ScAnyRefDlg::RefInputDone(bForced); if(bForced || !aRbAssign.IsVisible()) { aFilterCtr.SetRange(aEdAssign.GetText()); aFilterCtr.SetFocusToRange(); aEdAssign.Hide(); aRbAssign.Hide(); } } void ScHighlightChgDlg::SetActive() { /* if(pTPFilter!=NULL) { aAcceptChgCtr.GetFilterPage()->SetFocusToRange(); aEdAssign.Hide(); aRbAssign.Hide(); SFX_APPWINDOW->Enable(); SetDispatcherLock( FALSE ); } //RefInputDone(); */ } BOOL ScHighlightChgDlg::IsRefInputMode() const { return aEdAssign.IsVisible(); } IMPL_LINK( ScHighlightChgDlg, HighLightHandle, CheckBox*, pCb ) { if(pCb!=NULL) { if(aHighlightBox.IsChecked()) { aFilterCtr.Enable(TRUE,TRUE); aCbAccept.Enable(); aCbReject.Enable(); } else { aFilterCtr.Disable(TRUE); aCbAccept.Disable(); aCbReject.Disable(); } } return 0; } IMPL_LINK( ScHighlightChgDlg, RefHandle, SvxTPFilter*, pRef ) { if(pRef!=NULL) { SetDispatcherLock( TRUE ); //SFX_APPWINDOW->Disable(FALSE); aEdAssign.Show(); aRbAssign.Show(); aEdAssign.SetText(aFilterCtr.GetRange()); ScAnyRefDlg::RefInputStart(&aEdAssign,&aRbAssign); } return 0; } IMPL_LINK( ScHighlightChgDlg, OKBtnHdl, PushButton*, pOKBtn ) { if ( pOKBtn == &aOkButton) { aChangeViewSet.SetShowChanges(aHighlightBox.IsChecked()); aChangeViewSet.SetHasDate(aFilterCtr.IsDate()); ScChgsDateMode eMode = (ScChgsDateMode) aFilterCtr.GetDateMode(); aChangeViewSet.SetTheDateMode( eMode ); Date aFirstDate( aFilterCtr.GetFirstDate() ); Time aFirstTime( aFilterCtr.GetFirstTime() ); Date aLastDate( aFilterCtr.GetLastDate() ); Time aLastTime( aFilterCtr.GetLastTime() ); aChangeViewSet.SetTheFirstDateTime( DateTime( aFirstDate, aFirstTime ) ); aChangeViewSet.SetTheLastDateTime( DateTime( aLastDate, aLastTime ) ); aChangeViewSet.SetHasAuthor(aFilterCtr.IsAuthor()); aChangeViewSet.SetTheAuthorToShow(aFilterCtr.GetSelectedAuthor()); aChangeViewSet.SetHasRange(aFilterCtr.IsRange()); aChangeViewSet.SetShowAccepted(aCbAccept.IsChecked()); aChangeViewSet.SetShowRejected(aCbReject.IsChecked()); aChangeViewSet.SetHasComment(aFilterCtr.IsComment()); aChangeViewSet.SetTheComment(aFilterCtr.GetComment()); ScRangeList aLocalRangeList; aLocalRangeList.Parse(aFilterCtr.GetRange(), pDoc); aChangeViewSet.SetTheRangeList(aLocalRangeList); aChangeViewSet.AdjustDateMode( *pDoc ); pDoc->SetChangeViewSettings(aChangeViewSet); pViewData->GetDocShell()->PostPaintGridAll(); Close(); } return 0; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: textfile.cpp // Purpose: Implementation of class wxExTextFileWithListView // Author: Anton van Wezenbeek // Copyright: (c) 2013 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <cctype> // for isspace #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/extension/report/textfile.h> #include <wx/extension/frd.h> #include <wx/extension/listitem.h> #include <wx/extension/util.h> #include <wx/extension/report/defs.h> #include <wx/extension/report/frame.h> #include <wx/extension/report/listview.h> wxExListView* wxExTextFileWithListView::m_Report = NULL; wxExFrameWithHistory* wxExTextFileWithListView::m_Frame = NULL; wxExTextFileWithListView::wxExTextFileWithListView( const wxExFileName& filename, const wxExTool& tool) : wxExTextFile(filename, tool) , m_LastSyntaxType(SYNTAX_NONE) , m_SyntaxType(SYNTAX_NONE) , m_IsCommentStatement(false) , m_IsString(false) { } wxExTextFileWithListView::wxExCommentType wxExTextFileWithListView::CheckCommentSyntax( const wxString& syntax_begin, const wxString& syntax_end, const wxString& text) const { if (syntax_begin == text) { return (syntax_end == text) ? COMMENT_BOTH: COMMENT_BEGIN; } else { if (syntax_end == text || (syntax_end.empty() && text.empty())) { return COMMENT_END; } } if ( syntax_begin.StartsWith(text) || (!syntax_end.empty() && syntax_end.StartsWith(text))) { return COMMENT_INCOMPLETE; } return COMMENT_NONE; } wxExTextFileWithListView::wxExCommentType wxExTextFileWithListView::CheckForComment( const wxString& text) { if (GetFileName().GetLexer().GetCommentBegin2().empty()) { return CheckCommentSyntax( GetFileName().GetLexer().GetCommentBegin(), GetFileName().GetLexer().GetCommentEnd(), text); } wxExCommentType comment_type1 = COMMENT_NONE; if (m_SyntaxType == SYNTAX_NONE || m_SyntaxType == SYNTAX_ONE) { if ((comment_type1 = CheckCommentSyntax( GetFileName().GetLexer().GetCommentBegin(), GetFileName().GetLexer().GetCommentEnd(), text)) == COMMENT_BEGIN) m_SyntaxType = SYNTAX_ONE; } wxExCommentType comment_type2 = COMMENT_NONE; if (m_SyntaxType == SYNTAX_NONE || m_SyntaxType == SYNTAX_TWO) { if ((comment_type2 = CheckCommentSyntax( GetFileName().GetLexer().GetCommentBegin2(), GetFileName().GetLexer().GetCommentEnd2(), text)) == COMMENT_BEGIN) m_SyntaxType = SYNTAX_TWO; } wxExCommentType comment_type = COMMENT_NONE; switch (comment_type1) { case COMMENT_NONE: comment_type = comment_type2; break; case COMMENT_BEGIN: comment_type = COMMENT_BEGIN; break; case COMMENT_END: comment_type = COMMENT_END; break; case COMMENT_BOTH: comment_type = COMMENT_BOTH; break; case COMMENT_INCOMPLETE: comment_type = (comment_type2 == COMMENT_NONE) ? COMMENT_INCOMPLETE: comment_type2; break; default: wxFAIL; } if (comment_type == COMMENT_END) { // E.g. we have a correct /* */ comment, with */ at the end of the line. // Then the end of line itself should not generate a COMMENT_END. if (m_SyntaxType == SYNTAX_NONE) comment_type = COMMENT_NONE; // Keep the syntax type. m_LastSyntaxType = m_SyntaxType; m_SyntaxType = SYNTAX_NONE; } return comment_type; } void wxExTextFileWithListView::CommentStatementEnd() { m_IsCommentStatement = false; // Remove the end of comment characters (as last used) from the buffer. m_Comments = m_Comments.Left( m_Comments.length() - CommentEnd().length()); } void wxExTextFileWithListView::CommentStatementStart() { m_IsCommentStatement = true; } void wxExTextFileWithListView::InsertLine(const wxString& line) { if (GetCurrentLine() == GetLineCount()) { AddLine(line); } else { wxTextFile::InsertLine(line, GetCurrentLine()); } m_Modified = true; GoToLine(GetCurrentLine() + 1); } bool wxExTextFileWithListView::Parse() { if (GetTool().IsFindType()) { return wxExTextFile::Parse(); } else if (GetTool().GetId() == ID_TOOL_REPORT_KEYWORD) { if (m_Frame == NULL) { return false; } m_Report = m_Frame->Activate( wxExListViewWithFrame::GetTypeTool(GetTool()), &GetFileName().GetLexer()); if (m_Report == NULL) { return false; } } for (size_t i = 0; i < GetLineCount(); i++) { wxString& line = GetLine(i); GoToLine(i); if (!ParseLine(line)) { return false; } } if (GetTool().GetId() == ID_TOOL_REPORT_KEYWORD) { if (!GetFileName().GetLexer().GetKeywordsString().empty()) { IncActionsCompleted(); } wxExListItem item(m_Report, GetFileName()); item.Insert(); int total = 0; int col = 1; for (const auto& setit : GetFileName().GetLexer().GetKeywords()) { const wxExStatistics<int>& stat = GetStatistics().GetElements(); const auto it = stat.GetItems().find(setit); if (it != stat.GetItems().end()) { m_Report->SetItem( item.GetId(), col, wxString::Format("%d", it->second)); total += it->second; } col++; } m_Report->SetItem( item.GetId(), col, wxString::Format("%d", total)); } return true; } bool wxExTextFileWithListView::ParseLine(const wxString& line) { bool sequence = false; wxString codeword; for (size_t i = 0; i < line.length(); i++) // no auto { if (m_IsCommentStatement) { m_Comments += line[i]; } else if (line[i] == '"') { m_IsString = !m_IsString; } // Comments and codewords only appear outside strings. if (!m_IsString) { if (line.length() == 0) continue; if (i == 0) { if (!isspace(line[0])) { codeword = line[i]; } continue; } const size_t max_check_size = GetFileName().GetLexer().GetCommentBegin().Length(); const size_t check_size = (i > max_check_size ? max_check_size: i + 1); const wxString text = line.substr(i + 1 - check_size, check_size); switch (CheckForComment(text)) { case COMMENT_BEGIN: if (!m_IsCommentStatement) CommentStatementStart(); break; case COMMENT_END: CommentStatementEnd(); break; case COMMENT_BOTH: !m_IsCommentStatement ? CommentStatementStart(): CommentStatementEnd(); break; case COMMENT_NONE: if (!isspace(line[i]) && !m_IsCommentStatement) { if (!wxExIsCodewordSeparator(line[i])) { if (!sequence) { sequence = true; } codeword += line[i]; } } break; case COMMENT_INCOMPLETE: break; default: wxFAIL; break; } if ( sequence && (wxExIsCodewordSeparator(line[i]) || i ==0 || i == line.length() - 1)) { if (GetTool().GetId() == ID_TOOL_REPORT_KEYWORD) { if (GetFileName().GetLexer().IsKeyword(codeword)) { IncStatistics(codeword); } } sequence = false; codeword.clear(); } } } if (CheckForComment(wxEmptyString) == COMMENT_END) { CommentStatementEnd(); } return true; } void wxExTextFileWithListView::Report(size_t line) { wxASSERT(m_Report != NULL); wxExListItem item(m_Report, GetFileName()); item.Insert(); item.SetItem(_("Line No"), wxString::Format("%d", (int)line + 1)); switch (GetTool().GetId()) { case ID_TOOL_REPORT_REPLACE: item.SetItem(_("Replaced"), wxExFindReplaceData::Get()->GetReplaceString()); case ID_TOOL_REPORT_FIND: item.SetItem(_("Line"), GetLine(line).Strip(wxString::both)); item.SetItem(_("Match"), wxExFindReplaceData::Get()->GetFindString()); break; default: wxFAIL; } } bool wxExTextFileWithListView::SetupTool( const wxExTool& tool, wxExFrameWithHistory* frame, wxExListView* report) { m_Frame = frame; if (report == NULL) { if (tool.IsReportType()) { if (tool.GetId() != ID_TOOL_REPORT_KEYWORD) { m_Report = m_Frame->Activate(wxExListViewWithFrame::GetTypeTool(tool)); if (m_Report == NULL) { return false; } } } } else { m_Report = report; } return true; } <commit_msg>return comment_none if no comment chars defined<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: textfile.cpp // Purpose: Implementation of class wxExTextFileWithListView // Author: Anton van Wezenbeek // Copyright: (c) 2014 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <cctype> // for isspace #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/extension/report/textfile.h> #include <wx/extension/frd.h> #include <wx/extension/listitem.h> #include <wx/extension/util.h> #include <wx/extension/report/defs.h> #include <wx/extension/report/frame.h> #include <wx/extension/report/listview.h> wxExListView* wxExTextFileWithListView::m_Report = NULL; wxExFrameWithHistory* wxExTextFileWithListView::m_Frame = NULL; wxExTextFileWithListView::wxExTextFileWithListView( const wxExFileName& filename, const wxExTool& tool) : wxExTextFile(filename, tool) , m_LastSyntaxType(SYNTAX_NONE) , m_SyntaxType(SYNTAX_NONE) , m_IsCommentStatement(false) , m_IsString(false) { } wxExTextFileWithListView::wxExCommentType wxExTextFileWithListView::CheckCommentSyntax( const wxString& syntax_begin, const wxString& syntax_end, const wxString& text) const { if (syntax_begin.empty() && syntax_end.empty()) { return COMMENT_NONE; } if (syntax_begin == text) { return (syntax_end == text) ? COMMENT_BOTH: COMMENT_BEGIN; } else { if (syntax_end == text || (syntax_end.empty() && text.empty())) { return COMMENT_END; } } if ( syntax_begin.StartsWith(text) || (!syntax_end.empty() && syntax_end.StartsWith(text))) { return COMMENT_INCOMPLETE; } return COMMENT_NONE; } wxExTextFileWithListView::wxExCommentType wxExTextFileWithListView::CheckForComment( const wxString& text) { if (GetFileName().GetLexer().GetCommentBegin2().empty()) { return CheckCommentSyntax( GetFileName().GetLexer().GetCommentBegin(), GetFileName().GetLexer().GetCommentEnd(), text); } wxExCommentType comment_type1 = COMMENT_NONE; if (m_SyntaxType == SYNTAX_NONE || m_SyntaxType == SYNTAX_ONE) { if ((comment_type1 = CheckCommentSyntax( GetFileName().GetLexer().GetCommentBegin(), GetFileName().GetLexer().GetCommentEnd(), text)) == COMMENT_BEGIN) m_SyntaxType = SYNTAX_ONE; } wxExCommentType comment_type2 = COMMENT_NONE; if (m_SyntaxType == SYNTAX_NONE || m_SyntaxType == SYNTAX_TWO) { if ((comment_type2 = CheckCommentSyntax( GetFileName().GetLexer().GetCommentBegin2(), GetFileName().GetLexer().GetCommentEnd2(), text)) == COMMENT_BEGIN) m_SyntaxType = SYNTAX_TWO; } wxExCommentType comment_type = COMMENT_NONE; switch (comment_type1) { case COMMENT_NONE: comment_type = comment_type2; break; case COMMENT_BEGIN: comment_type = COMMENT_BEGIN; break; case COMMENT_END: comment_type = COMMENT_END; break; case COMMENT_BOTH: comment_type = COMMENT_BOTH; break; case COMMENT_INCOMPLETE: comment_type = (comment_type2 == COMMENT_NONE) ? COMMENT_INCOMPLETE: comment_type2; break; default: wxFAIL; } if (comment_type == COMMENT_END) { // E.g. we have a correct /* */ comment, with */ at the end of the line. // Then the end of line itself should not generate a COMMENT_END. if (m_SyntaxType == SYNTAX_NONE) comment_type = COMMENT_NONE; // Keep the syntax type. m_LastSyntaxType = m_SyntaxType; m_SyntaxType = SYNTAX_NONE; } return comment_type; } void wxExTextFileWithListView::CommentStatementEnd() { m_IsCommentStatement = false; // Remove the end of comment characters (as last used) from the buffer. m_Comments = m_Comments.Left( m_Comments.length() - CommentEnd().length()); } void wxExTextFileWithListView::CommentStatementStart() { m_IsCommentStatement = true; } void wxExTextFileWithListView::InsertLine(const wxString& line) { if (GetCurrentLine() == GetLineCount()) { AddLine(line); } else { wxTextFile::InsertLine(line, GetCurrentLine()); } m_Modified = true; GoToLine(GetCurrentLine() + 1); } bool wxExTextFileWithListView::Parse() { if (GetTool().IsFindType()) { return wxExTextFile::Parse(); } else if (GetTool().GetId() == ID_TOOL_REPORT_KEYWORD) { if (m_Frame == NULL) { return false; } m_Report = m_Frame->Activate( wxExListViewWithFrame::GetTypeTool(GetTool()), &GetFileName().GetLexer()); if (m_Report == NULL) { return false; } } for (size_t i = 0; i < GetLineCount(); i++) { wxString& line = GetLine(i); GoToLine(i); if (!ParseLine(line)) { return false; } } if (GetTool().GetId() == ID_TOOL_REPORT_KEYWORD) { if (!GetFileName().GetLexer().GetKeywordsString().empty()) { IncActionsCompleted(); } wxExListItem item(m_Report, GetFileName()); item.Insert(); int total = 0; int col = 1; for (const auto& setit : GetFileName().GetLexer().GetKeywords()) { const wxExStatistics<int>& stat = GetStatistics().GetElements(); const auto it = stat.GetItems().find(setit); if (it != stat.GetItems().end()) { m_Report->SetItem( item.GetId(), col, wxString::Format("%d", it->second)); total += it->second; } col++; } m_Report->SetItem( item.GetId(), col, wxString::Format("%d", total)); } return true; } bool wxExTextFileWithListView::ParseLine(const wxString& line) { bool sequence = false; wxString codeword; for (size_t i = 0; i < line.length(); i++) // no auto { if (m_IsCommentStatement) { m_Comments += line[i]; } else if (line[i] == '"') { m_IsString = !m_IsString; } // Comments and codewords only appear outside strings. if (!m_IsString) { if (line.length() == 0) continue; if (i == 0) { if (!isspace(line[0])) { codeword = line[i]; } continue; } const size_t max_check_size = GetFileName().GetLexer().GetCommentBegin().Length(); const size_t check_size = (i > max_check_size ? max_check_size: i + 1); const wxString text = line.substr(i + 1 - check_size, check_size); switch (CheckForComment(text)) { case COMMENT_BEGIN: if (!m_IsCommentStatement) CommentStatementStart(); break; case COMMENT_END: CommentStatementEnd(); break; case COMMENT_BOTH: !m_IsCommentStatement ? CommentStatementStart(): CommentStatementEnd(); break; case COMMENT_NONE: if (!isspace(line[i]) && !m_IsCommentStatement) { if (!wxExIsCodewordSeparator(line[i])) { if (!sequence) { sequence = true; } codeword += line[i]; } } break; case COMMENT_INCOMPLETE: break; default: wxFAIL; break; } if ( sequence && (wxExIsCodewordSeparator(line[i]) || i ==0 || i == line.length() - 1)) { if (GetTool().GetId() == ID_TOOL_REPORT_KEYWORD) { if (GetFileName().GetLexer().IsKeyword(codeword)) { IncStatistics(codeword); } } sequence = false; codeword.clear(); } } } if (CheckForComment(wxEmptyString) == COMMENT_END) { CommentStatementEnd(); } return true; } void wxExTextFileWithListView::Report(size_t line) { wxASSERT(m_Report != NULL); wxExListItem item(m_Report, GetFileName()); item.Insert(); item.SetItem(_("Line No"), wxString::Format("%d", (int)line + 1)); switch (GetTool().GetId()) { case ID_TOOL_REPORT_REPLACE: item.SetItem(_("Replaced"), wxExFindReplaceData::Get()->GetReplaceString()); case ID_TOOL_REPORT_FIND: item.SetItem(_("Line"), GetLine(line).Strip(wxString::both)); item.SetItem(_("Match"), wxExFindReplaceData::Get()->GetFindString()); break; default: wxFAIL; } } bool wxExTextFileWithListView::SetupTool( const wxExTool& tool, wxExFrameWithHistory* frame, wxExListView* report) { m_Frame = frame; if (report == NULL) { if (tool.IsReportType()) { if (tool.GetId() != ID_TOOL_REPORT_KEYWORD) { m_Report = m_Frame->Activate(wxExListViewWithFrame::GetTypeTool(tool)); if (m_Report == NULL) { return false; } } } } else { m_Report = report; } return true; } <|endoftext|>
<commit_before>/* Copyright © 2016 Taylor C. Richberger <taywee@gmx.com> * This code is released under the license described in the LICENSE file */ #include <algorithm> #include <functional> #include <list> #include <sstream> #include <string> #include <vector> #include <exception> namespace args { class ParseError : public std::runtime_error { public: ParseError(const char *problem) : std::runtime_error(problem) {} virtual ~ParseError() {}; }; // A class of "matchers", specifying short and long options that can possibly be matched class Matcher { private: const std::vector<char> shortOpts; const std::vector<std::string> longOpts; public: // Specify short and long opts separately as iterators template <typename ShortIt, typename LongIt> Matcher(ShortIt shortOptsStart, ShortIt shortOptsEnd, LongIt longOptsStart, LongIt longOptsEnd) : shortOpts(shortOptsStart, shortOptsEnd), longOpts(longOptsStart, longOptsEnd) {} // Specify short and long opts separately as iterables template <typename Short, typename Long> Matcher(Short &&shortIn, Long &&longIn) : shortOpts(std::begin(shortIn), std::end(shortIn)), longOpts(std::begin(longIn), std::end(longIn)) {} Matcher(const std::initializer_list<char> &shortIn, const std::initializer_list<std::string> &longIn) : shortOpts(std::begin(shortIn), std::end(shortIn)), longOpts(std::begin(longIn), std::end(longIn)) {} Matcher(const std::initializer_list<char> &shortIn) : shortOpts(std::begin(shortIn), std::end(shortIn)) {} Matcher(const std::initializer_list<std::string> &longIn) : longOpts(std::begin(longIn), std::end(longIn)) {} Matcher(const Matcher &other) : shortOpts(other.shortOpts), longOpts(other.longOpts) {} Matcher(Matcher &&other) : shortOpts(std::move(other.shortOpts)), longOpts(std::move(other.longOpts)) {} ~Matcher() {} bool Match(const char opt) const { return std::find(std::begin(shortOpts), std::end(shortOpts), opt) != shortOpts.end(); } bool Match(const std::string &opt) const { return std::find(std::begin(longOpts), std::end(longOpts), opt) != longOpts.end(); } }; // Base class for groups and individual argument types class Base { protected: bool matched; const std::string help; public: Base(const std::string &help) : matched(false), help(help) {} virtual ~Base() {} virtual Base *Match(const std::string &arg) = 0; virtual Base *Match(const char arg) = 0; virtual bool Matched() const noexcept { return matched; } operator bool() const noexcept { return matched; } }; // Base class that takes arguments class ArgBase : public Base { public: ArgBase(const std::string &help) : Base(help) {} virtual ~ArgBase() {} virtual void ParseArg(const std::string &arg, const std::string &value) = 0; }; class Group : public Base { private: std::vector<Base*> children; std::function<bool(int, int)> validator; public: Group(const std::string &help, const std::function<bool(int, int)> &validator = Validators::DontCare) : Base(help), validator(validator) {} virtual ~Group() {} virtual Base *Match(const std::string &arg) override { for (Base *child: children) { Base *match = child->Match(arg); if (match) { return match; } } return nullptr; } virtual Base *Match(const char arg) override { for (Base *child: children) { Base *match = child->Match(arg); if (match) { return match; } } return nullptr; } void Add(Base &child) { children.emplace_back(&child); } int MatchedChildren() const { int sum = 0; for (const Base * child: children) { if (child->Matched()) { ++sum; } } return sum; } virtual bool Matched() const noexcept override { return validator(children.size(), MatchedChildren()); } struct Validators { static bool Xor(int children, int matched) { return matched == 1; } static bool AtLeastOne(int children, int matched) { return matched >= 1; } static bool AtMostOne(int children, int matched) { return matched <= 1; } static bool All(int children, int matched) { return children == matched; } static bool DontCare(int children, int matched) { return true; } static bool CareTooMuch(int children, int matched) { return false; } static bool None(int children, int matched) { return matched == 0; } }; }; class ArgumentParser { private: std::string prog; std::string description; std::string epilog; std::string longprefix; std::string shortprefix; std::string longseparator; Group group; public: operator Group&() { return group; } ArgumentParser( const std::string &description, const std::string &longprefix = "--", const std::string &shortprefix = "-", const std::string &longseparator = "=", const std::string &prog = std::string(), const std::string &epilog = std::string() ) : prog(prog), description(description), epilog(epilog), longprefix(longprefix), shortprefix(shortprefix), longseparator(longseparator), group("arguments", Group::Validators::DontCare) {} void ParseArgs(const std::vector<std::string> &args) { // Check all arg chunks for (auto it = std::begin(args); it != std::end(args); ++it) { const std::string &chunk = *it; // If a long arg was found if (chunk.find(longprefix) == 0 && chunk.size() > longprefix.size()) { const std::string argchunk(chunk.substr(longprefix.size())); // Try to separate it, in case of a separator: const auto separator = argchunk.find(longseparator); const std::string arg = (separator != argchunk.npos ? std::string(argchunk, 0, separator) : argchunk); Base *base = group.Match(arg); if (base) { ArgBase *argbase = dynamic_cast<ArgBase *>(base); if (argbase) { if (separator != argchunk.npos) { argbase->ParseArg(arg, argchunk.substr(separator + longseparator.size())); } else { ++it; if (it == std::end(args)) { std::ostringstream problem; problem << "Argument " << arg << " requires an argument but received none"; throw ParseError(problem.str().c_str()); } else { argbase->ParseArg(arg, *it); } } } else if (separator != argchunk.npos) { std::ostringstream problem; problem << "Passed an argument into a non-argument flag: " << chunk; throw ParseError(problem.str().c_str()); } } else { std::ostringstream problem; problem << "Argument could not be matched: " << chunk; throw ParseError(problem.str().c_str()); } } else if (chunk.find(shortprefix) == 0 && chunk.size() > shortprefix.size()) { std::string argchunk(chunk.substr(shortprefix.size())); for (auto argit = std::begin(argchunk); argit != std::end(argchunk); ++argit) { const char arg = *argit; Base *base = group.Match(arg); if (base) { ArgBase *argbase = dynamic_cast<ArgBase *>(base); if (argbase) { argchunk.erase(std::begin(argchunk), ++argit); if (!argchunk.empty()) { argbase->ParseArg(std::string(1, arg), argchunk); } else { ++it; if (it == std::end(args)) { std::ostringstream problem; problem << "Argument " << arg << " requires an argument but received none"; throw ParseError(problem.str().c_str()); } else { argbase->ParseArg(std::string(1, arg), *it); } } // Because this argchunk is done regardless break; } } else { std::ostringstream problem; problem << "Argument could not be matched: " << arg; throw ParseError(problem.str().c_str()); } } } } } void ParseCLI(const int argc, const char * const * const argv) { if (prog.empty()) { prog.assign(argv[0]); } std::vector<std::string> args; for (int i = 1; i < argc; ++i) { args.emplace_back(argv[i]); } ParseArgs(args); } }; // Boolean argument matcher class Flag : public Base { private: const Matcher matcher; public: Flag(Group &group, const std::string &help, const Matcher &matcher): Base(help), matcher(matcher) { group.Add(*this); } Flag(Group &group, const std::string &help, Matcher &&matcher): Base(help), matcher(std::move(matcher)) { group.Add(*this); } virtual ~Flag() {} virtual Base *Match(const std::string &arg) override { if (matcher.Match(arg)) { matched = true; return this; } return nullptr; } virtual Base *Match(const char arg) override { if (matcher.Match(arg)) { matched = true; return this; } return nullptr; } }; // Count matches class Counter : public Base { private: const Matcher matcher; unsigned int count; public: Counter(Group &group, const std::string &help, const Matcher &matcher, const unsigned int startcount = 0): Base(help), matcher(matcher), count(startcount) { group.Add(*this); } Counter(Group &group, const std::string &help, Matcher &&matcher, const unsigned int startcount = 0): Base(help), matcher(std::move(matcher)), count(startcount) { group.Add(*this); } virtual ~Counter() {} virtual Base *Match(const std::string &arg) override { if (matcher.Match(arg)) { matched = true; ++count; return this; } return nullptr; } virtual Base *Match(const char arg) override { if (matcher.Match(arg)) { matched = true; ++count; return this; } return nullptr; } unsigned int Count() { return count; } }; template <typename T> void ArgReader(const std::string &arg, const std::string &value, T &destination) { std::istringstream ss(value); ss >> destination; if (ss.rdbuf()->in_avail() > 0) { std::ostringstream problem; problem << "Argument " << arg << " received invalid value type " << value; throw ParseError(problem.str().c_str()); } } template <> void ArgReader<std::string>(const std::string &arg, const std::string &value, std::string &destination) { destination.assign(value); } template <typename T, void (*Reader)(const std::string &, const std::string &, T&) = ArgReader<T>> class ArgFlag : public ArgBase { private: const Matcher matcher; T value; public: ArgFlag(Group &group, const std::string &help, const Matcher &matcher): ArgBase(help), matcher(matcher) { group.Add(*this); } ArgFlag(Group &group, const std::string &help, Matcher &&matcher): ArgBase(help), matcher(std::move(matcher)) { group.Add(*this); } virtual ~ArgFlag() {} virtual Base *Match(const std::string &arg) override { if (matcher.Match(arg)) { matched = true; return this; } return nullptr; } virtual Base *Match(const char arg) override { if (matcher.Match(arg)) { matched = true; return this; } return nullptr; } virtual void ParseArg(const std::string &arg, const std::string &value) override { Reader(arg, value, this->value); } const T &Value() { return value; } }; template <typename T, typename List = std::vector<T>, void (*Reader)(const std::string &, const std::string &, T&) = ArgReader<T>> class ArgFlagList : public ArgBase { private: const Matcher matcher; List values; public: ArgFlagList(Group &group, const std::string &help, const Matcher &matcher): ArgBase(help), matcher(matcher) { group.Add(*this); } ArgFlagList(Group &group, const std::string &help, Matcher &&matcher): ArgBase(help), matcher(std::move(matcher)) { group.Add(*this); } virtual ~ArgFlagList() {} virtual Base *Match(const std::string &arg) override { if (matcher.Match(arg)) { matched = true; return this; } return nullptr; } virtual Base *Match(const char arg) override { if (matcher.Match(arg)) { matched = true; return this; } return nullptr; } virtual void ParseArg(const std::string &arg, const std::string &value) override { values.emplace_back(); Reader(arg, value, values.back()); } const List &Values() { return values; } }; } <commit_msg>full argument parsing as needed. No help printing yet.<commit_after>/* Copyright © 2016 Taylor C. Richberger <taywee@gmx.com> * This code is released under the license described in the LICENSE file */ #include <algorithm> #include <functional> #include <list> #include <sstream> #include <string> #include <vector> #include <exception> namespace args { class ParseError : public std::runtime_error { public: ParseError(const char *problem) : std::runtime_error(problem) {} virtual ~ParseError() {}; }; // A class of "matchers", specifying short and long options that can possibly be matched class Matcher { private: const std::vector<char> shortOpts; const std::vector<std::string> longOpts; public: // Specify short and long opts separately as iterators template <typename ShortIt, typename LongIt> Matcher(ShortIt shortOptsStart, ShortIt shortOptsEnd, LongIt longOptsStart, LongIt longOptsEnd) : shortOpts(shortOptsStart, shortOptsEnd), longOpts(longOptsStart, longOptsEnd) {} // Specify short and long opts separately as iterables template <typename Short, typename Long> Matcher(Short &&shortIn, Long &&longIn) : shortOpts(std::begin(shortIn), std::end(shortIn)), longOpts(std::begin(longIn), std::end(longIn)) {} Matcher(const std::initializer_list<char> &shortIn, const std::initializer_list<std::string> &longIn) : shortOpts(std::begin(shortIn), std::end(shortIn)), longOpts(std::begin(longIn), std::end(longIn)) {} Matcher(const std::initializer_list<char> &shortIn) : shortOpts(std::begin(shortIn), std::end(shortIn)) {} Matcher(const std::initializer_list<std::string> &longIn) : longOpts(std::begin(longIn), std::end(longIn)) {} Matcher(const Matcher &other) : shortOpts(other.shortOpts), longOpts(other.longOpts) {} Matcher(Matcher &&other) : shortOpts(std::move(other.shortOpts)), longOpts(std::move(other.longOpts)) {} ~Matcher() {} bool Match(const char opt) const { return std::find(std::begin(shortOpts), std::end(shortOpts), opt) != shortOpts.end(); } bool Match(const std::string &opt) const { return std::find(std::begin(longOpts), std::end(longOpts), opt) != longOpts.end(); } }; // Base class for groups and individual argument types class Base { protected: bool matched; const std::string help; public: Base(const std::string &help) : matched(false), help(help) {} virtual ~Base() {} virtual bool Matched() const noexcept { return matched; } operator bool() const noexcept { return Matched(); } }; // Named arguments, not including groups class NamedBase : public Base { protected: const std::string name; public: NamedBase(const std::string &name, const std::string &help) : Base(help), name(name) {} virtual ~NamedBase() {} const std::string &Name(); }; // Base class for flag arguments class FlagBase : public NamedBase { protected: const Matcher matcher; public: FlagBase(const std::string &name, const std::string &help, const Matcher &matcher) : NamedBase(name, help), matcher(matcher) {} FlagBase(const std::string &name, const std::string &help, Matcher &&matcher) : NamedBase(name, help), matcher(std::move(matcher)) {} virtual ~FlagBase() {} virtual FlagBase *Match(const std::string &arg) { if (matcher.Match(arg)) { matched = true; return this; } return nullptr; } virtual FlagBase *Match(const char arg) { if (matcher.Match(arg)) { matched = true; return this; } return nullptr; } }; // Base class that takes arguments class ArgFlagBase : public FlagBase { public: ArgFlagBase(const std::string &name, const std::string &help, const Matcher &matcher) : FlagBase(name, help, matcher) {} ArgFlagBase(const std::string &name, const std::string &help, Matcher &&matcher) : FlagBase(name, help, std::move(matcher)) {} virtual ~ArgFlagBase() {} virtual void ParseArg(const std::string &value) = 0; }; // Base class for positional arguments class PosBase : public NamedBase { protected: bool ready; public: PosBase(const std::string &name, const std::string &help) : NamedBase(name, help), ready(true) {} virtual ~PosBase() {} bool Ready() { return ready; } virtual void ParseArg(const std::string &value) = 0; }; class Group : public Base { private: std::vector<Base*> children; std::function<bool(const Group &)> validator; public: Group(const std::string &help, const std::function<bool(const Group &)> &validator = Validators::DontCare) : Base(help), validator(validator) {} virtual ~Group() {} FlagBase *Match(const std::string &arg) { for (Base *child: children) { FlagBase *flag = dynamic_cast<FlagBase *>(child); Group *group = dynamic_cast<Group *>(child); if (flag) { FlagBase *match = flag->Match(arg); if (match) { return match; } } else if (group) { FlagBase *match = group->Match(arg); if (match) { return match; } } } return nullptr; } FlagBase *Match(const char arg) { for (Base *child: children) { FlagBase *flag = dynamic_cast<FlagBase *>(child); Group *group = dynamic_cast<Group *>(child); if (flag) { FlagBase *match = flag->Match(arg); if (match) { return match; } } else if (group) { FlagBase *match = group->Match(arg); if (match) { return match; } } } return nullptr; } PosBase *GetNextPos() { for (Base *child: children) { PosBase *next = dynamic_cast<PosBase *>(child); Group *group = dynamic_cast<Group *>(child); if (group) { next = group->GetNextPos(); } if (next and next->Ready()) { return next; } } return nullptr; } void Add(Base &child) { children.emplace_back(&child); } const std::vector<Base *> Children() const { return children; } std::vector<Base *>::size_type MatchedChildren() const { std::vector<Base *>::size_type sum = 0; for (const Base * child: children) { if (child->Matched()) { ++sum; } } return sum; } virtual bool Matched() const noexcept override { return validator(*this); } struct Validators { static bool Xor(const Group &group) { return group.MatchedChildren() == 1; } static bool AtLeastOne(const Group &group) { return group.MatchedChildren() >= 1; } static bool AtMostOne(const Group &group) { return group.MatchedChildren() <= 1; } static bool All(const Group &group) { return group.Children().size() == group.MatchedChildren(); } static bool AllOrNone(const Group &group) { return (All(group) || None(group)); } static bool AllChildGroups(const Group &group) { for (const auto child: group.Children()) { const Group *group = dynamic_cast<Group *>(child); if (group && (!group->Matched())) { return false; } } return true; } static bool DontCare(const Group &group) { return true; } static bool CareTooMuch(const Group &group) { return false; } static bool None(const Group &group) { return group.MatchedChildren() == 0; } }; }; // Command line argument parser class ArgumentParser { private: std::string prog; std::string description; std::string epilog; std::string longprefix; std::string shortprefix; std::string longseparator; Group group; public: operator Group&() { return group; } ArgumentParser( const std::string &description, const std::string &longprefix = "--", const std::string &shortprefix = "-", const std::string &longseparator = "=", const std::string &prog = std::string(), const std::string &epilog = std::string() ) : prog(prog), description(description), epilog(epilog), longprefix(longprefix), shortprefix(shortprefix), longseparator(longseparator), group("arguments", Group::Validators::AllChildGroups) {} void Add(Base &child) { group.Add(child); } void ParseArgs(const std::vector<std::string> &args) { // Check all arg chunks for (auto it = std::begin(args); it != std::end(args); ++it) { const std::string &chunk = *it; // If a long arg was found if (chunk.find(longprefix) == 0 && chunk.size() > longprefix.size()) { const std::string argchunk(chunk.substr(longprefix.size())); // Try to separate it, in case of a separator: const auto separator = argchunk.find(longseparator); const std::string arg = (separator != argchunk.npos ? std::string(argchunk, 0, separator) : argchunk); FlagBase *base = group.Match(arg); if (base) { ArgFlagBase *argbase = dynamic_cast<ArgFlagBase *>(base); if (argbase) { if (separator != argchunk.npos) { argbase->ParseArg(argchunk.substr(separator + longseparator.size())); } else { ++it; if (it == std::end(args)) { std::ostringstream problem; problem << "Argument " << arg << " requires an argument but received none"; throw ParseError(problem.str().c_str()); } else { argbase->ParseArg(*it); } } } else if (separator != argchunk.npos) { std::ostringstream problem; problem << "Passed an argument into a non-argument flag: " << chunk; throw ParseError(problem.str().c_str()); } } else { std::ostringstream problem; problem << "Argument could not be matched: " << arg; throw ParseError(problem.str().c_str()); } // Check short args } else if (chunk.find(shortprefix) == 0 && chunk.size() > shortprefix.size()) { std::string argchunk(chunk.substr(shortprefix.size())); for (auto argit = std::begin(argchunk); argit != std::end(argchunk); ++argit) { const char arg = *argit; Base *base = group.Match(arg); if (base) { ArgFlagBase *argbase = dynamic_cast<ArgFlagBase *>(base); if (argbase) { argchunk.erase(std::begin(argchunk), ++argit); if (!argchunk.empty()) { argbase->ParseArg(argchunk); } else { ++it; if (it == std::end(args)) { std::ostringstream problem; problem << "Flag '" << arg << "' requires an argument but received none"; throw ParseError(problem.str().c_str()); } else { argbase->ParseArg(*it); } } // Because this argchunk is done regardless break; } } else { std::ostringstream problem; problem << "Argument could not be matched: '" << arg << "'"; throw ParseError(problem.str().c_str()); } } } else { SetNextPositional(chunk); } } if (!group.Matched()) { std::ostringstream problem; problem << "Group validation failed somewhere!"; throw ParseError(problem.str().c_str()); } } void SetNextPositional(const std::string &arg) { PosBase *pos = group.GetNextPos(); if (pos) { pos->ParseArg(arg); } else { std::ostringstream problem; problem << "Passed in argument, but no positional arguments were ready to receive it" << arg; throw ParseError(problem.str().c_str()); } } void ParseCLI(const int argc, const char * const * const argv) { if (prog.empty()) { prog.assign(argv[0]); } std::vector<std::string> args; for (int i = 1; i < argc; ++i) { args.emplace_back(argv[i]); } ParseArgs(args); } }; // Boolean argument matcher class Flag : public FlagBase { public: Flag(Group &group, const std::string &name, const std::string &help, const Matcher &matcher): FlagBase(name, help, matcher) { group.Add(*this); } Flag(Group &group, const std::string &name, const std::string &help, Matcher &&matcher): FlagBase(name, help, std::move(matcher)) { group.Add(*this); } virtual ~Flag() {} }; // Count matches class Counter : public FlagBase { private: unsigned int count; public: Counter(Group &group, const std::string &name, const std::string &help, const Matcher &matcher, const unsigned int startcount = 0): FlagBase(name, help, matcher), count(startcount) { group.Add(*this); } Counter(Group &group, const std::string &name, const std::string &help, Matcher &&matcher, const unsigned int startcount = 0): FlagBase(name, help, std::move(matcher)), count(startcount) { group.Add(*this); } virtual ~Counter() {} virtual FlagBase *Match(const std::string &arg) override { FlagBase *me = FlagBase::Match(arg); if (me) { ++count; } return me; } virtual FlagBase *Match(const char arg) override { FlagBase *me = FlagBase::Match(arg); if (me) { ++count; } return me; } unsigned int Count() { return count; } }; template <typename T> void ArgReader(const std::string &name, const std::string &value, T &destination) { std::istringstream ss(value); ss >> destination; if (ss.rdbuf()->in_avail() > 0) { std::ostringstream problem; problem << "Argument '" << name << "' received invalid value type '" << value << "'"; throw ParseError(problem.str().c_str()); } } template <> void ArgReader<std::string>(const std::string &name, const std::string &value, std::string &destination) { destination.assign(value); } template <typename T, void (*Reader)(const std::string &, const std::string &, T&) = ArgReader<T>> class ArgFlag : public ArgFlagBase { private: T value; public: ArgFlag(Group &group, const std::string &name, const std::string &help, const Matcher &matcher): ArgFlagBase(name, help, matcher) { group.Add(*this); } ArgFlag(Group &group, const std::string &name, const std::string &help, Matcher &&matcher): ArgFlagBase(name, help, std::move(matcher)) { group.Add(*this); } virtual ~ArgFlag() {} virtual void ParseArg(const std::string &value) override { Reader(name, value, this->value); } const T &Value() { return value; } }; template < typename T, typename List = std::vector<T>, void (*Reader)(const std::string &, const std::string &, T&) = ArgReader<T>> class ArgFlagList : public ArgFlagBase { private: List values; public: ArgFlagList(Group &group, const std::string &name, const std::string &help, const Matcher &matcher): ArgFlagBase(name, help, matcher) { group.Add(*this); } ArgFlagList(Group &group, const std::string &name, const std::string &help, Matcher &&matcher): ArgFlagBase(name, help, std::move(matcher)) { group.Add(*this); } virtual ~ArgFlagList() {} virtual void ParseArg(const std::string &value) override { values.emplace_back(); Reader(name, value, values.back()); } const List &Values() { return values; } }; template <typename T, void (*Reader)(const std::string &, const std::string &, T&) = ArgReader<T>> class PosArg : public PosBase { private: T value; public: PosArg(Group &group, const std::string &name, const std::string &help): PosBase(name, help) { group.Add(*this); } virtual ~PosArg() {} virtual void ParseArg(const std::string &value) override { Reader(name, value, this->value); ready = false; matched = true; } const T &Value() { return value; } }; template < typename T, typename List = std::vector<T>, void (*Reader)(const std::string &, const std::string &, T&) = ArgReader<T>> class PosArgList : public PosBase { private: List values; public: PosArgList(Group &group, const std::string &name, const std::string &help): PosBase(name, help) { group.Add(*this); } virtual ~PosArgList() {} virtual void ParseArg(const std::string &value) override { values.emplace_back(); Reader(name, value, values.back()); matched = true; } const List &Values() { return values; } }; } <|endoftext|>
<commit_before>#ifndef URPC_CLIENT_HPP #define URPC_CLIENT_HPP #include <string> #include <boost/smart_ptr.hpp> #include <google/protobuf/message.h> #include "zmq.hpp" #include "dns/dns.hpp" namespace urpc { class Client { public: /** Create a connection to a service * \param connection ZMQ connection string * \param nIOThread number of ZMQ IO threads */ Client(const std::string &connection); /** Send a request to a service * \param service name of the service requested * \param version service version * \param request protobuf containing parameters of service requested * \param moreToFollow TRUE if is request is not the last part of a * multi-part request. */ void sendRequest (const std::string &service, int version, const google::protobuf::Message &request, bool moreToFollow = false); /** Get reply from a sent request * \param reply protobuf containing the service reply * \return TRUE if additional messages exist after this reply, as in the * case of multi-part replies. */ bool getReply (google::protobuf::Message &reply); private: std::string connection; boost::scoped_ptr<zmq::context_t> context; boost::scoped_ptr<zmq::socket_t> socket; }; } #endif // URPC_CLIENT_HPP <commit_msg>whitespace<commit_after>#ifndef URPC_CLIENT_HPP #define URPC_CLIENT_HPP #include <string> #include <boost/smart_ptr.hpp> #include <google/protobuf/message.h> #include "zmq.hpp" #include "dns/dns.hpp" namespace urpc { class Client { public: /** Create a connection to a service * \param connection ZMQ connection string * \param nIOThread number of ZMQ IO threads */ Client(const std::string &connection); /** Send a request to a service * \param service name of the service requested * \param version service version * \param request protobuf containing parameters of service requested * \param moreToFollow TRUE if is request is not the last part of a * multi-part request. */ void sendRequest (const std::string &service, int version, const google::protobuf::Message &request, bool moreToFollow = false); /** Get reply from a sent request * \param reply protobuf containing the service reply * \return TRUE if additional messages exist after this reply, as in the * case of multi-part replies. */ bool getReply (google::protobuf::Message &reply); private: std::string connection; boost::scoped_ptr<zmq::context_t> context; boost::scoped_ptr<zmq::socket_t> socket; }; } #endif // URPC_CLIENT_HPP <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // This source file is part of Hect. // // Copyright (c) 2016 Colin Hill // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /////////////////////////////////////////////////////////////////////////////// #include "Hect/Graphics/Renderer.h" #include "Hect/Core/Configuration.h" #ifndef HECT_RENDERER_OPENGL #include "Hect/Graphics/FrameBuffer.h" #include "Hect/Graphics/Mesh.h" #include "Hect/Graphics/RenderTarget.h" #include "Hect/Graphics/Shader.h" #include "Hect/Graphics/Texture2.h" #include "Hect/Graphics/Texture3.h" #include "Hect/Runtime/Window.h" using namespace hect; namespace { class ShaderData : public Renderer::Data<Shader> { public: ShaderData(Renderer& renderer, Shader& object) : Renderer::Data<Shader>(renderer, object) { } ~ShaderData() { if (object && object->isUploaded()) { renderer->destroyShader(*object); } } }; class Texture2Data : public Renderer::Data<Texture2> { public: Texture2Data(Renderer& renderer, Texture2& object) : Renderer::Data<Texture2>(renderer, object), pixelData(object.image().pixelData()) { } ~Texture2Data() { if (object && object->isUploaded()) { renderer->destroyTexture(*object); } } ByteVector pixelData; }; class Texture3Data : public Renderer::Data<Texture3> { public: Texture3Data(Renderer& renderer, Texture3& object) : Renderer::Data<Texture3>(renderer, object) { for (unsigned z = 0; z < object.depth(); ++z) { ByteVector& imagePixelData = object.image(z).pixelData(); pixelData.push_back(imagePixelData); } } ~Texture3Data() { if (object && object->isUploaded()) { renderer->destroyTexture(*object); } } std::vector<ByteVector> pixelData; }; class TextureCubeData : public Renderer::Data<TextureCube> { public: TextureCubeData(Renderer& renderer, TextureCube& object) : Renderer::Data<TextureCube>(renderer, object) { } ~TextureCubeData() { if (object && object->isUploaded()) { renderer->destroyTexture(*object); } } }; class FrameBufferData : public Renderer::Data<FrameBuffer> { public: FrameBufferData(Renderer& renderer, FrameBuffer& object) : Renderer::Data<FrameBuffer>(renderer, object) { } ~FrameBufferData() { if (object && object->isUploaded()) { renderer->destroyFrameBuffer(*object); } } }; class MeshData : public Renderer::Data<Mesh> { public: MeshData(Renderer& renderer, Mesh& object) : Renderer::Data<Mesh>(renderer, object) { } ~MeshData() { if (object && object->isUploaded()) { renderer->destroyMesh(*object); } } }; } void Renderer::uploadFrameBuffer(FrameBuffer& frameBuffer) { if (frameBuffer.isUploaded()) { return; } frameBuffer.setAsUploaded(*this, new FrameBufferData(*this, frameBuffer)); } void Renderer::destroyFrameBuffer(FrameBuffer& frameBuffer) { if (!frameBuffer.isUploaded()) { return; } frameBuffer.setAsDestroyed(); } void Renderer::uploadShader(Shader& shader) { if (shader.isUploaded()) { return; } shader.setAsUploaded(*this, new ShaderData(*this, shader)); } void Renderer::destroyShader(Shader& shader) { if (!shader.isUploaded()) { return; } shader.setAsDestroyed(); } void Renderer::uploadTexture(Texture2& texture) { if (texture.isUploaded()) { return; } texture.setAsUploaded(*this, new Texture2Data(*this, texture)); } void Renderer::uploadTexture(Texture3& texture) { if (texture.isUploaded()) { return; } texture.setAsUploaded(*this, new Texture3Data(*this, texture)); } void Renderer::uploadTexture(TextureCube& texture) { if (texture.isUploaded()) { return; } texture.setAsUploaded(*this, new TextureCubeData(*this, texture)); } void Renderer::destroyTexture(Texture2& texture, bool downloadImage) { if (!texture.isUploaded()) { return; } if (downloadImage) { // Force the texture to download its image texture.image(); } texture.setAsDestroyed(); } void Renderer::destroyTexture(Texture3& texture, bool downloadImage) { if (!texture.isUploaded()) { return; } if (downloadImage) { // Force the texture to download its images texture.image(0); } texture.setAsDestroyed(); } void Renderer::destroyTexture(TextureCube& texture, bool downloadImage) { (void)downloadImage; if (!texture.isUploaded()) { return; } texture.setAsDestroyed(); } void Renderer::downloadTextureImage(Texture2& texture) { if (!texture.isUploaded()) { throw InvalidOperation("The texture is not uploaded"); } auto data = texture.dataAs<Texture2Data>(); ByteVector pixelData = data->pixelData; texture.image().setPixelData(std::move(pixelData)); } void Renderer::downloadTextureImages(Texture3& texture) { if (!texture.isUploaded()) { throw InvalidOperation("The texture is not uploaded"); } auto data = texture.dataAs<Texture3Data>(); for (unsigned z = 0; z < texture.depth(); ++z) { ByteVector pixelData = data->pixelData[z]; texture.image(z).setPixelData(std::move(pixelData)); } } void Renderer::uploadMesh(Mesh& mesh) { if (mesh.isUploaded()) { return; } mesh.setAsUploaded(*this, new MeshData(*this, mesh)); } void Renderer::destroyMesh(Mesh& mesh) { if (!mesh.isUploaded()) { return; } mesh.setAsDestroyed(); } void Renderer::initialize() { } void Renderer::shutdown() { } void Renderer::onBeginFrame(RenderTarget& target) { (void)target; } void Renderer::onEndFrame() { } void Renderer::setTarget(RenderTarget& target) { (void)target; } void Renderer::setTarget(Window& window) { (void)window; } void Renderer::setTarget(FrameBuffer& frameBuffer) { if (!frameBuffer.isUploaded()) { uploadFrameBuffer(frameBuffer); } } void Renderer::setCullMode(CullMode cullMode) { (void)cullMode; } void Renderer::setShader(Shader& shader) { if (!shader.isUploaded()) { _renderer.uploadShader(shader); } } void Renderer::setUniform(const Uniform& uniform, int value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, double value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, Vector2 value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, Vector3 value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, Vector4 value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, const Matrix4& value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, Color value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, Texture2& value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, Texture3& value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, TextureCube& value) { (void)uniform; (void)value; } void Renderer::renderMesh(Mesh& mesh) { (void)mesh; } void Renderer::renderViewport() { } void Renderer::clear(Color color, bool depth) { (void)color; (void)depth; } #endif <commit_msg>Fix compilation error in stub Renderer<commit_after>/////////////////////////////////////////////////////////////////////////////// // This source file is part of Hect. // // Copyright (c) 2016 Colin Hill // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /////////////////////////////////////////////////////////////////////////////// #include "Hect/Graphics/Renderer.h" #include "Hect/Core/Configuration.h" #ifndef HECT_RENDERER_OPENGL #include "Hect/Graphics/FrameBuffer.h" #include "Hect/Graphics/Mesh.h" #include "Hect/Graphics/RenderTarget.h" #include "Hect/Graphics/Shader.h" #include "Hect/Graphics/Texture2.h" #include "Hect/Graphics/Texture3.h" #include "Hect/Runtime/Window.h" using namespace hect; namespace { class ShaderData : public Renderer::Data<Shader> { public: ShaderData(Renderer& renderer, Shader& object) : Renderer::Data<Shader>(renderer, object) { } ~ShaderData() { if (object && object->isUploaded()) { renderer->destroyShader(*object); } } }; class Texture2Data : public Renderer::Data<Texture2> { public: Texture2Data(Renderer& renderer, Texture2& object) : Renderer::Data<Texture2>(renderer, object), pixelData(object.image().pixelData()) { } ~Texture2Data() { if (object && object->isUploaded()) { renderer->destroyTexture(*object); } } ByteVector pixelData; }; class Texture3Data : public Renderer::Data<Texture3> { public: Texture3Data(Renderer& renderer, Texture3& object) : Renderer::Data<Texture3>(renderer, object) { for (unsigned z = 0; z < object.depth(); ++z) { ByteVector& imagePixelData = object.image(z).pixelData(); pixelData.push_back(imagePixelData); } } ~Texture3Data() { if (object && object->isUploaded()) { renderer->destroyTexture(*object); } } std::vector<ByteVector> pixelData; }; class TextureCubeData : public Renderer::Data<TextureCube> { public: TextureCubeData(Renderer& renderer, TextureCube& object) : Renderer::Data<TextureCube>(renderer, object) { } ~TextureCubeData() { if (object && object->isUploaded()) { renderer->destroyTexture(*object); } } }; class FrameBufferData : public Renderer::Data<FrameBuffer> { public: FrameBufferData(Renderer& renderer, FrameBuffer& object) : Renderer::Data<FrameBuffer>(renderer, object) { } ~FrameBufferData() { if (object && object->isUploaded()) { renderer->destroyFrameBuffer(*object); } } }; class MeshData : public Renderer::Data<Mesh> { public: MeshData(Renderer& renderer, Mesh& object) : Renderer::Data<Mesh>(renderer, object) { } ~MeshData() { if (object && object->isUploaded()) { renderer->destroyMesh(*object); } } }; } void Renderer::uploadFrameBuffer(FrameBuffer& frameBuffer) { if (frameBuffer.isUploaded()) { return; } frameBuffer.setAsUploaded(*this, new FrameBufferData(*this, frameBuffer)); } void Renderer::destroyFrameBuffer(FrameBuffer& frameBuffer) { if (!frameBuffer.isUploaded()) { return; } frameBuffer.setAsDestroyed(); } void Renderer::uploadShader(Shader& shader) { if (shader.isUploaded()) { return; } shader.setAsUploaded(*this, new ShaderData(*this, shader)); } void Renderer::destroyShader(Shader& shader) { if (!shader.isUploaded()) { return; } shader.setAsDestroyed(); } void Renderer::uploadTexture(Texture2& texture) { if (texture.isUploaded()) { return; } texture.setAsUploaded(*this, new Texture2Data(*this, texture)); } void Renderer::uploadTexture(Texture3& texture) { if (texture.isUploaded()) { return; } texture.setAsUploaded(*this, new Texture3Data(*this, texture)); } void Renderer::uploadTexture(TextureCube& texture) { if (texture.isUploaded()) { return; } texture.setAsUploaded(*this, new TextureCubeData(*this, texture)); } void Renderer::destroyTexture(Texture2& texture, bool downloadImage) { if (!texture.isUploaded()) { return; } if (downloadImage) { // Force the texture to download its image texture.image(); } texture.setAsDestroyed(); } void Renderer::destroyTexture(Texture3& texture, bool downloadImage) { if (!texture.isUploaded()) { return; } if (downloadImage) { // Force the texture to download its images texture.image(0); } texture.setAsDestroyed(); } void Renderer::destroyTexture(TextureCube& texture, bool downloadImage) { (void)downloadImage; if (!texture.isUploaded()) { return; } texture.setAsDestroyed(); } void Renderer::downloadTextureImage(Texture2& texture) { if (!texture.isUploaded()) { throw InvalidOperation("The texture is not uploaded"); } auto data = texture.dataAs<Texture2Data>(); ByteVector pixelData = data->pixelData; texture.image().setPixelData(std::move(pixelData)); } void Renderer::downloadTextureImages(Texture3& texture) { if (!texture.isUploaded()) { throw InvalidOperation("The texture is not uploaded"); } auto data = texture.dataAs<Texture3Data>(); for (unsigned z = 0; z < texture.depth(); ++z) { ByteVector pixelData = data->pixelData[z]; texture.image(z).setPixelData(std::move(pixelData)); } } void Renderer::uploadMesh(Mesh& mesh) { if (mesh.isUploaded()) { return; } mesh.setAsUploaded(*this, new MeshData(*this, mesh)); } void Renderer::destroyMesh(Mesh& mesh) { if (!mesh.isUploaded()) { return; } mesh.setAsDestroyed(); } void Renderer::initialize() { } void Renderer::shutdown() { } void Renderer::onBeginFrame(RenderTarget& target) { (void)target; } void Renderer::onEndFrame() { } void Renderer::setTarget(RenderTarget& target) { (void)target; } void Renderer::setTarget(Window& window) { (void)window; } void Renderer::setTarget(FrameBuffer& frameBuffer) { if (!frameBuffer.isUploaded()) { uploadFrameBuffer(frameBuffer); } } void Renderer::setCullMode(CullMode cullMode) { (void)cullMode; } void Renderer::setShader(Shader& shader) { if (!shader.isUploaded()) { uploadShader(shader); } } void Renderer::setUniform(const Uniform& uniform, int value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, double value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, Vector2 value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, Vector3 value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, Vector4 value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, const Matrix4& value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, Color value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, Texture2& value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, Texture3& value) { (void)uniform; (void)value; } void Renderer::setUniform(const Uniform& uniform, TextureCube& value) { (void)uniform; (void)value; } void Renderer::renderMesh(Mesh& mesh) { (void)mesh; } void Renderer::renderViewport() { } void Renderer::clear(Color color, bool depth) { (void)color; (void)depth; } #endif <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2013-2020 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <fstream> #include <unordered_map> #include <unistd.h> //for getuid #include <sys/types.h> //for getuid #include <sys/stat.h> //For mkdir #ifdef _WIN32 #include <shlobj.h> #else #include <pwd.h> //For getpwuid #endif #include "config.hpp" #include "utils.hpp" #include "assets.hpp" #include "fortune.hpp" using namespace budget; using config_type = std::unordered_map<std::string, std::string>; namespace { bool server_running = false; bool load_configuration(const std::string& path, config_type& configuration){ if (file_exists(path)) { std::ifstream file(path); if (is_server_running()) { std::cout << "INFO: Load configuration from " << path << std::endl; } if (file.is_open() && file.good()) { std::string line; while (file.good() && getline(file, line)) { // Ignore empty lines if (line.empty()) { continue; } // Ignore comments if(line[0] == '#'){ continue; } auto first = line.find('='); if (first == std::string::npos || line.rfind('=') != first) { std::cout << "The configuration file " << path << " is invalid only supports entries in form of key=value" << std::endl; return false; } auto key = line.substr(0, first); auto value = line.substr(first + 1, line.size()); configuration[key] = value; } } else { std::cerr << "ERROR: Unable to open config file " << path << std::endl; } } return true; } void save_configuration(const std::string& path, const config_type& configuration){ std::ofstream file(path); for(auto& [key, value] : configuration){ file << key << "=" << value << std::endl; } } bool verify_folder(){ auto folder_path = budget_folder(); if (is_server_running()) { std::cout << "INFO: Using " << folder_path << " as data directory" << std::endl; } if(!folder_exists(folder_path)){ std::cout << "The folder " << folder_path << " does not exist. Would like to create it [yes/no] ? "; std::string answer; std::cin >> answer; if(answer == "yes" || answer == "y"){ #ifdef _WIN32 if(mkdir(folder_path.c_str()) == 0){ #else if(mkdir(folder_path.c_str(), ACCESSPERMS) == 0){ #endif std::cout << "The folder " << folder_path << " was created. " << std::endl; return true; } else { std::cout << "Impossible to create the folder " << folder_path << std::endl; return false; } } else { return false; } } return true; } } //end of anonymous namespace static config_type configuration; static config_type internal; static config_type internal_bak; bool budget::load_config(){ if(!load_configuration(path_to_home_file(".budgetrc"), configuration)){ return false; } if(!verify_folder()){ return false; } if(!load_configuration(path_to_budget_file("config"), internal)){ return false; } internal_bak = internal; //At the first start, the version is not set if(internal.find("data_version") == internal.end()){ internal["data_version"] = budget::to_string(budget::DATA_VERSION); } return true; } void budget::save_config() { if (internal != internal_bak) { save_configuration(path_to_budget_file("config"), internal); internal_bak = internal; } } std::string budget::home_folder(){ #ifdef _WIN32 TCHAR path[MAX_PATH]; if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, path))) { std::wstring wpath(path); return std::string(wpath.begin(), wpath.end()); } return "c:\\"; #else struct passwd *pw = getpwuid(getuid()); const char* homedir = pw->pw_dir; return std::string(homedir); #endif } std::string budget::path_to_home_file(const std::string& file){ return home_folder() + "/" + file; } std::string budget::budget_folder(){ if(config_contains("directory")){ return config_value("directory"); } return path_to_home_file(".budget"); } std::string budget::path_to_budget_file(const std::string& file){ return budget_folder() + "/" + file; } bool budget::config_contains(const std::string& key){ return configuration.find(key) != configuration.end(); } std::string budget::config_value(const std::string& key){ return configuration[key]; } std::string budget::config_value(const std::string& key, const std::string& def){ if (config_contains(key)) { return config_value(key); } return def; } bool budget::config_contains_and_true(const std::string& key) { if (config_contains(key)) { return config_value(key) == "true"; } return false; } std::string budget::user_config_value(const std::string& key, const std::string& def) { // 1. Check for the global configuration if (config_contains(key)) { return config_value(key); } // 2. Check foir the internal configuration if (internal_config_contains(key)) { return internal_config_value(key); } // 3. Return the default value return def; } bool budget::user_config_value_bool(const std::string& key, bool def) { // 1. Check for the global configuration if (config_contains(key)) { return config_value(key) == "true"; } // 2. Check foir the internal configuration if (internal_config_contains(key)) { return internal_config_value(key) == "true"; } // 3. Return the default value return def; } bool budget::internal_config_contains(const std::string& key){ return internal.find(key) != internal.end(); } std::string& budget::internal_config_value(const std::string& key){ return internal[key]; } void budget::internal_config_remove(const std::string& key){ internal.erase(key); } std::string budget::get_web_user(){ return user_config_value("web_user", "admin"); } std::string budget::get_web_password(){ return user_config_value("web_password", "1234"); } std::string budget::get_server_listen(){ if (config_contains("server_listen")) { return config_value("server_listen"); } return "localhost"; } size_t budget::get_server_port(){ if (config_contains("server_port")) { return to_number<size_t>(config_value("server_port")); } return 8080; } bool budget::is_server_mode(){ // The server cannot run in server mode if (is_server_running()) { return false; } return config_contains_and_true("server_mode"); } bool budget::is_secure(){ if (config_contains("server_secure")) { return config_value("server_secure") != "false"; } return true; } bool budget::is_server_ssl(){ if (config_contains("server_ssl")) { return config_value("server_ssl") == "true"; } return config_contains_and_true("server_ssl"); } bool budget::is_fortune_disabled(){ return user_config_value_bool("disable_fortune", false); } bool budget::is_debts_disabled(){ return user_config_value_bool("disable_debts", false); } bool budget::net_worth_over_fortune(){ // If the fortune module is disabled, use net worth if (is_fortune_disabled()) { return true; } // By default, fortune is the thing being taken into account // Unless it's not used and net worth is used // TODO This can be a very expensive operation! return !no_asset_values() && no_fortunes(); } void budget::set_server_running(){ // Indicates to the system that it's running in server mode server_running = true; } bool budget::is_server_running(){ return server_running; } <commit_msg>Extra logging<commit_after>//======================================================================= // Copyright (c) 2013-2020 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <fstream> #include <unordered_map> #include <unistd.h> //for getuid #include <sys/types.h> //for getuid #include <sys/stat.h> //For mkdir #ifdef _WIN32 #include <shlobj.h> #else #include <pwd.h> //For getpwuid #endif #include "config.hpp" #include "utils.hpp" #include "assets.hpp" #include "fortune.hpp" using namespace budget; using config_type = std::unordered_map<std::string, std::string>; namespace { bool server_running = false; bool load_configuration(const std::string& path, config_type& configuration){ if (file_exists(path)) { std::ifstream file(path); if (is_server_running()) { std::cout << "INFO: Load configuration from " << path << std::endl; } if (file.is_open() && file.good()) { std::string line; while (file.good() && getline(file, line)) { // Ignore empty lines if (line.empty()) { continue; } // Ignore comments if(line[0] == '#'){ continue; } auto first = line.find('='); if (first == std::string::npos || line.rfind('=') != first) { std::cout << "The configuration file " << path << " is invalid only supports entries in form of key=value" << std::endl; return false; } auto key = line.substr(0, first); auto value = line.substr(first + 1, line.size()); configuration[key] = value; } } else { std::cerr << "ERROR: Unable to open config file " << path << std::endl; } } return true; } void save_configuration(const std::string& path, const config_type& configuration){ std::ofstream file(path); for(auto& [key, value] : configuration){ file << key << "=" << value << std::endl; } } bool verify_folder(){ auto folder_path = budget_folder(); if (is_server_running()) { std::cout << "INFO: Using " << folder_path << " as data directory" << std::endl; } if(!folder_exists(folder_path)){ std::cout << "The folder " << folder_path << " does not exist. Would like to create it [yes/no] ? "; std::string answer; std::cin >> answer; if(answer == "yes" || answer == "y"){ #ifdef _WIN32 if(mkdir(folder_path.c_str()) == 0){ #else if(mkdir(folder_path.c_str(), ACCESSPERMS) == 0){ #endif std::cout << "The folder " << folder_path << " was created. " << std::endl; return true; } else { std::cout << "Impossible to create the folder " << folder_path << std::endl; return false; } } else { return false; } } return true; } } //end of anonymous namespace static config_type configuration; static config_type internal; static config_type internal_bak; bool budget::load_config(){ if(!load_configuration(path_to_home_file(".budgetrc"), configuration)){ return false; } if(!verify_folder()){ return false; } if(!load_configuration(path_to_budget_file("config"), internal)){ return false; } internal_bak = internal; //At the first start, the version is not set if(internal.find("data_version") == internal.end()){ internal["data_version"] = budget::to_string(budget::DATA_VERSION); } return true; } void budget::save_config() { if (internal != internal_bak) { save_configuration(path_to_budget_file("config"), internal); internal_bak = internal; if (is_server_running()) { std::cout << "INFO: Save internal configuration" << std::endl; } } } std::string budget::home_folder(){ #ifdef _WIN32 TCHAR path[MAX_PATH]; if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, path))) { std::wstring wpath(path); return std::string(wpath.begin(), wpath.end()); } return "c:\\"; #else struct passwd *pw = getpwuid(getuid()); const char* homedir = pw->pw_dir; return std::string(homedir); #endif } std::string budget::path_to_home_file(const std::string& file){ return home_folder() + "/" + file; } std::string budget::budget_folder(){ if(config_contains("directory")){ return config_value("directory"); } return path_to_home_file(".budget"); } std::string budget::path_to_budget_file(const std::string& file){ return budget_folder() + "/" + file; } bool budget::config_contains(const std::string& key){ return configuration.find(key) != configuration.end(); } std::string budget::config_value(const std::string& key){ return configuration[key]; } std::string budget::config_value(const std::string& key, const std::string& def){ if (config_contains(key)) { return config_value(key); } return def; } bool budget::config_contains_and_true(const std::string& key) { if (config_contains(key)) { return config_value(key) == "true"; } return false; } std::string budget::user_config_value(const std::string& key, const std::string& def) { // 1. Check for the global configuration if (config_contains(key)) { return config_value(key); } // 2. Check foir the internal configuration if (internal_config_contains(key)) { return internal_config_value(key); } // 3. Return the default value return def; } bool budget::user_config_value_bool(const std::string& key, bool def) { // 1. Check for the global configuration if (config_contains(key)) { return config_value(key) == "true"; } // 2. Check foir the internal configuration if (internal_config_contains(key)) { return internal_config_value(key) == "true"; } // 3. Return the default value return def; } bool budget::internal_config_contains(const std::string& key){ return internal.find(key) != internal.end(); } std::string& budget::internal_config_value(const std::string& key){ return internal[key]; } void budget::internal_config_remove(const std::string& key){ internal.erase(key); } std::string budget::get_web_user(){ return user_config_value("web_user", "admin"); } std::string budget::get_web_password(){ return user_config_value("web_password", "1234"); } std::string budget::get_server_listen(){ if (config_contains("server_listen")) { return config_value("server_listen"); } return "localhost"; } size_t budget::get_server_port(){ if (config_contains("server_port")) { return to_number<size_t>(config_value("server_port")); } return 8080; } bool budget::is_server_mode(){ // The server cannot run in server mode if (is_server_running()) { return false; } return config_contains_and_true("server_mode"); } bool budget::is_secure(){ if (config_contains("server_secure")) { return config_value("server_secure") != "false"; } return true; } bool budget::is_server_ssl(){ if (config_contains("server_ssl")) { return config_value("server_ssl") == "true"; } return config_contains_and_true("server_ssl"); } bool budget::is_fortune_disabled(){ return user_config_value_bool("disable_fortune", false); } bool budget::is_debts_disabled(){ return user_config_value_bool("disable_debts", false); } bool budget::net_worth_over_fortune(){ // If the fortune module is disabled, use net worth if (is_fortune_disabled()) { return true; } // By default, fortune is the thing being taken into account // Unless it's not used and net worth is used // TODO This can be a very expensive operation! return !no_asset_values() && no_fortunes(); } void budget::set_server_running(){ // Indicates to the system that it's running in server mode server_running = true; } bool budget::is_server_running(){ return server_running; } <|endoftext|>
<commit_before>/* * Smithsonian Astrophysical Observatory, Cambridge, MA, USA * This code has been modified under the terms listed below and is made * available under the same terms. */ /* * Copyright 1993-2004 George A Howlett. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <string.h> #include "tkbltGraph.h" #include "tkbltGrBind.h" #include "tkbltGrXAxisOp.h" #include "tkbltGrAxis.h" #include "tkbltGrAxisOp.h" using namespace Blt; static Axis* GetAxisFromCmd(ClientData clientData, Tcl_Obj* obj) { Graph* graphPtr = (Graph*)clientData; GraphOptions* ops = (GraphOptions*)graphPtr->ops_; int margin; const char* name = Tcl_GetString(obj); if (!strcmp(name,"xaxis")) margin = (ops->inverted) ? MARGIN_LEFT : MARGIN_BOTTOM; else if (!strcmp(name,"yaxis")) margin = (ops->inverted) ? MARGIN_BOTTOM : MARGIN_LEFT; else if (!strcmp(name,"x2axis")) margin = (ops->inverted) ? MARGIN_RIGHT : MARGIN_TOP; else if (!strcmp(name,"y2axis")) margin = (ops->inverted) ? MARGIN_TOP : MARGIN_RIGHT; else return NULL; ChainLink* link = Chain_FirstLink(ops->margins[margin].axes); return (Axis*)Chain_GetValue(link); } static int CgetOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return AxisCgetOp(axisPtr, interp, objc, objv); } static int ConfigureOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return AxisConfigureOp(axisPtr, interp, objc, objv); } static int ActivateOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return AxisActivateOp(axisPtr, interp, objc, objv); } static int BindOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Graph* graphPtr = (Graph*)clientData; Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return graphPtr->bindTable_->configure(graphPtr->axisTag(axisPtr->name_), objc-3, objv+3); } static int InvTransformOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return AxisInvTransformOp(axisPtr, interp, objc, objv); } static int LimitsOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return AxisLimitsOp(axisPtr, interp, objc, objv); } static int TransformOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return AxisTransformOp(axisPtr, interp, objc, objv); } static int UseOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Graph* graphPtr = (Graph*)clientData; GraphOptions* ops = (GraphOptions*)graphPtr->ops_; int margin; ClassId classId; const char* name = Tcl_GetString(objv[1]); if (!strcmp(name,"xaxis")) { classId = CID_AXIS_X; margin = (ops->inverted) ? MARGIN_LEFT : MARGIN_BOTTOM; } else if (!strcmp(name,"yaxis")) { classId = CID_AXIS_Y; margin = (ops->inverted) ? MARGIN_BOTTOM : MARGIN_LEFT; } else if (!strcmp(name,"x2axis")) { classId = CID_AXIS_X; margin = (ops->inverted) ? MARGIN_RIGHT : MARGIN_TOP; } else if (!strcmp(name,"y2axis")) { classId = CID_AXIS_Y; margin = (ops->inverted) ? MARGIN_TOP : MARGIN_RIGHT; } else return TCL_ERROR; Chain* chain = ops->margins[margin].axes; if (objc == 3) { Tcl_Obj* listObjPtr = Tcl_NewListObj(0, (Tcl_Obj **)NULL); for (ChainLink* link = Chain_FirstLink(chain); link; link = Chain_NextLink(link)) { Axis* axisPtr = (Axis*)Chain_GetValue(link); Tcl_ListObjAppendElement(interp, listObjPtr, Tcl_NewStringObj(axisPtr->name_, -1)); } Tcl_SetObjResult(interp, listObjPtr); return TCL_OK; } int axisObjc; Tcl_Obj **axisObjv; if (Tcl_ListObjGetElements(interp, objv[3], &axisObjc, &axisObjv) != TCL_OK) return TCL_ERROR; for (ChainLink* link = Chain_FirstLink(chain); link; link = Chain_NextLink(link)) { Axis* axisPtr = (Axis*)Chain_GetValue(link); axisPtr->link = NULL; axisPtr->use_ =0; // Clear the axis type if it's not currently used if (axisPtr->refCount_ == 0) axisPtr->setClass(CID_NONE); } chain->reset(); for (int ii=0; ii<axisObjc; ii++) { Axis* axisPtr; if (graphPtr->getAxis(axisObjv[ii], &axisPtr) != TCL_OK) return TCL_ERROR; if (axisPtr->classId_ == CID_NONE) axisPtr->setClass(classId); else if (axisPtr->classId_ != classId) { Tcl_AppendResult(interp, "wrong type axis \"", axisPtr->name_, "\": can't use ", axisPtr->className_, " type axis.", NULL); return TCL_ERROR; } if (axisPtr->link) { // Move the axis from the old margin's "use" list to the new axisPtr->chain->unlinkLink(axisPtr->link); chain->linkAfter(axisPtr->link, NULL); } else axisPtr->link = chain->append(axisPtr); axisPtr->chain = chain; axisPtr->use_ =1; } graphPtr->flags |= RESET; graphPtr->eventuallyRedraw(); return TCL_OK; } static int ViewOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return AxisViewOp(axisPtr, interp, objc, objv); } const Ensemble Blt::xaxisEnsemble[] = { {"activate", ActivateOp, 0}, {"bind", BindOp, 0}, {"cget", CgetOp, 0}, {"configure", ConfigureOp, 0}, {"deactivate", ActivateOp, 0}, {"invtransform", InvTransformOp, 0}, {"limits", LimitsOp, 0}, {"transform", TransformOp, 0}, {"use", UseOp, 0}, {"view", ViewOp, 0}, { 0,0,0 } }; <commit_msg>Update axis' margin when using it<commit_after>/* * Smithsonian Astrophysical Observatory, Cambridge, MA, USA * This code has been modified under the terms listed below and is made * available under the same terms. */ /* * Copyright 1993-2004 George A Howlett. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <string.h> #include "tkbltGraph.h" #include "tkbltGrBind.h" #include "tkbltGrXAxisOp.h" #include "tkbltGrAxis.h" #include "tkbltGrAxisOp.h" using namespace Blt; static Axis* GetAxisFromCmd(ClientData clientData, Tcl_Obj* obj) { Graph* graphPtr = (Graph*)clientData; GraphOptions* ops = (GraphOptions*)graphPtr->ops_; int margin; const char* name = Tcl_GetString(obj); if (!strcmp(name,"xaxis")) margin = (ops->inverted) ? MARGIN_LEFT : MARGIN_BOTTOM; else if (!strcmp(name,"yaxis")) margin = (ops->inverted) ? MARGIN_BOTTOM : MARGIN_LEFT; else if (!strcmp(name,"x2axis")) margin = (ops->inverted) ? MARGIN_RIGHT : MARGIN_TOP; else if (!strcmp(name,"y2axis")) margin = (ops->inverted) ? MARGIN_TOP : MARGIN_RIGHT; else return NULL; ChainLink* link = Chain_FirstLink(ops->margins[margin].axes); return (Axis*)Chain_GetValue(link); } static int CgetOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return AxisCgetOp(axisPtr, interp, objc, objv); } static int ConfigureOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return AxisConfigureOp(axisPtr, interp, objc, objv); } static int ActivateOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return AxisActivateOp(axisPtr, interp, objc, objv); } static int BindOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Graph* graphPtr = (Graph*)clientData; Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return graphPtr->bindTable_->configure(graphPtr->axisTag(axisPtr->name_), objc-3, objv+3); } static int InvTransformOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return AxisInvTransformOp(axisPtr, interp, objc, objv); } static int LimitsOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return AxisLimitsOp(axisPtr, interp, objc, objv); } static int TransformOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return AxisTransformOp(axisPtr, interp, objc, objv); } static int UseOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Graph* graphPtr = (Graph*)clientData; GraphOptions* ops = (GraphOptions*)graphPtr->ops_; int margin; ClassId classId; const char* name = Tcl_GetString(objv[1]); if (!strcmp(name,"xaxis")) { classId = CID_AXIS_X; margin = (ops->inverted) ? MARGIN_LEFT : MARGIN_BOTTOM; } else if (!strcmp(name,"yaxis")) { classId = CID_AXIS_Y; margin = (ops->inverted) ? MARGIN_BOTTOM : MARGIN_LEFT; } else if (!strcmp(name,"x2axis")) { classId = CID_AXIS_X; margin = (ops->inverted) ? MARGIN_RIGHT : MARGIN_TOP; } else if (!strcmp(name,"y2axis")) { classId = CID_AXIS_Y; margin = (ops->inverted) ? MARGIN_TOP : MARGIN_RIGHT; } else return TCL_ERROR; Chain* chain = ops->margins[margin].axes; if (objc == 3) { Tcl_Obj* listObjPtr = Tcl_NewListObj(0, (Tcl_Obj **)NULL); for (ChainLink* link = Chain_FirstLink(chain); link; link = Chain_NextLink(link)) { Axis* axisPtr = (Axis*)Chain_GetValue(link); Tcl_ListObjAppendElement(interp, listObjPtr, Tcl_NewStringObj(axisPtr->name_, -1)); } Tcl_SetObjResult(interp, listObjPtr); return TCL_OK; } int axisObjc; Tcl_Obj **axisObjv; if (Tcl_ListObjGetElements(interp, objv[3], &axisObjc, &axisObjv) != TCL_OK) return TCL_ERROR; for (ChainLink* link = Chain_FirstLink(chain); link; link = Chain_NextLink(link)) { Axis* axisPtr = (Axis*)Chain_GetValue(link); axisPtr->link = NULL; axisPtr->use_ =0; axisPtr->margin_ = MARGIN_NONE; // Clear the axis type if it's not currently used if (axisPtr->refCount_ == 0) axisPtr->setClass(CID_NONE); } chain->reset(); for (int ii=0; ii<axisObjc; ii++) { Axis* axisPtr; if (graphPtr->getAxis(axisObjv[ii], &axisPtr) != TCL_OK) return TCL_ERROR; if (axisPtr->classId_ == CID_NONE) axisPtr->setClass(classId); else if (axisPtr->classId_ != classId) { Tcl_AppendResult(interp, "wrong type axis \"", axisPtr->name_, "\": can't use ", axisPtr->className_, " type axis.", NULL); return TCL_ERROR; } if (axisPtr->link) { // Move the axis from the old margin's "use" list to the new axisPtr->chain->unlinkLink(axisPtr->link); chain->linkAfter(axisPtr->link, NULL); } else axisPtr->link = chain->append(axisPtr); axisPtr->chain = chain; axisPtr->use_ =1; axisPtr->margin_ = margin; } graphPtr->flags |= RESET; graphPtr->eventuallyRedraw(); return TCL_OK; } static int ViewOp(ClientData clientData, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { Axis* axisPtr = GetAxisFromCmd(clientData, objv[1]); return AxisViewOp(axisPtr, interp, objc, objv); } const Ensemble Blt::xaxisEnsemble[] = { {"activate", ActivateOp, 0}, {"bind", BindOp, 0}, {"cget", CgetOp, 0}, {"configure", ConfigureOp, 0}, {"deactivate", ActivateOp, 0}, {"invtransform", InvTransformOp, 0}, {"limits", LimitsOp, 0}, {"transform", TransformOp, 0}, {"use", UseOp, 0}, {"view", ViewOp, 0}, { 0,0,0 } }; <|endoftext|>
<commit_before>/* Copyright (C) 2000-2007 MySQL AB 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ /* based on Wei Dai's misc.cpp from CryptoPP */ #include "runtime.hpp" #include "misc.hpp" #ifdef __GNUC__ #include <signal.h> #include <setjmp.h> #endif #ifdef USE_SYS_STL #include <algorithm> #else #include "algorithm.hpp" #endif namespace STL = STL_NAMESPACE; #ifdef YASSL_PURE_C void* operator new(size_t sz, TaoCrypt::new_t) { void* ptr = malloc(sz ? sz : 1); if (!ptr) abort(); return ptr; } void operator delete(void* ptr, TaoCrypt::new_t) { if (ptr) free(ptr); } void* operator new[](size_t sz, TaoCrypt::new_t nt) { return ::operator new(sz, nt); } void operator delete[](void* ptr, TaoCrypt::new_t nt) { ::operator delete(ptr, nt); } /* uncomment to test // make sure not using globals anywhere by forgetting to use overloaded void* operator new(size_t sz); void operator delete(void* ptr); void* operator new[](size_t sz); void operator delete[](void* ptr); */ namespace TaoCrypt { new_t tc; // for library new } #if defined(__ICC) || defined(__INTEL_COMPILER) extern "C" { int __cxa_pure_virtual() { assert("Pure virtual method called." == "Aborted"); return 0; } } // extern "C" #endif #endif // YASSL_PURE_C namespace TaoCrypt { inline void XorWords(word* r, const word* a, unsigned int n) { for (unsigned int i=0; i<n; i++) r[i] ^= a[i]; } void xorbuf(byte* buf, const byte* mask, unsigned int count) { if (((size_t)buf | (size_t)mask | count) % WORD_SIZE == 0) XorWords((word *)buf, (const word *)mask, count/WORD_SIZE); else { for (unsigned int i=0; i<count; i++) buf[i] ^= mask[i]; } } unsigned int BytePrecision(word value) { unsigned int i; for (i=sizeof(value); i; --i) if (value >> (i-1)*8) break; return i; } unsigned int BitPrecision(word value) { if (!value) return 0; unsigned int l = 0, h = 8 * sizeof(value); while (h-l > 1) { unsigned int t = (l+h)/2; if (value >> t) l = t; else h = t; } return h; } word Crop(word value, unsigned int size) { if (size < 8*sizeof(value)) return (value & ((1L << size) - 1)); else return value; } #ifdef TAOCRYPT_X86ASM_AVAILABLE #ifndef _MSC_VER static jmp_buf s_env; static void SigIllHandler(int) { longjmp(s_env, 1); } #endif bool HaveCpuId() { #ifdef _MSC_VER __try { __asm { mov eax, 0 cpuid } } __except (1) { return false; } return true; #else typedef void (*SigHandler)(int); SigHandler oldHandler = signal(SIGILL, SigIllHandler); if (oldHandler == SIG_ERR) return false; bool result = true; if (setjmp(s_env)) result = false; else __asm__ __volatile ( // save ebx in case -fPIC is being used "push %%ebx; mov $0, %%eax; cpuid; pop %%ebx" : : : "%eax", "%ecx", "%edx" ); signal(SIGILL, oldHandler); return result; #endif } void CpuId(word32 input, word32 *output) { #ifdef __GNUC__ __asm__ ( // save ebx in case -fPIC is being used "push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx" : "=a" (output[0]), "=D" (output[1]), "=c" (output[2]), "=d"(output[3]) : "a" (input) ); #else __asm { mov eax, input cpuid mov edi, output mov [edi], eax mov [edi+4], ebx mov [edi+8], ecx mov [edi+12], edx } #endif } bool IsPentium() { if (!HaveCpuId()) return false; word32 cpuid[4]; CpuId(0, cpuid); STL::swap(cpuid[2], cpuid[3]); if (memcmp(cpuid+1, "GenuineIntel", 12) != 0) return false; CpuId(1, cpuid); byte family = ((cpuid[0] >> 8) & 0xf); if (family < 5) return false; return true; } static bool IsMmx() { if (!IsPentium()) return false; word32 cpuid[4]; CpuId(1, cpuid); if ((cpuid[3] & (1 << 23)) == 0) return false; return true; } bool isMMX = IsMmx(); #endif // TAOCRYPT_X86ASM_AVAILABLE } // namespace <commit_msg>Bug#21765 Illegal Instruction crash on pre-pentium when using YASSL - Import patch with different method of detecting if machine has cpuid instruction<commit_after>/* Copyright (C) 2000-2007 MySQL AB 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ /* based on Wei Dai's misc.cpp from CryptoPP */ #include "runtime.hpp" #include "misc.hpp" #ifdef __GNUC__ #include <signal.h> #include <setjmp.h> #endif #ifdef USE_SYS_STL #include <algorithm> #else #include "algorithm.hpp" #endif namespace STL = STL_NAMESPACE; #ifdef YASSL_PURE_C void* operator new(size_t sz, TaoCrypt::new_t) { void* ptr = malloc(sz ? sz : 1); if (!ptr) abort(); return ptr; } void operator delete(void* ptr, TaoCrypt::new_t) { if (ptr) free(ptr); } void* operator new[](size_t sz, TaoCrypt::new_t nt) { return ::operator new(sz, nt); } void operator delete[](void* ptr, TaoCrypt::new_t nt) { ::operator delete(ptr, nt); } /* uncomment to test // make sure not using globals anywhere by forgetting to use overloaded void* operator new(size_t sz); void operator delete(void* ptr); void* operator new[](size_t sz); void operator delete[](void* ptr); */ namespace TaoCrypt { new_t tc; // for library new } #if defined(__ICC) || defined(__INTEL_COMPILER) extern "C" { int __cxa_pure_virtual() { assert("Pure virtual method called." == "Aborted"); return 0; } } // extern "C" #endif #endif // YASSL_PURE_C namespace TaoCrypt { inline void XorWords(word* r, const word* a, unsigned int n) { for (unsigned int i=0; i<n; i++) r[i] ^= a[i]; } void xorbuf(byte* buf, const byte* mask, unsigned int count) { if (((size_t)buf | (size_t)mask | count) % WORD_SIZE == 0) XorWords((word *)buf, (const word *)mask, count/WORD_SIZE); else { for (unsigned int i=0; i<count; i++) buf[i] ^= mask[i]; } } unsigned int BytePrecision(word value) { unsigned int i; for (i=sizeof(value); i; --i) if (value >> (i-1)*8) break; return i; } unsigned int BitPrecision(word value) { if (!value) return 0; unsigned int l = 0, h = 8 * sizeof(value); while (h-l > 1) { unsigned int t = (l+h)/2; if (value >> t) l = t; else h = t; } return h; } word Crop(word value, unsigned int size) { if (size < 8*sizeof(value)) return (value & ((1L << size) - 1)); else return value; } #ifdef TAOCRYPT_X86ASM_AVAILABLE #ifndef _MSC_VER static jmp_buf s_env; static void SigIllHandler(int) { longjmp(s_env, 1); } #endif bool HaveCpuId() { #ifdef _MSC_VER __try { __asm { mov eax, 0 cpuid } } __except (1) { return false; } return true; #else word32 eax, ebx; __asm__ __volatile ( /* Put EFLAGS in eax and ebx */ "pushf;" "pushf;" "pop %0;" "movl %0,%1;" /* Flip the cpuid bit and store back in EFLAGS */ "xorl $0x200000,%0;" "push %0;" "popf;" /* Read EFLAGS again */ "pushf;" "pop %0;" "popf" : "=r" (eax), "=r" (ebx) : : "cc" ); if (eax == ebx) return false; return true; #endif } void CpuId(word32 input, word32 *output) { #ifdef __GNUC__ __asm__ ( // save ebx in case -fPIC is being used "push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx" : "=a" (output[0]), "=D" (output[1]), "=c" (output[2]), "=d"(output[3]) : "a" (input) ); #else __asm { mov eax, input cpuid mov edi, output mov [edi], eax mov [edi+4], ebx mov [edi+8], ecx mov [edi+12], edx } #endif } bool IsPentium() { if (!HaveCpuId()) return false; word32 cpuid[4]; CpuId(0, cpuid); STL::swap(cpuid[2], cpuid[3]); if (memcmp(cpuid+1, "GenuineIntel", 12) != 0) return false; CpuId(1, cpuid); byte family = ((cpuid[0] >> 8) & 0xf); if (family < 5) return false; return true; } static bool IsMmx() { if (!IsPentium()) return false; word32 cpuid[4]; CpuId(1, cpuid); if ((cpuid[3] & (1 << 23)) == 0) return false; return true; } bool isMMX = IsMmx(); #endif // TAOCRYPT_X86ASM_AVAILABLE } // namespace <|endoftext|>
<commit_before>/* * Copyright 2021 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 * * 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 "fcp/client/engine/tflite_utils.h" #include "fcp/base/monitoring.h" #include "tensorflow/lite/string_util.h" namespace fcp { namespace client { namespace engine { namespace { // Returns whether the TfLiteTensor is a resource or variant tensor. bool IsResourceOrVariant(const TfLiteTensor* tensor) { return tensor->type == kTfLiteResource || tensor->type == kTfLiteVariant; } // Returns the TF C API Data type that corresponds to the given TfLiteType. tensorflow::DataType GetTensorFlowDataType(TfLiteType type) { switch (type) { case kTfLiteNoType: return tensorflow::DataType::DT_FLOAT; case kTfLiteFloat32: return tensorflow::DataType::DT_FLOAT; case kTfLiteFloat16: return tensorflow::DataType::DT_HALF; case kTfLiteFloat64: return tensorflow::DataType::DT_DOUBLE; case kTfLiteInt16: return tensorflow::DataType::DT_INT16; case kTfLiteInt32: return tensorflow::DataType::DT_INT32; case kTfLiteUInt32: return tensorflow::DataType::DT_UINT32; case kTfLiteUInt8: return tensorflow::DataType::DT_UINT8; case kTfLiteInt8: return tensorflow::DataType::DT_INT8; case kTfLiteInt64: return tensorflow::DataType::DT_INT64; case kTfLiteUInt64: return tensorflow::DataType::DT_UINT64; case kTfLiteComplex64: return tensorflow::DataType::DT_COMPLEX64; case kTfLiteComplex128: return tensorflow::DataType::DT_COMPLEX128; case kTfLiteString: return tensorflow::DataType::DT_STRING; case kTfLiteBool: return tensorflow::DataType::DT_BOOL; case kTfLiteResource: return tensorflow::DataType::DT_RESOURCE; case kTfLiteVariant: return tensorflow::DataType::DT_VARIANT; } } } // anonymous namespace absl::StatusOr<tensorflow::Tensor> CreateTfTensorFromTfLiteTensor( const TfLiteTensor* tflite_tensor) { // If the tflite tensor is a resource or variant tensor, then we can assume // that it's underlying data is a pointer to a TF tensor and just return a // copy of that Tensor (which will share the underlying data with the original // tensor, and increase its refcount). if (IsResourceOrVariant(tflite_tensor)) { return absl::InvalidArgumentError( "Resource and Variant tensors are not supported as output tensor."); } // If the tflite tensor does not point to an already existing Tensorflow // tensor though, we have to make a copy of it because TfLite tensor and TF // tensor might have different memory alignment, and there is no guarantee // that the TfLite tensor will outlive the TF tensor. tensorflow::TensorShape shape; int num_dims = tflite_tensor->dims->size; for (int i = 0; i < num_dims; ++i) { shape.AddDim(tflite_tensor->dims->data[i]); } tensorflow::Tensor tf_tensor(GetTensorFlowDataType(tflite_tensor->type), shape); if (tf_tensor.dtype() == tensorflow::DataType::DT_STRING) { if (tf_tensor.data()) { tensorflow::tstring* p = static_cast<tensorflow::tstring*>(tf_tensor.data()); for (int i = 0; i < tflite::GetStringCount(tflite_tensor); ++p, ++i) { auto ref = tflite::GetString(tflite_tensor, i); p->assign(ref.str, ref.len); } } } else { FCP_CHECK(tf_tensor.tensor_data().size() == tflite_tensor->bytes); if (tflite_tensor->data.raw) { std::memcpy(tf_tensor.data(), tflite_tensor->data.raw, tflite_tensor->bytes); } } return tf_tensor; } } // namespace engine } // namespace client } // namespace fcp <commit_msg>Support uint16 in TFLite<commit_after>/* * Copyright 2021 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 * * 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 "fcp/client/engine/tflite_utils.h" #include "fcp/base/monitoring.h" #include "tensorflow/lite/string_util.h" namespace fcp { namespace client { namespace engine { namespace { // Returns whether the TfLiteTensor is a resource or variant tensor. bool IsResourceOrVariant(const TfLiteTensor* tensor) { return tensor->type == kTfLiteResource || tensor->type == kTfLiteVariant; } // Returns the TF C API Data type that corresponds to the given TfLiteType. tensorflow::DataType GetTensorFlowDataType(TfLiteType type) { switch (type) { case kTfLiteNoType: return tensorflow::DataType::DT_FLOAT; case kTfLiteFloat32: return tensorflow::DataType::DT_FLOAT; case kTfLiteFloat16: return tensorflow::DataType::DT_HALF; case kTfLiteFloat64: return tensorflow::DataType::DT_DOUBLE; case kTfLiteInt16: return tensorflow::DataType::DT_INT16; case kTfLiteInt32: return tensorflow::DataType::DT_INT32; case kTfLiteUInt32: return tensorflow::DataType::DT_UINT32; case kTfLiteUInt8: return tensorflow::DataType::DT_UINT8; case kTfLiteInt8: return tensorflow::DataType::DT_INT8; case kTfLiteInt64: return tensorflow::DataType::DT_INT64; case kTfLiteUInt64: return tensorflow::DataType::DT_UINT64; case kTfLiteComplex64: return tensorflow::DataType::DT_COMPLEX64; case kTfLiteComplex128: return tensorflow::DataType::DT_COMPLEX128; case kTfLiteString: return tensorflow::DataType::DT_STRING; case kTfLiteBool: return tensorflow::DataType::DT_BOOL; case kTfLiteResource: return tensorflow::DataType::DT_RESOURCE; case kTfLiteVariant: return tensorflow::DataType::DT_VARIANT; default: return tensorflow::DataType::DT_INVALID; } } } // anonymous namespace absl::StatusOr<tensorflow::Tensor> CreateTfTensorFromTfLiteTensor( const TfLiteTensor* tflite_tensor) { // If the tflite tensor is a resource or variant tensor, then we can assume // that it's underlying data is a pointer to a TF tensor and just return a // copy of that Tensor (which will share the underlying data with the original // tensor, and increase its refcount). if (IsResourceOrVariant(tflite_tensor)) { return absl::InvalidArgumentError( "Resource and Variant tensors are not supported as output tensor."); } // If the tflite tensor does not point to an already existing Tensorflow // tensor though, we have to make a copy of it because TfLite tensor and TF // tensor might have different memory alignment, and there is no guarantee // that the TfLite tensor will outlive the TF tensor. tensorflow::TensorShape shape; int num_dims = tflite_tensor->dims->size; for (int i = 0; i < num_dims; ++i) { shape.AddDim(tflite_tensor->dims->data[i]); } tensorflow::Tensor tf_tensor(GetTensorFlowDataType(tflite_tensor->type), shape); if (tf_tensor.dtype() == tensorflow::DataType::DT_STRING) { if (tf_tensor.data()) { tensorflow::tstring* p = static_cast<tensorflow::tstring*>(tf_tensor.data()); for (int i = 0; i < tflite::GetStringCount(tflite_tensor); ++p, ++i) { auto ref = tflite::GetString(tflite_tensor, i); p->assign(ref.str, ref.len); } } } else { FCP_CHECK(tf_tensor.tensor_data().size() == tflite_tensor->bytes); if (tflite_tensor->data.raw) { std::memcpy(tf_tensor.data(), tflite_tensor->data.raw, tflite_tensor->bytes); } } return tf_tensor; } } // namespace engine } // namespace client } // namespace fcp <|endoftext|>
<commit_before>/* Boar - Boar is a collection of tools to process text files. * Copyright (C) 2017 Katsuya Iida. All rights reserved. */ #include "stdafx.h" #include "boar.h" #include "count.h" namespace boar { namespace fs = boost::filesystem; static int CountUsage() { std::wcout << "Usage: boar count [OPTION]... INPUTFILE..." << std::endl; std::wcout << "Estimate number of lines in the file by reading only the first 100MB." << std::endl; std::wcout << std::endl; std::wcout << " -c full count mode" << std::endl; std::wcout << " -h show this help message" << std::endl; std::wcout << " INPUTFILE input file" << std::endl; std::wcout << std::endl; return 1; } int CountCommand(int argc, wchar_t *argv[]) { int optind = 1; bool fullCountMode = false; std::vector<fs::path> inputFileNameList; if (argc <= 1) { return CountUsage(); } while (optind < argc) { const wchar_t *p = argv[optind++]; if (*p == '-') { ++p; while (*p != '\0') { switch (*p) { case 'c': fullCountMode = true; break; case 'h': return CountUsage(); default: std::wcerr << "Unknown option `" << *p << "'." << std::endl; return 1; } ++p; } } else { // Input files start. optind--; break; } } while (optind < argc) { const wchar_t *p = argv[optind++]; inputFileNameList.push_back(p); } if (inputFileNameList.size() == 0) { std::cerr << "No input files." << std::endl; return 1; } if (!CheckInputFiles(inputFileNameList)) { return 1; } int status; for (auto &fileName : inputFileNameList) { if (fullCountMode) { boost::timer::cpu_timer timer; // 1059203072 404601 // 36,762,348,544 bytes. // AMD E2-7110 uintmax_t lineCount = FileCountLines<char>(fileName); std::cerr << timer.format() << std::endl; std::wcout << fileName.native() << "\tLineCount\t" << lineCount << std::endl; } else { GuessLineInfo info = FileStatLines<char>(fileName); std::wcout << fileName.native() << "\tMinLineSize\t" << info.minLineSize << std::endl; std::wcout << fileName.native() << "\tMaxLineSize\t" << info.maxLineSize << std::endl; std::wcout << fileName.native() << "\tAvgLineSize\t" << std::fixed << std::setprecision(2) << info.avgLineSize << std::endl; std::wcout << fileName.native() << "\tStdLineSize\t" << info.stdLineSize << std::endl; std::wcout << fileName.native() << "\tUsedLineCount\t" << info.lineCount << std::endl; uintmax_t size = fs::file_size(fileName); std::wcout << fileName.native() << "\tFileSize\t" << size << std::endl; if (info.isAccurate) { std::wcout << fileName.native() << "\tEstLineCount\t" << info.lineCount << std::endl; } else { double estLineCount = info.stdLineSize == 0 ? 1.0 : info.avgLineSize; // We assume the char size is 1. std::wcout << fileName.native() << "\tEstLineCount\t" << estLineCount << std::endl; } status = 0; } } return status; } } <commit_msg>Fix line count bug.<commit_after>/* Boar - Boar is a collection of tools to process text files. * Copyright (C) 2017 Katsuya Iida. All rights reserved. */ #include "stdafx.h" #include "boar.h" #include "count.h" namespace boar { namespace fs = boost::filesystem; static int CountUsage() { std::wcout << "Usage: boar count [OPTION]... INPUTFILE..." << std::endl; std::wcout << "Estimate number of lines in the file by reading only the first 100MB." << std::endl; std::wcout << std::endl; std::wcout << " -c full count mode" << std::endl; std::wcout << " -h show this help message" << std::endl; std::wcout << " INPUTFILE input file" << std::endl; std::wcout << std::endl; return 1; } int CountCommand(int argc, wchar_t *argv[]) { int optind = 1; bool fullCountMode = false; std::vector<fs::path> inputFileNameList; if (argc <= 1) { return CountUsage(); } while (optind < argc) { const wchar_t *p = argv[optind++]; if (*p == '-') { ++p; while (*p != '\0') { switch (*p) { case 'c': fullCountMode = true; break; case 'h': return CountUsage(); default: std::wcerr << "Unknown option `" << *p << "'." << std::endl; return 1; } ++p; } } else { // Input files start. optind--; break; } } while (optind < argc) { const wchar_t *p = argv[optind++]; inputFileNameList.push_back(p); } if (inputFileNameList.size() == 0) { std::cerr << "No input files." << std::endl; return 1; } if (!CheckInputFiles(inputFileNameList)) { return 1; } int status; for (auto &fileName : inputFileNameList) { if (fullCountMode) { boost::timer::cpu_timer timer; // 1059203072 404601 // 36,762,348,544 bytes. // AMD E2-7110 uintmax_t lineCount = FileCountLines<char>(fileName); std::cerr << timer.format() << std::endl; std::wcout << fileName.native() << "\tLineCount\t" << lineCount << std::endl; } else { GuessLineInfo info = FileStatLines<char>(fileName); std::wcout << fileName.native() << "\tMinLineSize\t" << info.minLineSize << std::endl; std::wcout << fileName.native() << "\tMaxLineSize\t" << info.maxLineSize << std::endl; std::wcout << fileName.native() << "\tAvgLineSize\t" << std::fixed << std::setprecision(2) << info.avgLineSize << std::endl; std::wcout << fileName.native() << "\tStdLineSize\t" << info.stdLineSize << std::endl; std::wcout << fileName.native() << "\tUsedLineCount\t" << info.lineCount << std::endl; uintmax_t size = fs::file_size(fileName); std::wcout << fileName.native() << "\tFileSize\t" << size << std::endl; if (info.isAccurate) { std::wcout << fileName.native() << "\tEstLineCount\t" << info.lineCount << std::endl; } else { double estLineCount = info.avgLineSize == 0 ? 1.0 : (size / info.avgLineSize); // We assume the char size is 1. std::wcout << fileName.native() << "\tEstLineCount\t" << estLineCount << std::endl; } status = 0; } } return status; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: sdxmlwrp.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: cl $ $Date: 2000-11-08 12:41:52 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _SFXDOCFILE_HXX #include <sfx2/docfile.hxx> #endif #ifndef _SDXMLWRP_HXX #include "sdxmlwrp.hxx" #endif #ifndef _SDXMLIMP_HXX #include <xmloff/sdxmlimp.hxx> #endif #ifndef _SDXMLEXP_HXX #include <xmloff/sdxmlexp.hxx> #endif #ifndef _DRAWDOC_HXX #include "drawdoc.hxx" #endif #ifndef _UNO_MAPPING_HXX_ #include <uno/mapping.hxx> //! only necessary until SfxMedium has a uno3 DataSource / DataSink #endif #include <com/sun/star/xml/sax/XErrorHandler.hpp> #include <com/sun/star/xml/sax/XEntityResolver.hpp> #include <com/sun/star/xml/sax/InputSource.hpp> #include <com/sun/star/xml/sax/XDTDHandler.hpp> #include <com/sun/star/xml/sax/XParser.hpp> #include <com/sun/star/io/XActiveDataSource.hpp> #include <com/sun/star/io/XActiveDataControl.hpp> #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _UNOTOOLS_PROCESSFACTORY_HXX_ #include <unotools/processfactory.hxx> #endif #include "pkgurl.hxx" using namespace com::sun::star; using namespace rtl; ////////////////////////////////////////////////////////////////////////////// char __READONLY_DATA sXML_drawing[] = "drawing"; char __READONLY_DATA sXML_impress[] = "presentation"; ////////////////////////////////////////////////////////////////////////////// SdXMLWrapper::SdXMLWrapper( uno::Reference<frame::XModel>& xRef, SfxMedium& rMedium, BOOL bIsDraw, BOOL bShowProg) : mxLocalModel(xRef), mrMedium(rMedium), mbIsDraw(bIsDraw), mbShowProgress(bShowProg) { } BOOL SdXMLWrapper::Import() { if(!mxLocalModel.is()) { DBG_ERROR("Got NO Model in XMLImport"); return FALSE; } uno::Reference<lang::XServiceInfo> xServiceInfo(mxLocalModel, uno::UNO_QUERY); if(!xServiceInfo.is() || !xServiceInfo->supportsService(OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DrawingDocument")))) { DBG_ERROR("Model is no DrawingDocument in XMLImport"); return FALSE; } uno::Reference<lang::XMultiServiceFactory> xServiceFactory(utl::getProcessServiceFactory()); if(!xServiceFactory.is()) { DBG_ERROR("XMLReader::Read: got no service manager"); return FALSE; } // Get data source ... uno::Reference<io::XActiveDataSource> xSource = mrMedium.GetDataSource(); if(!xSource.is()) { // // If we didn't get a data source from a medium, we have to create one // XInterfaceRef xFactory = xServiceFactory->createInstance(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.DataSourceFactory")); // if(xFactory.is()) // { // XMultiServiceFactoryRef xMFactory(xFactory, USR_QUERY); // // if(xMFactory.is()) // { // UString sURL(S2WS(mrMedium.GetName())); // Sequence<Any> aArgs(1); // Any* pArgs = aArgs.getArray(); // // pArgs->setString(sURL); // // XInterfaceRef xSrc = xMFactory->createInstanceWithArguments(sURL, aArgs); // // if(xSrc.is()) // { // xSrc->queryInterface(XActiveDataSource::getSmartUik(), xSource); // } // } // } } // get data source if(!xSource.is()) { DBG_ERROR("XMLReader::Read: data source missing"); return FALSE; } // get parser uno::Reference<uno::XInterface> xXMLParser(xServiceFactory->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Parser")))); if(!xXMLParser.is()) { DBG_ERROR("com.sun.star.xml.sax.Parser service missing"); return FALSE; } // get a pipe for connecting the data source to the parser uno::Reference<uno::XInterface> xPipe(xServiceFactory->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.io.Pipe")))); if(!xPipe.is()) { DBG_ERROR("com.sun.star.io.Pipe service missing"); return FALSE; } UINT16 nStyleFamilyMask(0); BOOL bLoadDoc(TRUE); // this is stuff for loading only styles or add-load documents, needed later // USHORT nStyleFamilyMask = SFX_STYLE_FAMILY_ALL; // BOOL bInsert; // if( aOpt.IsFmtsOnly() ) // { // bLoadDoc = FALSE; // bInsert = aOpt.IsMerge(); // nStyleFamilyMask = 0U; // if( aOpt.IsFrmFmts() ) // nStyleFamilyMask |= SFX_STYLE_FAMILY_FRAME; // if( aOpt.IsPageDescs() ) // nStyleFamilyMask |= SFX_STYLE_FAMILY_PAGE; // if( aOpt.IsTxtFmts() ) // nStyleFamilyMask |= (SFX_STYLE_FAMILY_CHAR|SFX_STYLE_FAMILY_PARA); // if( aOpt.IsNumRules() ) // nStyleFamilyMask |= SFX_STYLE_FAMILY_PSEUDO; // } // else // { // bLoadDoc = TRUE; // bInsert = bInsertMode; // nStyleFamilyMask = SFX_STYLE_FAMILY_ALL; // } // aOpt.ResetAllFmtsOnly(); // get filter uno::Reference<xml::sax::XDocumentHandler> xFilter = new SdXMLImport(mxLocalModel, bLoadDoc, nStyleFamilyMask, mbShowProgress, IsDraw()); // connect pipe's output stream to the data source uno::Reference<io::XOutputStream> xPipeOutput(xPipe, uno::UNO_QUERY); xSource->setOutputStream(xPipeOutput); // connect pipe's input stream to the parser xml::sax::InputSource aParserInput; uno::Reference<io::XInputStream> xPipeInput(xPipe, uno::UNO_QUERY); aParserInput.aInputStream = xPipeInput; aParserInput.sSystemId = mrMedium.GetName(); OUString sFileName = mrMedium.GetName(); // connect parser and filter uno::Reference<xml::sax::XParser> xParser(xXMLParser, uno::UNO_QUERY); // uno::Reference<xml::sax::XDocumentHandler> xPacker = // new URLPacker(sFileName, xFilter, sal_True, sal_False); // xParser->setDocumentHandler(xPacker); xParser->setDocumentHandler(xFilter); // parse uno::Reference<io::XActiveDataControl> xSourceControl(xSource, uno::UNO_QUERY); xSourceControl->start(); BOOL bRetval(TRUE); try { xParser->parseStream(aParserInput); } catch(xml::sax::SAXParseException) { bRetval = FALSE; } catch(xml::sax::SAXException) { bRetval = FALSE; } catch(io::IOException) { bRetval = FALSE; } return bRetval; } BOOL SdXMLWrapper::Export() { if(!mxLocalModel.is()) { DBG_ERROR("Got NO Model in XMLExport"); return FALSE; } uno::Reference<lang::XServiceInfo> xServiceInfo(mxLocalModel, uno::UNO_QUERY); if(!xServiceInfo.is() || !xServiceInfo->supportsService( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DrawingDocument")))) { DBG_ERROR("Model is no DrawingDocument in XMLExport"); return FALSE; } uno::Reference<lang::XMultiServiceFactory> xServiceFactory(utl::getProcessServiceFactory()); if(!xServiceFactory.is()) { DBG_ERROR("got no service manager"); return FALSE; } uno::Reference<uno::XInterface> xWriter(xServiceFactory->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Writer")))); if(!xWriter.is()) { DBG_ERROR("com.sun.star.xml.sax.Writer service missing"); return FALSE; } // smart -> uno3 conversion only until SfxMedium has a uno3 DataSink uno::Reference<io::XOutputStream> xOut = mrMedium.GetDataSink(); uno::Reference<io::XActiveDataSource> xSrc(xWriter, uno::UNO_QUERY); xSrc->setOutputStream(xOut); uno::Reference<xml::sax::XDocumentHandler> xHandler(xWriter, uno::UNO_QUERY); OUString sFileName = mrMedium.GetName(); uno::Reference<xml::sax::XDocumentHandler> xPacker = new URLPacker(sFileName, xHandler, sal_False, sal_True); SdXMLExport aExp(mxLocalModel, sFileName, xPacker, mbShowProgress, IsDraw()); // SdXMLExport aExp(mxLocalModel, sFileName, xHandler, mbShowProgress, IsDraw()); // give string descriptor as parameter for doc type BOOL bRet = (0 == aExp.exportDoc( IsDraw() ? sXML_drawing : sXML_impress )); return bRet; } <commit_msg>only export binaries in test case<commit_after>/************************************************************************* * * $RCSfile: sdxmlwrp.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: cl $ $Date: 2000-11-13 09:18:29 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _SFXDOCFILE_HXX #include <sfx2/docfile.hxx> #endif #ifndef _SDXMLWRP_HXX #include "sdxmlwrp.hxx" #endif #ifndef _SDXMLIMP_HXX #include <xmloff/sdxmlimp.hxx> #endif #ifndef _SDXMLEXP_HXX #include <xmloff/sdxmlexp.hxx> #endif #ifndef _DRAWDOC_HXX #include "drawdoc.hxx" #endif #ifndef _UNO_MAPPING_HXX_ #include <uno/mapping.hxx> //! only necessary until SfxMedium has a uno3 DataSource / DataSink #endif #include <com/sun/star/xml/sax/XErrorHandler.hpp> #include <com/sun/star/xml/sax/XEntityResolver.hpp> #include <com/sun/star/xml/sax/InputSource.hpp> #include <com/sun/star/xml/sax/XDTDHandler.hpp> #include <com/sun/star/xml/sax/XParser.hpp> #include <com/sun/star/io/XActiveDataSource.hpp> #include <com/sun/star/io/XActiveDataControl.hpp> #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _UNOTOOLS_PROCESSFACTORY_HXX_ #include <unotools/processfactory.hxx> #endif #include "pkgurl.hxx" using namespace com::sun::star; using namespace rtl; ////////////////////////////////////////////////////////////////////////////// char __READONLY_DATA sXML_drawing[] = "drawing"; char __READONLY_DATA sXML_impress[] = "presentation"; ////////////////////////////////////////////////////////////////////////////// SdXMLWrapper::SdXMLWrapper( uno::Reference<frame::XModel>& xRef, SfxMedium& rMedium, BOOL bIsDraw, BOOL bShowProg) : mxLocalModel(xRef), mrMedium(rMedium), mbIsDraw(bIsDraw), mbShowProgress(bShowProg) { } BOOL SdXMLWrapper::Import() { if(!mxLocalModel.is()) { DBG_ERROR("Got NO Model in XMLImport"); return FALSE; } uno::Reference<lang::XServiceInfo> xServiceInfo(mxLocalModel, uno::UNO_QUERY); if(!xServiceInfo.is() || !xServiceInfo->supportsService(OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DrawingDocument")))) { DBG_ERROR("Model is no DrawingDocument in XMLImport"); return FALSE; } uno::Reference<lang::XMultiServiceFactory> xServiceFactory(utl::getProcessServiceFactory()); if(!xServiceFactory.is()) { DBG_ERROR("XMLReader::Read: got no service manager"); return FALSE; } // Get data source ... uno::Reference<io::XActiveDataSource> xSource = mrMedium.GetDataSource(); if(!xSource.is()) { // // If we didn't get a data source from a medium, we have to create one // XInterfaceRef xFactory = xServiceFactory->createInstance(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.DataSourceFactory")); // if(xFactory.is()) // { // XMultiServiceFactoryRef xMFactory(xFactory, USR_QUERY); // // if(xMFactory.is()) // { // UString sURL(S2WS(mrMedium.GetName())); // Sequence<Any> aArgs(1); // Any* pArgs = aArgs.getArray(); // // pArgs->setString(sURL); // // XInterfaceRef xSrc = xMFactory->createInstanceWithArguments(sURL, aArgs); // // if(xSrc.is()) // { // xSrc->queryInterface(XActiveDataSource::getSmartUik(), xSource); // } // } // } } // get data source if(!xSource.is()) { DBG_ERROR("XMLReader::Read: data source missing"); return FALSE; } // get parser uno::Reference<uno::XInterface> xXMLParser(xServiceFactory->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Parser")))); if(!xXMLParser.is()) { DBG_ERROR("com.sun.star.xml.sax.Parser service missing"); return FALSE; } // get a pipe for connecting the data source to the parser uno::Reference<uno::XInterface> xPipe(xServiceFactory->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.io.Pipe")))); if(!xPipe.is()) { DBG_ERROR("com.sun.star.io.Pipe service missing"); return FALSE; } UINT16 nStyleFamilyMask(0); BOOL bLoadDoc(TRUE); // this is stuff for loading only styles or add-load documents, needed later // USHORT nStyleFamilyMask = SFX_STYLE_FAMILY_ALL; // BOOL bInsert; // if( aOpt.IsFmtsOnly() ) // { // bLoadDoc = FALSE; // bInsert = aOpt.IsMerge(); // nStyleFamilyMask = 0U; // if( aOpt.IsFrmFmts() ) // nStyleFamilyMask |= SFX_STYLE_FAMILY_FRAME; // if( aOpt.IsPageDescs() ) // nStyleFamilyMask |= SFX_STYLE_FAMILY_PAGE; // if( aOpt.IsTxtFmts() ) // nStyleFamilyMask |= (SFX_STYLE_FAMILY_CHAR|SFX_STYLE_FAMILY_PARA); // if( aOpt.IsNumRules() ) // nStyleFamilyMask |= SFX_STYLE_FAMILY_PSEUDO; // } // else // { // bLoadDoc = TRUE; // bInsert = bInsertMode; // nStyleFamilyMask = SFX_STYLE_FAMILY_ALL; // } // aOpt.ResetAllFmtsOnly(); // get filter uno::Reference<xml::sax::XDocumentHandler> xFilter = new SdXMLImport(mxLocalModel, bLoadDoc, nStyleFamilyMask, mbShowProgress, IsDraw()); // connect pipe's output stream to the data source uno::Reference<io::XOutputStream> xPipeOutput(xPipe, uno::UNO_QUERY); xSource->setOutputStream(xPipeOutput); // connect pipe's input stream to the parser xml::sax::InputSource aParserInput; uno::Reference<io::XInputStream> xPipeInput(xPipe, uno::UNO_QUERY); aParserInput.aInputStream = xPipeInput; aParserInput.sSystemId = mrMedium.GetName(); OUString sFileName = mrMedium.GetName(); // connect parser and filter uno::Reference<xml::sax::XParser> xParser(xXMLParser, uno::UNO_QUERY); // uno::Reference<xml::sax::XDocumentHandler> xPacker = // new URLPacker(sFileName, xFilter, sal_True, sal_False); // xParser->setDocumentHandler(xPacker); xParser->setDocumentHandler(xFilter); // parse uno::Reference<io::XActiveDataControl> xSourceControl(xSource, uno::UNO_QUERY); xSourceControl->start(); BOOL bRetval(TRUE); try { xParser->parseStream(aParserInput); } catch(xml::sax::SAXParseException) { bRetval = FALSE; } catch(xml::sax::SAXException) { bRetval = FALSE; } catch(io::IOException) { bRetval = FALSE; } return bRetval; } BOOL SdXMLWrapper::Export() { if(!mxLocalModel.is()) { DBG_ERROR("Got NO Model in XMLExport"); return FALSE; } uno::Reference<lang::XServiceInfo> xServiceInfo(mxLocalModel, uno::UNO_QUERY); if(!xServiceInfo.is() || !xServiceInfo->supportsService( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DrawingDocument")))) { DBG_ERROR("Model is no DrawingDocument in XMLExport"); return FALSE; } uno::Reference<lang::XMultiServiceFactory> xServiceFactory(utl::getProcessServiceFactory()); if(!xServiceFactory.is()) { DBG_ERROR("got no service manager"); return FALSE; } uno::Reference<uno::XInterface> xWriter(xServiceFactory->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Writer")))); if(!xWriter.is()) { DBG_ERROR("com.sun.star.xml.sax.Writer service missing"); return FALSE; } // smart -> uno3 conversion only until SfxMedium has a uno3 DataSink uno::Reference<io::XOutputStream> xOut = mrMedium.GetDataSink(); uno::Reference<io::XActiveDataSource> xSrc(xWriter, uno::UNO_QUERY); xSrc->setOutputStream(xOut); uno::Reference<xml::sax::XDocumentHandler> xHandler(xWriter, uno::UNO_QUERY); OUString sFileName = mrMedium.GetName(); #ifdef XMLTESTBIN uno::Reference<xml::sax::XDocumentHandler> xPacker = new URLPacker(sFileName, xHandler, sal_False, sal_True); SdXMLExport aExp(mxLocalModel, sFileName, xPacker, mbShowProgress, IsDraw()); #else SdXMLExport aExp(mxLocalModel, sFileName, xHandler, mbShowProgress, IsDraw()); #endif // give string descriptor as parameter for doc type BOOL bRet = (0 == aExp.exportDoc( IsDraw() ? sXML_drawing : sXML_impress )); return bRet; } <|endoftext|>
<commit_before>// Copyright (c) 2015-2016 Andrew Sutton // All rights reserved #include "expression.hpp" #include "ast-expr.hpp" #include "context.hpp" #include "lookup.hpp" namespace banjo { // A helper function for the typing of expressions occurring in a // requires-expressions. This performs a lookup of an iniitally // constructed expression, and adjusts its type as needed. Expr& make_required_expression(Context& cxt, Expr& e) { if (Expr* prev = requirement_lookup(cxt, e)) e.type_ = prev->type_; return e; } // A requires expression has type bool. // // TODO: Actually validate information about the requires expression. The // statement cannot be emtpy. No variadic parameter, etc. // // TODO: Eventually move this to a different expr_ module. Expr& make_requirements(Context& cxt, Decl_list const& tparms, Decl_list const& parms, Req_list const& reqs) { return cxt.make_requires(tparms, parms, reqs); } //TODO: Find a type for the Expr_list Expr& make_tuple_expr(Context& cxt, Expr_list& l) { Type& t = l.begin()->type(); return cxt.make_tuple_expr(t, l); } } // namespace banjo <commit_msg>Tuple_expr now has a type<commit_after>// Copyright (c) 2015-2016 Andrew Sutton // All rights reserved #include "expression.hpp" #include "ast-expr.hpp" #include "ast-type.hpp" #include "context.hpp" #include "lookup.hpp" namespace banjo { // A helper function for the typing of expressions occurring in a // requires-expressions. This performs a lookup of an iniitally // constructed expression, and adjusts its type as needed. Expr& make_required_expression(Context& cxt, Expr& e) { if (Expr* prev = requirement_lookup(cxt, e)) e.type_ = prev->type_; return e; } // A requires expression has type bool. // // TODO: Actually validate information about the requires expression. The // statement cannot be emtpy. No variadic parameter, etc. // // TODO: Eventually move this to a different expr_ module. Expr& make_requirements(Context& cxt, Decl_list const& tparms, Decl_list const& parms, Req_list const& reqs) { return cxt.make_requires(tparms, parms, reqs); } //TODO: Find a type for the Expr_list Expr& make_tuple_expr(Context& cxt, Expr_list& l) { Type_list tlist; for(auto eli = l.begin(); eli != l.end(); eli++) { tlist.push_back(eli->type()); } Tuple_type t(tlist); return cxt.make_tuple_expr(t, l); } } // namespace banjo <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/gfx/gtk_util.h" #include <gdk/gdk.h> #include <gtk/gtk.h> #include <stdlib.h> #include "base/gfx/rect.h" #include "base/linux_util.h" #include "third_party/skia/include/core/SkBitmap.h" namespace { void FreePixels(guchar* pixels, gpointer data) { free(data); } } // namespace namespace gfx { const GdkColor kGdkWhite = GDK_COLOR_RGB(0xff, 0xff, 0xff); const GdkColor kGdkBlack = GDK_COLOR_RGB(0x00, 0x00, 0x00); const GdkColor kGdkGreen = GDK_COLOR_RGB(0x00, 0xff, 0x00); GdkPixbuf* GdkPixbufFromSkBitmap(const SkBitmap* bitmap) { bitmap->lockPixels(); int width = bitmap->width(); int height = bitmap->height(); int stride = bitmap->rowBytes(); const guchar* orig_data = static_cast<guchar*>(bitmap->getPixels()); guchar* data = base::BGRAToRGBA(orig_data, width, height, stride); // This pixbuf takes ownership of our malloc()ed data and will // free it for us when it is destroyed. GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data( data, GDK_COLORSPACE_RGB, // The only colorspace gtk supports. true, // There is an alpha channel. 8, width, height, stride, &FreePixels, data); bitmap->unlockPixels(); return pixbuf; } void SubtractRectanglesFromRegion(GdkRegion* region, const std::vector<Rect>& cutouts) { for (size_t i = 0; i < cutouts.size(); ++i) { GdkRectangle rect = cutouts[i].ToGdkRectangle(); GdkRegion* rect_region = gdk_region_rectangle(&rect); gdk_region_subtract(region, rect_region); // TODO(deanm): It would be nice to be able to reuse the GdkRegion here. gdk_region_destroy(rect_region); } } } // namespace gfx <commit_msg>GdkPixbufFromSkBitmap needs to un-premultiply the alpha before passing off the data to gdk_pixbuf. This is required in the theme code for tinted bitmaps.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/gfx/gtk_util.h" #include <gdk/gdk.h> #include <gtk/gtk.h> #include <stdlib.h> #include "base/basictypes.h" #include "base/gfx/rect.h" #include "base/linux_util.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkUnPreMultiply.h" namespace { void FreePixels(guchar* pixels, gpointer data) { free(data); } } // namespace namespace gfx { const GdkColor kGdkWhite = GDK_COLOR_RGB(0xff, 0xff, 0xff); const GdkColor kGdkBlack = GDK_COLOR_RGB(0x00, 0x00, 0x00); const GdkColor kGdkGreen = GDK_COLOR_RGB(0x00, 0xff, 0x00); GdkPixbuf* GdkPixbufFromSkBitmap(const SkBitmap* bitmap) { bitmap->lockPixels(); int width = bitmap->width(); int height = bitmap->height(); int stride = bitmap->rowBytes(); // SkBitmaps are premultiplied, we need to unpremultiply them. const int kBytesPerPixel = 4; uint8* divided = static_cast<uint8*>(malloc(height * stride)); for (int y = 0, i = 0; y < height; y++) { for (int x = 0; x < width; x++) { uint32 pixel = bitmap->getAddr32(0, y)[x]; int alpha = SkColorGetA(pixel); if (alpha != 0 && alpha != 255) { SkColor unmultiplied = SkUnPreMultiply::PMColorToColor(pixel); divided[i + 0] = SkColorGetR(unmultiplied); divided[i + 1] = SkColorGetG(unmultiplied); divided[i + 2] = SkColorGetB(unmultiplied); divided[i + 3] = alpha; } else { divided[i + 0] = SkColorGetR(pixel); divided[i + 1] = SkColorGetG(pixel); divided[i + 2] = SkColorGetB(pixel); divided[i + 3] = alpha; } i += kBytesPerPixel; } } // This pixbuf takes ownership of our malloc()ed data and will // free it for us when it is destroyed. GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data( divided, GDK_COLORSPACE_RGB, // The only colorspace gtk supports. true, // There is an alpha channel. 8, width, height, stride, &FreePixels, divided); bitmap->unlockPixels(); return pixbuf; } void SubtractRectanglesFromRegion(GdkRegion* region, const std::vector<Rect>& cutouts) { for (size_t i = 0; i < cutouts.size(); ++i) { GdkRectangle rect = cutouts[i].ToGdkRectangle(); GdkRegion* rect_region = gdk_region_rectangle(&rect); gdk_region_subtract(region, rect_region); // TODO(deanm): It would be nice to be able to reuse the GdkRegion here. gdk_region_destroy(rect_region); } } } // namespace gfx <|endoftext|>
<commit_before>#include <bencode/tokenizer.h> #include <bencode/element.h> #include <cassert> #include <sstream> #define _THROW(d, ptr) { \ std::ostringstream __s; \ size_t pos = len - (end - ptr); \ __s << d; \ throw TokenizerError(__s.str(), pos); \ } #define THROW(d) _THROW(d, str) #define THROW_FIRST(d) _THROW(d, first) namespace BEncode { int64_t intValue(const struct Token& t) { assert(t.type == Token::INT); std::istringstream s(t.value); std::ostringstream o; int64_t v; s >> v; o << v; assert(o.str() == t.value); return v; } std::vector<Token> tokenize(const char* str, size_t len) { std::vector<Token> toks; const char* const end = &str[len]; const char* first = str; enum { SNONE, SNEG, SINT } state = SNONE; while (str < end) { switch (state) { case SNONE: first = str; switch (*str) { case 'i': toks.push_back(Token("i", Token::I)); state = SNONE; break; case 'l': toks.push_back(Token("l", Token::L)); state = SNONE; break; case 'd': toks.push_back(Token("d", Token::D)); state = SNONE; break; case 'e': toks.push_back(Token("e", Token::E)); state = SNONE; break; case ':': if (toks.size() != 0 && toks.back().type == Token::INT) { int64_t slen = intValue(toks.back()); toks.push_back(Token(":", Token::COLON)); // in here because we check toks.back() if (slen >= 0 && slen < end - str) { toks.push_back(Token(str + 1, slen, Token::STRING)); str += slen; } } else { toks.push_back(Token(":", Token::COLON)); } state = SNONE; break; case '-': state = SNEG; break; case '0': toks.push_back(Token("0", Token::INT)); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = SINT; break; default: THROW("Unexpected character."); } *str++; break; case SNEG: switch (*str) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = SINT; break; default: THROW_FIRST("Invalid integer value."); } *str++; break; case SINT: switch (*str) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': *str++; break; default: toks.push_back(Token(first, str - first, Token::INT)); state = SNONE; break; } break; } } switch (state) { case SNONE: break; case SINT: toks.push_back(Token(first, str - first, Token::INT)); break; case SNEG: THROW_FIRST("Invalid integer value."); } return toks; } } <commit_msg>bencode: Adding comments on the tokenizer.<commit_after>#include <bencode/tokenizer.h> #include <bencode/element.h> #include <cassert> #include <sstream> #define _THROW(d, ptr) { \ std::ostringstream __s; \ size_t pos = len - (end - ptr); \ __s << d; \ throw TokenizerError(__s.str(), pos); \ } #define THROW(d) _THROW(d, str) #define THROW_FIRST(d) _THROW(d, first) namespace BEncode { int64_t intValue(const struct Token& t) { assert(t.type == Token::INT); std::istringstream s(t.value); std::ostringstream o; int64_t v; s >> v; o << v; assert(o.str() == t.value); return v; } std::vector<Token> tokenize(const char* str, size_t len) { std::vector<Token> toks; const char* const end = &str[len]; const char* first = str; enum { SNONE, SNEG, SINT } state = SNONE; /* * Unfortunately, bencoded data cannot be tokenized by a straight DFA due * to the way strings behave. Regardless, we treat as much as possible as * a DFA until we hit a semicolon. In that case we will try to treat the * data as a string, but if we can't, then we attempt to treat it as * normal bencoded data. */ while (str < end) { switch (state) { case SNONE: first = str; switch (*str) { case 'i': toks.push_back(Token("i", Token::I)); state = SNONE; break; case 'l': toks.push_back(Token("l", Token::L)); state = SNONE; break; case 'd': toks.push_back(Token("d", Token::D)); state = SNONE; break; case 'e': toks.push_back(Token("e", Token::E)); state = SNONE; break; case ':': if (toks.size() != 0 && toks.back().type == Token::INT) { int64_t slen = intValue(toks.back()); toks.push_back(Token(":", Token::COLON)); // in here because we check toks.back() if (slen >= 0 && slen < end - str) { toks.push_back(Token(str + 1, slen, Token::STRING)); str += slen; } } else { toks.push_back(Token(":", Token::COLON)); } state = SNONE; break; case '-': state = SNEG; break; case '0': toks.push_back(Token("0", Token::INT)); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = SINT; break; default: THROW("Unexpected character."); } *str++; break; case SNEG: switch (*str) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = SINT; break; default: THROW_FIRST("Invalid integer value."); } *str++; break; case SINT: switch (*str) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': *str++; break; default: toks.push_back(Token(first, str - first, Token::INT)); state = SNONE; break; } break; } } switch (state) { case SNONE: break; case SINT: toks.push_back(Token(first, str - first, Token::INT)); break; case SNEG: THROW_FIRST("Invalid integer value."); } return toks; } } <|endoftext|>