text
stringlengths
54
60.6k
<commit_before>#include <iostream> #include <iomanip> #include "Point.hpp" #include "TimeHelpers.hpp" const double tolerance = 0.00001; const size_t malla = 10000; using Row = vector<real>; using Matrix = vector<Row>; class Mu { public: Mu(size_t n) : m_M(n,Row(n,0)) { } real operator()(size_t x, size_t y) const { return m_M[x][y]; } real& operator()(size_t x, size_t y) { return m_M[x][y]; } size_t numcols() const { return m_M.size(); } size_t numrows() const { return m_M.size(); } void Realize(const vector<Point>& P, real C); real Integrate() const; private: Matrix m_M; }; Mu operator+(const Mu& A, const Mu& B) { Mu C(A.numrows()); for (size_t x = 0; x < C.numcols(); ++x) { for (size_t y = 0; y < C.numrows(); ++y) { C(x,y) = A(x,y) + B(x,y) - A(x,y)*B(x,y); } } return C; } Mu operator*(const Mu& A, const Mu& B) { Mu C(A.numrows()); for (size_t x = 0; x < C.numcols(); ++x) { for (size_t y = 0; y < C.numrows(); ++y) { C(x,y) = A(x,y)*B(x,y); } } return C; } void Mu::Realize(const vector<Point>& P, real C) { // TODO: Pasar lo de los puntos para afuera y dependiendo de C, ver qué debo modificar para cada punto. // Seguramente búsuqeda binaria for (size_t x = 0; x < numcols(); ++x) { for (size_t y = 0; y < numrows(); ++y) { m_M[x][y] = -1; } } double d = sqrt(-log(tolerance)/C); long di = long(d+1); // cout << "di = " << di << endl; for (const Point& p : P) { size_t minX = max(long(0),long(p.x)-di); size_t maxX = min(long(numcols()), long(p.x)+di); size_t minY = max(long(0),long(p.y)-di); size_t maxY = min(long(numrows()), long(p.y)+di); for (size_t x = minX; x < maxX; ++x) { for (size_t y = minY; y < maxY; ++y) { real d2 = p.DistanceSq(Point(x,y)); m_M[x][y] *= (1-exp(-C*d2)); } } } for (size_t x = 0; x < numcols(); ++x) { for (size_t y = 0; y < numrows(); ++y) { m_M[x][y] += 1; if (abs(m_M[x][y]) < tolerance) m_M[x][y] = 0.0; } } } real Mu::Integrate() const { real result = 0; for (size_t x = 0; x < numcols(); ++x) { for (size_t y = 0; y < numrows(); ++y) { result += m_M[x][y]; } } return result; } std::ostream& operator<<(std::ostream& os, const Mu& C) { const size_t maxtoprint = 20; os << '\n'; os << setprecision(3); for (size_t x = 0; x < min(C.numcols(),maxtoprint); ++x) { for (size_t y = 0; y < min(C.numrows(),maxtoprint); ++y) { os << C(x,y) << '\t'; } os << '\n'; } return os; } real random_real() { int r = rand(); return double(r)/RAND_MAX; } vector<Point> GenerateRandomPoints(int n, int resolution) { vector<Point> result; result.reserve(n); while (result.size() < n) { result.emplace_back(random_real()*resolution, random_real()*resolution); } return result; } int main() { Chronometer T; vector<Point> Especie1 = GenerateRandomPoints(1000,malla); vector<Point> Especie2 = GenerateRandomPoints(1000,malla); Mu A(malla); A.Realize(Especie1,0.005); cout << "Para la malla 1 tardé " << T.Reset() << endl; Mu B(malla); B.Realize(Especie2,0.005); cout << "Para la malla 2 tardé " << T.Reset() << endl; cout << "La arista de A a B debería tener peso: " << (A*B).Integrate()/A.Integrate() << endl; cout << "La arista de B a A debería tener peso: " << (A*B).Integrate()/B.Integrate() << endl; return 0; } <commit_msg>Añadi otra especie más<commit_after>#include <iostream> #include <iomanip> #include "Point.hpp" #include "TimeHelpers.hpp" const double tolerance = 0.00001; const size_t malla = 10000; using Row = vector<real>; using Matrix = vector<Row>; class Mu { public: Mu(size_t n) : m_M(n,Row(n,0)) { } real operator()(size_t x, size_t y) const { return m_M[x][y]; } real& operator()(size_t x, size_t y) { return m_M[x][y]; } size_t numcols() const { return m_M.size(); } size_t numrows() const { return m_M.size(); } void Realize(const vector<Point>& P, real C); real Integrate() const; private: Matrix m_M; }; Mu operator+(const Mu& A, const Mu& B) { Mu C(A.numrows()); for (size_t x = 0; x < C.numcols(); ++x) { for (size_t y = 0; y < C.numrows(); ++y) { C(x,y) = A(x,y) + B(x,y) - A(x,y)*B(x,y); } } return C; } Mu operator*(const Mu& A, const Mu& B) { Mu C(A.numrows()); for (size_t x = 0; x < C.numcols(); ++x) { for (size_t y = 0; y < C.numrows(); ++y) { C(x,y) = A(x,y)*B(x,y); } } return C; } void Mu::Realize(const vector<Point>& P, real C) { // TODO: Pasar lo de los puntos para afuera y dependiendo de C, ver qué debo modificar para cada punto. // Seguramente búsuqeda binaria for (size_t x = 0; x < numcols(); ++x) { for (size_t y = 0; y < numrows(); ++y) { m_M[x][y] = -1; } } double d = sqrt(-log(tolerance)/C); long di = long(d+1); // cout << "di = " << di << endl; for (const Point& p : P) { size_t minX = max(long(0),long(p.x)-di); size_t maxX = min(long(numcols()), long(p.x)+di); size_t minY = max(long(0),long(p.y)-di); size_t maxY = min(long(numrows()), long(p.y)+di); for (size_t x = minX; x < maxX; ++x) { for (size_t y = minY; y < maxY; ++y) { real d2 = p.DistanceSq(Point(x,y)); m_M[x][y] *= (1-exp(-C*d2)); } } } for (size_t x = 0; x < numcols(); ++x) { for (size_t y = 0; y < numrows(); ++y) { m_M[x][y] += 1; if (abs(m_M[x][y]) < tolerance) m_M[x][y] = 0.0; } } } real Mu::Integrate() const { real result = 0; for (size_t x = 0; x < numcols(); ++x) { for (size_t y = 0; y < numrows(); ++y) { result += m_M[x][y]; } } return result; } std::ostream& operator<<(std::ostream& os, const Mu& C) { const size_t maxtoprint = 20; os << '\n'; os << setprecision(3); for (size_t x = 0; x < min(C.numcols(),maxtoprint); ++x) { for (size_t y = 0; y < min(C.numrows(),maxtoprint); ++y) { os << C(x,y) << '\t'; } os << '\n'; } return os; } real random_real() { int r = rand(); return double(r)/RAND_MAX; } vector<Point> GenerateRandomPoints(int n, int resolution) { vector<Point> result; result.reserve(n); while (result.size() < n) { result.emplace_back(random_real()*resolution, random_real()*resolution); } return result; } int main() { Chronometer T; vector<Point> Especie1 = GenerateRandomPoints(1000,malla); vector<Point> Especie2 = GenerateRandomPoints(684,malla); vector<Point> Especie3 = GenerateRandomPoints(321,malla); Mu A(malla); A.Realize(Especie1,0.005); cout << "Para la malla 1 tardé " << T.Reset() << endl; Mu B(malla); B.Realize(Especie2,0.005); cout << "Para la malla 2 tardé " << T.Reset() << endl; Mu C(malla); C.Realize(Especie3,0.005); cout << "Para la malla 3 tardé " << T.Reset() << endl; double overlapAB = (A*B).Integrate(); double overlapBC = (B*C).Integrate(); double overlapCA = (C*A).Integrate(); double areaA = A.Integrate(); double areaB = B.Integrate(); double areaC = C.Integrate(); cout << "En calcular áreas me tardé " << T.Reset() << endl; cout << "La arista de A a B debería tener peso: " << overlapAB/areaA << endl; cout << "La arista de B a A debería tener peso: " << overlapAB/areaB << endl; cout << "La arista de B a C debería tener peso: " << overlapBC/areaB << endl; cout << "La arista de C a B debería tener peso: " << overlapBC/areaC << endl; cout << "La arista de C a A debería tener peso: " << overlapCA/areaC << endl; cout << "La arista de A a C debería tener peso: " << overlapCA/areaA << endl; return 0; } <|endoftext|>
<commit_before>f79b1874-585a-11e5-8dae-6c40088e03e4<commit_msg>f7a206e6-585a-11e5-a1f8-6c40088e03e4<commit_after>f7a206e6-585a-11e5-a1f8-6c40088e03e4<|endoftext|>
<commit_before>#include "serial.h" speed_t baud = 4800; std::string port = "/dev/ttyUSB0"; Serial gps(baud, port); void readGPS() { for(int i = 0; i < 4; ++i) { gps.serialRead(); std::cout << "Sentence: " << gps.getData() << std::endl; } } void printConfig() { termios cur_config = gps.getConfig(); std::cout << "c_cflag: " << cur_config.c_cflag << std::endl; std::cout << "c_iflag: " << cur_config.c_iflag << std::endl; std::cout << "c_oflag: " << cur_config.c_oflag << std::endl; std::cout << "c_lflag: " << cur_config.c_lflag << std::endl; } int main() { printConfig(); std::cout << "Baud 1: " << gps.getBaud() << std::endl; std::cout << "Applying change: " << gps.applyNewConfig() << std::endl; baud = 9600; std::cout << "Setting Baud to " << baud << ": " << gps.setBaud(baud) << std::endl; std::cout << "Applying change: " << gps.applyNewConfig() << std::endl; std::cout << "Baud 2: " << gps.getBaud() << std::endl; baud = 4800; std::cout << "Setting Baud to " << baud << ": " << gps.setBaud(baud) << std::endl; std::cout << "Applying change: " << gps.applyNewConfig() << std::endl; readGPS(); baud = 4800; std::cout << "Restoring baud to " << baud << ": " << gps.setBaud(baud) << std::endl; std::cout << "Applying change: " << gps.applyNewConfig() << std::endl; std::cout << "Baud 2: " << gps.getBaud() << std::endl; readGPS(); return 0; } <commit_msg>Delete main.cpp<commit_after><|endoftext|>
<commit_before>eaf77bf8-585a-11e5-8d37-6c40088e03e4<commit_msg>eafe6fd0-585a-11e5-8e99-6c40088e03e4<commit_after>eafe6fd0-585a-11e5-8e99-6c40088e03e4<|endoftext|>
<commit_before>#include <iostream> #include <memory> #include <fstream> #include "Game/Game.h" #include "Game/Board.h" #include "Moves/Move.h" #include "Players/Genetic_AI.h" #include "Players/Human_Player.h" #include "Players/Random_AI.h" #include "Players/Outside_Player.h" #include "Genes/Gene_Pool.h" #include "Exceptions/Illegal_Move_Exception.h" #include "Exceptions/Game_Ending_Exception.h" #include "Utility.h" #include "Testing.h" void print_help() { std::cout << "\n\nGenetic Chess" << std::endl << "=============" << std::endl << std::endl << "Options:" << std::endl << "\t-genepool [file name]" << std::endl << "\t\tStart a run of a gene pool with parameters set in the given\n\t\tfile name." << std::endl << std::endl << "\t-replay [filename]" << std::endl << "\t\tStep through a PGN game file, drawing the board after each\n\t\tmove with an option to begin playing at any time." << std::endl << std::endl << "The following options start a game with various players. If two players are\nspecified, the first plays white and the second black. If only one player is\nspecified, the program will wait for a CECP command from outside to start\nplaying." << std::endl << std::endl << "\t-human" << std::endl << "\t\tSpecify a human player for a game." << std::endl << std::endl << "\t-genetic [filename [number]]" << std::endl << "\t\tSpecify a genetic AI player for a game. Optional file name and\n\t\tID number to load an AI from a file." << std::endl << std::endl << "\t-random" << std::endl << "\t\tSpecify a player that makes random moves for a game." << std::endl << std::endl << "\t-time [number]" << std::endl << "\t\tSpecify the time each player has to play the game or to make\n\t\ta set number of moves (see -reset_moves option)." << std::endl << std::endl << "\t-reset_moves [number]" << std::endl << "\t\tSpecify the number of moves a player must make within the time\n\t\tlimit. The clock resets to the initial time every time this\n\t\tnumber of moves is made." << std::endl << std::endl; } int main(int argc, char *argv[]) { try { run_tests(); if(argc > 1) { if(std::string(argv[1]) == "-genepool") { std::string gene_pool_config_file_name; if(argc > 2) { gene_pool_config_file_name = argv[2]; } gene_pool(gene_pool_config_file_name); } else if(std::string(argv[1]) == "-replay") { if(argc > 2) { Board board; std::string file_name = argv[2]; std::ifstream ifs(file_name); std::string line; bool game_started = false; while( ! board.game_has_ended() && std::getline(ifs, line)) { line = String::trim_outer_whitespace(line); line = String::strip_block_comment(line, '{', '}'); line = String::strip_comments(line, ';'); if(line.empty()) { if(game_started) { break; } else { continue; } } if(line[0] == '[') { std::cout << line << std::endl; continue; } for(const auto& s : String::split(line)) { try { board.submit_move(board.get_complete_move(s)); } catch(const Illegal_Move_Exception&) { std::cout << "Ignoring: " << s << std::endl; continue; } catch(const Game_Ending_Exception& e) { std::cout << e.what() << std::endl; } board.ascii_draw(WHITE); game_started = true; std::cout << "Last move: "; std::cout << (board.get_game_record().size() + 1)/2 << ". "; std::cout << (board.whose_turn() == WHITE ? "... " : ""); std::cout << board.get_game_record().back() << std::endl; if(board.game_has_ended()) { break; } std::cout << "Enter \"y\" to play game from here: " << std::endl; char response = std::cin.get(); if(std::tolower(response) == 'y') { play_game_with_board(Human_Player(), Human_Player(), 0, 0, file_name + "_continued.pgn", board); break; } } } } else { std::cerr << "-replay must be followed by a file name." << std::endl; return 1; } } else { std::unique_ptr<Player> white; std::unique_ptr<Player> black; std::unique_ptr<Player> latest; int game_time = 0; int moves_per_reset = 0; for(int i = 1; i < argc; ++i) { std::string opt = argv[i]; if(opt == "-human") { latest.reset(new Human_Player()); } else if(opt == "-random") { latest.reset(new Random_AI()); } else if(opt == "-genetic") { Genetic_AI *genetic_ptr = nullptr; std::string filename; int id = -1; if(i + 1 < argc) { filename = argv[i+1]; if(filename.front() == '-') { filename.clear(); } } if(i + 2 < argc) { try { id = std::stoi(argv[i+2]); } catch(const std::exception&) { } } if(filename.empty()) { genetic_ptr = new Genetic_AI; for(int j = 0; j < 100; ++j) { genetic_ptr->mutate(); } } else { if(id < 0) { genetic_ptr = new Genetic_AI(filename); i += 1; } else { genetic_ptr = new Genetic_AI(filename, id); i += 2; } } latest.reset(genetic_ptr); } else if(opt == "-time") { game_time = std::stoi(argv[++i]); } else if(opt == "-reset_moves") { moves_per_reset = std::stoi(argv[++i]); } else { throw std::runtime_error("Invalid option: " + opt); } if(latest) { if( ! white) { white = std::move(latest); continue; } if( ! black) { black = std::move(latest); continue; } } } if( ! white || ! black) { std::cerr << "Choose two players.\n"; return 1; } play_game(*white, *black, game_time, moves_per_reset, "game.pgn"); } } else { print_help(); } } catch(const std::exception& e) { std::cerr << "\n\nERROR: " << e.what() << std::endl; return 1; } return 0; } <commit_msg>If one player specified on command line, assume CECP interface is needed<commit_after>#include <iostream> #include <memory> #include <fstream> #include "Game/Game.h" #include "Game/Board.h" #include "Moves/Move.h" #include "Players/Genetic_AI.h" #include "Players/Human_Player.h" #include "Players/Random_AI.h" #include "Players/Outside_Player.h" #include "Genes/Gene_Pool.h" #include "Exceptions/Illegal_Move_Exception.h" #include "Exceptions/Game_Ending_Exception.h" #include "Utility.h" #include "Testing.h" void print_help() { std::cout << "\n\nGenetic Chess" << std::endl << "=============" << std::endl << std::endl << "Options:" << std::endl << "\t-genepool [file name]" << std::endl << "\t\tStart a run of a gene pool with parameters set in the given\n\t\tfile name." << std::endl << std::endl << "\t-replay [filename]" << std::endl << "\t\tStep through a PGN game file, drawing the board after each\n\t\tmove with an option to begin playing at any time." << std::endl << std::endl << "The following options start a game with various players. If two players are\nspecified, the first plays white and the second black. If only one player is\nspecified, the program will wait for a CECP command from outside to start\nplaying." << std::endl << std::endl << "\t-human" << std::endl << "\t\tSpecify a human player for a game." << std::endl << std::endl << "\t-genetic [filename [number]]" << std::endl << "\t\tSpecify a genetic AI player for a game. Optional file name and\n\t\tID number to load an AI from a file." << std::endl << std::endl << "\t-random" << std::endl << "\t\tSpecify a player that makes random moves for a game." << std::endl << std::endl << "\t-time [number]" << std::endl << "\t\tSpecify the time each player has to play the game or to make\n\t\ta set number of moves (see -reset_moves option)." << std::endl << std::endl << "\t-reset_moves [number]" << std::endl << "\t\tSpecify the number of moves a player must make within the time\n\t\tlimit. The clock resets to the initial time every time this\n\t\tnumber of moves is made." << std::endl << std::endl; } int main(int argc, char *argv[]) { try { run_tests(); if(argc > 1) { if(std::string(argv[1]) == "-genepool") { std::string gene_pool_config_file_name; if(argc > 2) { gene_pool_config_file_name = argv[2]; } gene_pool(gene_pool_config_file_name); } else if(std::string(argv[1]) == "-replay") { if(argc > 2) { Board board; std::string file_name = argv[2]; std::ifstream ifs(file_name); std::string line; bool game_started = false; while( ! board.game_has_ended() && std::getline(ifs, line)) { line = String::trim_outer_whitespace(line); line = String::strip_block_comment(line, '{', '}'); line = String::strip_comments(line, ';'); if(line.empty()) { if(game_started) { break; } else { continue; } } if(line[0] == '[') { std::cout << line << std::endl; continue; } for(const auto& s : String::split(line)) { try { board.submit_move(board.get_complete_move(s)); } catch(const Illegal_Move_Exception&) { std::cout << "Ignoring: " << s << std::endl; continue; } catch(const Game_Ending_Exception& e) { std::cout << e.what() << std::endl; } board.ascii_draw(WHITE); game_started = true; std::cout << "Last move: "; std::cout << (board.get_game_record().size() + 1)/2 << ". "; std::cout << (board.whose_turn() == WHITE ? "... " : ""); std::cout << board.get_game_record().back() << std::endl; if(board.game_has_ended()) { break; } std::cout << "Enter \"y\" to play game from here: " << std::endl; char response = std::cin.get(); if(std::tolower(response) == 'y') { play_game_with_board(Human_Player(), Human_Player(), 0, 0, file_name + "_continued.pgn", board); break; } } } } else { std::cerr << "-replay must be followed by a file name." << std::endl; return 1; } } else { std::unique_ptr<Player> white; std::unique_ptr<Player> black; std::unique_ptr<Player> latest; int game_time = 0; int moves_per_reset = 0; for(int i = 1; i < argc; ++i) { std::string opt = argv[i]; if(opt == "-human") { latest.reset(new Human_Player()); } else if(opt == "-random") { latest.reset(new Random_AI()); } else if(opt == "-genetic") { Genetic_AI *genetic_ptr = nullptr; std::string filename; int id = -1; if(i + 1 < argc) { filename = argv[i+1]; if(filename.front() == '-') { filename.clear(); } } if(i + 2 < argc) { try { id = std::stoi(argv[i+2]); } catch(const std::exception&) { } } if(filename.empty()) { genetic_ptr = new Genetic_AI; for(int j = 0; j < 100; ++j) { genetic_ptr->mutate(); } } else { if(id < 0) { genetic_ptr = new Genetic_AI(filename); i += 1; } else { genetic_ptr = new Genetic_AI(filename, id); i += 2; } } latest.reset(genetic_ptr); } else if(opt == "-time") { game_time = std::stoi(argv[++i]); } else if(opt == "-reset_moves") { moves_per_reset = std::stoi(argv[++i]); } else { throw std::runtime_error("Invalid option: " + opt); } if(latest) { if( ! white) { white = std::move(latest); continue; } if( ! black) { black = std::move(latest); continue; } } } if(black) { play_game(*white, *black, game_time, moves_per_reset, "game.pgn"); } else { auto outside = Outside_Player(); if(outside.get_ai_color() == WHITE) { play_game(*white, outside, 0, 0, ""); } else { play_game(outside, *white, 0, 0, ""); } } } } else { print_help(); } } catch(const std::exception& e) { std::cerr << "\n\nERROR: " << e.what() << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>51c850e1-2e4f-11e5-bf32-28cfe91dbc4b<commit_msg>51cf0835-2e4f-11e5-8dfb-28cfe91dbc4b<commit_after>51cf0835-2e4f-11e5-8dfb-28cfe91dbc4b<|endoftext|>
<commit_before>66fb6914-2fa5-11e5-b8bb-00012e3d3f12<commit_msg>66fd8bf4-2fa5-11e5-a5f4-00012e3d3f12<commit_after>66fd8bf4-2fa5-11e5-a5f4-00012e3d3f12<|endoftext|>
<commit_before>8c3d208f-2d14-11e5-af21-0401358ea401<commit_msg>8c3d2090-2d14-11e5-af21-0401358ea401<commit_after>8c3d2090-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>90a5ffb0-ad58-11e7-a2af-ac87a332f658<commit_msg>Initial commit.13<commit_after>9108495e-ad58-11e7-a8f5-ac87a332f658<|endoftext|>
<commit_before>49b206d8-5216-11e5-8b78-6c40088e03e4<commit_msg>49b8e9f6-5216-11e5-8154-6c40088e03e4<commit_after>49b8e9f6-5216-11e5-8154-6c40088e03e4<|endoftext|>
<commit_before>2c770621-2748-11e6-8361-e0f84713e7b8<commit_msg>Did a thing<commit_after>2c81bb75-2748-11e6-9150-e0f84713e7b8<|endoftext|>
<commit_before>4696e450-5216-11e5-8173-6c40088e03e4<commit_msg>469e321c-5216-11e5-a4fc-6c40088e03e4<commit_after>469e321c-5216-11e5-a4fc-6c40088e03e4<|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmlnewprojectwizard.h" #include <coreplugin/icore.h> #include <coreplugin/mimedatabase.h> #include <projectexplorer/projectexplorer.h> #include <utils/filenamevalidatinglineedit.h> #include <utils/filewizardpage.h> #include <utils/pathchooser.h> #include <utils/projectintropage.h> #include <QtCore/QDir> #include <QtCore/QtDebug> #include <QtGui/QDirModel> #include <QtGui/QFormLayout> #include <QtGui/QListView> #include <QtGui/QTreeView> using namespace QmlProjectManager::Internal; using namespace Core::Utils; namespace { class DirModel : public QDirModel { public: DirModel(QObject *parent) : QDirModel(parent) { setFilter(QDir::Dirs | QDir::NoDotAndDotDot); } virtual ~DirModel() { } public: virtual int columnCount(const QModelIndex &) const { return 1; } virtual Qt::ItemFlags flags(const QModelIndex &index) const { return QDirModel::flags(index) | Qt::ItemIsUserCheckable; } virtual QVariant data(const QModelIndex &index, int role) const { if (index.column() == 0 && role == Qt::CheckStateRole) { if (m_selectedPaths.contains(index)) return Qt::Checked; return Qt::Unchecked; } return QDirModel::data(index, role); } virtual bool setData(const QModelIndex &index, const QVariant &value, int role) { if (index.column() == 0 && role == Qt::CheckStateRole) { if (value.toBool()) m_selectedPaths.insert(index); else m_selectedPaths.remove(index); return true; } return QDirModel::setData(index, value, role); } void clearSelectedPaths() { m_selectedPaths.clear(); } QSet<QString> selectedPaths() const { QSet<QString> paths; foreach (const QModelIndex &index, m_selectedPaths) paths.insert(filePath(index)); return paths; } private: QSet<QModelIndex> m_selectedPaths; }; } // end of anonymous namespace ////////////////////////////////////////////////////////////////////////////// // QmlNewProjectWizardDialog ////////////////////////////////////////////////////////////////////////////// QmlNewProjectWizardDialog::QmlNewProjectWizardDialog(QWidget *parent) : QWizard(parent) { setWindowTitle(tr("New QML Project")); m_introPage = new Core::Utils::ProjectIntroPage(); m_introPage->setDescription(tr("This wizard generates a QML application project.")); addPage(m_introPage); } QmlNewProjectWizardDialog::~QmlNewProjectWizardDialog() { } QString QmlNewProjectWizardDialog::path() const { return m_introPage->path(); } void QmlNewProjectWizardDialog::setPath(const QString &path) { m_introPage->setPath(path); } QString QmlNewProjectWizardDialog::projectName() const { return m_introPage->name(); } void QmlNewProjectWizardDialog::updateFilesView(const QModelIndex &current, const QModelIndex &) { if (! current.isValid()) m_filesView->setModel(0); else { const QString selectedPath = m_dirModel->filePath(current); if (! m_filesView->model()) m_filesView->setModel(m_filesModel); m_filesView->setRootIndex(m_filesModel->index(selectedPath)); } } void QmlNewProjectWizardDialog::initializePage(int id) { Q_UNUSED(id) } bool QmlNewProjectWizardDialog::validateCurrentPage() { return QWizard::validateCurrentPage(); } QmlNewProjectWizard::QmlNewProjectWizard() : Core::BaseFileWizard(parameters()) { } QmlNewProjectWizard::~QmlNewProjectWizard() { } Core::BaseFileWizardParameters QmlNewProjectWizard::parameters() { static Core::BaseFileWizardParameters parameters(ProjectWizard); parameters.setIcon(QIcon(":/wizards/images/console.png")); parameters.setName(tr("QML Application")); parameters.setDescription(tr("Creates a QML application.")); parameters.setCategory(QLatin1String("Projects")); parameters.setTrCategory(tr("Projects")); return parameters; } QWizard *QmlNewProjectWizard::createWizardDialog(QWidget *parent, const QString &defaultPath, const WizardPageList &extensionPages) const { QmlNewProjectWizardDialog *wizard = new QmlNewProjectWizardDialog(parent); setupWizard(wizard); wizard->setPath(defaultPath); foreach (QWizardPage *p, extensionPages) wizard->addPage(p); return wizard; } Core::GeneratedFiles QmlNewProjectWizard::generateFiles(const QWizard *w, QString *errorMessage) const { Q_UNUSED(errorMessage) const QmlNewProjectWizardDialog *wizard = qobject_cast<const QmlNewProjectWizardDialog *>(w); const QString projectName = wizard->projectName(); const QString projectPath = wizard->path() + QLatin1Char('/') + projectName; const QString creatorFileName = Core::BaseFileWizard::buildFileName(projectPath, projectName, QLatin1String("qmlproject")); const QString mainFileName = Core::BaseFileWizard::buildFileName(projectPath, projectName, QLatin1String("qml")); QString contents; QTextStream out(&contents); out << "import Qt 4.6" << endl << endl << "Rect {" << endl << " width: 200" << endl << " height: 200" << endl << " color: \"white\"" << endl << " Text {" << endl << " text: \"Hello World\"" << endl << " anchors.centerIn: parent" << endl << " }" << endl << "}" << endl; Core::GeneratedFile generatedMainFile(mainFileName); generatedMainFile.setContents(contents); Core::GeneratedFile generatedCreatorFile(creatorFileName); generatedCreatorFile.setContents(projectName + QLatin1String(".qml\n")); Core::GeneratedFiles files; files.append(generatedMainFile); files.append(generatedCreatorFile); return files; } bool QmlNewProjectWizard::postGenerateFiles(const Core::GeneratedFiles &l, QString *errorMessage) { // Post-Generate: Open the project const QString proFileName = l.back().path(); if (!ProjectExplorer::ProjectExplorerPlugin::instance()->openProject(proFileName)) { *errorMessage = tr("The project %1 could not be opened.").arg(proFileName); return false; } return true; } <commit_msg>Change to new API<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmlnewprojectwizard.h" #include <coreplugin/icore.h> #include <coreplugin/mimedatabase.h> #include <projectexplorer/projectexplorer.h> #include <utils/filenamevalidatinglineedit.h> #include <utils/filewizardpage.h> #include <utils/pathchooser.h> #include <utils/projectintropage.h> #include <QtCore/QDir> #include <QtCore/QtDebug> #include <QtGui/QDirModel> #include <QtGui/QFormLayout> #include <QtGui/QListView> #include <QtGui/QTreeView> using namespace QmlProjectManager::Internal; using namespace Core::Utils; namespace { class DirModel : public QDirModel { public: DirModel(QObject *parent) : QDirModel(parent) { setFilter(QDir::Dirs | QDir::NoDotAndDotDot); } virtual ~DirModel() { } public: virtual int columnCount(const QModelIndex &) const { return 1; } virtual Qt::ItemFlags flags(const QModelIndex &index) const { return QDirModel::flags(index) | Qt::ItemIsUserCheckable; } virtual QVariant data(const QModelIndex &index, int role) const { if (index.column() == 0 && role == Qt::CheckStateRole) { if (m_selectedPaths.contains(index)) return Qt::Checked; return Qt::Unchecked; } return QDirModel::data(index, role); } virtual bool setData(const QModelIndex &index, const QVariant &value, int role) { if (index.column() == 0 && role == Qt::CheckStateRole) { if (value.toBool()) m_selectedPaths.insert(index); else m_selectedPaths.remove(index); return true; } return QDirModel::setData(index, value, role); } void clearSelectedPaths() { m_selectedPaths.clear(); } QSet<QString> selectedPaths() const { QSet<QString> paths; foreach (const QModelIndex &index, m_selectedPaths) paths.insert(filePath(index)); return paths; } private: QSet<QModelIndex> m_selectedPaths; }; } // end of anonymous namespace ////////////////////////////////////////////////////////////////////////////// // QmlNewProjectWizardDialog ////////////////////////////////////////////////////////////////////////////// QmlNewProjectWizardDialog::QmlNewProjectWizardDialog(QWidget *parent) : QWizard(parent) { setWindowTitle(tr("New QML Project")); m_introPage = new Core::Utils::ProjectIntroPage(); m_introPage->setDescription(tr("This wizard generates a QML application project.")); addPage(m_introPage); } QmlNewProjectWizardDialog::~QmlNewProjectWizardDialog() { } QString QmlNewProjectWizardDialog::path() const { return m_introPage->path(); } void QmlNewProjectWizardDialog::setPath(const QString &path) { m_introPage->setPath(path); } QString QmlNewProjectWizardDialog::projectName() const { return m_introPage->name(); } void QmlNewProjectWizardDialog::updateFilesView(const QModelIndex &current, const QModelIndex &) { if (! current.isValid()) m_filesView->setModel(0); else { const QString selectedPath = m_dirModel->filePath(current); if (! m_filesView->model()) m_filesView->setModel(m_filesModel); m_filesView->setRootIndex(m_filesModel->index(selectedPath)); } } void QmlNewProjectWizardDialog::initializePage(int id) { Q_UNUSED(id) } bool QmlNewProjectWizardDialog::validateCurrentPage() { return QWizard::validateCurrentPage(); } QmlNewProjectWizard::QmlNewProjectWizard() : Core::BaseFileWizard(parameters()) { } QmlNewProjectWizard::~QmlNewProjectWizard() { } Core::BaseFileWizardParameters QmlNewProjectWizard::parameters() { static Core::BaseFileWizardParameters parameters(ProjectWizard); parameters.setIcon(QIcon(":/wizards/images/console.png")); parameters.setName(tr("QML Application")); parameters.setDescription(tr("Creates a QML application.")); parameters.setCategory(QLatin1String("Projects")); parameters.setTrCategory(tr("Projects")); return parameters; } QWizard *QmlNewProjectWizard::createWizardDialog(QWidget *parent, const QString &defaultPath, const WizardPageList &extensionPages) const { QmlNewProjectWizardDialog *wizard = new QmlNewProjectWizardDialog(parent); setupWizard(wizard); wizard->setPath(defaultPath); foreach (QWizardPage *p, extensionPages) wizard->addPage(p); return wizard; } Core::GeneratedFiles QmlNewProjectWizard::generateFiles(const QWizard *w, QString *errorMessage) const { Q_UNUSED(errorMessage) const QmlNewProjectWizardDialog *wizard = qobject_cast<const QmlNewProjectWizardDialog *>(w); const QString projectName = wizard->projectName(); const QString projectPath = wizard->path() + QLatin1Char('/') + projectName; const QString creatorFileName = Core::BaseFileWizard::buildFileName(projectPath, projectName, QLatin1String("qmlproject")); const QString mainFileName = Core::BaseFileWizard::buildFileName(projectPath, projectName, QLatin1String("qml")); QString contents; QTextStream out(&contents); out << "import Qt 4.6" << endl << endl << "Rectangle {" << endl << " width: 200" << endl << " height: 200" << endl << " color: \"white\"" << endl << " Text {" << endl << " text: \"Hello World\"" << endl << " anchors.centerIn: parent" << endl << " }" << endl << "}" << endl; Core::GeneratedFile generatedMainFile(mainFileName); generatedMainFile.setContents(contents); Core::GeneratedFile generatedCreatorFile(creatorFileName); generatedCreatorFile.setContents(projectName + QLatin1String(".qml\n")); Core::GeneratedFiles files; files.append(generatedMainFile); files.append(generatedCreatorFile); return files; } bool QmlNewProjectWizard::postGenerateFiles(const Core::GeneratedFiles &l, QString *errorMessage) { // Post-Generate: Open the project const QString proFileName = l.back().path(); if (!ProjectExplorer::ProjectExplorerPlugin::instance()->openProject(proFileName)) { *errorMessage = tr("The project %1 could not be opened.").arg(proFileName); return false; } return true; } <|endoftext|>
<commit_before>#include <SDL2/SDL.h> #ifdef main #undef main #endif #include "cudaray.h" #include <vector> #ifdef HAVE_OPENMP #include <omp.h> #endif static float rnd() { static long a = 3; a = (((a * 214013L + 2531011L) >> 16) & 32767); return (((a % 65556) + 1)) / 65556.0f; } struct t_light_aux { float r; float xangle; float yangle; float speed; }; double time_get() { uint64_t time = SDL_GetPerformanceCounter(); uint64_t frequency = SDL_GetPerformanceFrequency(); return ((double)time) / ((double)frequency); } int main( int argc, char * argv[] ) { bool cpu_mode = false; for( int i = 1; i < argc; ++i ) { char * arg = argv[i]; if( !strcmp( arg, "--cpu" ) ) cpu_mode = true; } if( cpu_mode ) { #ifdef HAVE_OPENMP omp_set_dynamic(0); printf( "running with OpenMP (use OMP_NUM_THREADS to change number of threads)\n" ); #else printf( "running on the CPU\n" ); #endif } else printf( "running on the GPU\n" ); SDL_Init( SDL_INIT_VIDEO ); static const int width = 800; static const int height = 800; SDL_Window * window; SDL_Renderer * renderer; SDL_CreateWindowAndRenderer( width, height, SDL_WINDOW_SHOWN, &window, &renderer ); SDL_Texture * texture = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height ); SDL_RenderSetLogicalSize( renderer, width, height ); std :: vector< t_sphere > spheres; const int sphere_columns = 4; const int sphere_rows = 4; const int sphere_vertical_stride = height / sphere_rows; const int sphere_horizontal_stride = width / sphere_columns; const int n_spheres = sphere_rows * sphere_columns; for( int i = 0; i < n_spheres; ++i ) { t_sphere sphere; int y = i / sphere_columns; int x = i - y * sphere_columns; vec3_set( sphere.position, sphere_horizontal_stride * (x + 0.5), sphere_vertical_stride * (y + 0.5), 0.0f ); vec3_set( sphere.color, 0.50 + rnd() * 0.50, 0.50 + rnd() * 0.50, 0.50 + rnd() * 0.50 ); sphere.radius = 50.0f + rnd() * 25.0f; spheres.push_back( sphere ); } const size_t n_lights = 1; t_light * lights = (t_light *)calloc( n_lights, sizeof( t_light ) ); t_light_aux * lights_aux = ( t_light_aux * )calloc( n_lights, sizeof( t_light_aux ) ); for( int i = 1; i < n_lights; ++i ) { t_light * light = lights + i; t_light_aux * aux = lights_aux + i; light->intensity = 0.25f + rnd(); if( light->intensity > 1.0f ) light->intensity = 1.0f; vec3_set( light->color, rnd() + 0.25f, rnd() + 0.25f, rnd() + 0.25f ); vec3_clamp( light->color, 0.0f, 1.0f ); aux->r = 50.0f + rnd() * 200.0f; aux->xangle = rnd() * 3.14; aux->yangle = rnd() * 3.14; aux->speed = rnd() * 4.0f; } lights[0].intensity = 1.0f; vec3_set( lights[0].color, 1.0f, 1.0f, 1.0f ); vec3_set( lights[0].position, width / 2.0f, height / 2.0f, 500.0f ); uint32_t img[ width ][ height ]; memset( &img, 0, sizeof( img ) ); float t = 0.0f; float speed = 0.3f; int acceleration = 0;; double timestamp = time_get(); int frame_counter = 0; double average = 0.0f; bool average_initialized = false; bool running = true; while( running ) { SDL_Event event; while( SDL_PollEvent( &event ) ) { switch( event.type ) { case SDL_KEYUP: switch( event.key.keysym.sym ) { case SDLK_ESCAPE: running = false; break; case SDLK_RIGHT: if( !event.key.repeat ) acceleration -= 1; break; case SDLK_LEFT: if( !event.key.repeat ) acceleration += 1; break; } break; case SDL_KEYDOWN: switch( event.key.keysym.sym ) { case SDLK_RIGHT: if( !event.key.repeat ) acceleration += 1; break; case SDLK_LEFT: if( !event.key.repeat ) acceleration -= 1; break; } break; } if( !running ) break; } if( !running ) break; vec3_set( lights[0].position, width / 2.0f, height / 2.0f, 300.0f ); t_vec3 shift; vec3_set( shift, (150.0f) * cosf(t), 0.0f, (150.0f) * sinf(t) ); vec3_add( lights[0].position, shift ); for( int i = 1; i < n_lights; ++i ) { t_light * light = lights + i; t_light_aux * aux = lights_aux + i; t_vec3 shift; vec3_set( shift, aux->r * cosf( aux->xangle ) * sin( aux->yangle ), aux->r * sin( aux->xangle ) * cos( aux->yangle ), aux->r * sinf( aux->yangle ) ); vec3_set( light->position, width / 2.0f, height / 2.0f, 0.0f ); vec3_add( light->position, shift ); aux->xangle += speed * aux->speed; aux->yangle += speed * aux->speed; } if( cpu_mode ) cuda_main_cpu( width, height, (uint32_t *)img, &spheres.front(), spheres.size(), lights, n_lights ); else cuda_main( width, height, (uint32_t *)img, &spheres.front(), spheres.size(), lights, n_lights ); SDL_UpdateTexture( texture, NULL, img, width * sizeof( uint32_t ) ); SDL_RenderClear( renderer ); SDL_RenderCopy( renderer, texture, NULL, NULL ); SDL_RenderPresent( renderer ); SDL_Delay( 2 ); t += speed; speed += acceleration * 0.01f; frame_counter++; if( frame_counter == 10 ) { frame_counter = 0; double now = time_get(); double time_per_frame = (now - timestamp) / 10.0; timestamp = now; printf( "time per frame: %fms\n", time_per_frame * 1000.0 ); if( !average_initialized ) average = time_per_frame; else average = (average + time_per_frame) / 2.0; } } printf( "average time per frame: %fms\n", average * 1000.0 ); SDL_DestroyWindow( window ); SDL_Quit(); return 0; } <commit_msg>Make the resolution settable from the command line.<commit_after>#include <SDL2/SDL.h> #ifdef main #undef main #endif #include "cudaray.h" #include <vector> #ifdef HAVE_OPENMP #include <omp.h> #endif static float rnd() { static long a = 3; a = (((a * 214013L + 2531011L) >> 16) & 32767); return (((a % 65556) + 1)) / 65556.0f; } struct t_light_aux { float r; float xangle; float yangle; float speed; }; double time_get() { uint64_t time = SDL_GetPerformanceCounter(); uint64_t frequency = SDL_GetPerformanceFrequency(); return ((double)time) / ((double)frequency); } int main( int argc, char * argv[] ) { int width = 800; int height = 800; bool cpu_mode = false; for( int i = 1; i < argc; ++i ) { char * arg = argv[i]; if( !strcmp( arg, "--cpu" ) ) cpu_mode = true; else if( !strcmp( arg, "--width" ) ) { i++; width = atoi( argv[i] ); } else if( !strcmp( arg, "--height" ) ) { i++; height = atoi( argv[i] ); } } if( cpu_mode ) { #ifdef HAVE_OPENMP omp_set_dynamic(0); printf( "running with OpenMP (use OMP_NUM_THREADS to change number of threads)\n" ); #else printf( "running on the CPU\n" ); #endif } else printf( "running on the GPU\n" ); SDL_Init( SDL_INIT_VIDEO ); SDL_Window * window; SDL_Renderer * renderer; SDL_CreateWindowAndRenderer( width, height, SDL_WINDOW_SHOWN, &window, &renderer ); SDL_Texture * texture = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height ); SDL_RenderSetLogicalSize( renderer, width, height ); std :: vector< t_sphere > spheres; const int sphere_columns = 4; const int sphere_rows = 4; const int sphere_vertical_stride = height / sphere_rows; const int sphere_horizontal_stride = width / sphere_columns; const int n_spheres = sphere_rows * sphere_columns; for( int i = 0; i < n_spheres; ++i ) { t_sphere sphere; int y = i / sphere_columns; int x = i - y * sphere_columns; vec3_set( sphere.position, sphere_horizontal_stride * (x + 0.5), sphere_vertical_stride * (y + 0.5), 0.0f ); vec3_set( sphere.color, 0.50 + rnd() * 0.50, 0.50 + rnd() * 0.50, 0.50 + rnd() * 0.50 ); sphere.radius = 50.0f + rnd() * 25.0f; spheres.push_back( sphere ); } const size_t n_lights = 1; t_light * lights = (t_light *)calloc( n_lights, sizeof( t_light ) ); t_light_aux * lights_aux = ( t_light_aux * )calloc( n_lights, sizeof( t_light_aux ) ); for( int i = 1; i < n_lights; ++i ) { t_light * light = lights + i; t_light_aux * aux = lights_aux + i; light->intensity = 0.25f + rnd(); if( light->intensity > 1.0f ) light->intensity = 1.0f; vec3_set( light->color, rnd() + 0.25f, rnd() + 0.25f, rnd() + 0.25f ); vec3_clamp( light->color, 0.0f, 1.0f ); aux->r = 50.0f + rnd() * 200.0f; aux->xangle = rnd() * 3.14; aux->yangle = rnd() * 3.14; aux->speed = rnd() * 4.0f; } lights[0].intensity = 1.0f; vec3_set( lights[0].color, 1.0f, 1.0f, 1.0f ); vec3_set( lights[0].position, width / 2.0f, height / 2.0f, 500.0f ); uint32_t img[ width ][ height ]; memset( &img, 0, sizeof( img ) ); float t = 0.0f; float speed = 0.3f; int acceleration = 0;; double timestamp = time_get(); int frame_counter = 0; double average = 0.0f; bool average_initialized = false; bool running = true; while( running ) { SDL_Event event; while( SDL_PollEvent( &event ) ) { switch( event.type ) { case SDL_KEYUP: switch( event.key.keysym.sym ) { case SDLK_ESCAPE: running = false; break; case SDLK_RIGHT: if( !event.key.repeat ) acceleration -= 1; break; case SDLK_LEFT: if( !event.key.repeat ) acceleration += 1; break; } break; case SDL_KEYDOWN: switch( event.key.keysym.sym ) { case SDLK_RIGHT: if( !event.key.repeat ) acceleration += 1; break; case SDLK_LEFT: if( !event.key.repeat ) acceleration -= 1; break; } break; } if( !running ) break; } if( !running ) break; vec3_set( lights[0].position, width / 2.0f, height / 2.0f, 300.0f ); t_vec3 shift; vec3_set( shift, (150.0f) * cosf(t), 0.0f, (150.0f) * sinf(t) ); vec3_add( lights[0].position, shift ); for( int i = 1; i < n_lights; ++i ) { t_light * light = lights + i; t_light_aux * aux = lights_aux + i; t_vec3 shift; vec3_set( shift, aux->r * cosf( aux->xangle ) * sin( aux->yangle ), aux->r * sin( aux->xangle ) * cos( aux->yangle ), aux->r * sinf( aux->yangle ) ); vec3_set( light->position, width / 2.0f, height / 2.0f, 0.0f ); vec3_add( light->position, shift ); aux->xangle += speed * aux->speed; aux->yangle += speed * aux->speed; } if( cpu_mode ) cuda_main_cpu( width, height, (uint32_t *)img, &spheres.front(), spheres.size(), lights, n_lights ); else cuda_main( width, height, (uint32_t *)img, &spheres.front(), spheres.size(), lights, n_lights ); SDL_UpdateTexture( texture, NULL, img, width * sizeof( uint32_t ) ); SDL_RenderClear( renderer ); SDL_RenderCopy( renderer, texture, NULL, NULL ); SDL_RenderPresent( renderer ); SDL_Delay( 2 ); t += speed; speed += acceleration * 0.01f; frame_counter++; if( frame_counter == 10 ) { frame_counter = 0; double now = time_get(); double time_per_frame = (now - timestamp) / 10.0; timestamp = now; printf( "time per frame: %fms\n", time_per_frame * 1000.0 ); if( !average_initialized ) average = time_per_frame; else average = (average + time_per_frame) / 2.0; } } printf( "average time per frame: %fms\n", average * 1000.0 ); SDL_DestroyWindow( window ); SDL_Quit(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MNameMapper.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 06:29:03 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <MNameMapper.hxx> #if OSL_DEBUG_LEVEL > 0 # define OUtoCStr( x ) ( ::rtl::OUStringToOString ( (x), RTL_TEXTENCODING_ASCII_US).getStr()) #else /* OSL_DEBUG_LEVEL */ # define OUtoCStr( x ) ("dummy") #endif /* OSL_DEBUG_LEVEL */ using namespace connectivity::mozab; using namespace rtl; bool MNameMapper::ltstr::operator()( const ::rtl::OUString &s1, const ::rtl::OUString &s2) const { return s1.compareTo(s2) < 0; } MNameMapper::MNameMapper() { mDirMap = new MNameMapper::dirMap; mUriMap = new MNameMapper::uriMap; } MNameMapper::~MNameMapper() { clear(); } void MNameMapper::reset() { clear(); mDirMap = new MNameMapper::dirMap; mUriMap = new MNameMapper::uriMap; } void MNameMapper::clear() { if ( mUriMap != NULL ) { delete mUriMap; } if ( mDirMap != NULL ) { MNameMapper::dirMap::iterator iter; for (iter = mDirMap -> begin(); iter != mDirMap -> end(); ++iter) { NS_IF_RELEASE(((*iter).second)); } delete mDirMap; } } const char * getURI(const nsIAbDirectory* directory) { nsresult retCode; nsCOMPtr<nsIRDFResource> rdfResource = do_QueryInterface((nsISupports *)directory, &retCode) ; if (NS_FAILED(retCode)) { return NULL; } const char * uri; retCode=rdfResource->GetValueConst(&uri); if (NS_FAILED(retCode)) { return NULL; } return uri; } // May modify the name passed in so that it's unique nsresult MNameMapper::add( ::rtl::OUString& str, nsIAbDirectory* abook ) { MNameMapper::dirMap::iterator iter; OSL_TRACE( "IN MNameMapper::add()\n" ); if ( abook == NULL ) { OSL_TRACE( "\tOUT MNameMapper::add() called with null abook\n" ); return -1; } ::rtl::OUString ouUri=::rtl::OUString::createFromAscii(getURI(abook)); if ( mUriMap->find (ouUri) != mUriMap->end() ) //There's already an entry with same uri { return -1; } mUriMap->insert( MNameMapper::uriMap::value_type( ouUri, abook ) ); ::rtl::OUString tempStr=str; long count =1; while ( mDirMap->find( tempStr ) != mDirMap->end() ) { tempStr = str + ::rtl::OUString::valueOf(count);; count ++; } str = tempStr; NS_IF_ADDREF(abook); mDirMap->insert( MNameMapper::dirMap::value_type( str, abook ) ); OSL_TRACE( "\tOUT MNameMapper::add()\n" ); return 0; } // Will replace the given dir void MNameMapper::replace( const ::rtl::OUString& str, nsIAbDirectory* abook ) { // TODO - needs to be implemented... OSL_TRACE( "IN/OUT MNameMapper::add()\n" ); } bool MNameMapper::getDir( const ::rtl::OUString& str, nsIAbDirectory* *abook ) { MNameMapper::dirMap::iterator iter; OSL_TRACE( "IN MNameMapper::getDir( %s )\n", OUtoCStr(str)?OUtoCStr(str):"NULL" ); if ( (iter = mDirMap->find( str )) != mDirMap->end() ) { *abook = (*iter).second; NS_IF_ADDREF(*abook); } else { *abook = NULL; } OSL_TRACE( "\tOUT MNameMapper::getDir() : %s\n", (*abook)?"True":"False" ); return( (*abook) != NULL ); } <commit_msg>INTEGRATION: CWS warnings01 (1.6.30); FILE MERGED 2005/11/16 12:59:16 fs 1.6.30.2: #i57457# warning free code 2005/11/07 14:43:57 fs 1.6.30.1: #i57457# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MNameMapper.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-06-20 01:51:38 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <MNameMapper.hxx> #if OSL_DEBUG_LEVEL > 0 # define OUtoCStr( x ) ( ::rtl::OUStringToOString ( (x), RTL_TEXTENCODING_ASCII_US).getStr()) #else /* OSL_DEBUG_LEVEL */ # define OUtoCStr( x ) ("dummy") #endif /* OSL_DEBUG_LEVEL */ using namespace connectivity::mozab; using namespace rtl; bool MNameMapper::ltstr::operator()( const ::rtl::OUString &s1, const ::rtl::OUString &s2) const { return s1.compareTo(s2) < 0; } MNameMapper::MNameMapper() { mDirMap = new MNameMapper::dirMap; mUriMap = new MNameMapper::uriMap; } MNameMapper::~MNameMapper() { clear(); } void MNameMapper::reset() { clear(); mDirMap = new MNameMapper::dirMap; mUriMap = new MNameMapper::uriMap; } void MNameMapper::clear() { if ( mUriMap != NULL ) { delete mUriMap; } if ( mDirMap != NULL ) { MNameMapper::dirMap::iterator iter; for (iter = mDirMap -> begin(); iter != mDirMap -> end(); ++iter) { NS_IF_RELEASE(((*iter).second)); } delete mDirMap; } } const char * getURI(const nsIAbDirectory* directory) { nsresult retCode; nsCOMPtr<nsIRDFResource> rdfResource = do_QueryInterface((nsISupports *)directory, &retCode) ; if (NS_FAILED(retCode)) { return NULL; } const char * uri; retCode=rdfResource->GetValueConst(&uri); if (NS_FAILED(retCode)) { return NULL; } return uri; } // May modify the name passed in so that it's unique nsresult MNameMapper::add( ::rtl::OUString& str, nsIAbDirectory* abook ) { MNameMapper::dirMap::iterator iter; OSL_TRACE( "IN MNameMapper::add()\n" ); if ( abook == NULL ) { OSL_TRACE( "\tOUT MNameMapper::add() called with null abook\n" ); return NS_ERROR_NULL_POINTER; } ::rtl::OUString ouUri=::rtl::OUString::createFromAscii(getURI(abook)); if ( mUriMap->find (ouUri) != mUriMap->end() ) //There's already an entry with same uri { return NS_ERROR_FILE_NOT_FOUND; } mUriMap->insert( MNameMapper::uriMap::value_type( ouUri, abook ) ); ::rtl::OUString tempStr=str; long count =1; while ( mDirMap->find( tempStr ) != mDirMap->end() ) { tempStr = str + ::rtl::OUString::valueOf(count);; count ++; } str = tempStr; NS_IF_ADDREF(abook); mDirMap->insert( MNameMapper::dirMap::value_type( str, abook ) ); OSL_TRACE( "\tOUT MNameMapper::add()\n" ); return 0; } bool MNameMapper::getDir( const ::rtl::OUString& str, nsIAbDirectory* *abook ) { MNameMapper::dirMap::iterator iter; OSL_TRACE( "IN MNameMapper::getDir( %s )\n", OUtoCStr(str)?OUtoCStr(str):"NULL" ); if ( (iter = mDirMap->find( str )) != mDirMap->end() ) { *abook = (*iter).second; NS_IF_ADDREF(*abook); } else { *abook = NULL; } OSL_TRACE( "\tOUT MNameMapper::getDir() : %s\n", (*abook)?"True":"False" ); return( (*abook) != NULL ); } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgUtil/ReversePrimitiveFunctor> #include <algorithm> template <typename Type> osg::PrimitiveSet * drawElementsTemplate(GLenum mode,GLsizei count, const typename Type::value_type* indices) { if (indices==0 || count==0) return NULL; Type * dePtr = new Type(mode); Type & de = *dePtr; de.reserve(count); typedef const typename Type::value_type* IndexPointer; switch(mode) { case(GL_TRIANGLES): { IndexPointer ilast = &indices[count]; for (IndexPointer iptr=indices; iptr<ilast; iptr+=3) { de.push_back(*(iptr)); de.push_back(*(iptr+2)); de.push_back(*(iptr+1)); } break; } case (GL_QUADS): { IndexPointer ilast = &indices[count - 3]; for (IndexPointer iptr = indices; iptr<ilast; iptr+=4) { de.push_back(*(iptr)); de.push_back(*(iptr+3)); de.push_back(*(iptr+2)); de.push_back(*(iptr+1)); } break; } case (GL_TRIANGLE_STRIP): case (GL_QUAD_STRIP): { IndexPointer ilast = &indices[count]; for (IndexPointer iptr = indices; iptr<ilast; iptr+=2) { de.push_back(*(iptr+1)); de.push_back(*(iptr)); } break; } case (GL_TRIANGLE_FAN): { de.push_back(*indices); IndexPointer iptr = indices + 1; IndexPointer ilast = &indices[count]; de.resize(count); std::reverse_copy(iptr, ilast, de.begin() + 1); break; } case (GL_POLYGON): case (GL_POINTS): case (GL_LINES): case (GL_LINE_STRIP): case (GL_LINE_LOOP): { IndexPointer iptr = indices; IndexPointer ilast = &indices[count]; de.resize(count); std::reverse_copy(iptr, ilast, de.begin()); break; } default: break; } return &de; } namespace osgUtil { void ReversePrimitiveFunctor::drawArrays(GLenum mode, GLint first, GLsizei count) { if (count==0) return ; osg::DrawElementsUInt * dePtr = new osg::DrawElementsUInt(mode); osg::DrawElementsUInt & de = *dePtr; de.reserve(count); GLint end = first + count; switch (mode) { case (GL_TRIANGLES): { for (GLint i=first; i<end; i+=3) { de.push_back(i); de.push_back(i+2); de.push_back(i+1); } break; } case (GL_QUADS): { for (GLint i=first; i<end; i+=4) { de.push_back(i); de.push_back(i+3); de.push_back(i+2); de.push_back(i+1); } break; } case (GL_TRIANGLE_STRIP): case (GL_QUAD_STRIP): { for (GLint i=first; i<end; i+=2) { de.push_back(i+1); de.push_back(i); } break; } case (GL_TRIANGLE_FAN): { de.push_back(first); for (GLint i=end-1; i>first; i--) de.push_back(i); break; } case (GL_POLYGON): case (GL_POINTS): case (GL_LINES): case (GL_LINE_STRIP): case (GL_LINE_LOOP): { for (GLint i=end-1; i>=first; i--) de.push_back(i); break; } default: break; } _reversedPrimitiveSet = &de; } void ReversePrimitiveFunctor::drawElements(GLenum mode,GLsizei count,const GLubyte* indices) { _reversedPrimitiveSet = drawElementsTemplate<osg::DrawElementsUByte>(mode, count, indices); } void ReversePrimitiveFunctor::drawElements(GLenum mode,GLsizei count,const GLushort* indices) { _reversedPrimitiveSet = drawElementsTemplate<osg::DrawElementsUShort>(mode, count, indices); } void ReversePrimitiveFunctor::drawElements(GLenum mode,GLsizei count,const GLuint* indices) { _reversedPrimitiveSet = drawElementsTemplate<osg::DrawElementsUInt>(mode, count, indices); } void ReversePrimitiveFunctor::begin(GLenum mode) { if (_running) { OSG_WARN << "ReversePrimitiveFunctor : call \"begin\" without call \"end\"." << std::endl; } else { _running = true; _reversedPrimitiveSet = new osg::DrawElementsUInt(mode); } } void ReversePrimitiveFunctor::vertex(unsigned int pos) { if (_running == false) { OSG_WARN << "ReversePrimitiveFunctor : call \"vertex(" << pos << ")\" without call \"begin\"." << std::endl; } else { static_cast<osg::DrawElementsUInt*>(_reversedPrimitiveSet.get())->push_back(pos); } } void ReversePrimitiveFunctor::end() { if (_running == false) { OSG_WARN << "ReversePrimitiveFunctor : call \"end\" without call \"begin\"." << std::endl; } else { _running = false; osg::ref_ptr<osg::DrawElementsUInt> tmpDe(static_cast<osg::DrawElementsUInt*>(_reversedPrimitiveSet.get())); _reversedPrimitiveSet = drawElementsTemplate<osg::DrawElementsUInt>(tmpDe->getMode(), tmpDe->size(), &(tmpDe->front())); } } } // end osgUtil namespace <commit_msg>Improved readaibility of text by removing redundent indirection.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgUtil/ReversePrimitiveFunctor> #include <algorithm> template <typename Type> osg::PrimitiveSet * drawElementsTemplate(GLenum mode,GLsizei count, const typename Type::value_type* indices) { if (indices==0 || count==0) return NULL; Type * primitives = new Type(mode); primitives->reserve(count); typedef const typename Type::value_type* IndexPointer; switch(mode) { case(GL_TRIANGLES): { IndexPointer ilast = &indices[count]; for (IndexPointer iptr=indices; iptr<ilast; iptr+=3) { primitives->push_back(*(iptr)); primitives->push_back(*(iptr+2)); primitives->push_back(*(iptr+1)); } break; } case (GL_QUADS): { IndexPointer ilast = &indices[count - 3]; for (IndexPointer iptr = indices; iptr<ilast; iptr+=4) { primitives->push_back(*(iptr)); primitives->push_back(*(iptr+3)); primitives->push_back(*(iptr+2)); primitives->push_back(*(iptr+1)); } break; } case (GL_TRIANGLE_STRIP): case (GL_QUAD_STRIP): { IndexPointer ilast = &indices[count]; for (IndexPointer iptr = indices; iptr<ilast; iptr+=2) { primitives->push_back(*(iptr+1)); primitives->push_back(*(iptr)); } break; } case (GL_TRIANGLE_FAN): { primitives->push_back(*indices); IndexPointer iptr = indices + 1; IndexPointer ilast = &indices[count]; primitives->resize(count); std::reverse_copy(iptr, ilast, primitives->begin() + 1); break; } case (GL_POLYGON): case (GL_POINTS): case (GL_LINES): case (GL_LINE_STRIP): case (GL_LINE_LOOP): { IndexPointer iptr = indices; IndexPointer ilast = &indices[count]; primitives->resize(count); std::reverse_copy(iptr, ilast, primitives->begin()); break; } default: break; } return primitives; } namespace osgUtil { void ReversePrimitiveFunctor::drawArrays(GLenum mode, GLint first, GLsizei count) { if (count==0) return ; osg::DrawElementsUInt * primitives = new osg::DrawElementsUInt(mode); primitives->reserve(count); GLint end = first + count; switch (mode) { case (GL_TRIANGLES): { for (GLint i=first; i<end; i+=3) { primitives->push_back(i); primitives->push_back(i+2); primitives->push_back(i+1); } break; } case (GL_QUADS): { for (GLint i=first; i<end; i+=4) { primitives->push_back(i); primitives->push_back(i+3); primitives->push_back(i+2); primitives->push_back(i+1); } break; } case (GL_TRIANGLE_STRIP): case (GL_QUAD_STRIP): { for (GLint i=first; i<end; i+=2) { primitives->push_back(i+1); primitives->push_back(i); } break; } case (GL_TRIANGLE_FAN): { primitives->push_back(first); for (GLint i=end-1; i>first; i--) primitives->push_back(i); break; } case (GL_POLYGON): case (GL_POINTS): case (GL_LINES): case (GL_LINE_STRIP): case (GL_LINE_LOOP): { for (GLint i=end-1; i>=first; i--) primitives->push_back(i); break; } default: break; } _reversedPrimitiveSet = primitives; } void ReversePrimitiveFunctor::drawElements(GLenum mode,GLsizei count,const GLubyte* indices) { _reversedPrimitiveSet = drawElementsTemplate<osg::DrawElementsUByte>(mode, count, indices); } void ReversePrimitiveFunctor::drawElements(GLenum mode,GLsizei count,const GLushort* indices) { _reversedPrimitiveSet = drawElementsTemplate<osg::DrawElementsUShort>(mode, count, indices); } void ReversePrimitiveFunctor::drawElements(GLenum mode,GLsizei count,const GLuint* indices) { _reversedPrimitiveSet = drawElementsTemplate<osg::DrawElementsUInt>(mode, count, indices); } void ReversePrimitiveFunctor::begin(GLenum mode) { if (_running) { OSG_WARN << "ReversePrimitiveFunctor : call \"begin\" without call \"end\"." << std::endl; } else { _running = true; _reversedPrimitiveSet = new osg::DrawElementsUInt(mode); } } void ReversePrimitiveFunctor::vertex(unsigned int pos) { if (_running == false) { OSG_WARN << "ReversePrimitiveFunctor : call \"vertex(" << pos << ")\" without call \"begin\"." << std::endl; } else { static_cast<osg::DrawElementsUInt*>(_reversedPrimitiveSet.get())->push_back(pos); } } void ReversePrimitiveFunctor::end() { if (_running == false) { OSG_WARN << "ReversePrimitiveFunctor : call \"end\" without call \"begin\"." << std::endl; } else { _running = false; osg::ref_ptr<osg::DrawElementsUInt> tmpDe(static_cast<osg::DrawElementsUInt*>(_reversedPrimitiveSet.get())); _reversedPrimitiveSet = drawElementsTemplate<osg::DrawElementsUInt>(tmpDe->getMode(), tmpDe->size(), &(tmpDe->front())); } } } // end osgUtil namespace <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: MNameMapper.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hjs $ $Date: 2004-06-25 18:33:16 $ * * 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): Darren Kenny * * ************************************************************************/ #ifndef _CONNECTIVITY_MAB_NAMEMAPPER_HXX_ #define _CONNECTIVITY_MAB_NAMEMAPPER_HXX_ 1 #include <map> // Mozilla includes #include <MNSInclude.hxx> // Star Includes #include <rtl/ustring.hxx> namespace connectivity { namespace mozab { class MNameMapper { private: struct ltstr { bool operator()( const ::rtl::OUString &s1, const ::rtl::OUString &s2) const; }; typedef ::std::multimap< ::rtl::OUString, nsIAbDirectory *, ltstr > dirMap; typedef ::std::multimap< ::rtl::OUString, nsIAbDirectory *, ltstr > uriMap; static MNameMapper *instance; dirMap *mDirMap; uriMap *mUriMap; //clear dirs void clear(); public: static MNameMapper* getInstance(); MNameMapper(); ~MNameMapper(); // May modify the name passed in so that it's unique nsresult add( ::rtl::OUString& str, nsIAbDirectory* abook ); //reset dirs void reset(); // Will replace the given dir void replace( const ::rtl::OUString& str, nsIAbDirectory* abook ); // Get the directory corresponding to str bool getDir( const ::rtl::OUString& str, nsIAbDirectory* *abook ); }; } } #endif //_CONNECTIVITY_MAB_NAMEMAPPER_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.3.138); FILE MERGED 2005/09/05 17:24:36 rt 1.3.138.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MNameMapper.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 06:29:16 $ * * 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 _CONNECTIVITY_MAB_NAMEMAPPER_HXX_ #define _CONNECTIVITY_MAB_NAMEMAPPER_HXX_ 1 #include <map> // Mozilla includes #include <MNSInclude.hxx> // Star Includes #include <rtl/ustring.hxx> namespace connectivity { namespace mozab { class MNameMapper { private: struct ltstr { bool operator()( const ::rtl::OUString &s1, const ::rtl::OUString &s2) const; }; typedef ::std::multimap< ::rtl::OUString, nsIAbDirectory *, ltstr > dirMap; typedef ::std::multimap< ::rtl::OUString, nsIAbDirectory *, ltstr > uriMap; static MNameMapper *instance; dirMap *mDirMap; uriMap *mUriMap; //clear dirs void clear(); public: static MNameMapper* getInstance(); MNameMapper(); ~MNameMapper(); // May modify the name passed in so that it's unique nsresult add( ::rtl::OUString& str, nsIAbDirectory* abook ); //reset dirs void reset(); // Will replace the given dir void replace( const ::rtl::OUString& str, nsIAbDirectory* abook ); // Get the directory corresponding to str bool getDir( const ::rtl::OUString& str, nsIAbDirectory* *abook ); }; } } #endif //_CONNECTIVITY_MAB_NAMEMAPPER_HXX_ <|endoftext|>
<commit_before>/* * Copyright (c) 2021, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <openthread/config.h> #include "test_platform.h" #include "test_util.hpp" #include "common/data.hpp" namespace ot { template <DataLengthType kDataLengthType> void TestData(void) { typedef Data<kDataLengthType> Data; const uint8_t kData[] = {0x12, 0x03, 0x19, 0x77}; const uint8_t kDataCopy[] = {0x12, 0x03, 0x19, 0x77}; Data data; Data data2; uint8_t buffer[sizeof(kData) + 1]; uint8_t u8; uint16_t u16; data.Clear(); data2.Clear(); VerifyOrQuit(data.GetLength() == 0); VerifyOrQuit(data.GetBytes() == nullptr); VerifyOrQuit(data == data2); VerifyOrQuit(data.StartsWith(data)); VerifyOrQuit(data2.StartsWith(data)); data.Init(kData, sizeof(kData)); VerifyOrQuit(data.GetLength() == sizeof(kData)); VerifyOrQuit(data.GetBytes() == &kData[0]); VerifyOrQuit(data == data); VerifyOrQuit(data.StartsWith(data)); memset(buffer, 0, sizeof(buffer)); data.CopyBytesTo(buffer); VerifyOrQuit(memcmp(buffer, kData, sizeof(kData)) == 0); VerifyOrQuit(buffer[sizeof(kData)] == 0); VerifyOrQuit(data.MatchesBytesIn(buffer)); data2.InitFrom(kDataCopy); VerifyOrQuit(data2.GetLength() == sizeof(kDataCopy)); VerifyOrQuit(data2.GetBytes() == &kDataCopy[0]); VerifyOrQuit(data == data2); VerifyOrQuit(data.StartsWith(data2)); VerifyOrQuit(data2.StartsWith(data)); data2.SetLength(sizeof(kDataCopy) - 1); VerifyOrQuit(data2.GetLength() == sizeof(kDataCopy) - 1); VerifyOrQuit(data2.GetBytes() == &kDataCopy[0]); VerifyOrQuit(data2.MatchesBytesIn(kDataCopy)); VerifyOrQuit(data != data2); VerifyOrQuit(data.StartsWith(data2)); VerifyOrQuit(!data2.StartsWith(data)); data2.InitFromRange(&kDataCopy[0], &kDataCopy[2]); VerifyOrQuit(data2.GetLength() == 2); VerifyOrQuit(data2.GetBytes() == &kDataCopy[0]); VerifyOrQuit(data != data2); VerifyOrQuit(data.StartsWith(data2)); VerifyOrQuit(!data2.StartsWith(data)); data2 = data; VerifyOrQuit(data2 == data); data.Clear(); VerifyOrQuit(data.GetLength() == 0); VerifyOrQuit(data.GetBytes() == nullptr); VerifyOrQuit(data != data2); VerifyOrQuit(!data.StartsWith(data2)); VerifyOrQuit(data2.StartsWith(data)); memset(buffer, 0xaa, sizeof(buffer)); data.CopyBytesTo(buffer); VerifyOrQuit(buffer[0] == 0xaa); data.InitFrom(u8); VerifyOrQuit(data.GetLength() == sizeof(u8)); VerifyOrQuit(data.GetBytes() == &u8); data.InitFrom(u16); VerifyOrQuit(data.GetLength() == sizeof(u16)); VerifyOrQuit(data.GetBytes() == reinterpret_cast<uint8_t *>(&u16)); printf("- TestData<%s> passed\n", kDataLengthType == kWithUint8Length ? "kWithUint8Length" : "kWithUint16Length"); } template <DataLengthType kDataLengthType> void TestMutableData(void) { typedef Data<kDataLengthType> Data; typedef MutableData<kDataLengthType> MutableData; constexpr uint8_t kMaxSize = 20; const uint8_t kData[] = {10, 20, 3, 15, 10, 00, 60, 16}; const uint8_t kData2[] = {0xab, 0xbc, 0xcd, 0xde, 0xef}; MutableData mutableData; Data data; uint8_t buffer[kMaxSize]; uint8_t u8; uint16_t u16; data.Init(kData, sizeof(kData)); mutableData.Clear(); VerifyOrQuit(mutableData.GetLength() == 0); VerifyOrQuit(mutableData.GetBytes() == nullptr); mutableData.Init(buffer, sizeof(buffer)); VerifyOrQuit(mutableData.GetLength() == sizeof(buffer)); VerifyOrQuit(mutableData.GetBytes() == &buffer[0]); SuccessOrQuit(mutableData.CopyBytesFrom(kData, sizeof(kData))); VerifyOrQuit(mutableData.GetLength() == sizeof(kData)); VerifyOrQuit(mutableData.GetBytes() == &buffer[0]); VerifyOrQuit(mutableData == data); SuccessOrQuit(mutableData.CopyBytesFrom(kData2, sizeof(kData2))); VerifyOrQuit(mutableData.GetLength() == sizeof(kData2)); VerifyOrQuit(mutableData.GetBytes() == &buffer[0]); VerifyOrQuit(memcmp(mutableData.GetBytes(), kData2, sizeof(kData2)) == 0); memset(buffer, 0, sizeof(buffer)); mutableData.InitFrom(buffer); SuccessOrQuit(mutableData.CopyBytesFrom(kData, sizeof(kData))); VerifyOrQuit(mutableData == data); memset(buffer, 0, sizeof(buffer)); SuccessOrQuit(mutableData.CopyBytesFrom(data)); VerifyOrQuit(mutableData == data); memset(buffer, 0, sizeof(buffer)); mutableData.InitFromRange(&buffer[0], &buffer[2]); VerifyOrQuit(mutableData.GetLength() == 2); VerifyOrQuit(mutableData.GetBytes() == &buffer[0]); VerifyOrQuit(mutableData.CopyBytesFrom(kData, sizeof(kData)) == kErrorNoBufs); VerifyOrQuit(mutableData.GetLength() == 2); VerifyOrQuit(mutableData.GetBytes() == &buffer[0]); VerifyOrQuit(memcmp(mutableData.GetBytes(), kData, 2) == 0); VerifyOrQuit(mutableData.CopyBytesFrom(data) == kErrorNoBufs); VerifyOrQuit(mutableData.GetLength() == 2); VerifyOrQuit(mutableData.GetBytes() == &buffer[0]); VerifyOrQuit(memcmp(mutableData.GetBytes(), kData, 2) == 0); memset(buffer, 0xff, sizeof(buffer)); mutableData.InitFrom(buffer); VerifyOrQuit(mutableData.GetLength() == sizeof(buffer)); VerifyOrQuit(mutableData.GetBytes() == &buffer[0]); u8 = 0xaa; mutableData.InitFrom(u8); VerifyOrQuit(mutableData.GetLength() == sizeof(u8)); VerifyOrQuit(mutableData.GetBytes() == &u8); mutableData.ClearBytes(); VerifyOrQuit(u8 == 0); u16 = 0x1234; mutableData.InitFrom(u16); VerifyOrQuit(mutableData.GetLength() == sizeof(u16)); VerifyOrQuit(mutableData.GetBytes() == reinterpret_cast<uint8_t *>(&u16)); mutableData.ClearBytes(); VerifyOrQuit(u16 == 0); printf("- TestMutableData<%s> passed\n", kDataLengthType == kWithUint8Length ? "kWithUint8Length" : "kWithUint16Length"); } } // namespace ot int main(void) { ot::TestData<ot::kWithUint8Length>(); ot::TestData<ot::kWithUint16Length>(); ot::TestMutableData<ot::kWithUint8Length>(); ot::TestMutableData<ot::kWithUint16Length>(); printf("All tests passed\n"); return 0; } <commit_msg>[test] address uninitialized reference use warning (#7459)<commit_after>/* * Copyright (c) 2021, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <openthread/config.h> #include "test_platform.h" #include "test_util.hpp" #include "common/data.hpp" namespace ot { template <DataLengthType kDataLengthType> void TestData(void) { typedef Data<kDataLengthType> Data; const uint8_t kData[] = {0x12, 0x03, 0x19, 0x77}; const uint8_t kDataCopy[] = {0x12, 0x03, 0x19, 0x77}; Data data; Data data2; uint8_t buffer[sizeof(kData) + 1]; uint8_t u8 = 0x12; uint16_t u16 = 0x3456; data.Clear(); data2.Clear(); VerifyOrQuit(data.GetLength() == 0); VerifyOrQuit(data.GetBytes() == nullptr); VerifyOrQuit(data == data2); VerifyOrQuit(data.StartsWith(data)); VerifyOrQuit(data2.StartsWith(data)); data.Init(kData, sizeof(kData)); VerifyOrQuit(data.GetLength() == sizeof(kData)); VerifyOrQuit(data.GetBytes() == &kData[0]); VerifyOrQuit(data == data); VerifyOrQuit(data.StartsWith(data)); memset(buffer, 0, sizeof(buffer)); data.CopyBytesTo(buffer); VerifyOrQuit(memcmp(buffer, kData, sizeof(kData)) == 0); VerifyOrQuit(buffer[sizeof(kData)] == 0); VerifyOrQuit(data.MatchesBytesIn(buffer)); data2.InitFrom(kDataCopy); VerifyOrQuit(data2.GetLength() == sizeof(kDataCopy)); VerifyOrQuit(data2.GetBytes() == &kDataCopy[0]); VerifyOrQuit(data == data2); VerifyOrQuit(data.StartsWith(data2)); VerifyOrQuit(data2.StartsWith(data)); data2.SetLength(sizeof(kDataCopy) - 1); VerifyOrQuit(data2.GetLength() == sizeof(kDataCopy) - 1); VerifyOrQuit(data2.GetBytes() == &kDataCopy[0]); VerifyOrQuit(data2.MatchesBytesIn(kDataCopy)); VerifyOrQuit(data != data2); VerifyOrQuit(data.StartsWith(data2)); VerifyOrQuit(!data2.StartsWith(data)); data2.InitFromRange(&kDataCopy[0], &kDataCopy[2]); VerifyOrQuit(data2.GetLength() == 2); VerifyOrQuit(data2.GetBytes() == &kDataCopy[0]); VerifyOrQuit(data != data2); VerifyOrQuit(data.StartsWith(data2)); VerifyOrQuit(!data2.StartsWith(data)); data2 = data; VerifyOrQuit(data2 == data); data.Clear(); VerifyOrQuit(data.GetLength() == 0); VerifyOrQuit(data.GetBytes() == nullptr); VerifyOrQuit(data != data2); VerifyOrQuit(!data.StartsWith(data2)); VerifyOrQuit(data2.StartsWith(data)); memset(buffer, 0xaa, sizeof(buffer)); data.CopyBytesTo(buffer); VerifyOrQuit(buffer[0] == 0xaa); data.InitFrom(u8); VerifyOrQuit(data.GetLength() == sizeof(u8)); VerifyOrQuit(data.GetBytes() == &u8); data.InitFrom(u16); VerifyOrQuit(data.GetLength() == sizeof(u16)); VerifyOrQuit(data.GetBytes() == reinterpret_cast<uint8_t *>(&u16)); printf("- TestData<%s> passed\n", kDataLengthType == kWithUint8Length ? "kWithUint8Length" : "kWithUint16Length"); } template <DataLengthType kDataLengthType> void TestMutableData(void) { typedef Data<kDataLengthType> Data; typedef MutableData<kDataLengthType> MutableData; constexpr uint8_t kMaxSize = 20; const uint8_t kData[] = {10, 20, 3, 15, 10, 00, 60, 16}; const uint8_t kData2[] = {0xab, 0xbc, 0xcd, 0xde, 0xef}; MutableData mutableData; Data data; uint8_t buffer[kMaxSize]; uint8_t u8; uint16_t u16; data.Init(kData, sizeof(kData)); mutableData.Clear(); VerifyOrQuit(mutableData.GetLength() == 0); VerifyOrQuit(mutableData.GetBytes() == nullptr); mutableData.Init(buffer, sizeof(buffer)); VerifyOrQuit(mutableData.GetLength() == sizeof(buffer)); VerifyOrQuit(mutableData.GetBytes() == &buffer[0]); SuccessOrQuit(mutableData.CopyBytesFrom(kData, sizeof(kData))); VerifyOrQuit(mutableData.GetLength() == sizeof(kData)); VerifyOrQuit(mutableData.GetBytes() == &buffer[0]); VerifyOrQuit(mutableData == data); SuccessOrQuit(mutableData.CopyBytesFrom(kData2, sizeof(kData2))); VerifyOrQuit(mutableData.GetLength() == sizeof(kData2)); VerifyOrQuit(mutableData.GetBytes() == &buffer[0]); VerifyOrQuit(memcmp(mutableData.GetBytes(), kData2, sizeof(kData2)) == 0); memset(buffer, 0, sizeof(buffer)); mutableData.InitFrom(buffer); SuccessOrQuit(mutableData.CopyBytesFrom(kData, sizeof(kData))); VerifyOrQuit(mutableData == data); memset(buffer, 0, sizeof(buffer)); SuccessOrQuit(mutableData.CopyBytesFrom(data)); VerifyOrQuit(mutableData == data); memset(buffer, 0, sizeof(buffer)); mutableData.InitFromRange(&buffer[0], &buffer[2]); VerifyOrQuit(mutableData.GetLength() == 2); VerifyOrQuit(mutableData.GetBytes() == &buffer[0]); VerifyOrQuit(mutableData.CopyBytesFrom(kData, sizeof(kData)) == kErrorNoBufs); VerifyOrQuit(mutableData.GetLength() == 2); VerifyOrQuit(mutableData.GetBytes() == &buffer[0]); VerifyOrQuit(memcmp(mutableData.GetBytes(), kData, 2) == 0); VerifyOrQuit(mutableData.CopyBytesFrom(data) == kErrorNoBufs); VerifyOrQuit(mutableData.GetLength() == 2); VerifyOrQuit(mutableData.GetBytes() == &buffer[0]); VerifyOrQuit(memcmp(mutableData.GetBytes(), kData, 2) == 0); memset(buffer, 0xff, sizeof(buffer)); mutableData.InitFrom(buffer); VerifyOrQuit(mutableData.GetLength() == sizeof(buffer)); VerifyOrQuit(mutableData.GetBytes() == &buffer[0]); u8 = 0xaa; mutableData.InitFrom(u8); VerifyOrQuit(mutableData.GetLength() == sizeof(u8)); VerifyOrQuit(mutableData.GetBytes() == &u8); mutableData.ClearBytes(); VerifyOrQuit(u8 == 0); u16 = 0x1234; mutableData.InitFrom(u16); VerifyOrQuit(mutableData.GetLength() == sizeof(u16)); VerifyOrQuit(mutableData.GetBytes() == reinterpret_cast<uint8_t *>(&u16)); mutableData.ClearBytes(); VerifyOrQuit(u16 == 0); printf("- TestMutableData<%s> passed\n", kDataLengthType == kWithUint8Length ? "kWithUint8Length" : "kWithUint16Length"); } } // namespace ot int main(void) { ot::TestData<ot::kWithUint8Length>(); ot::TestData<ot::kWithUint16Length>(); ot::TestMutableData<ot::kWithUint8Length>(); ot::TestMutableData<ot::kWithUint16Length>(); printf("All tests passed\n"); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2018 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 "net/third_party/quiche/src/quic/core/legacy_quic_stream_id_manager.h" #include "net/third_party/quiche/src/quic/core/quic_session.h" #include "net/third_party/quiche/src/quic/core/quic_types.h" #include "net/third_party/quiche/src/quic/core/quic_utils.h" #include "net/third_party/quiche/src/quic/core/quic_versions.h" #include "net/third_party/quiche/src/quic/platform/api/quic_map_util.h" #include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h" namespace quic { LegacyQuicStreamIdManager::LegacyQuicStreamIdManager( Perspective perspective, QuicTransportVersion transport_version, size_t max_open_outgoing_streams, size_t max_open_incoming_streams) : perspective_(perspective), transport_version_(transport_version), max_open_outgoing_streams_(max_open_outgoing_streams), max_open_incoming_streams_(max_open_incoming_streams), next_outgoing_stream_id_( QuicUtils::GetFirstBidirectionalStreamId(transport_version_, perspective_)), largest_peer_created_stream_id_( perspective_ == Perspective::IS_SERVER ? (QuicVersionUsesCryptoFrames(transport_version_) ? QuicUtils::GetInvalidStreamId(transport_version_) : QuicUtils::GetCryptoStreamId(transport_version_)) : QuicUtils::GetInvalidStreamId(transport_version_)), num_open_incoming_streams_(0), num_open_outgoing_streams_(0), handles_accounting_( GetQuicReloadableFlag(quic_stream_id_manager_handles_accounting)) {} LegacyQuicStreamIdManager::~LegacyQuicStreamIdManager() {} bool LegacyQuicStreamIdManager::CanOpenNextOutgoingStream( size_t current_num_open_outgoing_streams) const { if (handles_accounting_) { DCHECK_LE(num_open_outgoing_streams_, max_open_outgoing_streams_); QUIC_DLOG_IF(INFO, num_open_outgoing_streams_ == max_open_outgoing_streams_) << "Failed to create a new outgoing stream. " << "Already " << num_open_outgoing_streams_ << " open."; return num_open_outgoing_streams_ < max_open_outgoing_streams_; } if (current_num_open_outgoing_streams >= max_open_outgoing_streams_) { QUIC_DLOG(INFO) << "Failed to create a new outgoing stream. " << "Already " << current_num_open_outgoing_streams << " open."; return false; } return true; } bool LegacyQuicStreamIdManager::CanOpenIncomingStream( size_t current_num_open_incoming_streams) const { if (handles_accounting_) { return num_open_incoming_streams_ < max_open_incoming_streams_; } // Check if the new number of open streams would cause the number of // open streams to exceed the limit. return current_num_open_incoming_streams < max_open_incoming_streams_; } bool LegacyQuicStreamIdManager::MaybeIncreaseLargestPeerStreamId( const QuicStreamId stream_id) { available_streams_.erase(stream_id); if (largest_peer_created_stream_id_ != QuicUtils::GetInvalidStreamId(transport_version_) && stream_id <= largest_peer_created_stream_id_) { return true; } // Check if the new number of available streams would cause the number of // available streams to exceed the limit. Note that the peer can create // only alternately-numbered streams. size_t additional_available_streams = (stream_id - largest_peer_created_stream_id_) / 2 - 1; if (largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(transport_version_)) { additional_available_streams = (stream_id + 1) / 2 - 1; } size_t new_num_available_streams = GetNumAvailableStreams() + additional_available_streams; if (new_num_available_streams > MaxAvailableStreams()) { QUIC_DLOG(INFO) << perspective_ << "Failed to create a new incoming stream with id:" << stream_id << ". There are already " << GetNumAvailableStreams() << " streams available, which would become " << new_num_available_streams << ", which exceeds the limit " << MaxAvailableStreams() << "."; return false; } QuicStreamId first_available_stream = largest_peer_created_stream_id_ + 2; if (largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(transport_version_)) { first_available_stream = QuicUtils::GetFirstBidirectionalStreamId( transport_version_, QuicUtils::InvertPerspective(perspective_)); } for (QuicStreamId id = first_available_stream; id < stream_id; id += 2) { available_streams_.insert(id); } largest_peer_created_stream_id_ = stream_id; return true; } QuicStreamId LegacyQuicStreamIdManager::GetNextOutgoingStreamId() { QuicStreamId id = next_outgoing_stream_id_; next_outgoing_stream_id_ += 2; return id; } void LegacyQuicStreamIdManager::ActivateStream(bool is_incoming) { DCHECK(handles_accounting_); if (is_incoming) { ++num_open_incoming_streams_; return; } ++num_open_outgoing_streams_; } void LegacyQuicStreamIdManager::OnStreamClosed(bool is_incoming) { DCHECK(handles_accounting_); if (is_incoming) { QUIC_BUG_IF(num_open_incoming_streams_ == 0); --num_open_incoming_streams_; return; } QUIC_BUG_IF(num_open_outgoing_streams_ == 0); --num_open_outgoing_streams_; } bool LegacyQuicStreamIdManager::IsAvailableStream(QuicStreamId id) const { if (!IsIncomingStream(id)) { // Stream IDs under next_ougoing_stream_id_ are either open or previously // open but now closed. return id >= next_outgoing_stream_id_; } // For peer created streams, we also need to consider available streams. return largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(transport_version_) || id > largest_peer_created_stream_id_ || QuicContainsKey(available_streams_, id); } bool LegacyQuicStreamIdManager::IsIncomingStream(QuicStreamId id) const { return id % 2 != next_outgoing_stream_id_ % 2; } size_t LegacyQuicStreamIdManager::GetNumAvailableStreams() const { return available_streams_.size(); } size_t LegacyQuicStreamIdManager::MaxAvailableStreams() const { return max_open_incoming_streams_ * kMaxAvailableStreamsMultiplier; } } // namespace quic <commit_msg>Add missing flag counts for gfe2_reloadable_flag_quic_record_frontend_service_vip_mapping and gfe2_reloadable_flag_quic_stream_id_manager_handles_accounting<commit_after>// Copyright (c) 2018 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 "net/third_party/quiche/src/quic/core/legacy_quic_stream_id_manager.h" #include "net/third_party/quiche/src/quic/core/quic_session.h" #include "net/third_party/quiche/src/quic/core/quic_types.h" #include "net/third_party/quiche/src/quic/core/quic_utils.h" #include "net/third_party/quiche/src/quic/core/quic_versions.h" #include "net/third_party/quiche/src/quic/platform/api/quic_map_util.h" #include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h" namespace quic { LegacyQuicStreamIdManager::LegacyQuicStreamIdManager( Perspective perspective, QuicTransportVersion transport_version, size_t max_open_outgoing_streams, size_t max_open_incoming_streams) : perspective_(perspective), transport_version_(transport_version), max_open_outgoing_streams_(max_open_outgoing_streams), max_open_incoming_streams_(max_open_incoming_streams), next_outgoing_stream_id_( QuicUtils::GetFirstBidirectionalStreamId(transport_version_, perspective_)), largest_peer_created_stream_id_( perspective_ == Perspective::IS_SERVER ? (QuicVersionUsesCryptoFrames(transport_version_) ? QuicUtils::GetInvalidStreamId(transport_version_) : QuicUtils::GetCryptoStreamId(transport_version_)) : QuicUtils::GetInvalidStreamId(transport_version_)), num_open_incoming_streams_(0), num_open_outgoing_streams_(0), handles_accounting_( GetQuicReloadableFlag(quic_stream_id_manager_handles_accounting)) { if (handles_accounting_) { QUIC_RELOADABLE_FLAG_COUNT(quic_stream_id_manager_handles_accounting); } } LegacyQuicStreamIdManager::~LegacyQuicStreamIdManager() {} bool LegacyQuicStreamIdManager::CanOpenNextOutgoingStream( size_t current_num_open_outgoing_streams) const { if (handles_accounting_) { DCHECK_LE(num_open_outgoing_streams_, max_open_outgoing_streams_); QUIC_DLOG_IF(INFO, num_open_outgoing_streams_ == max_open_outgoing_streams_) << "Failed to create a new outgoing stream. " << "Already " << num_open_outgoing_streams_ << " open."; return num_open_outgoing_streams_ < max_open_outgoing_streams_; } if (current_num_open_outgoing_streams >= max_open_outgoing_streams_) { QUIC_DLOG(INFO) << "Failed to create a new outgoing stream. " << "Already " << current_num_open_outgoing_streams << " open."; return false; } return true; } bool LegacyQuicStreamIdManager::CanOpenIncomingStream( size_t current_num_open_incoming_streams) const { if (handles_accounting_) { return num_open_incoming_streams_ < max_open_incoming_streams_; } // Check if the new number of open streams would cause the number of // open streams to exceed the limit. return current_num_open_incoming_streams < max_open_incoming_streams_; } bool LegacyQuicStreamIdManager::MaybeIncreaseLargestPeerStreamId( const QuicStreamId stream_id) { available_streams_.erase(stream_id); if (largest_peer_created_stream_id_ != QuicUtils::GetInvalidStreamId(transport_version_) && stream_id <= largest_peer_created_stream_id_) { return true; } // Check if the new number of available streams would cause the number of // available streams to exceed the limit. Note that the peer can create // only alternately-numbered streams. size_t additional_available_streams = (stream_id - largest_peer_created_stream_id_) / 2 - 1; if (largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(transport_version_)) { additional_available_streams = (stream_id + 1) / 2 - 1; } size_t new_num_available_streams = GetNumAvailableStreams() + additional_available_streams; if (new_num_available_streams > MaxAvailableStreams()) { QUIC_DLOG(INFO) << perspective_ << "Failed to create a new incoming stream with id:" << stream_id << ". There are already " << GetNumAvailableStreams() << " streams available, which would become " << new_num_available_streams << ", which exceeds the limit " << MaxAvailableStreams() << "."; return false; } QuicStreamId first_available_stream = largest_peer_created_stream_id_ + 2; if (largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(transport_version_)) { first_available_stream = QuicUtils::GetFirstBidirectionalStreamId( transport_version_, QuicUtils::InvertPerspective(perspective_)); } for (QuicStreamId id = first_available_stream; id < stream_id; id += 2) { available_streams_.insert(id); } largest_peer_created_stream_id_ = stream_id; return true; } QuicStreamId LegacyQuicStreamIdManager::GetNextOutgoingStreamId() { QuicStreamId id = next_outgoing_stream_id_; next_outgoing_stream_id_ += 2; return id; } void LegacyQuicStreamIdManager::ActivateStream(bool is_incoming) { DCHECK(handles_accounting_); if (is_incoming) { ++num_open_incoming_streams_; return; } ++num_open_outgoing_streams_; } void LegacyQuicStreamIdManager::OnStreamClosed(bool is_incoming) { DCHECK(handles_accounting_); if (is_incoming) { QUIC_BUG_IF(num_open_incoming_streams_ == 0); --num_open_incoming_streams_; return; } QUIC_BUG_IF(num_open_outgoing_streams_ == 0); --num_open_outgoing_streams_; } bool LegacyQuicStreamIdManager::IsAvailableStream(QuicStreamId id) const { if (!IsIncomingStream(id)) { // Stream IDs under next_ougoing_stream_id_ are either open or previously // open but now closed. return id >= next_outgoing_stream_id_; } // For peer created streams, we also need to consider available streams. return largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(transport_version_) || id > largest_peer_created_stream_id_ || QuicContainsKey(available_streams_, id); } bool LegacyQuicStreamIdManager::IsIncomingStream(QuicStreamId id) const { return id % 2 != next_outgoing_stream_id_ % 2; } size_t LegacyQuicStreamIdManager::GetNumAvailableStreams() const { return available_streams_.size(); } size_t LegacyQuicStreamIdManager::MaxAvailableStreams() const { return max_open_incoming_streams_ * kMaxAvailableStreamsMultiplier; } } // namespace quic <|endoftext|>
<commit_before>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkArenaAlloc.h" #include "SkAutoBlitterChoose.h" #include "SkComposeShader.h" #include "SkDraw.h" #include "SkNx.h" #include "SkPM4fPriv.h" #include "SkRasterClip.h" #include "SkScan.h" #include "SkShaderBase.h" #include "SkString.h" #include "SkVertState.h" #include "SkArenaAlloc.h" #include "SkCoreBlitters.h" #include "SkColorSpaceXform.h" #include "SkColorSpace_Base.h" struct Matrix43 { float fMat[12]; // column major Sk4f map(float x, float y) const { return Sk4f::Load(&fMat[0]) * x + Sk4f::Load(&fMat[4]) * y + Sk4f::Load(&fMat[8]); } void setConcat(const Matrix43& a, const SkMatrix& b) { fMat[ 0] = a.dot(0, b.getScaleX(), b.getSkewY()); fMat[ 1] = a.dot(1, b.getScaleX(), b.getSkewY()); fMat[ 2] = a.dot(2, b.getScaleX(), b.getSkewY()); fMat[ 3] = a.dot(3, b.getScaleX(), b.getSkewY()); fMat[ 4] = a.dot(0, b.getSkewX(), b.getScaleY()); fMat[ 5] = a.dot(1, b.getSkewX(), b.getScaleY()); fMat[ 6] = a.dot(2, b.getSkewX(), b.getScaleY()); fMat[ 7] = a.dot(3, b.getSkewX(), b.getScaleY()); fMat[ 8] = a.dot(0, b.getTranslateX(), b.getTranslateY()) + a.fMat[ 8]; fMat[ 9] = a.dot(1, b.getTranslateX(), b.getTranslateY()) + a.fMat[ 9]; fMat[10] = a.dot(2, b.getTranslateX(), b.getTranslateY()) + a.fMat[10]; fMat[11] = a.dot(3, b.getTranslateX(), b.getTranslateY()) + a.fMat[11]; } private: float dot(int index, float x, float y) const { return fMat[index + 0] * x + fMat[index + 4] * y; } }; static SkScan::HairRCProc ChooseHairProc(bool doAntiAlias) { return doAntiAlias ? SkScan::AntiHairLine : SkScan::HairLine; } static bool texture_to_matrix(const VertState& state, const SkPoint verts[], const SkPoint texs[], SkMatrix* matrix) { SkPoint src[3], dst[3]; src[0] = texs[state.f0]; src[1] = texs[state.f1]; src[2] = texs[state.f2]; dst[0] = verts[state.f0]; dst[1] = verts[state.f1]; dst[2] = verts[state.f2]; return matrix->setPolyToPoly(src, dst, 3); } class SkTriColorShader : public SkShaderBase { public: SkTriColorShader(bool isOpaque) : fIsOpaque(isOpaque) {} Matrix43* getMatrix43() { return &fM43; } bool isOpaque() const override { return fIsOpaque; } SK_TO_STRING_OVERRIDE() // For serialization. This will never be called. Factory getFactory() const override { sk_throw(); return nullptr; } protected: Context* onMakeContext(const ContextRec& rec, SkArenaAlloc* alloc) const override { return nullptr; } bool onAppendStages(SkRasterPipeline* pipeline, SkColorSpace* dstCS, SkArenaAlloc* alloc, const SkMatrix&, const SkPaint&, const SkMatrix*) const override { pipeline->append(SkRasterPipeline::seed_shader); pipeline->append(SkRasterPipeline::matrix_4x3, &fM43); // In theory we should never need to clamp. However, either due to imprecision in our // matrix43, or the scan converter passing us pixel centers that in fact are not within // the triangle, we do see occasional (slightly) out-of-range values, so we add these // clamp stages. It would be nice to find a way to detect when these are not needed. pipeline->append(SkRasterPipeline::clamp_0); pipeline->append(SkRasterPipeline::clamp_a); return true; } private: Matrix43 fM43; const bool fIsOpaque; typedef SkShaderBase INHERITED; }; #ifndef SK_IGNORE_TO_STRING void SkTriColorShader::toString(SkString* str) const { str->append("SkTriColorShader: ("); this->INHERITED::toString(str); str->append(")"); } #endif static bool update_tricolor_matrix(const SkMatrix& ctmInv, const SkPoint pts[], const SkPM4f colors[], int index0, int index1, int index2, Matrix43* result) { SkMatrix m, im; m.reset(); m.set(0, pts[index1].fX - pts[index0].fX); m.set(1, pts[index2].fX - pts[index0].fX); m.set(2, pts[index0].fX); m.set(3, pts[index1].fY - pts[index0].fY); m.set(4, pts[index2].fY - pts[index0].fY); m.set(5, pts[index0].fY); if (!m.invert(&im)) { return false; } SkMatrix dstToUnit; dstToUnit.setConcat(im, ctmInv); Sk4f c0 = colors[index0].to4f(), c1 = colors[index1].to4f(), c2 = colors[index2].to4f(); Matrix43 colorm; (c1 - c0).store(&colorm.fMat[0]); (c2 - c0).store(&colorm.fMat[4]); c0.store(&colorm.fMat[8]); result->setConcat(colorm, dstToUnit); return true; } // Convert the SkColors into float colors. The conversion depends on some conditions: // - If the pixmap has a dst colorspace, we have to be "color-correct". // Do we map into dst-colorspace before or after we interpolate? // - We have to decide when to apply per-color alpha (before or after we interpolate) // // For now, we will take a simple approach, but recognize this is just a start: // - convert colors into dst colorspace before interpolation (matches gradients) // - apply per-color alpha before interpolation (matches old version of vertices) // static SkPM4f* convert_colors(const SkColor src[], int count, SkColorSpace* deviceCS, SkArenaAlloc* alloc) { SkPM4f* dst = alloc->makeArray<SkPM4f>(count); if (!deviceCS) { for (int i = 0; i < count; ++i) { dst[i] = SkPM4f_from_SkColor(src[i], nullptr); } } else { auto srcCS = SkColorSpace::MakeSRGB(); auto dstCS = as_CSB(deviceCS)->makeLinearGamma(); SkColorSpaceXform::Apply(dstCS.get(), SkColorSpaceXform::kRGBA_F32_ColorFormat, dst, srcCS.get(), SkColorSpaceXform::kBGRA_8888_ColorFormat, src, count, SkColorSpaceXform::kPremul_AlphaOp); } return dst; } static bool compute_is_opaque(const SkColor colors[], int count) { uint32_t c = ~0; for (int i = 0; i < count; ++i) { c &= colors[i]; } return SkColorGetA(c) == 0xFF; } void SkDraw::drawVertices(SkVertices::VertexMode vmode, int count, const SkPoint vertices[], const SkPoint textures[], const SkColor colors[], SkBlendMode bmode, const uint16_t indices[], int indexCount, const SkPaint& paint) const { SkASSERT(0 == count || vertices); // abort early if there is nothing to draw if (count < 3 || (indices && indexCount < 3) || fRC->isEmpty()) { return; } SkMatrix ctmInv; if (!fMatrix->invert(&ctmInv)) { return; } // make textures and shader mutually consistent SkShader* shader = paint.getShader(); if (!(shader && textures)) { shader = nullptr; textures = nullptr; } constexpr size_t defCount = 16; constexpr size_t outerSize = sizeof(SkTriColorShader) + sizeof(SkComposeShader) + (sizeof(SkPoint) + sizeof(SkPM4f)) * defCount; SkSTArenaAlloc<outerSize> outerAlloc; SkPoint* devVerts = outerAlloc.makeArray<SkPoint>(count); fMatrix->mapPoints(devVerts, vertices, count); VertState state(count, indices, indexCount); VertState::Proc vertProc = state.chooseProc(vmode); if (colors || textures) { SkPM4f* dstColors = nullptr; Matrix43* matrix43 = nullptr; if (colors) { dstColors = convert_colors(colors, count, fDst.colorSpace(), &outerAlloc); SkTriColorShader* triShader = outerAlloc.make<SkTriColorShader>( compute_is_opaque(colors, count)); matrix43 = triShader->getMatrix43(); if (shader) { shader = outerAlloc.make<SkComposeShader>(sk_ref_sp(triShader), sk_ref_sp(shader), bmode); } else { shader = triShader; } } SkPaint p(paint); p.setShader(sk_ref_sp(shader)); if (!textures) { // only tricolor shader SkASSERT(matrix43); auto blitter = SkCreateRasterPipelineBlitter(fDst, p, *fMatrix, &outerAlloc); while (vertProc(&state)) { if (!update_tricolor_matrix(ctmInv, vertices, dstColors, state.f0, state.f1, state.f2, matrix43)) { continue; } SkPoint tmp[] = { devVerts[state.f0], devVerts[state.f1], devVerts[state.f2] }; SkScan::FillTriangle(tmp, *fRC, blitter); } } else { while (vertProc(&state)) { SkSTArenaAlloc<2048> innerAlloc; const SkMatrix* ctm = fMatrix; SkMatrix tmpCtm; if (textures) { SkMatrix localM; texture_to_matrix(state, vertices, textures, &localM); tmpCtm = SkMatrix::Concat(*fMatrix, localM); ctm = &tmpCtm; } if (matrix43 && !update_tricolor_matrix(ctmInv, vertices, dstColors, state.f0, state.f1, state.f2, matrix43)) { continue; } SkPoint tmp[] = { devVerts[state.f0], devVerts[state.f1], devVerts[state.f2] }; auto blitter = SkCreateRasterPipelineBlitter(fDst, p, *ctm, &innerAlloc); SkScan::FillTriangle(tmp, *fRC, blitter); } } } else { // no colors[] and no texture, stroke hairlines with paint's color. SkPaint p; p.setStyle(SkPaint::kStroke_Style); SkAutoBlitterChoose blitter(fDst, *fMatrix, p); // Abort early if we failed to create a shader context. if (blitter->isNullBlitter()) { return; } SkScan::HairRCProc hairProc = ChooseHairProc(paint.isAntiAlias()); const SkRasterClip& clip = *fRC; while (vertProc(&state)) { SkPoint array[] = { devVerts[state.f0], devVerts[state.f1], devVerts[state.f2], devVerts[state.f0] }; hairProc(array, 4, clip, blitter.get()); } } } <commit_msg>simplify verts in certain modes<commit_after>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkArenaAlloc.h" #include "SkAutoBlitterChoose.h" #include "SkComposeShader.h" #include "SkDraw.h" #include "SkNx.h" #include "SkPM4fPriv.h" #include "SkRasterClip.h" #include "SkScan.h" #include "SkShaderBase.h" #include "SkString.h" #include "SkVertState.h" #include "SkArenaAlloc.h" #include "SkCoreBlitters.h" #include "SkColorSpaceXform.h" #include "SkColorSpace_Base.h" struct Matrix43 { float fMat[12]; // column major Sk4f map(float x, float y) const { return Sk4f::Load(&fMat[0]) * x + Sk4f::Load(&fMat[4]) * y + Sk4f::Load(&fMat[8]); } void setConcat(const Matrix43& a, const SkMatrix& b) { fMat[ 0] = a.dot(0, b.getScaleX(), b.getSkewY()); fMat[ 1] = a.dot(1, b.getScaleX(), b.getSkewY()); fMat[ 2] = a.dot(2, b.getScaleX(), b.getSkewY()); fMat[ 3] = a.dot(3, b.getScaleX(), b.getSkewY()); fMat[ 4] = a.dot(0, b.getSkewX(), b.getScaleY()); fMat[ 5] = a.dot(1, b.getSkewX(), b.getScaleY()); fMat[ 6] = a.dot(2, b.getSkewX(), b.getScaleY()); fMat[ 7] = a.dot(3, b.getSkewX(), b.getScaleY()); fMat[ 8] = a.dot(0, b.getTranslateX(), b.getTranslateY()) + a.fMat[ 8]; fMat[ 9] = a.dot(1, b.getTranslateX(), b.getTranslateY()) + a.fMat[ 9]; fMat[10] = a.dot(2, b.getTranslateX(), b.getTranslateY()) + a.fMat[10]; fMat[11] = a.dot(3, b.getTranslateX(), b.getTranslateY()) + a.fMat[11]; } private: float dot(int index, float x, float y) const { return fMat[index + 0] * x + fMat[index + 4] * y; } }; static SkScan::HairRCProc ChooseHairProc(bool doAntiAlias) { return doAntiAlias ? SkScan::AntiHairLine : SkScan::HairLine; } static bool texture_to_matrix(const VertState& state, const SkPoint verts[], const SkPoint texs[], SkMatrix* matrix) { SkPoint src[3], dst[3]; src[0] = texs[state.f0]; src[1] = texs[state.f1]; src[2] = texs[state.f2]; dst[0] = verts[state.f0]; dst[1] = verts[state.f1]; dst[2] = verts[state.f2]; return matrix->setPolyToPoly(src, dst, 3); } class SkTriColorShader : public SkShaderBase { public: SkTriColorShader(bool isOpaque) : fIsOpaque(isOpaque) {} Matrix43* getMatrix43() { return &fM43; } bool isOpaque() const override { return fIsOpaque; } SK_TO_STRING_OVERRIDE() // For serialization. This will never be called. Factory getFactory() const override { sk_throw(); return nullptr; } protected: Context* onMakeContext(const ContextRec& rec, SkArenaAlloc* alloc) const override { return nullptr; } bool onAppendStages(SkRasterPipeline* pipeline, SkColorSpace* dstCS, SkArenaAlloc* alloc, const SkMatrix&, const SkPaint&, const SkMatrix*) const override { pipeline->append(SkRasterPipeline::seed_shader); pipeline->append(SkRasterPipeline::matrix_4x3, &fM43); // In theory we should never need to clamp. However, either due to imprecision in our // matrix43, or the scan converter passing us pixel centers that in fact are not within // the triangle, we do see occasional (slightly) out-of-range values, so we add these // clamp stages. It would be nice to find a way to detect when these are not needed. pipeline->append(SkRasterPipeline::clamp_0); pipeline->append(SkRasterPipeline::clamp_a); return true; } private: Matrix43 fM43; const bool fIsOpaque; typedef SkShaderBase INHERITED; }; #ifndef SK_IGNORE_TO_STRING void SkTriColorShader::toString(SkString* str) const { str->append("SkTriColorShader: ("); this->INHERITED::toString(str); str->append(")"); } #endif static bool update_tricolor_matrix(const SkMatrix& ctmInv, const SkPoint pts[], const SkPM4f colors[], int index0, int index1, int index2, Matrix43* result) { SkMatrix m, im; m.reset(); m.set(0, pts[index1].fX - pts[index0].fX); m.set(1, pts[index2].fX - pts[index0].fX); m.set(2, pts[index0].fX); m.set(3, pts[index1].fY - pts[index0].fY); m.set(4, pts[index2].fY - pts[index0].fY); m.set(5, pts[index0].fY); if (!m.invert(&im)) { return false; } SkMatrix dstToUnit; dstToUnit.setConcat(im, ctmInv); Sk4f c0 = colors[index0].to4f(), c1 = colors[index1].to4f(), c2 = colors[index2].to4f(); Matrix43 colorm; (c1 - c0).store(&colorm.fMat[0]); (c2 - c0).store(&colorm.fMat[4]); c0.store(&colorm.fMat[8]); result->setConcat(colorm, dstToUnit); return true; } // Convert the SkColors into float colors. The conversion depends on some conditions: // - If the pixmap has a dst colorspace, we have to be "color-correct". // Do we map into dst-colorspace before or after we interpolate? // - We have to decide when to apply per-color alpha (before or after we interpolate) // // For now, we will take a simple approach, but recognize this is just a start: // - convert colors into dst colorspace before interpolation (matches gradients) // - apply per-color alpha before interpolation (matches old version of vertices) // static SkPM4f* convert_colors(const SkColor src[], int count, SkColorSpace* deviceCS, SkArenaAlloc* alloc) { SkPM4f* dst = alloc->makeArray<SkPM4f>(count); if (!deviceCS) { for (int i = 0; i < count; ++i) { dst[i] = SkPM4f_from_SkColor(src[i], nullptr); } } else { auto srcCS = SkColorSpace::MakeSRGB(); auto dstCS = as_CSB(deviceCS)->makeLinearGamma(); SkColorSpaceXform::Apply(dstCS.get(), SkColorSpaceXform::kRGBA_F32_ColorFormat, dst, srcCS.get(), SkColorSpaceXform::kBGRA_8888_ColorFormat, src, count, SkColorSpaceXform::kPremul_AlphaOp); } return dst; } static bool compute_is_opaque(const SkColor colors[], int count) { uint32_t c = ~0; for (int i = 0; i < count; ++i) { c &= colors[i]; } return SkColorGetA(c) == 0xFF; } void SkDraw::drawVertices(SkVertices::VertexMode vmode, int count, const SkPoint vertices[], const SkPoint textures[], const SkColor colors[], SkBlendMode bmode, const uint16_t indices[], int indexCount, const SkPaint& paint) const { SkASSERT(0 == count || vertices); // abort early if there is nothing to draw if (count < 3 || (indices && indexCount < 3) || fRC->isEmpty()) { return; } SkMatrix ctmInv; if (!fMatrix->invert(&ctmInv)) { return; } // make textures and shader mutually consistent SkShader* shader = paint.getShader(); if (!(shader && textures)) { shader = nullptr; textures = nullptr; } // We can simplify things for certain blendmodes. This is for speed, and SkComposeShader // itself insists we don't pass kSrc or kDst to it. // if (colors && textures) { switch (bmode) { case SkBlendMode::kSrc: colors = nullptr; break; case SkBlendMode::kDst: textures = nullptr; break; default: break; } } // we don't use the shader if there are no textures if (!textures) { shader = nullptr; } constexpr size_t defCount = 16; constexpr size_t outerSize = sizeof(SkTriColorShader) + sizeof(SkComposeShader) + (sizeof(SkPoint) + sizeof(SkPM4f)) * defCount; SkSTArenaAlloc<outerSize> outerAlloc; SkPoint* devVerts = outerAlloc.makeArray<SkPoint>(count); fMatrix->mapPoints(devVerts, vertices, count); VertState state(count, indices, indexCount); VertState::Proc vertProc = state.chooseProc(vmode); if (colors || textures) { SkPM4f* dstColors = nullptr; Matrix43* matrix43 = nullptr; if (colors) { dstColors = convert_colors(colors, count, fDst.colorSpace(), &outerAlloc); SkTriColorShader* triShader = outerAlloc.make<SkTriColorShader>( compute_is_opaque(colors, count)); matrix43 = triShader->getMatrix43(); if (shader) { shader = outerAlloc.make<SkComposeShader>(sk_ref_sp(triShader), sk_ref_sp(shader), bmode); } else { shader = triShader; } } SkPaint p(paint); p.setShader(sk_ref_sp(shader)); if (!textures) { // only tricolor shader SkASSERT(matrix43); auto blitter = SkCreateRasterPipelineBlitter(fDst, p, *fMatrix, &outerAlloc); while (vertProc(&state)) { if (!update_tricolor_matrix(ctmInv, vertices, dstColors, state.f0, state.f1, state.f2, matrix43)) { continue; } SkPoint tmp[] = { devVerts[state.f0], devVerts[state.f1], devVerts[state.f2] }; SkScan::FillTriangle(tmp, *fRC, blitter); } } else { while (vertProc(&state)) { SkSTArenaAlloc<2048> innerAlloc; const SkMatrix* ctm = fMatrix; SkMatrix tmpCtm; if (textures) { SkMatrix localM; texture_to_matrix(state, vertices, textures, &localM); tmpCtm = SkMatrix::Concat(*fMatrix, localM); ctm = &tmpCtm; } if (matrix43 && !update_tricolor_matrix(ctmInv, vertices, dstColors, state.f0, state.f1, state.f2, matrix43)) { continue; } SkPoint tmp[] = { devVerts[state.f0], devVerts[state.f1], devVerts[state.f2] }; auto blitter = SkCreateRasterPipelineBlitter(fDst, p, *ctm, &innerAlloc); SkScan::FillTriangle(tmp, *fRC, blitter); } } } else { // no colors[] and no texture, stroke hairlines with paint's color. SkPaint p; p.setStyle(SkPaint::kStroke_Style); SkAutoBlitterChoose blitter(fDst, *fMatrix, p); // Abort early if we failed to create a shader context. if (blitter->isNullBlitter()) { return; } SkScan::HairRCProc hairProc = ChooseHairProc(paint.isAntiAlias()); const SkRasterClip& clip = *fRC; while (vertProc(&state)) { SkPoint array[] = { devVerts[state.f0], devVerts[state.f1], devVerts[state.f2], devVerts[state.f0] }; hairProc(array, 4, clip, blitter.get()); } } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $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 "qmltransitionmanager_p_p.h" #include "qmlstate_p_p.h" #include <qmlbinding.h> QT_BEGIN_NAMESPACE class QmlTransitionManagerPrivate { public: QmlTransitionManagerPrivate() : state(0), transition(0) {} void applyBindings(); typedef QList<SimpleAction> SimpleActionList; QmlState *state; QmlTransition *transition; QmlStateOperation::ActionList bindingsList; SimpleActionList completeList; }; QmlTransitionManager::QmlTransitionManager() : d(new QmlTransitionManagerPrivate) { } void QmlTransitionManager::setState(QmlState *s) { d->state = s; } QmlTransitionManager::~QmlTransitionManager() { delete d; d = 0; } void QmlTransitionManager::complete() { d->applyBindings(); for (int ii = 0; ii < d->completeList.count(); ++ii) { const QmlMetaProperty &prop = d->completeList.at(ii).property; prop.write(d->completeList.at(ii).value); } d->completeList.clear(); if (d->state) static_cast<QmlStatePrivate*>(QObjectPrivate::get(d->state))->complete(); } void QmlTransitionManagerPrivate::applyBindings() { foreach(const Action &action, bindingsList) { if (action.toBinding) { action.property.setBinding(action.toBinding); } else if (action.event) { if (action.reverseEvent) action.event->reverse(); else action.event->execute(); } } bindingsList.clear(); } void QmlTransitionManager::transition(const QList<Action> &list, QmlTransition *transition) { cancel(); QmlStateOperation::ActionList applyList = list; // Determine which actions are binding changes. foreach(const Action &action, applyList) { if (action.toBinding) d->bindingsList << action; if (action.fromBinding) action.property.setBinding(0); // Disable current binding if (action.event && action.event->changesBindings()) { //### assume isReversable()? d->bindingsList << action; if (action.reverseEvent) action.event->clearReverseBindings(); else action.event->clearForwardBindings(); } } // Animated transitions need both the start and the end value for // each property change. In the presence of bindings, the end values // are non-trivial to calculate. As a "best effort" attempt, we first // apply all the property and binding changes, then read all the actual // final values, then roll back the changes and proceed as normal. // // This doesn't catch everything, and it might be a little fragile in // some cases - but whatcha going to do? if (!d->bindingsList.isEmpty()) { //### do extra actions here? // Apply all the property and binding changes for (int ii = 0; ii < applyList.size(); ++ii) { const Action &action = applyList.at(ii); if (action.toBinding) { action.property.setBinding(action.toBinding, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding); } else if (!action.event) { action.property.write(action.toValue, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding); } else if (action.event->isReversable()) { if (action.reverseEvent) action.event->reverse(); else action.event->execute(); applyList << action.event->extraActions(); } } // Read all the end values for binding changes for (int ii = 0; ii < applyList.size(); ++ii) { Action *action = &applyList[ii]; if (action->event) continue; const QmlMetaProperty &prop = action->property; if (action->toBinding || !action->toValue.isValid()) { //### is this always right (used for exta actions) action->toValue = prop.read(); } } // Revert back to the original values foreach(const Action &action, applyList) { if (action.event) { if (action.event->isReversable()) { if (action.reverseEvent) { //reverse the reverse action.event->clearForwardBindings(); action.event->rewind(); action.event->clearReverseBindings(); } else { action.event->clearReverseBindings(); action.event->rewind(); action.event->clearForwardBindings(); } } continue; } if (action.toBinding) action.property.setBinding(0); // Make sure this is disabled during the transition action.property.write(action.fromValue, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding); } } if (transition) { QList<QmlMetaProperty> touched; d->transition = transition; d->transition->prepare(applyList, touched, this); // Modify the action list to remove actions handled in the transition for (int ii = 0; ii < applyList.count(); ++ii) { const Action &action = applyList.at(ii); if (action.event) { if (action.actionDone) { applyList.removeAt(ii); --ii; } } else { if (touched.contains(action.property)) { if (action.toValue != action.fromValue) d->completeList << SimpleAction(action, SimpleAction::EndState); applyList.removeAt(ii); --ii; } } } } // Any actions remaining have not been handled by the transition and should // be applied immediately. We skip applying bindings, as they are all // applied at the end in applyBindings() to avoid any nastiness mid // transition foreach(const Action &action, applyList) { if (action.event && !action.event->changesBindings()) { if (action.event->isReversable() && action.reverseEvent) action.event->reverse(); else action.event->execute(); } else if (!action.event && !action.toBinding) { action.property.write(action.toValue); } } if (!transition) d->applyBindings(); } void QmlTransitionManager::cancel() { if (d->transition) { // ### this could potentially trigger a complete in rare circumstances d->transition->stop(); d->transition = 0; } for(int i = 0; i < d->bindingsList.count(); ++i) { Action action = d->bindingsList[i]; if (action.toBinding && action.deletableToBinding) { action.property.setBinding(0); action.toBinding->destroy(); action.toBinding = 0; action.deletableToBinding = false; } else if (action.event) { //### what do we do here? } } d->bindingsList.clear(); d->completeList.clear(); } QT_END_NAMESPACE <commit_msg>More statechange debugging<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $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 "qmltransitionmanager_p_p.h" #include "qmlstate_p_p.h" #include <qmlbinding.h> #include <qmlglobal_p.h> QT_BEGIN_NAMESPACE DEFINE_BOOL_CONFIG_OPTION(stateChangeDebug, STATECHANGE_DEBUG); class QmlTransitionManagerPrivate { public: QmlTransitionManagerPrivate() : state(0), transition(0) {} void applyBindings(); typedef QList<SimpleAction> SimpleActionList; QmlState *state; QmlTransition *transition; QmlStateOperation::ActionList bindingsList; SimpleActionList completeList; }; QmlTransitionManager::QmlTransitionManager() : d(new QmlTransitionManagerPrivate) { } void QmlTransitionManager::setState(QmlState *s) { d->state = s; } QmlTransitionManager::~QmlTransitionManager() { delete d; d = 0; } void QmlTransitionManager::complete() { d->applyBindings(); for (int ii = 0; ii < d->completeList.count(); ++ii) { const QmlMetaProperty &prop = d->completeList.at(ii).property; prop.write(d->completeList.at(ii).value); } d->completeList.clear(); if (d->state) static_cast<QmlStatePrivate*>(QObjectPrivate::get(d->state))->complete(); } void QmlTransitionManagerPrivate::applyBindings() { foreach(const Action &action, bindingsList) { if (action.toBinding) { action.property.setBinding(action.toBinding); } else if (action.event) { if (action.reverseEvent) action.event->reverse(); else action.event->execute(); } } bindingsList.clear(); } void QmlTransitionManager::transition(const QList<Action> &list, QmlTransition *transition) { cancel(); QmlStateOperation::ActionList applyList = list; // Determine which actions are binding changes. foreach(const Action &action, applyList) { if (action.toBinding) d->bindingsList << action; if (action.fromBinding) action.property.setBinding(0); // Disable current binding if (action.event && action.event->changesBindings()) { //### assume isReversable()? d->bindingsList << action; if (action.reverseEvent) action.event->clearReverseBindings(); else action.event->clearForwardBindings(); } } // Animated transitions need both the start and the end value for // each property change. In the presence of bindings, the end values // are non-trivial to calculate. As a "best effort" attempt, we first // apply all the property and binding changes, then read all the actual // final values, then roll back the changes and proceed as normal. // // This doesn't catch everything, and it might be a little fragile in // some cases - but whatcha going to do? if (!d->bindingsList.isEmpty()) { //### do extra actions here? // Apply all the property and binding changes for (int ii = 0; ii < applyList.size(); ++ii) { const Action &action = applyList.at(ii); if (action.toBinding) { action.property.setBinding(action.toBinding, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding); } else if (!action.event) { action.property.write(action.toValue, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding); } else if (action.event->isReversable()) { if (action.reverseEvent) action.event->reverse(); else action.event->execute(); applyList << action.event->extraActions(); } } // Read all the end values for binding changes for (int ii = 0; ii < applyList.size(); ++ii) { Action *action = &applyList[ii]; if (action->event) continue; const QmlMetaProperty &prop = action->property; if (action->toBinding || !action->toValue.isValid()) { //### is this always right (used for exta actions) action->toValue = prop.read(); } } // Revert back to the original values foreach(const Action &action, applyList) { if (action.event) { if (action.event->isReversable()) { if (action.reverseEvent) { //reverse the reverse action.event->clearForwardBindings(); action.event->rewind(); action.event->clearReverseBindings(); } else { action.event->clearReverseBindings(); action.event->rewind(); action.event->clearForwardBindings(); } } continue; } if (action.toBinding) action.property.setBinding(0); // Make sure this is disabled during the transition action.property.write(action.fromValue, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding); } } if (transition) { QList<QmlMetaProperty> touched; d->transition = transition; d->transition->prepare(applyList, touched, this); // Modify the action list to remove actions handled in the transition for (int ii = 0; ii < applyList.count(); ++ii) { const Action &action = applyList.at(ii); if (action.event) { if (action.actionDone) { applyList.removeAt(ii); --ii; } } else { if (touched.contains(action.property)) { if (action.toValue != action.fromValue) d->completeList << SimpleAction(action, SimpleAction::EndState); applyList.removeAt(ii); --ii; } } } } // Any actions remaining have not been handled by the transition and should // be applied immediately. We skip applying bindings, as they are all // applied at the end in applyBindings() to avoid any nastiness mid // transition foreach(const Action &action, applyList) { if (action.event && !action.event->changesBindings()) { if (action.event->isReversable() && action.reverseEvent) action.event->reverse(); else action.event->execute(); } else if (!action.event && !action.toBinding) { action.property.write(action.toValue); } } if (stateChangeDebug()) { foreach(const Action &action, applyList) { if (action.event) qWarning() << " No transition for event:" << action.event->typeName(); else qWarning() << " No transition for:" << action.property.object() << action.property.name() << action.fromValue << action.toValue; } } if (!transition) d->applyBindings(); } void QmlTransitionManager::cancel() { if (d->transition) { // ### this could potentially trigger a complete in rare circumstances d->transition->stop(); d->transition = 0; } for(int i = 0; i < d->bindingsList.count(); ++i) { Action action = d->bindingsList[i]; if (action.toBinding && action.deletableToBinding) { action.property.setBinding(0); action.toBinding->destroy(); action.toBinding = 0; action.deletableToBinding = false; } else if (action.event) { //### what do we do here? } } d->bindingsList.clear(); d->completeList.clear(); } QT_END_NAMESPACE <|endoftext|>
<commit_before>//Author: Christopher Lee Hiles //2015-02-13 //Entry point example for the ToyTetragraphHash class. //Hashes a string and returns the hash. //Basically: //The idea is to use consume a string to repeatedly fill in a set sized grid with characters that are converted to ints. //round 1: //A vector takes the running total result which is initially filled with 0's. //vector[i] = sum of column % 26. (26 is # of letters in alphabet) //round 2: //Each row in the original grid is shifted left by a different amount. //vector[i] = sum of column % 26. (again) //repeat the process until all characters in string have been consumed. //convert back to characters and output hash. #include "ToyTetragraphHash.h" #include <iostream> using namespace std; //entry point void main() { string testString; string hash; //example1 testString = "ABCDEFGHIJKLMNOP"; cout << "String to Hash: "<< testString << "\n"; ToyTetragraphHash testHash1; hash = testHash1.hashAString(testString); cout << "Hash: " << hash << "\n"; //example2 testString = "AB!CDEFGH,IJKLmn OP;"; cout << "String to Hash: " << testString << "\n"; ToyTetragraphHash testHash2; hash = testHash2.hashAString(testString); cout << "Hash: " << hash << "\n"; //example3 testString = "ABCDEFGHIJKLMNOPQ"; cout << "String to Hash: " << testString << "\n"; ToyTetragraphHash testHash3; hash = testHash3.hashAString(testString); cout << "Hash: " << hash << "\n"; //example4 testString = "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"; cout << "String to Hash: " << testString << "\n"; ToyTetragraphHash testHash4; hash = testHash4.hashAString(testString); cout << "Hash: " << hash << "\n"; //example5 testString = "AACDEFGHIJKLMNOP"; cout << "String to Hash: " << testString << "\n"; ToyTetragraphHash testHash5; hash = testHash5.hashAString(testString); cout << "Hash: " << hash << "\n"; return; }<commit_msg>Formatting<commit_after>//Author: Christopher Lee Hiles //2015-02-13 //Entry point example for the ToyTetragraphHash class. //Hashes a string and returns the hash. //Basically: //The idea is to use consume a string to repeatedly fill in a set sized grid with characters that are converted to ints. //round 1: //A vector takes the running total result which is initially filled with 0's. //vector[i] = sum of column % 26. (26 is # of letters in alphabet) //round 2: //Each row in the original grid is shifted left by a different amount. //vector[i] = sum of column % 26. (again) //repeat the process until all characters in string have been consumed. //convert back to characters and output hash. #include "ToyTetragraphHash.h" #include <iostream> using namespace std; //entry point void main() { string testString; string hash; //example1 testString = "ABCDEFGHIJKLMNOP"; cout << "String to Hash: "<< testString << "\n"; ToyTetragraphHash testHash1; hash = testHash1.hashAString(testString); cout << "Hash: " << hash << "\n"; //example2 testString = "AB!CDEFGH,IJKLmn OP;"; cout << "String to Hash: " << testString << "\n"; ToyTetragraphHash testHash2; hash = testHash2.hashAString(testString); cout << "Hash: " << hash << "\n"; //example3 testString = "ABCDEFGHIJKLMNOPQ"; cout << "String to Hash: " << testString << "\n"; ToyTetragraphHash testHash3; hash = testHash3.hashAString(testString); cout << "Hash: " << hash << "\n"; //example4 testString = "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"; cout << "String to Hash: " << testString << "\n"; ToyTetragraphHash testHash4; hash = testHash4.hashAString(testString); cout << "Hash: " << hash << "\n"; //example5 testString = "AACDEFGHIJKLMNOP"; cout << "String to Hash: " << testString << "\n"; ToyTetragraphHash testHash5; hash = testHash5.hashAString(testString); cout << "Hash: " << hash << "\n"; return; }<|endoftext|>
<commit_before>#include <gbBase/Log.hpp> #include <gbBase/Assert.hpp> #include <gbBase/LogHandlers.hpp> #include <boost/predef.h> #if BOOST_COMP_MSVC #pragma warning(push) #pragma warning(disable: 4146 4244) #endif #include <hinnant_date/date.h> #if BOOST_COMP_MSVC #pragma warning(pop) #endif #include <atomic> #include <chrono> #include <type_traits> namespace GHULBUS_BASE_NAMESPACE { namespace { /** Non-trivial static state that requires explicit initialization via initializeLogging(). */ struct StaticState { std::atomic<LogLevel> currentLogLevel; Log::LogHandler logHandler; StaticState() :currentLogLevel(LogLevel::Error), logHandler(&Log::Handlers::logToCout) {} }; /** Trivial static state that is initialized at compile time. * This is mainly used for doing the bookkeeping for initializeLogging() and shutdownLogging(). */ struct StaticData { int staticStorageRefcount; char staticStateStorage[sizeof(StaticState)]; StaticState* logState; } g_staticData; static_assert(std::is_trivial<StaticData>::value, "Non-trivial types not allowed in StaticData to avoid static initialization order headaches."); struct current_time_t {} current_time; inline std::ostream& operator<<(std::ostream& os, current_time_t const&) { #if _MSC_FULL_VER < 190023918 using date::floor; #endif std::chrono::system_clock::time_point const now = std::chrono::system_clock::now(); date::day_point const today = floor<date::days>(now); // the duration cast here determines the precision of the resulting time_of_day in the output auto const time_since_midnight = std::chrono::duration_cast<std::chrono::milliseconds>(now - today); return os << date::year_month_day(today) << ' ' << date::make_time(time_since_midnight); } } std::ostream& operator<<(std::ostream& os, LogLevel log_level) { switch(log_level) { default: GHULBUS_UNREACHABLE(); case LogLevel::Trace: os << "[TRACE]"; break; case LogLevel::Debug: os << "[DEBUG]"; break; case LogLevel::Info: os << "[INFO ]"; break; case LogLevel::Warning: os << "[WARN ]"; break; case LogLevel::Error: os << "[ERROR]"; break; case LogLevel::Critical: os << "[CRIT ]"; break; } return os; } namespace Log { void initializeLogging() { auto& staticData = g_staticData; GHULBUS_ASSERT(staticData.staticStorageRefcount >= 0); if(staticData.staticStorageRefcount == 0) { staticData.logState = new(staticData.staticStateStorage) StaticState(); } ++staticData.staticStorageRefcount; } void shutdownLogging() { auto& staticData = g_staticData; GHULBUS_ASSERT(g_staticData.staticStorageRefcount > 0); if(staticData.staticStorageRefcount == 1) { staticData.logState->~StaticState(); std::memset(staticData.staticStateStorage, 0, sizeof(staticData.staticStateStorage)); } --staticData.staticStorageRefcount; } void setLogLevel(LogLevel log_level) { GHULBUS_ASSERT(log_level >= LogLevel::Trace && log_level <= LogLevel::Critical); auto& staticData = g_staticData; staticData.logState->currentLogLevel.store(log_level); } LogLevel getLogLevel() { auto const& staticData = g_staticData; return staticData.logState->currentLogLevel.load(); } void setLogHandler(LogHandler handler) { auto& staticData = g_staticData; staticData.logState->logHandler = handler; } LogHandler getLogHandler() { auto const& staticData = g_staticData; return staticData.logState->logHandler; } std::stringstream createLogStream(LogLevel level) { std::stringstream log_stream; log_stream << level << ' ' << current_time << " - "; return log_stream; } void log(LogLevel log_level, std::stringstream&& log_stream) { auto const handler = getLogHandler(); if (handler) { handler(log_level, std::move(log_stream)); } } } } <commit_msg>missing #include<commit_after>#include <gbBase/Log.hpp> #include <gbBase/Assert.hpp> #include <gbBase/LogHandlers.hpp> #include <boost/predef.h> #if BOOST_COMP_MSVC #pragma warning(push) #pragma warning(disable: 4146 4244) #endif #include <hinnant_date/date.h> #if BOOST_COMP_MSVC #pragma warning(pop) #endif #include <atomic> #include <chrono> #include <cstring> #include <type_traits> namespace GHULBUS_BASE_NAMESPACE { namespace { /** Non-trivial static state that requires explicit initialization via initializeLogging(). */ struct StaticState { std::atomic<LogLevel> currentLogLevel; Log::LogHandler logHandler; StaticState() :currentLogLevel(LogLevel::Error), logHandler(&Log::Handlers::logToCout) {} }; /** Trivial static state that is initialized at compile time. * This is mainly used for doing the bookkeeping for initializeLogging() and shutdownLogging(). */ struct StaticData { int staticStorageRefcount; char staticStateStorage[sizeof(StaticState)]; StaticState* logState; } g_staticData; static_assert(std::is_trivial<StaticData>::value, "Non-trivial types not allowed in StaticData to avoid static initialization order headaches."); struct current_time_t {} current_time; inline std::ostream& operator<<(std::ostream& os, current_time_t const&) { #if _MSC_FULL_VER < 190023918 using date::floor; #endif std::chrono::system_clock::time_point const now = std::chrono::system_clock::now(); date::day_point const today = floor<date::days>(now); // the duration cast here determines the precision of the resulting time_of_day in the output auto const time_since_midnight = std::chrono::duration_cast<std::chrono::milliseconds>(now - today); return os << date::year_month_day(today) << ' ' << date::make_time(time_since_midnight); } } std::ostream& operator<<(std::ostream& os, LogLevel log_level) { switch(log_level) { default: GHULBUS_UNREACHABLE(); case LogLevel::Trace: os << "[TRACE]"; break; case LogLevel::Debug: os << "[DEBUG]"; break; case LogLevel::Info: os << "[INFO ]"; break; case LogLevel::Warning: os << "[WARN ]"; break; case LogLevel::Error: os << "[ERROR]"; break; case LogLevel::Critical: os << "[CRIT ]"; break; } return os; } namespace Log { void initializeLogging() { auto& staticData = g_staticData; GHULBUS_ASSERT(staticData.staticStorageRefcount >= 0); if(staticData.staticStorageRefcount == 0) { staticData.logState = new(staticData.staticStateStorage) StaticState(); } ++staticData.staticStorageRefcount; } void shutdownLogging() { auto& staticData = g_staticData; GHULBUS_ASSERT(g_staticData.staticStorageRefcount > 0); if(staticData.staticStorageRefcount == 1) { staticData.logState->~StaticState(); std::memset(staticData.staticStateStorage, 0, sizeof(staticData.staticStateStorage)); } --staticData.staticStorageRefcount; } void setLogLevel(LogLevel log_level) { GHULBUS_ASSERT(log_level >= LogLevel::Trace && log_level <= LogLevel::Critical); auto& staticData = g_staticData; staticData.logState->currentLogLevel.store(log_level); } LogLevel getLogLevel() { auto const& staticData = g_staticData; return staticData.logState->currentLogLevel.load(); } void setLogHandler(LogHandler handler) { auto& staticData = g_staticData; staticData.logState->logHandler = handler; } LogHandler getLogHandler() { auto const& staticData = g_staticData; return staticData.logState->logHandler; } std::stringstream createLogStream(LogLevel level) { std::stringstream log_stream; log_stream << level << ' ' << current_time << " - "; return log_stream; } void log(LogLevel log_level, std::stringstream&& log_stream) { auto const handler = getLogHandler(); if (handler) { handler(log_level, std::move(log_stream)); } } } } <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkPictureShader.h" #include "SkBitmap.h" #include "SkBitmapProcShader.h" #include "SkCanvas.h" #include "SkImage.h" #include "SkImageGenerator.h" #include "SkMatrixUtils.h" #include "SkPicture.h" #include "SkReadBuffer.h" #include "SkResourceCache.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrCaps.h" #endif namespace { static unsigned gBitmapSkaderKeyNamespaceLabel; struct BitmapShaderKey : public SkResourceCache::Key { public: BitmapShaderKey(uint32_t pictureID, const SkRect& tile, SkShader::TileMode tmx, SkShader::TileMode tmy, const SkSize& scale, const SkMatrix& localMatrix) : fPictureID(pictureID) , fTile(tile) , fTmx(tmx) , fTmy(tmy) , fScale(scale) { for (int i = 0; i < 9; ++i) { fLocalMatrixStorage[i] = localMatrix[i]; } static const size_t keySize = sizeof(fPictureID) + sizeof(fTile) + sizeof(fTmx) + sizeof(fTmy) + sizeof(fScale) + sizeof(fLocalMatrixStorage); // This better be packed. SkASSERT(sizeof(uint32_t) * (&fEndOfStruct - &fPictureID) == keySize); this->init(&gBitmapSkaderKeyNamespaceLabel, 0, keySize); } private: uint32_t fPictureID; SkRect fTile; SkShader::TileMode fTmx, fTmy; SkSize fScale; SkScalar fLocalMatrixStorage[9]; SkDEBUGCODE(uint32_t fEndOfStruct;) }; struct BitmapShaderRec : public SkResourceCache::Rec { BitmapShaderRec(const BitmapShaderKey& key, SkShader* tileShader, size_t bitmapBytes) : fKey(key) , fShader(SkRef(tileShader)) , fBitmapBytes(bitmapBytes) {} BitmapShaderKey fKey; SkAutoTUnref<SkShader> fShader; size_t fBitmapBytes; const Key& getKey() const override { return fKey; } size_t bytesUsed() const override { return sizeof(fKey) + sizeof(SkShader) + fBitmapBytes; } const char* getCategory() const override { return "bitmap-shader"; } SkDiscardableMemory* diagnostic_only_getDiscardable() const override { return nullptr; } static bool Visitor(const SkResourceCache::Rec& baseRec, void* contextShader) { const BitmapShaderRec& rec = static_cast<const BitmapShaderRec&>(baseRec); SkAutoTUnref<SkShader>* result = reinterpret_cast<SkAutoTUnref<SkShader>*>(contextShader); result->reset(SkRef(rec.fShader.get())); // The bitmap shader is backed by an image generator, thus it can always re-generate its // pixels if discarded. return true; } }; } // namespace SkPictureShader::SkPictureShader(const SkPicture* picture, TileMode tmx, TileMode tmy, const SkMatrix* localMatrix, const SkRect* tile) : INHERITED(localMatrix) , fPicture(SkRef(picture)) , fTile(tile ? *tile : picture->cullRect()) , fTmx(tmx) , fTmy(tmy) { } SkShader* SkPictureShader::Create(const SkPicture* picture, TileMode tmx, TileMode tmy, const SkMatrix* localMatrix, const SkRect* tile) { if (!picture || picture->cullRect().isEmpty() || (tile && tile->isEmpty())) { return SkShader::CreateEmptyShader(); } return new SkPictureShader(picture, tmx, tmy, localMatrix, tile); } SkFlattenable* SkPictureShader::CreateProc(SkReadBuffer& buffer) { SkMatrix lm; buffer.readMatrix(&lm); TileMode mx = (TileMode)buffer.read32(); TileMode my = (TileMode)buffer.read32(); SkRect tile; buffer.readRect(&tile); SkAutoTUnref<SkPicture> picture; if (buffer.isCrossProcess() && SkPicture::PictureIOSecurityPrecautionsEnabled()) { if (buffer.isVersionLT(SkReadBuffer::kPictureShaderHasPictureBool_Version)) { // Older code blindly serialized pictures. We don't trust them. buffer.validate(false); return nullptr; } // Newer code won't serialize pictures in disallow-cross-process-picture mode. // Assert that they didn't serialize anything except a false here. buffer.validate(!buffer.readBool()); } else { // Old code always serialized the picture. New code writes a 'true' first if it did. if (buffer.isVersionLT(SkReadBuffer::kPictureShaderHasPictureBool_Version) || buffer.readBool()) { picture.reset(SkPicture::CreateFromBuffer(buffer)); } } return SkPictureShader::Create(picture, mx, my, &lm, &tile); } void SkPictureShader::flatten(SkWriteBuffer& buffer) const { buffer.writeMatrix(this->getLocalMatrix()); buffer.write32(fTmx); buffer.write32(fTmy); buffer.writeRect(fTile); // The deserialization code won't trust that our serialized picture is safe to deserialize. // So write a 'false' telling it that we're not serializing a picture. if (buffer.isCrossProcess() && SkPicture::PictureIOSecurityPrecautionsEnabled()) { buffer.writeBool(false); } else { buffer.writeBool(true); fPicture->flatten(buffer); } } SkShader* SkPictureShader::refBitmapShader(const SkMatrix& viewMatrix, const SkMatrix* localM, const int maxTextureSize) const { SkASSERT(fPicture && !fPicture->cullRect().isEmpty()); SkMatrix m; m.setConcat(viewMatrix, this->getLocalMatrix()); if (localM) { m.preConcat(*localM); } // Use a rotation-invariant scale SkPoint scale; // // TODO: replace this with decomposeScale() -- but beware LayoutTest rebaselines! // if (!SkDecomposeUpper2x2(m, nullptr, &scale, nullptr)) { // Decomposition failed, use an approximation. scale.set(SkScalarSqrt(m.getScaleX() * m.getScaleX() + m.getSkewX() * m.getSkewX()), SkScalarSqrt(m.getScaleY() * m.getScaleY() + m.getSkewY() * m.getSkewY())); } SkSize scaledSize = SkSize::Make(SkScalarAbs(scale.x() * fTile.width()), SkScalarAbs(scale.y() * fTile.height())); // Clamp the tile size to about 4M pixels static const SkScalar kMaxTileArea = 2048 * 2048; SkScalar tileArea = SkScalarMul(scaledSize.width(), scaledSize.height()); if (tileArea > kMaxTileArea) { SkScalar clampScale = SkScalarSqrt(kMaxTileArea / tileArea); scaledSize.set(SkScalarMul(scaledSize.width(), clampScale), SkScalarMul(scaledSize.height(), clampScale)); } #if SK_SUPPORT_GPU // Scale down the tile size if larger than maxTextureSize for GPU Path or it should fail on create texture if (maxTextureSize) { if (scaledSize.width() > maxTextureSize || scaledSize.height() > maxTextureSize) { SkScalar downScale = maxTextureSize / SkMaxScalar(scaledSize.width(), scaledSize.height()); scaledSize.set(SkScalarFloorToScalar(SkScalarMul(scaledSize.width(), downScale)), SkScalarFloorToScalar(SkScalarMul(scaledSize.height(), downScale))); } } #endif SkISize tileSize = scaledSize.toRound(); if (tileSize.isEmpty()) { return SkShader::CreateEmptyShader(); } // The actual scale, compensating for rounding & clamping. SkSize tileScale = SkSize::Make(SkIntToScalar(tileSize.width()) / fTile.width(), SkIntToScalar(tileSize.height()) / fTile.height()); SkAutoTUnref<SkShader> tileShader; BitmapShaderKey key(fPicture->uniqueID(), fTile, fTmx, fTmy, tileScale, this->getLocalMatrix()); if (!SkResourceCache::Find(key, BitmapShaderRec::Visitor, &tileShader)) { SkMatrix tileMatrix; tileMatrix.setRectToRect(fTile, SkRect::MakeIWH(tileSize.width(), tileSize.height()), SkMatrix::kFill_ScaleToFit); SkAutoTDelete<SkImageGenerator> tileGenerator( SkImageGenerator::NewFromPicture(tileSize, fPicture, &tileMatrix, nullptr)); if (!tileGenerator) { return nullptr; } // Grab this before the generator goes poof! const SkImageInfo tileInfo = tileGenerator->getInfo(); SkAutoTUnref<SkImage> tileImage(SkImage::NewFromGenerator(tileGenerator.detach())); if (!tileImage) { return nullptr; } SkMatrix shaderMatrix = this->getLocalMatrix(); shaderMatrix.preScale(1 / tileScale.width(), 1 / tileScale.height()); tileShader.reset(tileImage->newShader(fTmx, fTmy, &shaderMatrix)); SkResourceCache::Add(new BitmapShaderRec(key, tileShader.get(), tileInfo.getSafeSize(tileInfo.minRowBytes()))); } return tileShader.detach(); } size_t SkPictureShader::contextSize() const { return sizeof(PictureShaderContext); } SkShader::Context* SkPictureShader::onCreateContext(const ContextRec& rec, void* storage) const { SkAutoTUnref<SkShader> bitmapShader(this->refBitmapShader(*rec.fMatrix, rec.fLocalMatrix)); if (nullptr == bitmapShader.get()) { return nullptr; } return PictureShaderContext::Create(storage, *this, rec, bitmapShader); } ///////////////////////////////////////////////////////////////////////////////////////// SkShader::Context* SkPictureShader::PictureShaderContext::Create(void* storage, const SkPictureShader& shader, const ContextRec& rec, SkShader* bitmapShader) { PictureShaderContext* ctx = new (storage) PictureShaderContext(shader, rec, bitmapShader); if (nullptr == ctx->fBitmapShaderContext) { ctx->~PictureShaderContext(); ctx = nullptr; } return ctx; } SkPictureShader::PictureShaderContext::PictureShaderContext( const SkPictureShader& shader, const ContextRec& rec, SkShader* bitmapShader) : INHERITED(shader, rec) , fBitmapShader(SkRef(bitmapShader)) { fBitmapShaderContextStorage = sk_malloc_throw(bitmapShader->contextSize()); fBitmapShaderContext = bitmapShader->createContext(rec, fBitmapShaderContextStorage); //if fBitmapShaderContext is null, we are invalid } SkPictureShader::PictureShaderContext::~PictureShaderContext() { if (fBitmapShaderContext) { fBitmapShaderContext->~Context(); } sk_free(fBitmapShaderContextStorage); } uint32_t SkPictureShader::PictureShaderContext::getFlags() const { SkASSERT(fBitmapShaderContext); return fBitmapShaderContext->getFlags(); } SkShader::Context::ShadeProc SkPictureShader::PictureShaderContext::asAShadeProc(void** ctx) { SkASSERT(fBitmapShaderContext); return fBitmapShaderContext->asAShadeProc(ctx); } void SkPictureShader::PictureShaderContext::shadeSpan(int x, int y, SkPMColor dstC[], int count) { SkASSERT(fBitmapShaderContext); fBitmapShaderContext->shadeSpan(x, y, dstC, count); } #ifndef SK_IGNORE_TO_STRING void SkPictureShader::toString(SkString* str) const { static const char* gTileModeName[SkShader::kTileModeCount] = { "clamp", "repeat", "mirror" }; str->appendf("PictureShader: [%f:%f:%f:%f] ", fPicture->cullRect().fLeft, fPicture->cullRect().fTop, fPicture->cullRect().fRight, fPicture->cullRect().fBottom); str->appendf("(%s, %s)", gTileModeName[fTmx], gTileModeName[fTmy]); this->INHERITED::toString(str); } #endif #if SK_SUPPORT_GPU const GrFragmentProcessor* SkPictureShader::asFragmentProcessor( GrContext* context, const SkMatrix& viewM, const SkMatrix* localMatrix, SkFilterQuality fq) const { int maxTextureSize = 0; if (context) { maxTextureSize = context->caps()->maxTextureSize(); } SkAutoTUnref<SkShader> bitmapShader(this->refBitmapShader(viewM, localMatrix, maxTextureSize)); if (!bitmapShader) { return nullptr; } return bitmapShader->asFragmentProcessor(context, viewM, nullptr, fq); } #endif <commit_msg>SkPictureShader cleanup<commit_after>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkPictureShader.h" #include "SkBitmap.h" #include "SkBitmapProcShader.h" #include "SkCanvas.h" #include "SkImage.h" #include "SkMatrixUtils.h" #include "SkPicture.h" #include "SkReadBuffer.h" #include "SkResourceCache.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrCaps.h" #endif namespace { static unsigned gBitmapSkaderKeyNamespaceLabel; struct BitmapShaderKey : public SkResourceCache::Key { public: BitmapShaderKey(uint32_t pictureID, const SkRect& tile, SkShader::TileMode tmx, SkShader::TileMode tmy, const SkSize& scale, const SkMatrix& localMatrix) : fPictureID(pictureID) , fTile(tile) , fTmx(tmx) , fTmy(tmy) , fScale(scale) { for (int i = 0; i < 9; ++i) { fLocalMatrixStorage[i] = localMatrix[i]; } static const size_t keySize = sizeof(fPictureID) + sizeof(fTile) + sizeof(fTmx) + sizeof(fTmy) + sizeof(fScale) + sizeof(fLocalMatrixStorage); // This better be packed. SkASSERT(sizeof(uint32_t) * (&fEndOfStruct - &fPictureID) == keySize); this->init(&gBitmapSkaderKeyNamespaceLabel, 0, keySize); } private: uint32_t fPictureID; SkRect fTile; SkShader::TileMode fTmx, fTmy; SkSize fScale; SkScalar fLocalMatrixStorage[9]; SkDEBUGCODE(uint32_t fEndOfStruct;) }; struct BitmapShaderRec : public SkResourceCache::Rec { BitmapShaderRec(const BitmapShaderKey& key, SkShader* tileShader, size_t bitmapBytes) : fKey(key) , fShader(SkRef(tileShader)) , fBitmapBytes(bitmapBytes) {} BitmapShaderKey fKey; SkAutoTUnref<SkShader> fShader; size_t fBitmapBytes; const Key& getKey() const override { return fKey; } size_t bytesUsed() const override { return sizeof(fKey) + sizeof(SkShader) + fBitmapBytes; } const char* getCategory() const override { return "bitmap-shader"; } SkDiscardableMemory* diagnostic_only_getDiscardable() const override { return nullptr; } static bool Visitor(const SkResourceCache::Rec& baseRec, void* contextShader) { const BitmapShaderRec& rec = static_cast<const BitmapShaderRec&>(baseRec); SkAutoTUnref<SkShader>* result = reinterpret_cast<SkAutoTUnref<SkShader>*>(contextShader); result->reset(SkRef(rec.fShader.get())); // The bitmap shader is backed by an image generator, thus it can always re-generate its // pixels if discarded. return true; } }; } // namespace SkPictureShader::SkPictureShader(const SkPicture* picture, TileMode tmx, TileMode tmy, const SkMatrix* localMatrix, const SkRect* tile) : INHERITED(localMatrix) , fPicture(SkRef(picture)) , fTile(tile ? *tile : picture->cullRect()) , fTmx(tmx) , fTmy(tmy) { } SkShader* SkPictureShader::Create(const SkPicture* picture, TileMode tmx, TileMode tmy, const SkMatrix* localMatrix, const SkRect* tile) { if (!picture || picture->cullRect().isEmpty() || (tile && tile->isEmpty())) { return SkShader::CreateEmptyShader(); } return new SkPictureShader(picture, tmx, tmy, localMatrix, tile); } SkFlattenable* SkPictureShader::CreateProc(SkReadBuffer& buffer) { SkMatrix lm; buffer.readMatrix(&lm); TileMode mx = (TileMode)buffer.read32(); TileMode my = (TileMode)buffer.read32(); SkRect tile; buffer.readRect(&tile); SkAutoTUnref<SkPicture> picture; if (buffer.isCrossProcess() && SkPicture::PictureIOSecurityPrecautionsEnabled()) { if (buffer.isVersionLT(SkReadBuffer::kPictureShaderHasPictureBool_Version)) { // Older code blindly serialized pictures. We don't trust them. buffer.validate(false); return nullptr; } // Newer code won't serialize pictures in disallow-cross-process-picture mode. // Assert that they didn't serialize anything except a false here. buffer.validate(!buffer.readBool()); } else { // Old code always serialized the picture. New code writes a 'true' first if it did. if (buffer.isVersionLT(SkReadBuffer::kPictureShaderHasPictureBool_Version) || buffer.readBool()) { picture.reset(SkPicture::CreateFromBuffer(buffer)); } } return SkPictureShader::Create(picture, mx, my, &lm, &tile); } void SkPictureShader::flatten(SkWriteBuffer& buffer) const { buffer.writeMatrix(this->getLocalMatrix()); buffer.write32(fTmx); buffer.write32(fTmy); buffer.writeRect(fTile); // The deserialization code won't trust that our serialized picture is safe to deserialize. // So write a 'false' telling it that we're not serializing a picture. if (buffer.isCrossProcess() && SkPicture::PictureIOSecurityPrecautionsEnabled()) { buffer.writeBool(false); } else { buffer.writeBool(true); fPicture->flatten(buffer); } } SkShader* SkPictureShader::refBitmapShader(const SkMatrix& viewMatrix, const SkMatrix* localM, const int maxTextureSize) const { SkASSERT(fPicture && !fPicture->cullRect().isEmpty()); SkMatrix m; m.setConcat(viewMatrix, this->getLocalMatrix()); if (localM) { m.preConcat(*localM); } // Use a rotation-invariant scale SkPoint scale; // // TODO: replace this with decomposeScale() -- but beware LayoutTest rebaselines! // if (!SkDecomposeUpper2x2(m, nullptr, &scale, nullptr)) { // Decomposition failed, use an approximation. scale.set(SkScalarSqrt(m.getScaleX() * m.getScaleX() + m.getSkewX() * m.getSkewX()), SkScalarSqrt(m.getScaleY() * m.getScaleY() + m.getSkewY() * m.getSkewY())); } SkSize scaledSize = SkSize::Make(SkScalarAbs(scale.x() * fTile.width()), SkScalarAbs(scale.y() * fTile.height())); // Clamp the tile size to about 4M pixels static const SkScalar kMaxTileArea = 2048 * 2048; SkScalar tileArea = SkScalarMul(scaledSize.width(), scaledSize.height()); if (tileArea > kMaxTileArea) { SkScalar clampScale = SkScalarSqrt(kMaxTileArea / tileArea); scaledSize.set(SkScalarMul(scaledSize.width(), clampScale), SkScalarMul(scaledSize.height(), clampScale)); } #if SK_SUPPORT_GPU // Scale down the tile size if larger than maxTextureSize for GPU Path or it should fail on create texture if (maxTextureSize) { if (scaledSize.width() > maxTextureSize || scaledSize.height() > maxTextureSize) { SkScalar downScale = maxTextureSize / SkMaxScalar(scaledSize.width(), scaledSize.height()); scaledSize.set(SkScalarFloorToScalar(SkScalarMul(scaledSize.width(), downScale)), SkScalarFloorToScalar(SkScalarMul(scaledSize.height(), downScale))); } } #endif SkISize tileSize = scaledSize.toRound(); if (tileSize.isEmpty()) { return SkShader::CreateEmptyShader(); } // The actual scale, compensating for rounding & clamping. SkSize tileScale = SkSize::Make(SkIntToScalar(tileSize.width()) / fTile.width(), SkIntToScalar(tileSize.height()) / fTile.height()); SkAutoTUnref<SkShader> tileShader; BitmapShaderKey key(fPicture->uniqueID(), fTile, fTmx, fTmy, tileScale, this->getLocalMatrix()); if (!SkResourceCache::Find(key, BitmapShaderRec::Visitor, &tileShader)) { SkMatrix tileMatrix; tileMatrix.setRectToRect(fTile, SkRect::MakeIWH(tileSize.width(), tileSize.height()), SkMatrix::kFill_ScaleToFit); SkAutoTUnref<SkImage> tileImage( SkImage::NewFromPicture(fPicture, tileSize, &tileMatrix, nullptr)); if (!tileImage) { return nullptr; } SkMatrix shaderMatrix = this->getLocalMatrix(); shaderMatrix.preScale(1 / tileScale.width(), 1 / tileScale.height()); tileShader.reset(tileImage->newShader(fTmx, fTmy, &shaderMatrix)); const SkImageInfo tileInfo = SkImageInfo::MakeN32Premul(tileSize); SkResourceCache::Add(new BitmapShaderRec(key, tileShader.get(), tileInfo.getSafeSize(tileInfo.minRowBytes()))); } return tileShader.detach(); } size_t SkPictureShader::contextSize() const { return sizeof(PictureShaderContext); } SkShader::Context* SkPictureShader::onCreateContext(const ContextRec& rec, void* storage) const { SkAutoTUnref<SkShader> bitmapShader(this->refBitmapShader(*rec.fMatrix, rec.fLocalMatrix)); if (nullptr == bitmapShader.get()) { return nullptr; } return PictureShaderContext::Create(storage, *this, rec, bitmapShader); } ///////////////////////////////////////////////////////////////////////////////////////// SkShader::Context* SkPictureShader::PictureShaderContext::Create(void* storage, const SkPictureShader& shader, const ContextRec& rec, SkShader* bitmapShader) { PictureShaderContext* ctx = new (storage) PictureShaderContext(shader, rec, bitmapShader); if (nullptr == ctx->fBitmapShaderContext) { ctx->~PictureShaderContext(); ctx = nullptr; } return ctx; } SkPictureShader::PictureShaderContext::PictureShaderContext( const SkPictureShader& shader, const ContextRec& rec, SkShader* bitmapShader) : INHERITED(shader, rec) , fBitmapShader(SkRef(bitmapShader)) { fBitmapShaderContextStorage = sk_malloc_throw(bitmapShader->contextSize()); fBitmapShaderContext = bitmapShader->createContext(rec, fBitmapShaderContextStorage); //if fBitmapShaderContext is null, we are invalid } SkPictureShader::PictureShaderContext::~PictureShaderContext() { if (fBitmapShaderContext) { fBitmapShaderContext->~Context(); } sk_free(fBitmapShaderContextStorage); } uint32_t SkPictureShader::PictureShaderContext::getFlags() const { SkASSERT(fBitmapShaderContext); return fBitmapShaderContext->getFlags(); } SkShader::Context::ShadeProc SkPictureShader::PictureShaderContext::asAShadeProc(void** ctx) { SkASSERT(fBitmapShaderContext); return fBitmapShaderContext->asAShadeProc(ctx); } void SkPictureShader::PictureShaderContext::shadeSpan(int x, int y, SkPMColor dstC[], int count) { SkASSERT(fBitmapShaderContext); fBitmapShaderContext->shadeSpan(x, y, dstC, count); } #ifndef SK_IGNORE_TO_STRING void SkPictureShader::toString(SkString* str) const { static const char* gTileModeName[SkShader::kTileModeCount] = { "clamp", "repeat", "mirror" }; str->appendf("PictureShader: [%f:%f:%f:%f] ", fPicture->cullRect().fLeft, fPicture->cullRect().fTop, fPicture->cullRect().fRight, fPicture->cullRect().fBottom); str->appendf("(%s, %s)", gTileModeName[fTmx], gTileModeName[fTmy]); this->INHERITED::toString(str); } #endif #if SK_SUPPORT_GPU const GrFragmentProcessor* SkPictureShader::asFragmentProcessor( GrContext* context, const SkMatrix& viewM, const SkMatrix* localMatrix, SkFilterQuality fq) const { int maxTextureSize = 0; if (context) { maxTextureSize = context->caps()->maxTextureSize(); } SkAutoTUnref<SkShader> bitmapShader(this->refBitmapShader(viewM, localMatrix, maxTextureSize)); if (!bitmapShader) { return nullptr; } return bitmapShader->asFragmentProcessor(context, viewM, nullptr, fq); } #endif <|endoftext|>
<commit_before>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban, Justin Madsen // ============================================================================= // // Main driver function for the HMMWV 9-body model, using rigid tire-terrain // contact. // // If using the Irrlicht interface, river inputs are obtained from the keyboard. // // The global reference frame has Z up, X towards the back of the vehicle, and // Y pointing to the right. // // ============================================================================= #include <vector> #include "core/ChFileutils.h" #include "core/ChStream.h" #include "core/ChRealtimeStep.h" #include "physics/ChSystem.h" #include "physics/ChLinkDistance.h" #include "utils/ChUtilsInputOutput.h" #include "models/hmmwv/HMMWV.h" #include "models/hmmwv/vehicle/HMMWV_VehicleReduced.h" #include "models/hmmwv/tire/HMMWV_RigidTire.h" #include "models/hmmwv/tire/HMMWV_LugreTire.h" #include "models/hmmwv/HMMWV_FuncDriver.h" #include "models/hmmwv/HMMWV_RigidTerrain.h" // If Irrlicht support is available... #if IRRLICHT_ENABLED // ...include additional headers # include "unit_IRRLICHT/ChIrrApp.h" # include "subsys/driver/ChIrrGuiDriver.h" // ...and specify whether the demo should actually use Irrlicht # define USE_IRRLICHT #endif using namespace chrono; using namespace hmmwv; // ============================================================================= // Initial vehicle position ChVector<> initLoc(0, 0, 1.7); // sprung mass height at design = 49.68 in ChQuaternion<> initRot(1,0,0,0); // forward is in the negative global x-direction // Type of tire model (RIGID, PACEJKA, or LUGRE) TireModelType tire_model = RIGID; // Rigid terrain dimensions double terrainHeight = 0; double terrainLength = 100.0; // size in X direction double terrainWidth = 100.0; // size in Y directoin // Simulation step size double step_size = 0.001; // Time interval between two render frames double render_step_size = 1.0 / 50; // FPS = 50 #ifdef USE_IRRLICHT // Point on chassis tracked by the camera ChVector<> trackPoint(0.0, 0.0, 1.0); #else double tend = 20.0; const std::string out_dir = "../HMMWV9"; const std::string pov_dir = out_dir + "/POVRAY"; #endif // ============================================================================= int main(int argc, char* argv[]) { SetChronoDataPath(CHRONO_DATA_DIR); // -------------------------- // Create the various modules // -------------------------- // Create the HMMWV vehicle HMMWV_VehicleReduced vehicle(false, hmmwv::NONE, hmmwv::MESH); vehicle.Initialize(ChCoordsys<>(initLoc, initRot)); // Create the ground HMMWV_RigidTerrain terrain(vehicle, terrainHeight, terrainLength, terrainWidth, 0.8); //terrain.AddMovingObstacles(10); terrain.AddFixedObstacles(); // Create and initialize the tires ChSharedPtr<ChTire> tire_front_right; ChSharedPtr<ChTire> tire_front_left; ChSharedPtr<ChTire> tire_rear_right; ChSharedPtr<ChTire> tire_rear_left; switch (tire_model) { case RIGID: { ChSharedPtr<HMMWV_RigidTire> tire_FR = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f)); ChSharedPtr<HMMWV_RigidTire> tire_FL = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f)); ChSharedPtr<HMMWV_RigidTire> tire_RR = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f)); ChSharedPtr<HMMWV_RigidTire> tire_RL = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f)); tire_FR->Initialize(vehicle.GetWheelBody(FRONT_RIGHT)); tire_FL->Initialize(vehicle.GetWheelBody(FRONT_LEFT)); tire_RR->Initialize(vehicle.GetWheelBody(REAR_RIGHT)); tire_RL->Initialize(vehicle.GetWheelBody(REAR_LEFT)); tire_front_right = tire_FR; tire_front_left = tire_FL; tire_rear_right = tire_RR; tire_rear_left = tire_RL; break; } case LUGRE: { ChSharedPtr<HMMWV_LugreTire> tire_FR = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain)); ChSharedPtr<HMMWV_LugreTire> tire_FL = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain)); ChSharedPtr<HMMWV_LugreTire> tire_RR = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain)); ChSharedPtr<HMMWV_LugreTire> tire_RL = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain)); tire_FR->Initialize(); tire_FL->Initialize(); tire_RR->Initialize(); tire_RL->Initialize(); tire_front_right = tire_FR; tire_front_left = tire_FL; tire_rear_right = tire_RR; tire_rear_left = tire_RL; break; } } #ifdef USE_IRRLICHT irr::ChIrrApp application(&vehicle, L"HMMWV 9-body demo", irr::core::dimension2d<irr::u32>(1000, 800), false, true); // make a skybox that has Z pointing up (default application.AddTypicalSky() makes Y up) std::string mtexturedir = GetChronoDataFile("skybox/"); std::string str_lf = mtexturedir + "sky_lf.jpg"; std::string str_up = mtexturedir + "sky_up.jpg"; std::string str_dn = mtexturedir + "sky_dn.jpg"; irr::video::ITexture* map_skybox_side = application.GetVideoDriver()->getTexture(str_lf.c_str()); irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode( application.GetVideoDriver()->getTexture(str_up.c_str()), application.GetVideoDriver()->getTexture(str_dn.c_str()), map_skybox_side, map_skybox_side, map_skybox_side, map_skybox_side); mbox->setRotation( irr::core::vector3df(90,0,0)); bool do_shadows = false; // shadow map is experimental if (do_shadows) application.AddLightWithShadow(irr::core::vector3df(20.f, 20.f, 80.f), irr::core::vector3df(20.f, 0.f, 0.f), 150, 60, 100, 40, 512, irr::video::SColorf(1, 1, 1)); else application.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130); application.SetTimestep(step_size); ChIrrGuiDriver driver(application, vehicle, trackPoint, 6.0, 0.5); // Set the time response for steering and throttle keyboard inputs. // NOTE: this is not exact, since we do not render quite at the specified FPS. double steering_time = 1.0; // time to go from 0 to +1 (or from 0 to -1) double throttle_time = 1.0; // time to go from 0 to +1 double braking_time = 0.3; // time to go from 0 to +1 driver.SetSteeringDelta(render_step_size / steering_time); driver.SetThrottleDelta(render_step_size / throttle_time); driver.SetBrakingDelta(render_step_size / braking_time); // Set up the assets for rendering application.AssetBindAll(); application.AssetUpdateAll(); if (do_shadows) { application.AddShadowAll(); } #else HMMWV_FuncDriver driver; #endif // --------------- // Simulation loop // --------------- ChTireForces tire_forces(4); // Number of simulation steps between two 3D view render frames int render_steps = (int)std::ceil(render_step_size / step_size); // Initialize simulation frame counter and simulation time int step_number = 0; double time = 0; #ifdef USE_IRRLICHT ChRealtimeStepTimer realtime_timer; while (application.GetDevice()->run()) { // Render scene if (step_number % render_steps == 0) { application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192)); driver.DrawAll(); application.GetVideoDriver()->endScene(); } // Update modules (inter-module communication) time = vehicle.GetChTime(); driver.Update(time); terrain.Update(time); tire_front_right->Update(time, vehicle.GetWheelState(FRONT_RIGHT)); tire_front_left->Update(time, vehicle.GetWheelState(FRONT_LEFT)); tire_rear_right->Update(time, vehicle.GetWheelState(REAR_RIGHT)); tire_rear_left->Update(time, vehicle.GetWheelState(REAR_LEFT)); tire_forces[FRONT_RIGHT] = tire_front_right->GetTireForce(); tire_forces[FRONT_LEFT] = tire_front_left->GetTireForce(); tire_forces[REAR_RIGHT] = tire_rear_right->GetTireForce(); tire_forces[REAR_LEFT] = tire_rear_left->GetTireForce(); vehicle.Update(time, driver.getThrottle(), driver.getSteering(), driver.getBraking(), tire_forces); // Advance simulation for one timestep for all modules double step = realtime_timer.SuggestSimulationStep(step_size); driver.Advance(step); terrain.Advance(step); tire_front_right->Advance(step); tire_front_left->Advance(step); tire_rear_right->Advance(step); tire_rear_left->Advance(step); vehicle.Advance(step); // Increment frame number step_number++; } application.GetDevice()->drop(); #else int render_frame = 0; if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) { std::cout << "Error creating directory " << out_dir << std::endl; return 1; } if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) { std::cout << "Error creating directory " << pov_dir << std::endl; return 1; } HMMWV_VehicleReduced::ExportMeshPovray(out_dir); HMMWV_WheelLeft::ExportMeshPovray(out_dir); HMMWV_WheelRight::ExportMeshPovray(out_dir); char filename[100]; while (time < tend) { if (step_number % render_steps == 0) { // Output render data sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1); utils::WriteShapesPovray(&vehicle, filename); std::cout << "Output frame: " << render_frame << std::endl; std::cout << "Sim frame: " << step_number << std::endl; std::cout << "Time: " << time << std::endl; std::cout << " throttle: " << driver.getThrottle() << " steering: " << driver.getSteering() << std::endl; std::cout << std::endl; render_frame++; } // Update modules time = vehicle.GetChTime(); driver.Update(time); terrain.Update(time); tire_front_right->Update(time, vehicle.GetWheelState(FRONT_RIGHT)); tire_front_left->Update(time, vehicle.GetWheelState(FRONT_LEFT)); tire_rear_right->Update(time, vehicle.GetWheelState(REAR_RIGHT)); tire_rear_left->Update(time, vehicle.GetWheelState(REAR_LEFT)); tire_forces[FRONT_RIGHT] = tire_front_right->GetTireForce(); tire_forces[FRONT_LEFT] = tire_front_left->GetTireForce(); tire_forces[REAR_RIGHT] = tire_rear_right->GetTireForce(); tire_forces[REAR_LEFT] = tire_rear_left->GetTireForce(); vehicle.Update(time, driver.getThrottle(), driver.getSteering(), driver.getBraking(), tire_forces); // Advance simulation for one timestep for all modules driver.Advance(step_size); terrain.Advance(step_size); tire_front_right->Advance(step_size); tire_front_left->Advance(step_size); tire_rear_right->Advance(step_size); tire_rear_left->Advance(step_size); vehicle.Advance(step_size); // Increment frame number step_number++; } #endif return 0; } <commit_msg>Fix logic for co-simulation data exchange.<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban, Justin Madsen // ============================================================================= // // Main driver function for the HMMWV 9-body model, using rigid tire-terrain // contact. // // If using the Irrlicht interface, river inputs are obtained from the keyboard. // // The global reference frame has Z up, X towards the back of the vehicle, and // Y pointing to the right. // // ============================================================================= #include <vector> #include "core/ChFileutils.h" #include "core/ChStream.h" #include "core/ChRealtimeStep.h" #include "physics/ChSystem.h" #include "physics/ChLinkDistance.h" #include "utils/ChUtilsInputOutput.h" #include "models/hmmwv/HMMWV.h" #include "models/hmmwv/vehicle/HMMWV_VehicleReduced.h" #include "models/hmmwv/tire/HMMWV_RigidTire.h" #include "models/hmmwv/tire/HMMWV_LugreTire.h" #include "models/hmmwv/HMMWV_FuncDriver.h" #include "models/hmmwv/HMMWV_RigidTerrain.h" // If Irrlicht support is available... #if IRRLICHT_ENABLED // ...include additional headers # include "unit_IRRLICHT/ChIrrApp.h" # include "subsys/driver/ChIrrGuiDriver.h" // ...and specify whether the demo should actually use Irrlicht # define USE_IRRLICHT #endif using namespace chrono; using namespace hmmwv; // ============================================================================= // Initial vehicle position ChVector<> initLoc(0, 0, 1.7); // sprung mass height at design = 49.68 in ChQuaternion<> initRot(1,0,0,0); // forward is in the negative global x-direction // Type of tire model (RIGID, PACEJKA, or LUGRE) TireModelType tire_model = RIGID; // Rigid terrain dimensions double terrainHeight = 0; double terrainLength = 100.0; // size in X direction double terrainWidth = 100.0; // size in Y directoin // Simulation step size double step_size = 0.001; // Time interval between two render frames double render_step_size = 1.0 / 50; // FPS = 50 #ifdef USE_IRRLICHT // Point on chassis tracked by the camera ChVector<> trackPoint(0.0, 0.0, 1.0); #else double tend = 20.0; const std::string out_dir = "../HMMWV9"; const std::string pov_dir = out_dir + "/POVRAY"; #endif // ============================================================================= int main(int argc, char* argv[]) { SetChronoDataPath(CHRONO_DATA_DIR); // -------------------------- // Create the various modules // -------------------------- // Create the HMMWV vehicle HMMWV_VehicleReduced vehicle(false, hmmwv::NONE, hmmwv::MESH); vehicle.Initialize(ChCoordsys<>(initLoc, initRot)); // Create the ground HMMWV_RigidTerrain terrain(vehicle, terrainHeight, terrainLength, terrainWidth, 0.8); //terrain.AddMovingObstacles(10); terrain.AddFixedObstacles(); // Create and initialize the tires ChSharedPtr<ChTire> tire_front_right; ChSharedPtr<ChTire> tire_front_left; ChSharedPtr<ChTire> tire_rear_right; ChSharedPtr<ChTire> tire_rear_left; switch (tire_model) { case RIGID: { ChSharedPtr<HMMWV_RigidTire> tire_FR = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f)); ChSharedPtr<HMMWV_RigidTire> tire_FL = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f)); ChSharedPtr<HMMWV_RigidTire> tire_RR = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f)); ChSharedPtr<HMMWV_RigidTire> tire_RL = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f)); tire_FR->Initialize(vehicle.GetWheelBody(FRONT_RIGHT)); tire_FL->Initialize(vehicle.GetWheelBody(FRONT_LEFT)); tire_RR->Initialize(vehicle.GetWheelBody(REAR_RIGHT)); tire_RL->Initialize(vehicle.GetWheelBody(REAR_LEFT)); tire_front_right = tire_FR; tire_front_left = tire_FL; tire_rear_right = tire_RR; tire_rear_left = tire_RL; break; } case LUGRE: { ChSharedPtr<HMMWV_LugreTire> tire_FR = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain)); ChSharedPtr<HMMWV_LugreTire> tire_FL = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain)); ChSharedPtr<HMMWV_LugreTire> tire_RR = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain)); ChSharedPtr<HMMWV_LugreTire> tire_RL = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain)); tire_FR->Initialize(); tire_FL->Initialize(); tire_RR->Initialize(); tire_RL->Initialize(); tire_front_right = tire_FR; tire_front_left = tire_FL; tire_rear_right = tire_RR; tire_rear_left = tire_RL; break; } } #ifdef USE_IRRLICHT irr::ChIrrApp application(&vehicle, L"HMMWV 9-body demo", irr::core::dimension2d<irr::u32>(1000, 800), false, true); // make a skybox that has Z pointing up (default application.AddTypicalSky() makes Y up) std::string mtexturedir = GetChronoDataFile("skybox/"); std::string str_lf = mtexturedir + "sky_lf.jpg"; std::string str_up = mtexturedir + "sky_up.jpg"; std::string str_dn = mtexturedir + "sky_dn.jpg"; irr::video::ITexture* map_skybox_side = application.GetVideoDriver()->getTexture(str_lf.c_str()); irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode( application.GetVideoDriver()->getTexture(str_up.c_str()), application.GetVideoDriver()->getTexture(str_dn.c_str()), map_skybox_side, map_skybox_side, map_skybox_side, map_skybox_side); mbox->setRotation( irr::core::vector3df(90,0,0)); bool do_shadows = false; // shadow map is experimental if (do_shadows) application.AddLightWithShadow(irr::core::vector3df(20.f, 20.f, 80.f), irr::core::vector3df(20.f, 0.f, 0.f), 150, 60, 100, 40, 512, irr::video::SColorf(1, 1, 1)); else application.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130); application.SetTimestep(step_size); ChIrrGuiDriver driver(application, vehicle, trackPoint, 6.0, 0.5); // Set the time response for steering and throttle keyboard inputs. // NOTE: this is not exact, since we do not render quite at the specified FPS. double steering_time = 1.0; // time to go from 0 to +1 (or from 0 to -1) double throttle_time = 1.0; // time to go from 0 to +1 double braking_time = 0.3; // time to go from 0 to +1 driver.SetSteeringDelta(render_step_size / steering_time); driver.SetThrottleDelta(render_step_size / throttle_time); driver.SetBrakingDelta(render_step_size / braking_time); // Set up the assets for rendering application.AssetBindAll(); application.AssetUpdateAll(); if (do_shadows) { application.AddShadowAll(); } #else HMMWV_FuncDriver driver; #endif // --------------- // Simulation loop // --------------- // Inter-module communication data ChTireForces tire_forces(4); ChBodyState wheel_states[4]; double throttle_input; double steering_input; double braking_input; // Number of simulation steps between two 3D view render frames int render_steps = (int)std::ceil(render_step_size / step_size); // Initialize simulation frame counter and simulation time int step_number = 0; double time = 0; #ifdef USE_IRRLICHT ChRealtimeStepTimer realtime_timer; while (application.GetDevice()->run()) { // Render scene if (step_number % render_steps == 0) { application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192)); driver.DrawAll(); application.GetVideoDriver()->endScene(); } // Collect output data from modules (for inter-module communication) throttle_input = driver.getThrottle(); steering_input = driver.getSteering(); braking_input = driver.getBraking(); tire_forces[FRONT_LEFT] = tire_front_left->GetTireForce(); tire_forces[FRONT_RIGHT] = tire_front_right->GetTireForce(); tire_forces[REAR_LEFT] = tire_rear_left->GetTireForce(); tire_forces[REAR_RIGHT] = tire_rear_right->GetTireForce(); wheel_states[FRONT_LEFT] = vehicle.GetWheelState(FRONT_RIGHT); wheel_states[FRONT_RIGHT] = vehicle.GetWheelState(FRONT_LEFT); wheel_states[REAR_LEFT] = vehicle.GetWheelState(REAR_RIGHT); wheel_states[REAR_RIGHT] = vehicle.GetWheelState(REAR_LEFT); // Update modules (process inputs from other modules) time = vehicle.GetChTime(); driver.Update(time); terrain.Update(time); tire_front_right->Update(time, wheel_states[FRONT_LEFT]); tire_front_left->Update(time, wheel_states[FRONT_RIGHT]); tire_rear_right->Update(time, wheel_states[REAR_LEFT]); tire_rear_left->Update(time, wheel_states[REAR_RIGHT]); vehicle.Update(time, throttle_input, steering_input, braking_input, tire_forces); // Advance simulation for one timestep for all modules double step = realtime_timer.SuggestSimulationStep(step_size); driver.Advance(step); terrain.Advance(step); tire_front_right->Advance(step); tire_front_left->Advance(step); tire_rear_right->Advance(step); tire_rear_left->Advance(step); vehicle.Advance(step); // Increment frame number step_number++; } application.GetDevice()->drop(); #else int render_frame = 0; if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) { std::cout << "Error creating directory " << out_dir << std::endl; return 1; } if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) { std::cout << "Error creating directory " << pov_dir << std::endl; return 1; } HMMWV_VehicleReduced::ExportMeshPovray(out_dir); HMMWV_WheelLeft::ExportMeshPovray(out_dir); HMMWV_WheelRight::ExportMeshPovray(out_dir); char filename[100]; while (time < tend) { if (step_number % render_steps == 0) { // Output render data sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1); utils::WriteShapesPovray(&vehicle, filename); std::cout << "Output frame: " << render_frame << std::endl; std::cout << "Sim frame: " << step_number << std::endl; std::cout << "Time: " << time << std::endl; std::cout << " throttle: " << driver.getThrottle() << " steering: " << driver.getSteering() << std::endl; std::cout << std::endl; render_frame++; } // Collect output data from modules (for inter-module communication) throttle_input = driver.getThrottle(); steering_input = driver.getSteering(); braking_input = driver.getBraking(); tire_forces[FRONT_LEFT] = tire_front_left->GetTireForce(); tire_forces[FRONT_RIGHT] = tire_front_right->GetTireForce(); tire_forces[REAR_LEFT] = tire_rear_left->GetTireForce(); tire_forces[REAR_RIGHT] = tire_rear_right->GetTireForce(); wheel_states[FRONT_LEFT] = vehicle.GetWheelState(FRONT_RIGHT); wheel_states[FRONT_RIGHT] = vehicle.GetWheelState(FRONT_LEFT); wheel_states[REAR_LEFT] = vehicle.GetWheelState(REAR_RIGHT); wheel_states[REAR_RIGHT] = vehicle.GetWheelState(REAR_LEFT); // Update modules (process inputs from other modules) time = vehicle.GetChTime(); driver.Update(time); terrain.Update(time); tire_front_right->Update(time, wheel_states[FRONT_LEFT]); tire_front_left->Update(time, wheel_states[FRONT_RIGHT]); tire_rear_right->Update(time, wheel_states[REAR_LEFT]); tire_rear_left->Update(time, wheel_states[REAR_RIGHT]); vehicle.Update(time, throttle_input, steering_input, braking_input, tire_forces); // Advance simulation for one timestep for all modules driver.Advance(step_size); terrain.Advance(step_size); tire_front_right->Advance(step_size); tire_front_left->Advance(step_size); tire_rear_right->Advance(step_size); tire_rear_left->Advance(step_size); vehicle.Advance(step_size); // Increment frame number step_number++; } #endif return 0; } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "debuggerrunner.h" #include <projectexplorer/debugginghelper.h> #include <projectexplorer/environment.h> #include <projectexplorer/project.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/target.h> #include <projectexplorer/buildconfiguration.h> #include <utils/qtcassert.h> #include <coreplugin/icore.h> #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtGui/QTextDocument> namespace Debugger { namespace Internal { using ProjectExplorer::RunConfiguration; using ProjectExplorer::RunControl; using ProjectExplorer::LocalApplicationRunConfiguration; //////////////////////////////////////////////////////////////////////// // // DebuggerRunControlFactory // //////////////////////////////////////////////////////////////////////// // A factory to create DebuggerRunControls DebuggerRunControlFactory::DebuggerRunControlFactory(DebuggerManager *manager) : m_manager(manager) {} bool DebuggerRunControlFactory::canRun(RunConfiguration *runConfiguration, const QString &mode) const { return mode == ProjectExplorer::Constants::DEBUGMODE && qobject_cast<LocalApplicationRunConfiguration *>(runConfiguration); } QString DebuggerRunControlFactory::displayName() const { return tr("Debug"); } RunControl *DebuggerRunControlFactory::create(const DebuggerStartParametersPtr &sp) { return new DebuggerRunControl(m_manager, sp); } RunControl *DebuggerRunControlFactory::create(RunConfiguration *runConfiguration, const QString &mode) { QTC_ASSERT(mode == ProjectExplorer::Constants::DEBUGMODE, return 0); LocalApplicationRunConfiguration *rc = qobject_cast<LocalApplicationRunConfiguration *>(runConfiguration); QTC_ASSERT(rc, return 0); return new DebuggerRunControl(m_manager, rc); } QWidget *DebuggerRunControlFactory::createConfigurationWidget(RunConfiguration *runConfiguration) { // NBS TODO: Add GDB-specific configuration widget Q_UNUSED(runConfiguration) return 0; } //////////////////////////////////////////////////////////////////////// // // DebuggerRunControl // //////////////////////////////////////////////////////////////////////// DebuggerRunControl::DebuggerRunControl(DebuggerManager *manager, LocalApplicationRunConfiguration *runConfiguration) : RunControl(runConfiguration), m_startParameters(new DebuggerStartParameters()), m_manager(manager), m_running(false) { init(); if (!runConfiguration) return; m_startParameters->startMode = StartInternal; m_startParameters->executable = runConfiguration->executable(); m_startParameters->environment = runConfiguration->environment().toStringList(); m_startParameters->workingDir = runConfiguration->workingDirectory(); m_startParameters->processArgs = runConfiguration->commandLineArguments(); switch (m_startParameters->toolChainType) { case ProjectExplorer::ToolChain::UNKNOWN: case ProjectExplorer::ToolChain::INVALID: m_startParameters->toolChainType = runConfiguration->toolChainType(); break; default: break; } if (runConfiguration->target()->project()) { m_startParameters->buildDir = runConfiguration->target()->activeBuildConfiguration()->buildDirectory(); } m_startParameters->useTerminal = runConfiguration->runMode() == LocalApplicationRunConfiguration::Console; m_startParameters->dumperLibrary = runConfiguration->dumperLibrary(); m_startParameters->dumperLibraryLocations = runConfiguration->dumperLibraryLocations(); QString qmakePath = ProjectExplorer::DebuggingHelperLibrary::findSystemQt( runConfiguration->environment()); if (!qmakePath.isEmpty()) { QProcess proc; QStringList args; args.append(QLatin1String("-query")); args.append(QLatin1String("QT_INSTALL_HEADERS")); proc.start(qmakePath, args); proc.waitForFinished(); QByteArray ba = proc.readAllStandardOutput().trimmed(); QFileInfo fi(QString::fromLocal8Bit(ba) + "/.."); m_startParameters->qtInstallPath = fi.absoluteFilePath(); } } DebuggerRunControl::DebuggerRunControl(DebuggerManager *manager, const DebuggerStartParametersPtr &startParameters) : RunControl(0), m_startParameters(startParameters), m_manager(manager), m_running(false) { init(); if (m_startParameters->environment.empty()) m_startParameters->environment = ProjectExplorer::Environment::Environment().toStringList(); m_startParameters->useTerminal = false; } void DebuggerRunControl::setCustomEnvironment(ProjectExplorer::Environment env) { m_startParameters->environment = env.toStringList(); } void DebuggerRunControl::init() { connect(m_manager, SIGNAL(debuggingFinished()), this, SLOT(debuggingFinished()), Qt::QueuedConnection); connect(m_manager, SIGNAL(applicationOutputAvailable(QString, bool)), this, SLOT(slotAddToOutputWindowInline(QString, bool)), Qt::QueuedConnection); connect(m_manager, SIGNAL(messageAvailable(QString, bool)), this, SLOT(slotMessageAvailable(QString, bool))); connect(m_manager, SIGNAL(inferiorPidChanged(qint64)), this, SLOT(bringApplicationToForeground(qint64)), Qt::QueuedConnection); connect(this, SIGNAL(stopRequested()), m_manager, SLOT(exitDebugger())); } void DebuggerRunControl::start() { m_running = true; QString errorMessage; QString settingsCategory; QString settingsPage; if (m_manager->checkDebugConfiguration(startParameters()->toolChainType, &errorMessage, &settingsCategory, &settingsPage)) { m_manager->startNewDebugger(m_startParameters); emit started(); } else { appendMessage(this, errorMessage, true); emit finished(); Core::ICore::instance()->showWarningWithOptions(tr("Debugger"), errorMessage, QString(), settingsCategory, settingsPage); } } void DebuggerRunControl::slotAddToOutputWindowInline(const QString &data, bool onStdErr) { emit addToOutputWindowInline(this, data, onStdErr); } void DebuggerRunControl::slotMessageAvailable(const QString &data, bool isError) { emit appendMessage(this, data, isError); } void DebuggerRunControl::stop() { m_running = false; emit stopRequested(); } void DebuggerRunControl::debuggingFinished() { m_running = false; emit finished(); } bool DebuggerRunControl::isRunning() const { return m_running; } } // namespace Internal } // namespace Debugger <commit_msg>Compile fix gcc 4.5/MinGW<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "debuggerrunner.h" #include <projectexplorer/debugginghelper.h> #include <projectexplorer/environment.h> #include <projectexplorer/project.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/target.h> #include <projectexplorer/buildconfiguration.h> #include <utils/qtcassert.h> #include <coreplugin/icore.h> #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtGui/QTextDocument> namespace Debugger { namespace Internal { using ProjectExplorer::RunConfiguration; using ProjectExplorer::RunControl; using ProjectExplorer::LocalApplicationRunConfiguration; //////////////////////////////////////////////////////////////////////// // // DebuggerRunControlFactory // //////////////////////////////////////////////////////////////////////// // A factory to create DebuggerRunControls DebuggerRunControlFactory::DebuggerRunControlFactory(DebuggerManager *manager) : m_manager(manager) {} bool DebuggerRunControlFactory::canRun(RunConfiguration *runConfiguration, const QString &mode) const { return mode == ProjectExplorer::Constants::DEBUGMODE && qobject_cast<LocalApplicationRunConfiguration *>(runConfiguration); } QString DebuggerRunControlFactory::displayName() const { return tr("Debug"); } RunControl *DebuggerRunControlFactory::create(const DebuggerStartParametersPtr &sp) { return new DebuggerRunControl(m_manager, sp); } RunControl *DebuggerRunControlFactory::create(RunConfiguration *runConfiguration, const QString &mode) { QTC_ASSERT(mode == ProjectExplorer::Constants::DEBUGMODE, return 0); LocalApplicationRunConfiguration *rc = qobject_cast<LocalApplicationRunConfiguration *>(runConfiguration); QTC_ASSERT(rc, return 0); return new DebuggerRunControl(m_manager, rc); } QWidget *DebuggerRunControlFactory::createConfigurationWidget(RunConfiguration *runConfiguration) { // NBS TODO: Add GDB-specific configuration widget Q_UNUSED(runConfiguration) return 0; } //////////////////////////////////////////////////////////////////////// // // DebuggerRunControl // //////////////////////////////////////////////////////////////////////// DebuggerRunControl::DebuggerRunControl(DebuggerManager *manager, LocalApplicationRunConfiguration *runConfiguration) : RunControl(runConfiguration), m_startParameters(new DebuggerStartParameters()), m_manager(manager), m_running(false) { init(); if (!runConfiguration) return; m_startParameters->startMode = StartInternal; m_startParameters->executable = runConfiguration->executable(); m_startParameters->environment = runConfiguration->environment().toStringList(); m_startParameters->workingDir = runConfiguration->workingDirectory(); m_startParameters->processArgs = runConfiguration->commandLineArguments(); switch (m_startParameters->toolChainType) { case ProjectExplorer::ToolChain::UNKNOWN: case ProjectExplorer::ToolChain::INVALID: m_startParameters->toolChainType = runConfiguration->toolChainType(); break; default: break; } if (runConfiguration->target()->project()) { m_startParameters->buildDir = runConfiguration->target()->activeBuildConfiguration()->buildDirectory(); } m_startParameters->useTerminal = runConfiguration->runMode() == LocalApplicationRunConfiguration::Console; m_startParameters->dumperLibrary = runConfiguration->dumperLibrary(); m_startParameters->dumperLibraryLocations = runConfiguration->dumperLibraryLocations(); QString qmakePath = ProjectExplorer::DebuggingHelperLibrary::findSystemQt( runConfiguration->environment()); if (!qmakePath.isEmpty()) { QProcess proc; QStringList args; args.append(QLatin1String("-query")); args.append(QLatin1String("QT_INSTALL_HEADERS")); proc.start(qmakePath, args); proc.waitForFinished(); QByteArray ba = proc.readAllStandardOutput().trimmed(); QFileInfo fi(QString::fromLocal8Bit(ba) + "/.."); m_startParameters->qtInstallPath = fi.absoluteFilePath(); } } DebuggerRunControl::DebuggerRunControl(DebuggerManager *manager, const DebuggerStartParametersPtr &startParameters) : RunControl(0), m_startParameters(startParameters), m_manager(manager), m_running(false) { init(); if (m_startParameters->environment.empty()) m_startParameters->environment = ProjectExplorer::Environment().toStringList(); m_startParameters->useTerminal = false; } void DebuggerRunControl::setCustomEnvironment(ProjectExplorer::Environment env) { m_startParameters->environment = env.toStringList(); } void DebuggerRunControl::init() { connect(m_manager, SIGNAL(debuggingFinished()), this, SLOT(debuggingFinished()), Qt::QueuedConnection); connect(m_manager, SIGNAL(applicationOutputAvailable(QString, bool)), this, SLOT(slotAddToOutputWindowInline(QString, bool)), Qt::QueuedConnection); connect(m_manager, SIGNAL(messageAvailable(QString, bool)), this, SLOT(slotMessageAvailable(QString, bool))); connect(m_manager, SIGNAL(inferiorPidChanged(qint64)), this, SLOT(bringApplicationToForeground(qint64)), Qt::QueuedConnection); connect(this, SIGNAL(stopRequested()), m_manager, SLOT(exitDebugger())); } void DebuggerRunControl::start() { m_running = true; QString errorMessage; QString settingsCategory; QString settingsPage; if (m_manager->checkDebugConfiguration(startParameters()->toolChainType, &errorMessage, &settingsCategory, &settingsPage)) { m_manager->startNewDebugger(m_startParameters); emit started(); } else { appendMessage(this, errorMessage, true); emit finished(); Core::ICore::instance()->showWarningWithOptions(tr("Debugger"), errorMessage, QString(), settingsCategory, settingsPage); } } void DebuggerRunControl::slotAddToOutputWindowInline(const QString &data, bool onStdErr) { emit addToOutputWindowInline(this, data, onStdErr); } void DebuggerRunControl::slotMessageAvailable(const QString &data, bool isError) { emit appendMessage(this, data, isError); } void DebuggerRunControl::stop() { m_running = false; emit stopRequested(); } void DebuggerRunControl::debuggingFinished() { m_running = false; emit finished(); } bool DebuggerRunControl::isRunning() const { return m_running; } } // namespace Internal } // namespace Debugger <|endoftext|>
<commit_before>/* libs/graphics/sgl/SkScan_AntiPath.cpp ** ** Copyright 2006, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ #include "SkScanPriv.h" #include "SkPath.h" #include "SkMatrix.h" #include "SkBlitter.h" #include "SkRegion.h" #include "SkAntiRun.h" #define SHIFT 2 #define SCALE (1 << SHIFT) #define MASK (SCALE - 1) /////////////////////////////////////////////////////////////////////////////////////////// class BaseSuperBlitter : public SkBlitter { public: BaseSuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkRegion& clip); virtual void blitAntiH(int x, int y, const SkAlpha antialias[], const int16_t runs[]) { SkASSERT(!"How did I get here?"); } virtual void blitV(int x, int y, int height, SkAlpha alpha) { SkASSERT(!"How did I get here?"); } virtual void blitRect(int x, int y, int width, int height) { SkASSERT(!"How did I get here?"); } protected: SkBlitter* fRealBlitter; int fCurrIY; int fWidth, fLeft, fSuperLeft; SkDEBUGCODE(int fCurrX;) SkDEBUGCODE(int fCurrY;) }; BaseSuperBlitter::BaseSuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkRegion& clip) { fRealBlitter = realBlitter; // take the union of the ir bounds and clip, since we may be called with an // inverse filltype const int left = SkMin32(ir.fLeft, clip.getBounds().fLeft); const int right = SkMax32(ir.fRight, clip.getBounds().fRight); fLeft = left; fSuperLeft = left << SHIFT; fWidth = right - left; fCurrIY = -1; SkDEBUGCODE(fCurrX = -1; fCurrY = -1;) } class SuperBlitter : public BaseSuperBlitter { public: SuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkRegion& clip); virtual ~SuperBlitter() { this->flush(); sk_free(fRuns.fRuns); } void flush(); virtual void blitH(int x, int y, int width); private: SkAlphaRuns fRuns; }; SuperBlitter::SuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkRegion& clip) : BaseSuperBlitter(realBlitter, ir, clip) { const int width = fWidth; // extra one to store the zero at the end fRuns.fRuns = (int16_t*)sk_malloc_throw((width + 1 + (width + 2)/2) * sizeof(int16_t)); fRuns.fAlpha = (uint8_t*)(fRuns.fRuns + width + 1); fRuns.reset(width); } void SuperBlitter::flush() { if (fCurrIY >= 0) { if (!fRuns.empty()) { // SkDEBUGCODE(fRuns.dump();) fRealBlitter->blitAntiH(fLeft, fCurrIY, fRuns.fAlpha, fRuns.fRuns); fRuns.reset(fWidth); } fCurrIY = -1; SkDEBUGCODE(fCurrX = -1;) } } static inline int coverage_to_alpha(int aa) { aa <<= 8 - 2*SHIFT; aa -= aa >> (8 - SHIFT - 1); return aa; } #define SUPER_Mask ((1 << SHIFT) - 1) void SuperBlitter::blitH(int x, int y, int width) { int iy = y >> SHIFT; SkASSERT(iy >= fCurrIY); x -= fSuperLeft; // hack, until I figure out why my cubics (I think) go beyond the bounds if (x < 0) { width += x; x = 0; } #ifdef SK_DEBUG SkASSERT(y >= fCurrY); SkASSERT(y != fCurrY || x >= fCurrX); fCurrY = y; #endif if (iy != fCurrIY) // new scanline { this->flush(); fCurrIY = iy; } // we sub 1 from maxValue 1 time for each block, so that we don't // hit 256 as a summed max, but 255. // int maxValue = (1 << (8 - SHIFT)) - (((y & MASK) + 1) >> SHIFT); #if 0 SkAntiRun<SHIFT> arun; arun.set(x, x + width); fRuns.add(x >> SHIFT, arun.getStartAlpha(), arun.getMiddleCount(), arun.getStopAlpha(), maxValue); #else { int start = x; int stop = x + width; SkASSERT(start >= 0 && stop > start); int fb = start & SUPER_Mask; int fe = stop & SUPER_Mask; int n = (stop >> SHIFT) - (start >> SHIFT) - 1; if (n < 0) { fb = fe - fb; n = 0; fe = 0; } else { if (fb == 0) n += 1; else fb = (1 << SHIFT) - fb; } fRuns.add(x >> SHIFT, coverage_to_alpha(fb), n, coverage_to_alpha(fe), (1 << (8 - SHIFT)) - (((y & MASK) + 1) >> SHIFT)); } #endif #ifdef SK_DEBUG fRuns.assertValid(y & MASK, (1 << (8 - SHIFT))); fCurrX = x + width; #endif } /////////////////////////////////////////////////////////////////////////////// class MaskSuperBlitter : public BaseSuperBlitter { public: MaskSuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkRegion& clip); virtual ~MaskSuperBlitter() { fRealBlitter->blitMask(fMask, fClipRect); } virtual void blitH(int x, int y, int width); static bool CanHandleRect(const SkIRect& bounds) { int width = bounds.width(); int rb = SkAlign4(width); return (width <= MaskSuperBlitter::kMAX_WIDTH) && (rb * bounds.height() <= MaskSuperBlitter::kMAX_STORAGE); } private: enum { kMAX_WIDTH = 32, // so we don't try to do very wide things, where the RLE blitter would be faster kMAX_STORAGE = 1024 }; SkMask fMask; SkIRect fClipRect; // we add 1 because add_aa_span can write (unchanged) 1 extra byte at the end, rather than // perform a test to see if stopAlpha != 0 uint32_t fStorage[(kMAX_STORAGE >> 2) + 1]; }; MaskSuperBlitter::MaskSuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkRegion& clip) : BaseSuperBlitter(realBlitter, ir, clip) { SkASSERT(CanHandleRect(ir)); fMask.fImage = (uint8_t*)fStorage; fMask.fBounds = ir; fMask.fRowBytes = ir.width(); fMask.fFormat = SkMask::kA8_Format; fClipRect = ir; fClipRect.intersect(clip.getBounds()); // For valgrind, write 1 extra byte at the end so we don't read // uninitialized memory. See comment in add_aa_span and fStorage[]. memset(fStorage, 0, fMask.fBounds.height() * fMask.fRowBytes + 1); } static void add_aa_span(uint8_t* alpha, U8CPU startAlpha) { /* I should be able to just add alpha[x] + startAlpha. However, if the trailing edge of the previous span and the leading edge of the current span round to the same super-sampled x value, I might overflow to 256 with this add, hence the funny subtract. */ unsigned tmp = *alpha + startAlpha; SkASSERT(tmp <= 256); *alpha = SkToU8(tmp - (tmp >> 8)); } static void add_aa_span(uint8_t* alpha, U8CPU startAlpha, int middleCount, U8CPU stopAlpha, U8CPU maxValue) { SkASSERT(middleCount >= 0); /* I should be able to just add alpha[x] + startAlpha. However, if the trailing edge of the previous span and the leading edge of the current span round to the same super-sampled x value, I might overflow to 256 with this add, hence the funny subtract. */ unsigned tmp = *alpha + startAlpha; SkASSERT(tmp <= 256); *alpha++ = SkToU8(tmp - (tmp >> 8)); while (--middleCount >= 0) { alpha[0] = SkToU8(alpha[0] + maxValue); alpha += 1; } // potentially this can be off the end of our "legal" alpha values, but that // only happens if stopAlpha is also 0. Rather than test for stopAlpha != 0 // every time (slow), we just do it, and ensure that we've allocated extra space // (see the + 1 comment in fStorage[] *alpha = SkToU8(*alpha + stopAlpha); } void MaskSuperBlitter::blitH(int x, int y, int width) { int iy = (y >> SHIFT); SkASSERT(iy >= fMask.fBounds.fTop && iy < fMask.fBounds.fBottom); iy -= fMask.fBounds.fTop; // make it relative to 0 #ifdef SK_DEBUG { int ix = x >> SHIFT; SkASSERT(ix >= fMask.fBounds.fLeft && ix < fMask.fBounds.fRight); } #endif x -= (fMask.fBounds.fLeft << SHIFT); // hack, until I figure out why my cubics (I think) go beyond the bounds if (x < 0) { width += x; x = 0; } // we sub 1 from maxValue 1 time for each block, so that we don't // hit 256 as a summed max, but 255. // int maxValue = (1 << (8 - SHIFT)) - (((y & MASK) + 1) >> SHIFT); uint8_t* row = fMask.fImage + iy * fMask.fRowBytes + (x >> SHIFT); int start = x; int stop = x + width; SkASSERT(start >= 0 && stop > start); int fb = start & SUPER_Mask; int fe = stop & SUPER_Mask; int n = (stop >> SHIFT) - (start >> SHIFT) - 1; if (n < 0) { add_aa_span(row, coverage_to_alpha(fe - fb)); } else { fb = (1 << SHIFT) - fb; add_aa_span(row, coverage_to_alpha(fb), n, coverage_to_alpha(fe), (1 << (8 - SHIFT)) - (((y & MASK) + 1) >> SHIFT)); } #ifdef SK_DEBUG fCurrX = x + width; #endif } /////////////////////////////////////////////////////////////////////////////// /* Returns non-zero if (value << shift) overflows a short, which would mean we could not shift it up and then convert to SkFixed. i.e. is x expressible as signed (16-shift) bits? */ static int overflows_short_shift(int value, int shift) { const int s = 16 + shift; return (value << s >> s) - value; } void SkScan::AntiFillPath(const SkPath& path, const SkRegion& clip, SkBlitter* blitter) { if (clip.isEmpty()) { return; } SkIRect ir; path.getBounds().roundOut(&ir); if (ir.isEmpty()) { return; } // use bit-or since we expect all to pass, so no need to go slower with // a short-circuiting logical-or if (overflows_short_shift(ir.fLeft, SHIFT) | overflows_short_shift(ir.fRight, SHIFT) | overflows_short_shift(ir.fTop, SHIFT) | overflows_short_shift(ir.fBottom, SHIFT)) { // can't supersample, so draw w/o antialiasing SkScan::FillPath(path, clip, blitter); return; } SkScanClipper clipper(blitter, &clip, ir); const SkIRect* clipRect = clipper.getClipRect(); if (clipper.getBlitter() == NULL) { // clipped out if (path.isInverseFillType()) { blitter->blitRegion(clip); } return; } // now use the (possibly wrapped) blitter blitter = clipper.getBlitter(); if (path.isInverseFillType()) { sk_blit_above_and_below(blitter, ir, clip); } SkIRect superRect, *superClipRect = NULL; if (clipRect) { superRect.set( clipRect->fLeft << SHIFT, clipRect->fTop << SHIFT, clipRect->fRight << SHIFT, clipRect->fBottom << SHIFT); superClipRect = &superRect; } // MaskSuperBlitter can't handle drawing outside of ir, so we can't use it // if we're an inverse filltype if (!path.isInverseFillType() && MaskSuperBlitter::CanHandleRect(ir)) { MaskSuperBlitter superBlit(blitter, ir, clip); sk_fill_path(path, superClipRect, &superBlit, ir.fBottom, SHIFT, clip); } else { SuperBlitter superBlit(blitter, ir, clip); sk_fill_path(path, superClipRect, &superBlit, ir.fBottom, SHIFT, clip); } } <commit_msg>Add some SkASSERT's, to try to track down a reliability issue in Chrome.<commit_after>/* libs/graphics/sgl/SkScan_AntiPath.cpp ** ** Copyright 2006, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ #include "SkScanPriv.h" #include "SkPath.h" #include "SkMatrix.h" #include "SkBlitter.h" #include "SkRegion.h" #include "SkAntiRun.h" #define SHIFT 2 #define SCALE (1 << SHIFT) #define MASK (SCALE - 1) /////////////////////////////////////////////////////////////////////////////////////////// class BaseSuperBlitter : public SkBlitter { public: BaseSuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkRegion& clip); virtual void blitAntiH(int x, int y, const SkAlpha antialias[], const int16_t runs[]) { SkASSERT(!"How did I get here?"); } virtual void blitV(int x, int y, int height, SkAlpha alpha) { SkASSERT(!"How did I get here?"); } virtual void blitRect(int x, int y, int width, int height) { SkASSERT(!"How did I get here?"); } protected: SkBlitter* fRealBlitter; int fCurrIY; int fWidth, fLeft, fSuperLeft; SkDEBUGCODE(int fCurrX;) SkDEBUGCODE(int fCurrY;) }; BaseSuperBlitter::BaseSuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkRegion& clip) { fRealBlitter = realBlitter; // take the union of the ir bounds and clip, since we may be called with an // inverse filltype const int left = SkMin32(ir.fLeft, clip.getBounds().fLeft); const int right = SkMax32(ir.fRight, clip.getBounds().fRight); fLeft = left; fSuperLeft = left << SHIFT; fWidth = right - left; fCurrIY = -1; SkDEBUGCODE(fCurrX = -1; fCurrY = -1;) } class SuperBlitter : public BaseSuperBlitter { public: SuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkRegion& clip); virtual ~SuperBlitter() { this->flush(); sk_free(fRuns.fRuns); } void flush(); virtual void blitH(int x, int y, int width); private: SkAlphaRuns fRuns; }; SuperBlitter::SuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkRegion& clip) : BaseSuperBlitter(realBlitter, ir, clip) { const int width = fWidth; // extra one to store the zero at the end fRuns.fRuns = (int16_t*)sk_malloc_throw((width + 1 + (width + 2)/2) * sizeof(int16_t)); fRuns.fAlpha = (uint8_t*)(fRuns.fRuns + width + 1); fRuns.reset(width); } void SuperBlitter::flush() { if (fCurrIY >= 0) { if (!fRuns.empty()) { // SkDEBUGCODE(fRuns.dump();) fRealBlitter->blitAntiH(fLeft, fCurrIY, fRuns.fAlpha, fRuns.fRuns); fRuns.reset(fWidth); } fCurrIY = -1; SkDEBUGCODE(fCurrX = -1;) } } static inline int coverage_to_alpha(int aa) { aa <<= 8 - 2*SHIFT; aa -= aa >> (8 - SHIFT - 1); return aa; } #define SUPER_Mask ((1 << SHIFT) - 1) void SuperBlitter::blitH(int x, int y, int width) { int iy = y >> SHIFT; SkASSERT(iy >= fCurrIY); x -= fSuperLeft; // hack, until I figure out why my cubics (I think) go beyond the bounds if (x < 0) { width += x; x = 0; } #ifdef SK_DEBUG SkASSERT(y >= fCurrY); SkASSERT(y != fCurrY || x >= fCurrX); fCurrY = y; #endif if (iy != fCurrIY) // new scanline { this->flush(); fCurrIY = iy; } // we sub 1 from maxValue 1 time for each block, so that we don't // hit 256 as a summed max, but 255. // int maxValue = (1 << (8 - SHIFT)) - (((y & MASK) + 1) >> SHIFT); #if 0 SkAntiRun<SHIFT> arun; arun.set(x, x + width); fRuns.add(x >> SHIFT, arun.getStartAlpha(), arun.getMiddleCount(), arun.getStopAlpha(), maxValue); #else { int start = x; int stop = x + width; SkASSERT(start >= 0 && stop > start); int fb = start & SUPER_Mask; int fe = stop & SUPER_Mask; int n = (stop >> SHIFT) - (start >> SHIFT) - 1; if (n < 0) { fb = fe - fb; n = 0; fe = 0; } else { if (fb == 0) n += 1; else fb = (1 << SHIFT) - fb; } fRuns.add(x >> SHIFT, coverage_to_alpha(fb), n, coverage_to_alpha(fe), (1 << (8 - SHIFT)) - (((y & MASK) + 1) >> SHIFT)); } #endif #ifdef SK_DEBUG fRuns.assertValid(y & MASK, (1 << (8 - SHIFT))); fCurrX = x + width; #endif } /////////////////////////////////////////////////////////////////////////////// class MaskSuperBlitter : public BaseSuperBlitter { public: MaskSuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkRegion& clip); virtual ~MaskSuperBlitter() { fRealBlitter->blitMask(fMask, fClipRect); } virtual void blitH(int x, int y, int width); static bool CanHandleRect(const SkIRect& bounds) { int width = bounds.width(); int rb = SkAlign4(width); return (width <= MaskSuperBlitter::kMAX_WIDTH) && (rb * bounds.height() <= MaskSuperBlitter::kMAX_STORAGE); } private: enum { kMAX_WIDTH = 32, // so we don't try to do very wide things, where the RLE blitter would be faster kMAX_STORAGE = 1024 }; SkMask fMask; SkIRect fClipRect; // we add 1 because add_aa_span can write (unchanged) 1 extra byte at the end, rather than // perform a test to see if stopAlpha != 0 uint32_t fStorage[(kMAX_STORAGE >> 2) + 1]; }; MaskSuperBlitter::MaskSuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkRegion& clip) : BaseSuperBlitter(realBlitter, ir, clip) { SkASSERT(CanHandleRect(ir)); fMask.fImage = (uint8_t*)fStorage; fMask.fBounds = ir; fMask.fRowBytes = ir.width(); fMask.fFormat = SkMask::kA8_Format; fClipRect = ir; fClipRect.intersect(clip.getBounds()); // For valgrind, write 1 extra byte at the end so we don't read // uninitialized memory. See comment in add_aa_span and fStorage[]. memset(fStorage, 0, fMask.fBounds.height() * fMask.fRowBytes + 1); } static void add_aa_span(uint8_t* alpha, U8CPU startAlpha) { /* I should be able to just add alpha[x] + startAlpha. However, if the trailing edge of the previous span and the leading edge of the current span round to the same super-sampled x value, I might overflow to 256 with this add, hence the funny subtract. */ unsigned tmp = *alpha + startAlpha; SkASSERT(tmp <= 256); *alpha = SkToU8(tmp - (tmp >> 8)); } static void add_aa_span(uint8_t* alpha, U8CPU startAlpha, int middleCount, U8CPU stopAlpha, U8CPU maxValue) { SkASSERT(middleCount >= 0); /* I should be able to just add alpha[x] + startAlpha. However, if the trailing edge of the previous span and the leading edge of the current span round to the same super-sampled x value, I might overflow to 256 with this add, hence the funny subtract. */ unsigned tmp = *alpha + startAlpha; SkASSERT(tmp <= 256); *alpha++ = SkToU8(tmp - (tmp >> 8)); while (--middleCount >= 0) { alpha[0] = SkToU8(alpha[0] + maxValue); alpha += 1; } // potentially this can be off the end of our "legal" alpha values, but that // only happens if stopAlpha is also 0. Rather than test for stopAlpha != 0 // every time (slow), we just do it, and ensure that we've allocated extra space // (see the + 1 comment in fStorage[] *alpha = SkToU8(*alpha + stopAlpha); } void MaskSuperBlitter::blitH(int x, int y, int width) { int iy = (y >> SHIFT); SkASSERT(iy >= fMask.fBounds.fTop && iy < fMask.fBounds.fBottom); iy -= fMask.fBounds.fTop; // make it relative to 0 #ifdef SK_DEBUG { int ix = x >> SHIFT; SkASSERT(ix >= fMask.fBounds.fLeft && ix < fMask.fBounds.fRight); } #endif x -= (fMask.fBounds.fLeft << SHIFT); // hack, until I figure out why my cubics (I think) go beyond the bounds if (x < 0) { width += x; x = 0; } // we sub 1 from maxValue 1 time for each block, so that we don't // hit 256 as a summed max, but 255. // int maxValue = (1 << (8 - SHIFT)) - (((y & MASK) + 1) >> SHIFT); uint8_t* row = fMask.fImage + iy * fMask.fRowBytes + (x >> SHIFT); int start = x; int stop = x + width; SkASSERT(start >= 0 && stop > start); int fb = start & SUPER_Mask; int fe = stop & SUPER_Mask; int n = (stop >> SHIFT) - (start >> SHIFT) - 1; if (n < 0) { SkASSERT(row >= fMask.fImage); SkASSERT(row < fMask.fImage + kMAX_STORAGE + 1); add_aa_span(row, coverage_to_alpha(fe - fb)); } else { fb = (1 << SHIFT) - fb; SkASSERT(row >= fMask.fImage); SkASSERT(row + n + 1 < fMask.fImage + kMAX_STORAGE + 1); add_aa_span(row, coverage_to_alpha(fb), n, coverage_to_alpha(fe), (1 << (8 - SHIFT)) - (((y & MASK) + 1) >> SHIFT)); } #ifdef SK_DEBUG fCurrX = x + width; #endif } /////////////////////////////////////////////////////////////////////////////// /* Returns non-zero if (value << shift) overflows a short, which would mean we could not shift it up and then convert to SkFixed. i.e. is x expressible as signed (16-shift) bits? */ static int overflows_short_shift(int value, int shift) { const int s = 16 + shift; return (value << s >> s) - value; } void SkScan::AntiFillPath(const SkPath& path, const SkRegion& clip, SkBlitter* blitter) { if (clip.isEmpty()) { return; } SkIRect ir; path.getBounds().roundOut(&ir); if (ir.isEmpty()) { return; } // use bit-or since we expect all to pass, so no need to go slower with // a short-circuiting logical-or if (overflows_short_shift(ir.fLeft, SHIFT) | overflows_short_shift(ir.fRight, SHIFT) | overflows_short_shift(ir.fTop, SHIFT) | overflows_short_shift(ir.fBottom, SHIFT)) { // can't supersample, so draw w/o antialiasing SkScan::FillPath(path, clip, blitter); return; } SkScanClipper clipper(blitter, &clip, ir); const SkIRect* clipRect = clipper.getClipRect(); if (clipper.getBlitter() == NULL) { // clipped out if (path.isInverseFillType()) { blitter->blitRegion(clip); } return; } // now use the (possibly wrapped) blitter blitter = clipper.getBlitter(); if (path.isInverseFillType()) { sk_blit_above_and_below(blitter, ir, clip); } SkIRect superRect, *superClipRect = NULL; if (clipRect) { superRect.set( clipRect->fLeft << SHIFT, clipRect->fTop << SHIFT, clipRect->fRight << SHIFT, clipRect->fBottom << SHIFT); superClipRect = &superRect; } // MaskSuperBlitter can't handle drawing outside of ir, so we can't use it // if we're an inverse filltype if (!path.isInverseFillType() && MaskSuperBlitter::CanHandleRect(ir)) { MaskSuperBlitter superBlit(blitter, ir, clip); sk_fill_path(path, superClipRect, &superBlit, ir.fBottom, SHIFT, clip); } else { SuperBlitter superBlit(blitter, ir, clip); sk_fill_path(path, superClipRect, &superBlit, ir.fBottom, SHIFT, clip); } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.2 1999/12/23 01:43:37 aruna1 * MsgCatalog support added for solaris * * Revision 1.1.1.1 1999/11/09 01:07:16 twl * Initial checkin * * Revision 1.2 1999/11/08 20:45:27 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/XML4CDefs.hpp> #include <util/PlatformUtils.hpp> #include <util/XMLMsgLoader.hpp> #include <util/XMLString.hpp> #include <util/XMLUni.hpp> #include "MsgCatalogLoader.hpp" #include <locale.h> #include <stdlib.h> #include <stdio.h> // --------------------------------------------------------------------------- // Public Constructors and Destructor // --------------------------------------------------------------------------- MsgCatalogLoader::MsgCatalogLoader(const XMLCh* const msgDomain) : fCatalogHandle(0) , fMsgDomain(0) { // Try to get the module handle char* tempLoc = setlocale(LC_ALL, ""); char catfile[256]; if (XMLPlatformUtils::fgLibLocation) { strcpy(catfile, XMLPlatformUtils::fgLibLocation); strcat(catfile, "/msg/"); strcat(catfile, "XMLMessages.cat"); } fCatalogHandle = catopen(catfile , 0); if ((int)fCatalogHandle == -1) { // Probably have to call panic here printf("Could not open catalog XMLMessages\n"); // TBD: Tell user what the locale is exit(1); } fMsgDomain = XMLString::replicate(msgDomain); } MsgCatalogLoader::~MsgCatalogLoader() { if (fCatalogHandle) catclose( fCatalogHandle ); delete fMsgDomain; } // --------------------------------------------------------------------------- // Implementation of the virtual message loader API // --------------------------------------------------------------------------- bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned long maxChars) { int msgSet = 1; if (!XMLString::compareString(fMsgDomain, XMLUni::fgXMLErrDomain)) msgSet = 1; else if (!XMLString::compareString(fMsgDomain, XMLUni::fgExceptDomain)) msgSet = 2; else if (!XMLString::compareString(fMsgDomain, XMLUni::fgValidityDomain)) msgSet = 3; char msgString[100]; sprintf(msgString, "Could not find message ID %d from message set %d\n", msgToLoad, msgSet); char* catMessage = catgets( fCatalogHandle, msgSet, (int)msgToLoad, msgString); XMLString::copyString((XMLCh*)toFill, XMLString::transcode(catMessage)); return true; } bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned long maxChars , const XMLCh* const repText1 , const XMLCh* const repText2 , const XMLCh* const repText3 , const XMLCh* const repText4) { // Call the other version to load up the message if (!loadMsg(msgToLoad, toFill, maxChars)) return false; // And do the token replacement XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4); return true; } bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned long maxChars , const char* const repText1 , const char* const repText2 , const char* const repText3 , const char* const repText4) { // // Transcode the provided parameters and call the other version, // which will do the replacement work. // XMLCh* tmp1 = 0; XMLCh* tmp2 = 0; XMLCh* tmp3 = 0; XMLCh* tmp4 = 0; bool bRet = false; if (repText1) tmp1 = XMLString::transcode(repText1); if (repText2) tmp2 = XMLString::transcode(repText2); if (repText3) tmp3 = XMLString::transcode(repText3); if (repText4) tmp4 = XMLString::transcode(repText4); bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4); if (tmp1) delete [] tmp1; if (tmp2) delete [] tmp2; if (tmp3) delete [] tmp3; if (tmp4) delete [] tmp4; return bRet; } <commit_msg>Modified message 'set' attribute reading sequence. Removed dependencies on hard coded constants<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.3 2000/01/05 22:00:22 aruna1 * Modified message 'set' attribute reading sequence. Removed dependencies on hard coded constants * * Revision 1.2 1999/12/23 01:43:37 aruna1 * MsgCatalog support added for solaris * * Revision 1.1.1.1 1999/11/09 01:07:16 twl * Initial checkin * * Revision 1.2 1999/11/08 20:45:27 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/XML4CDefs.hpp> #include <util/PlatformUtils.hpp> #include <util/XMLMsgLoader.hpp> #include <util/XMLString.hpp> #include <util/XMLUni.hpp> #include "MsgCatalogLoader.hpp" #include "XMLMsgCat_Ids.hpp" #include <locale.h> #include <stdlib.h> #include <stdio.h> #include <string.h> // --------------------------------------------------------------------------- // Public Constructors and Destructor // --------------------------------------------------------------------------- MsgCatalogLoader::MsgCatalogLoader(const XMLCh* const msgDomain) : fCatalogHandle(0) , fMsgDomain(0) { // Try to get the module handle char* tempLoc = setlocale(LC_ALL, ""); char catfile[256]; if (XMLPlatformUtils::fgLibLocation) { strcpy(catfile, XMLPlatformUtils::fgLibLocation); strcat(catfile, "/msg/"); strcat(catfile, "XMLMessages.cat"); } fCatalogHandle = catopen(catfile , 0); if ((int)fCatalogHandle == -1) { // Probably have to call panic here printf("Could not open catalog XMLMessages\n"); // TBD: Tell user what the locale is exit(1); } fMsgDomain = XMLString::replicate(msgDomain); } MsgCatalogLoader::~MsgCatalogLoader() { if (fCatalogHandle) catclose( fCatalogHandle ); delete fMsgDomain; } // --------------------------------------------------------------------------- // Implementation of the virtual message loader API // --------------------------------------------------------------------------- bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned long maxChars) { int msgSet = CatId_XML4CErrs; if (!XMLString::compareString(fMsgDomain, XMLUni::fgXMLErrDomain)) msgSet = CatId_XML4CErrs; else if (!XMLString::compareString(fMsgDomain, XMLUni::fgExceptDomain)) msgSet = CatId_XML4CExcepts; else if (!XMLString::compareString(fMsgDomain, XMLUni::fgValidityDomain)) msgSet = CatId_XML4CValid; char msgString[100]; sprintf(msgString, "Could not find message ID %d from message set %d\n", msgToLoad, msgSet); char* catMessage = catgets( fCatalogHandle, msgSet, (int)msgToLoad, msgString); XMLString::copyString((XMLCh*)toFill, XMLString::transcode(catMessage)); return true; } bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned long maxChars , const XMLCh* const repText1 , const XMLCh* const repText2 , const XMLCh* const repText3 , const XMLCh* const repText4) { // Call the other version to load up the message if (!loadMsg(msgToLoad, toFill, maxChars)) return false; // And do the token replacement XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4); return true; } bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned long maxChars , const char* const repText1 , const char* const repText2 , const char* const repText3 , const char* const repText4) { // // Transcode the provided parameters and call the other version, // which will do the replacement work. // XMLCh* tmp1 = 0; XMLCh* tmp2 = 0; XMLCh* tmp3 = 0; XMLCh* tmp4 = 0; bool bRet = false; if (repText1) tmp1 = XMLString::transcode(repText1); if (repText2) tmp2 = XMLString::transcode(repText2); if (repText3) tmp3 = XMLString::transcode(repText3); if (repText4) tmp4 = XMLString::transcode(repText4); bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4); if (tmp1) delete [] tmp1; if (tmp2) delete [] tmp2; if (tmp3) delete [] tmp3; if (tmp4) delete [] tmp4; return bRet; } <|endoftext|>
<commit_before>#include <cmath> #include <cstring> #include <iostream> #include <set> #include <stdio.h> #include <stdlib.h> #include "../include/oasis.h" #if defined(_MSC_VER) #include "../wingetopt/wingetopt.h" #else #include <unistd.h> #endif namespace validatevulnerability { inline bool ProbabilityCheck(float prob) { return roundf(prob * 100000) / 100000 != 1.0; } inline bool ProbabilityError(Vulnerability v, float prob) { fprintf(stderr, "Probabilities for vulnerability ID %d", v.vulnerability_id); fprintf(stderr, " and intensity bin ID %d", v.intensity_bin_id); fprintf(stderr, " do not sum to 1.\n"); fprintf(stderr, "Probability = %f\n", prob); return false; } void doit() { Vulnerability p = {}, q; bool dataValid = true; std::set<int> damageBins; int maxDamageBin = 0; float prob = 0.0; char prevLine[4096], line[4096]; sprintf(prevLine, "%d, %d, %d, %f", p.vulnerability_id, p.intensity_bin_id, p.damage_bin_id, p.probability); int lineno = 0; fgets(line, sizeof(line), stdin); // Skip header line lineno++; while(fgets(line, sizeof(line), stdin) != 0) { // Check for invalid data if(sscanf(line, "%d,%d,%d,%f", &q.vulnerability_id, &q.intensity_bin_id, &q.damage_bin_id, &q.probability) != 4) { fprintf(stderr, "Invalid data in line %d:\n%s\n", lineno, line); dataValid = false; } // New vulnerability ID if(q.vulnerability_id != p.vulnerability_id) { // Check total probability for vulnerability-intensity bin combination // is 1.0 if(ProbabilityCheck(prob) && p.vulnerability_id != 0) { dataValid = ProbabilityError(p, prob); } damageBins.clear(); prob = 0.0; // Check event IDs listed in ascending order if(q.vulnerability_id < p.vulnerability_id) { fprintf(stderr, "Vulnerability ID in lines %d and %d", lineno-1, lineno); fprintf(stderr, " not in ascending order:\n"); fprintf(stderr, "%s\n%s\n", prevLine, line); dataValid = false; } } else if(q.intensity_bin_id != p.intensity_bin_id) { // Check total probability for vulnerability-intensity bin combination // is 1.0 if(ProbabilityCheck(prob)) { dataValid = ProbabilityError(p, prob); } damageBins.clear(); prob = 0.0; // Check intensity bin IDs listed in ascending order if(p.intensity_bin_id != q.intensity_bin_id-1) { fprintf(stderr, "Non-contiguous intensity bin IDs"); fprintf(stderr, " in lines %d and %d", lineno-1, lineno); fprintf(stderr, "%s\n%s\n", prevLine, line); dataValid = false; } } // Check no duplicate damage bins for each vulnerability-intensity bin // combination if(damageBins.find(q.damage_bin_id) == damageBins.end()) { damageBins.insert(q.damage_bin_id); prob += q.probability; // Get maximum value of damage_bin_index if(q.damage_bin_id > maxDamageBin) { maxDamageBin = q.damage_bin_id; } } else { fprintf(stderr, "Duplicate intensity bin for"); fprintf(stderr, " vulnerability-intesnity bin combination"); fprintf(stderr, "%s\n", line); dataValid = false; } lineno++; p = q; memcpy(prevLine, line, strlen(line)+1); prevLine[strlen(line)-1] = '\0'; } // Check total probability for last vulnerability-intensity bin combination // is 1.0 if(ProbabilityCheck(prob)) { dataValid = ProbabilityError(q, prob); } if(dataValid == true) { fprintf(stderr, "All checks pass.\n"); fprintf(stderr, "Maximum value of damage_bin_index = %d\n", maxDamageBin); } else { fprintf(stderr, "Some checks have failed. Please edit input file.\n"); } } } <commit_msg>Fix typo + update comment text<commit_after>#include <cmath> #include <cstring> #include <iostream> #include <set> #include <stdio.h> #include <stdlib.h> #include "../include/oasis.h" #if defined(_MSC_VER) #include "../wingetopt/wingetopt.h" #else #include <unistd.h> #endif namespace validatevulnerability { inline bool ProbabilityCheck(float prob) { return roundf(prob * 100000) / 100000 != 1.0; } inline bool ProbabilityError(Vulnerability v, float prob) { fprintf(stderr, "Probabilities for vulnerability ID %d", v.vulnerability_id); fprintf(stderr, " and intensity bin ID %d", v.intensity_bin_id); fprintf(stderr, " do not sum to 1.\n"); fprintf(stderr, "Probability = %f\n", prob); return false; } void doit() { Vulnerability p = {}, q; bool dataValid = true; std::set<int> damageBins; int maxDamageBin = 0; float prob = 0.0; char prevLine[4096], line[4096]; sprintf(prevLine, "%d, %d, %d, %f", p.vulnerability_id, p.intensity_bin_id, p.damage_bin_id, p.probability); int lineno = 0; fgets(line, sizeof(line), stdin); // Skip header line lineno++; while(fgets(line, sizeof(line), stdin) != 0) { // Check for invalid data if(sscanf(line, "%d,%d,%d,%f", &q.vulnerability_id, &q.intensity_bin_id, &q.damage_bin_id, &q.probability) != 4) { fprintf(stderr, "Invalid data in line %d:\n%s\n", lineno, line); dataValid = false; } // New vulnerability ID if(q.vulnerability_id != p.vulnerability_id) { // Check total probability for vulnerability-intensity bin combination // is 1.0 if(ProbabilityCheck(prob) && p.vulnerability_id != 0) { dataValid = ProbabilityError(p, prob); } damageBins.clear(); prob = 0.0; // Check event IDs listed in ascending order if(q.vulnerability_id < p.vulnerability_id) { fprintf(stderr, "Vulnerability ID in lines %d and %d", lineno-1, lineno); fprintf(stderr, " not in ascending order:\n"); fprintf(stderr, "%s\n%s\n", prevLine, line); dataValid = false; } } else if(q.intensity_bin_id != p.intensity_bin_id) { // Check total probability for vulnerability-intensity bin combination // is 1.0 if(ProbabilityCheck(prob)) { dataValid = ProbabilityError(p, prob); } damageBins.clear(); prob = 0.0; // Check intensity bin IDs are contiguous if(p.intensity_bin_id != q.intensity_bin_id-1) { fprintf(stderr, "Non-contiguous intensity bin IDs"); fprintf(stderr, " in lines %d and %d", lineno-1, lineno); fprintf(stderr, "%s\n%s\n", prevLine, line); dataValid = false; } } // Check no duplicate damage bins for each vulnerability-intensity bin // combination if(damageBins.find(q.damage_bin_id) == damageBins.end()) { damageBins.insert(q.damage_bin_id); prob += q.probability; // Get maximum value of damage_bin_index if(q.damage_bin_id > maxDamageBin) { maxDamageBin = q.damage_bin_id; } } else { fprintf(stderr, "Duplicate damage bin for"); fprintf(stderr, " vulnerability-intensity bin combination"); fprintf(stderr, "%s\n", line); dataValid = false; } lineno++; p = q; memcpy(prevLine, line, strlen(line)+1); prevLine[strlen(line)-1] = '\0'; } // Check total probability for last vulnerability-intensity bin combination // is 1.0 if(ProbabilityCheck(prob)) { dataValid = ProbabilityError(q, prob); } if(dataValid == true) { fprintf(stderr, "All checks pass.\n"); fprintf(stderr, "Maximum value of damage_bin_index = %d\n", maxDamageBin); } else { fprintf(stderr, "Some checks have failed. Please edit input file.\n"); } } } <|endoftext|>
<commit_before>// Requires Adafruit_ASFcore library! // Be careful to use a platform-specific conditional include to only make the // code visible for the appropriate platform. Arduino will try to compile and // link all .cpp files regardless of platform. #if defined(ARDUINO_ARCH_SAMD) #include <sam.h> #include "WatchdogSAMD.h" int WatchdogSAMD::enable(int maxPeriodMS, bool isForSleep) { // Enable the watchdog with a period up to the specified max period in // milliseconds. // Review the watchdog section from the SAMD21 datasheet section 17: // http://www.atmel.com/images/atmel-42181-sam-d21_datasheet.pdf int cycles; uint8_t bits; if(!_initialized) _initialize_wdt(); #if defined(__SAMD51__) USB->DEVICE.CTRLA.bit.ENABLE = 0; // Disable the USB peripheral while(USB->DEVICE.SYNCBUSY.bit.ENABLE); // Wait for synchronization USB->DEVICE.CTRLA.bit.RUNSTDBY = 0; // Deactivate run on standby USB->DEVICE.CTRLA.bit.ENABLE = 1; // Enable USB peripheral while(USB->DEVICE.SYNCBUSY.bit.ENABLE); // Wait for synchronization WDT->CTRLA.reg = 0; // Disable watchdog for config while(WDT->SYNCBUSY.reg); #else WDT->CTRL.reg = 0; // Disable watchdog for config while(WDT->STATUS.bit.SYNCBUSY); #endif // You'll see some occasional conversion here compensating between // milliseconds (1000 Hz) and WDT clock cycles (~1024 Hz). The low- // power oscillator used by the WDT ostensibly runs at 32,768 Hz with // a 1:32 prescale, thus 1024 Hz, though probably not super precise. if((maxPeriodMS >= 16000) || !maxPeriodMS) { cycles = 16384; bits = 0xB; } else { cycles = (maxPeriodMS * 1024L + 500) / 1000; // ms -> WDT cycles if(cycles >= 8192) { cycles = 8192; bits = 0xA; } else if(cycles >= 4096) { cycles = 4096; bits = 0x9; } else if(cycles >= 2048) { cycles = 2048; bits = 0x8; } else if(cycles >= 1024) { cycles = 1024; bits = 0x7; } else if(cycles >= 512) { cycles = 512; bits = 0x6; } else if(cycles >= 256) { cycles = 256; bits = 0x5; } else if(cycles >= 128) { cycles = 128; bits = 0x4; } else if(cycles >= 64) { cycles = 64; bits = 0x3; } else if(cycles >= 32) { cycles = 32; bits = 0x2; } else if(cycles >= 16) { cycles = 16; bits = 0x1; } else { cycles = 8; bits = 0x0; } } // Watchdog timer on SAMD is a slightly different animal than on AVR. // On AVR, the WTD timeout is configured in one register and then an // interrupt can optionally be enabled to handle the timeout in code // (as in waking from sleep) vs resetting the chip. Easy. // On SAMD, when the WDT fires, that's it, the chip's getting reset. // Instead, it has an "early warning interrupt" with a different set // interval prior to the reset. For equivalent behavior to the AVR // library, this requires a slightly different configuration depending // whether we're coming from the sleep() function (which needs the // interrupt), or just enable() (no interrupt, we want the chip reset // unless the WDT is cleared first). In the sleep case, 'windowed' // mode is used in order to allow access to the longest available // sleep interval (about 16 sec); the WDT 'period' (when a reset // occurs) follows this and is always just set to the max, since the // interrupt will trigger first. In the enable case, windowed mode // is not used, the WDT period is set and that's that. // The 'isForSleep' argument determines which behavior is used; // this isn't present in the AVR code, just here. It defaults to // 'false' so existing Arduino code works as normal, while the sleep() // function (later in this file) explicitly passes 'true' to get the // alternate behavior. #if defined(__SAMD51__) if(isForSleep) { WDT->INTFLAG.bit.EW = 1; // Clear interrupt flag WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt WDT->CONFIG.bit.PER = 0xB; // Period = max WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt WDT->EWCTRL.bit.EWOFFSET = 0x0; // Early warning offset WDT->CTRLA.bit.WEN = 1; // Enable window mode while(WDT->SYNCBUSY.reg); // Sync CTRL write } else { WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt WDT->CONFIG.bit.PER = bits; // Set period for chip reset WDT->CTRLA.bit.WEN = 0; // Disable window mode while(WDT->SYNCBUSY.reg); // Sync CTRL write } reset(); // Clear watchdog interval WDT->CTRLA.bit.ENABLE = 1; // Start watchdog now! while(WDT->SYNCBUSY.reg); #else if(isForSleep) { WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt WDT->CONFIG.bit.PER = 0xB; // Period = max WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt WDT->CTRL.bit.WEN = 1; // Enable window mode while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write } else { WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt WDT->CONFIG.bit.PER = bits; // Set period for chip reset WDT->CTRL.bit.WEN = 0; // Disable window mode while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write } reset(); // Clear watchdog interval WDT->CTRL.bit.ENABLE = 1; // Start watchdog now! while(WDT->STATUS.bit.SYNCBUSY); #endif return (cycles * 1000L + 512) / 1024; // WDT cycles -> ms } void WatchdogSAMD::reset() { // Write the watchdog clear key value (0xA5) to the watchdog // clear register to clear the watchdog timer and reset it. WDT->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; #if defined(__SAMD51__) while(WDT->SYNCBUSY.reg); #else while(WDT->STATUS.bit.SYNCBUSY); #endif } void WatchdogSAMD::disable() { #if defined(__SAMD51__) WDT->CTRLA.bit.ENABLE = 0; while(WDT->SYNCBUSY.reg); #else WDT->CTRL.bit.ENABLE = 0; while(WDT->STATUS.bit.SYNCBUSY); #endif } void WDT_Handler(void) { // ISR for watchdog early warning, DO NOT RENAME! #if defined(__SAMD51__) WDT->CTRLA.bit.ENABLE = 0; // Disable watchdog while(WDT->SYNCBUSY.reg); #else WDT->CTRL.bit.ENABLE = 0; // Disable watchdog while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write #endif WDT->INTFLAG.bit.EW = 1; // Clear interrupt flag } int WatchdogSAMD::sleep(int maxPeriodMS) { int actualPeriodMS = enable(maxPeriodMS, true); // true = for sleep // Enable standby sleep mode (deepest sleep) and activate. // Insights from Atmel ASF library. #if (SAMD20 || SAMD21) // Don't fully power down flash when in sleep NVMCTRL->CTRLB.bit.SLEEPPRM = NVMCTRL_CTRLB_SLEEPPRM_DISABLED_Val; #endif #if defined(__SAMD51__) PM->SLEEPCFG.bit.SLEEPMODE = 0x4; // Standby sleep mode while(PM->SLEEPCFG.bit.SLEEPMODE != 0x4); // Wait for it to take #else SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; #endif __DSB(); // Data sync to ensure outgoing memory accesses complete __WFI(); // Wait for interrupt (places device in sleep mode) // Code resumes here on wake (WDT early warning interrupt). // Bug: the return value assumes the WDT has run its course; // incorrect if the device woke due to an external interrupt. // Without an external RTC there's no way to provide a correct // sleep period in the latter case...but at the very least, // might indicate said condition occurred by returning 0 instead // (assuming we can pin down which interrupt caused the wake). return actualPeriodMS; } void WatchdogSAMD::_initialize_wdt() { // One-time initialization of watchdog timer. // Insights from rickrlh and rbrucemtl in Arduino forum! #if defined(__SAMD51__) // SAMD51 WDT uses OSCULP32k as input clock now // section: 20.5.3 OSC32KCTRL->OSCULP32K.bit.EN1K = 1; // Enable out 1K (for WDT) OSC32KCTRL->OSCULP32K.bit.EN32K = 0; // Disable out 32K // Enable WDT early-warning interrupt NVIC_DisableIRQ(WDT_IRQn); NVIC_ClearPendingIRQ(WDT_IRQn); NVIC_SetPriority(WDT_IRQn, 0); // Top priority NVIC_EnableIRQ(WDT_IRQn); while(WDT->SYNCBUSY.reg); #else // Generic clock generator 2, divisor = 32 (2^(DIV+1)) GCLK->GENDIV.reg = GCLK_GENDIV_ID(2) | GCLK_GENDIV_DIV(4); // Enable clock generator 2 using low-power 32KHz oscillator. // With /32 divisor above, this yields 1024Hz(ish) clock. GCLK->GENCTRL.reg = GCLK_GENCTRL_ID(2) | GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_OSCULP32K | GCLK_GENCTRL_DIVSEL; while(GCLK->STATUS.bit.SYNCBUSY); // WDT clock = clock gen 2 GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID_WDT | GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK2; // Enable WDT early-warning interrupt NVIC_DisableIRQ(WDT_IRQn); NVIC_ClearPendingIRQ(WDT_IRQn); NVIC_SetPriority(WDT_IRQn, 0); // Top priority NVIC_EnableIRQ(WDT_IRQn); #endif _initialized = true; } #endif // defined(ARDUINO_ARCH_SAMD) <commit_msg>Change to allow the SAMD51 to enter deep sleep<commit_after>// Requires Adafruit_ASFcore library! // Be careful to use a platform-specific conditional include to only make the // code visible for the appropriate platform. Arduino will try to compile and // link all .cpp files regardless of platform. #if defined(ARDUINO_ARCH_SAMD) #include <sam.h> #include "WatchdogSAMD.h" int WatchdogSAMD::enable(int maxPeriodMS, bool isForSleep) { // Enable the watchdog with a period up to the specified max period in // milliseconds. // Review the watchdog section from the SAMD21 datasheet section 17: // http://www.atmel.com/images/atmel-42181-sam-d21_datasheet.pdf int cycles; uint8_t bits; if(!_initialized) _initialize_wdt(); #if defined(__SAMD51__) WDT->CTRLA.reg = 0; // Disable watchdog for config while(WDT->SYNCBUSY.reg); #else WDT->CTRL.reg = 0; // Disable watchdog for config while(WDT->STATUS.bit.SYNCBUSY); #endif // You'll see some occasional conversion here compensating between // milliseconds (1000 Hz) and WDT clock cycles (~1024 Hz). The low- // power oscillator used by the WDT ostensibly runs at 32,768 Hz with // a 1:32 prescale, thus 1024 Hz, though probably not super precise. if((maxPeriodMS >= 16000) || !maxPeriodMS) { cycles = 16384; bits = 0xB; } else { cycles = (maxPeriodMS * 1024L + 500) / 1000; // ms -> WDT cycles if(cycles >= 8192) { cycles = 8192; bits = 0xA; } else if(cycles >= 4096) { cycles = 4096; bits = 0x9; } else if(cycles >= 2048) { cycles = 2048; bits = 0x8; } else if(cycles >= 1024) { cycles = 1024; bits = 0x7; } else if(cycles >= 512) { cycles = 512; bits = 0x6; } else if(cycles >= 256) { cycles = 256; bits = 0x5; } else if(cycles >= 128) { cycles = 128; bits = 0x4; } else if(cycles >= 64) { cycles = 64; bits = 0x3; } else if(cycles >= 32) { cycles = 32; bits = 0x2; } else if(cycles >= 16) { cycles = 16; bits = 0x1; } else { cycles = 8; bits = 0x0; } } // Watchdog timer on SAMD is a slightly different animal than on AVR. // On AVR, the WTD timeout is configured in one register and then an // interrupt can optionally be enabled to handle the timeout in code // (as in waking from sleep) vs resetting the chip. Easy. // On SAMD, when the WDT fires, that's it, the chip's getting reset. // Instead, it has an "early warning interrupt" with a different set // interval prior to the reset. For equivalent behavior to the AVR // library, this requires a slightly different configuration depending // whether we're coming from the sleep() function (which needs the // interrupt), or just enable() (no interrupt, we want the chip reset // unless the WDT is cleared first). In the sleep case, 'windowed' // mode is used in order to allow access to the longest available // sleep interval (about 16 sec); the WDT 'period' (when a reset // occurs) follows this and is always just set to the max, since the // interrupt will trigger first. In the enable case, windowed mode // is not used, the WDT period is set and that's that. // The 'isForSleep' argument determines which behavior is used; // this isn't present in the AVR code, just here. It defaults to // 'false' so existing Arduino code works as normal, while the sleep() // function (later in this file) explicitly passes 'true' to get the // alternate behavior. #if defined(__SAMD51__) if(isForSleep) { WDT->INTFLAG.bit.EW = 1; // Clear interrupt flag WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt WDT->CONFIG.bit.PER = 0xB; // Period = max WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt WDT->EWCTRL.bit.EWOFFSET = 0x0; // Early warning offset WDT->CTRLA.bit.WEN = 1; // Enable window mode while(WDT->SYNCBUSY.reg); // Sync CTRL write } else { WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt WDT->CONFIG.bit.PER = bits; // Set period for chip reset WDT->CTRLA.bit.WEN = 0; // Disable window mode while(WDT->SYNCBUSY.reg); // Sync CTRL write } reset(); // Clear watchdog interval WDT->CTRLA.bit.ENABLE = 1; // Start watchdog now! while(WDT->SYNCBUSY.reg); #else if(isForSleep) { WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt WDT->CONFIG.bit.PER = 0xB; // Period = max WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt WDT->CTRL.bit.WEN = 1; // Enable window mode while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write } else { WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt WDT->CONFIG.bit.PER = bits; // Set period for chip reset WDT->CTRL.bit.WEN = 0; // Disable window mode while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write } reset(); // Clear watchdog interval WDT->CTRL.bit.ENABLE = 1; // Start watchdog now! while(WDT->STATUS.bit.SYNCBUSY); #endif return (cycles * 1000L + 512) / 1024; // WDT cycles -> ms } void WatchdogSAMD::reset() { // Write the watchdog clear key value (0xA5) to the watchdog // clear register to clear the watchdog timer and reset it. WDT->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; #if defined(__SAMD51__) while(WDT->SYNCBUSY.reg); #else while(WDT->STATUS.bit.SYNCBUSY); #endif } void WatchdogSAMD::disable() { #if defined(__SAMD51__) WDT->CTRLA.bit.ENABLE = 0; while(WDT->SYNCBUSY.reg); #else WDT->CTRL.bit.ENABLE = 0; while(WDT->STATUS.bit.SYNCBUSY); #endif } void WDT_Handler(void) { // ISR for watchdog early warning, DO NOT RENAME! #if defined(__SAMD51__) WDT->CTRLA.bit.ENABLE = 0; // Disable watchdog while(WDT->SYNCBUSY.reg); #else WDT->CTRL.bit.ENABLE = 0; // Disable watchdog while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write #endif WDT->INTFLAG.bit.EW = 1; // Clear interrupt flag } int WatchdogSAMD::sleep(int maxPeriodMS) { int actualPeriodMS = enable(maxPeriodMS, true); // true = for sleep // Enable standby sleep mode (deepest sleep) and activate. // Insights from Atmel ASF library. #if (SAMD20 || SAMD21) // Don't fully power down flash when in sleep NVMCTRL->CTRLB.bit.SLEEPPRM = NVMCTRL_CTRLB_SLEEPPRM_DISABLED_Val; #endif #if defined(__SAMD51__) PM->SLEEPCFG.bit.SLEEPMODE = 0x4; // Standby sleep mode while(PM->SLEEPCFG.bit.SLEEPMODE != 0x4); // Wait for it to take #else SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; #endif __DSB(); // Data sync to ensure outgoing memory accesses complete __WFI(); // Wait for interrupt (places device in sleep mode) // Code resumes here on wake (WDT early warning interrupt). // Bug: the return value assumes the WDT has run its course; // incorrect if the device woke due to an external interrupt. // Without an external RTC there's no way to provide a correct // sleep period in the latter case...but at the very least, // might indicate said condition occurred by returning 0 instead // (assuming we can pin down which interrupt caused the wake). return actualPeriodMS; } void WatchdogSAMD::_initialize_wdt() { // One-time initialization of watchdog timer. // Insights from rickrlh and rbrucemtl in Arduino forum! #if defined(__SAMD51__) // SAMD51 WDT uses OSCULP32k as input clock now // section: 20.5.3 OSC32KCTRL->OSCULP32K.bit.EN1K = 1; // Enable out 1K (for WDT) OSC32KCTRL->OSCULP32K.bit.EN32K = 0; // Disable out 32K // Enable WDT early-warning interrupt NVIC_DisableIRQ(WDT_IRQn); NVIC_ClearPendingIRQ(WDT_IRQn); NVIC_SetPriority(WDT_IRQn, 0); // Top priority NVIC_EnableIRQ(WDT_IRQn); while(WDT->SYNCBUSY.reg); USB->DEVICE.CTRLA.bit.ENABLE = 0; // Disable the USB peripheral while(USB->DEVICE.SYNCBUSY.bit.ENABLE); // Wait for synchronization USB->DEVICE.CTRLA.bit.RUNSTDBY = 0; // Deactivate run on standby USB->DEVICE.CTRLA.bit.ENABLE = 1; // Enable USB peripheral while(USB->DEVICE.SYNCBUSY.bit.ENABLE); // Wait for synchronization #else // Generic clock generator 2, divisor = 32 (2^(DIV+1)) GCLK->GENDIV.reg = GCLK_GENDIV_ID(2) | GCLK_GENDIV_DIV(4); // Enable clock generator 2 using low-power 32KHz oscillator. // With /32 divisor above, this yields 1024Hz(ish) clock. GCLK->GENCTRL.reg = GCLK_GENCTRL_ID(2) | GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_OSCULP32K | GCLK_GENCTRL_DIVSEL; while(GCLK->STATUS.bit.SYNCBUSY); // WDT clock = clock gen 2 GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID_WDT | GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK2; // Enable WDT early-warning interrupt NVIC_DisableIRQ(WDT_IRQn); NVIC_ClearPendingIRQ(WDT_IRQn); NVIC_SetPriority(WDT_IRQn, 0); // Top priority NVIC_EnableIRQ(WDT_IRQn); #endif _initialized = true; } #endif // defined(ARDUINO_ARCH_SAMD) <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: stl_types.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: fs $ $Date: 2001-05-29 09:19:25 $ * * 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 WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRUNTIES 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 _COMPHELPER_STLTYPES_HXX_ #define _COMPHELPER_STLTYPES_HXX_ #if !defined(__SGI_STL_VECTOR_H) || !defined(__SGI_STL_MAP_H) || !defined(__SGI_STL_MULTIMAP_H) #include <vector> #include <map> #include <hash_map> #include <stack> #include <set> #include <math.h> // prevent conflict between exception and std::exception using namespace std; #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif //... namespace comphelper ................................................ namespace comphelper { //......................................................................... //======================================================================== // comparisation functions //------------------------------------------------------------------------ struct UStringLess : public binary_function< ::rtl::OUString, ::rtl::OUString, bool> { bool operator() (const ::rtl::OUString& x, const ::rtl::OUString& y) const { return x < y ? true : false;} // construct prevents a MSVC6 warning }; //------------------------------------------------------------------------ struct UStringMixLess : public binary_function< ::rtl::OUString, ::rtl::OUString, bool> { bool m_bCaseSensitive; public: UStringMixLess(bool bCaseSensitive = true):m_bCaseSensitive(bCaseSensitive){} bool operator() (const ::rtl::OUString& x, const ::rtl::OUString& y) const { if (m_bCaseSensitive) return rtl_ustr_compare(x.getStr(), y.getStr()) < 0 ? true : false; else return rtl_ustr_compareIgnoreAsciiCase(x.getStr(), y.getStr()) < 0 ? true : false; } bool isCaseSensitive() const {return m_bCaseSensitive;} }; //------------------------------------------------------------------------ struct UStringEqual { sal_Bool operator() (const ::rtl::OUString& lhs, const ::rtl::OUString& rhs) const { return lhs.equals( rhs );} }; //------------------------------------------------------------------------ struct UStringIEqual { sal_Bool operator() (const ::rtl::OUString& lhs, const ::rtl::OUString& rhs) const { return lhs.equalsIgnoreAsciiCase( rhs );} }; //------------------------------------------------------------------------ struct UStringHash { size_t operator() (const ::rtl::OUString& rStr) const {return rStr.hashCode();} }; //------------------------------------------------------------------------ class UStringMixEqual { sal_Bool m_bCaseSensitive; public: UStringMixEqual(sal_Bool bCaseSensitive = sal_True):m_bCaseSensitive(bCaseSensitive){} sal_Bool operator() (const ::rtl::OUString& lhs, const ::rtl::OUString& rhs) const { return m_bCaseSensitive ? lhs.equals( rhs ) : lhs.equalsIgnoreAsciiCase( rhs ); } sal_Bool isCaseSensitive() const {return m_bCaseSensitive;} }; //------------------------------------------------------------------------ class UStringMixHash { sal_Bool m_bCaseSensitive; public: UStringMixHash(sal_Bool bCaseSensitive = sal_True):m_bCaseSensitive(bCaseSensitive){} size_t operator() (const ::rtl::OUString& rStr) const { return m_bCaseSensitive ? rStr.hashCode() : rStr.toAsciiUpperCase().hashCode(); } sal_Bool isCaseSensitive() const {return m_bCaseSensitive;} }; //===================================================================== //= OInterfaceCompare //===================================================================== /** is stl-compliant structure for comparing Reference&lt; &lt;iface&gt; &gt; instances */ template < class IAFCE > struct OInterfaceCompare :public ::std::binary_function < ::com::sun::star::uno::Reference< IAFCE > , ::com::sun::star::uno::Reference< IAFCE > , bool > { bool operator() (const ::com::sun::star::uno::Reference< IAFCE >& lhs, const ::com::sun::star::uno::Reference< IAFCE >& rhs) const { return lhs.get() < rhs.get(); // this does not make any sense if you see the semantics of the pointer returned by get: // It's a pointer to a point in memory where an interface implementation lies. // But for our purpose (provide a reliable less-operator which can be used with the STL), this is // sufficient .... } }; //......................................................................... } //... namespace comphelper ................................................ //================================================================== // consistently defining stl-types //================================================================== #define DECLARE_STL_ITERATORS(classname) \ typedef classname::iterator classname##Iterator; \ typedef classname::const_iterator Const##classname##Iterator \ #define DECLARE_STL_MAP(keytype, valuetype, comparefct, classname) \ typedef std::map< keytype, valuetype, comparefct > classname; \ DECLARE_STL_ITERATORS(classname) \ #define DECLARE_STL_STDKEY_MAP(keytype, valuetype, classname) \ DECLARE_STL_MAP(keytype, valuetype, std::less< keytype >, classname) \ #define DECLARE_STL_VECTOR(valuetyp, classname) \ typedef std::vector< valuetyp > classname; \ DECLARE_STL_ITERATORS(classname) \ #define DECLARE_STL_USTRINGACCESS_MAP(valuetype, classname) \ DECLARE_STL_MAP(::rtl::OUString, valuetype, ::comphelper::UStringLess, classname) \ #define DECLARE_STL_STDKEY_SET(valuetype, classname) \ typedef ::std::set< valuetype > classname; \ DECLARE_STL_ITERATORS(classname) \ #define DECLARE_STL_SET(valuetype, comparefct, classname) \ typedef ::std::set< valuetype, comparefct > classname; \ DECLARE_STL_ITERATORS(classname) \ #endif #endif // _COMPHELPER_STLTYPES_HXX_ <commit_msg>#93229# new struct for MixEqual<commit_after>/************************************************************************* * * $RCSfile: stl_types.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: oj $ $Date: 2001-10-18 10:43:35 $ * * 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 WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRUNTIES 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 _COMPHELPER_STLTYPES_HXX_ #define _COMPHELPER_STLTYPES_HXX_ #if !defined(__SGI_STL_VECTOR_H) || !defined(__SGI_STL_MAP_H) || !defined(__SGI_STL_MULTIMAP_H) #include <vector> #include <map> #include <hash_map> #include <stack> #include <set> #include <math.h> // prevent conflict between exception and std::exception using namespace std; #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif //... namespace comphelper ................................................ namespace comphelper { //......................................................................... //======================================================================== // comparisation functions //------------------------------------------------------------------------ struct UStringLess : public binary_function< ::rtl::OUString, ::rtl::OUString, bool> { bool operator() (const ::rtl::OUString& x, const ::rtl::OUString& y) const { return x < y ? true : false;} // construct prevents a MSVC6 warning }; //------------------------------------------------------------------------ struct UStringMixLess : public binary_function< ::rtl::OUString, ::rtl::OUString, bool> { bool m_bCaseSensitive; public: UStringMixLess(bool bCaseSensitive = true):m_bCaseSensitive(bCaseSensitive){} bool operator() (const ::rtl::OUString& x, const ::rtl::OUString& y) const { if (m_bCaseSensitive) return rtl_ustr_compare(x.getStr(), y.getStr()) < 0 ? true : false; else return rtl_ustr_compareIgnoreAsciiCase(x.getStr(), y.getStr()) < 0 ? true : false; } bool isCaseSensitive() const {return m_bCaseSensitive;} }; //------------------------------------------------------------------------ struct UStringEqual { sal_Bool operator() (const ::rtl::OUString& lhs, const ::rtl::OUString& rhs) const { return lhs.equals( rhs );} }; //------------------------------------------------------------------------ struct UStringIEqual { sal_Bool operator() (const ::rtl::OUString& lhs, const ::rtl::OUString& rhs) const { return lhs.equalsIgnoreAsciiCase( rhs );} }; //------------------------------------------------------------------------ struct UStringHash { size_t operator() (const ::rtl::OUString& rStr) const {return rStr.hashCode();} }; //------------------------------------------------------------------------ class UStringMixEqual { sal_Bool m_bCaseSensitive; public: UStringMixEqual(sal_Bool bCaseSensitive = sal_True):m_bCaseSensitive(bCaseSensitive){} sal_Bool operator() (const ::rtl::OUString& lhs, const ::rtl::OUString& rhs) const { return m_bCaseSensitive ? lhs.equals( rhs ) : lhs.equalsIgnoreAsciiCase( rhs ); } sal_Bool isCaseSensitive() const {return m_bCaseSensitive;} }; //------------------------------------------------------------------------ class TStringMixEqualFunctor : public ::std::binary_function< ::rtl::OUString,::rtl::OUString,bool> { sal_Bool m_bCaseSensitive; public: TStringMixEqualFunctor(sal_Bool bCaseSensitive = sal_True) :m_bCaseSensitive(bCaseSensitive) {} bool operator() (const ::rtl::OUString& lhs, const ::rtl::OUString& rhs) const { return m_bCaseSensitive ? lhs.equals( rhs ) : lhs.equalsIgnoreAsciiCase( rhs ); } sal_Bool isCaseSensitive() const {return m_bCaseSensitive;} }; //------------------------------------------------------------------------ class UStringMixHash { sal_Bool m_bCaseSensitive; public: UStringMixHash(sal_Bool bCaseSensitive = sal_True):m_bCaseSensitive(bCaseSensitive){} size_t operator() (const ::rtl::OUString& rStr) const { return m_bCaseSensitive ? rStr.hashCode() : rStr.toAsciiUpperCase().hashCode(); } sal_Bool isCaseSensitive() const {return m_bCaseSensitive;} }; //===================================================================== //= OInterfaceCompare //===================================================================== /** is stl-compliant structure for comparing Reference&lt; &lt;iface&gt; &gt; instances */ template < class IAFCE > struct OInterfaceCompare :public ::std::binary_function < ::com::sun::star::uno::Reference< IAFCE > , ::com::sun::star::uno::Reference< IAFCE > , bool > { bool operator() (const ::com::sun::star::uno::Reference< IAFCE >& lhs, const ::com::sun::star::uno::Reference< IAFCE >& rhs) const { return lhs.get() < rhs.get(); // this does not make any sense if you see the semantics of the pointer returned by get: // It's a pointer to a point in memory where an interface implementation lies. // But for our purpose (provide a reliable less-operator which can be used with the STL), this is // sufficient .... } }; //......................................................................... } //... namespace comphelper ................................................ //================================================================== // consistently defining stl-types //================================================================== #define DECLARE_STL_ITERATORS(classname) \ typedef classname::iterator classname##Iterator; \ typedef classname::const_iterator Const##classname##Iterator \ #define DECLARE_STL_MAP(keytype, valuetype, comparefct, classname) \ typedef std::map< keytype, valuetype, comparefct > classname; \ DECLARE_STL_ITERATORS(classname) \ #define DECLARE_STL_STDKEY_MAP(keytype, valuetype, classname) \ DECLARE_STL_MAP(keytype, valuetype, std::less< keytype >, classname) \ #define DECLARE_STL_VECTOR(valuetyp, classname) \ typedef std::vector< valuetyp > classname; \ DECLARE_STL_ITERATORS(classname) \ #define DECLARE_STL_USTRINGACCESS_MAP(valuetype, classname) \ DECLARE_STL_MAP(::rtl::OUString, valuetype, ::comphelper::UStringLess, classname) \ #define DECLARE_STL_STDKEY_SET(valuetype, classname) \ typedef ::std::set< valuetype > classname; \ DECLARE_STL_ITERATORS(classname) \ #define DECLARE_STL_SET(valuetype, comparefct, classname) \ typedef ::std::set< valuetype, comparefct > classname; \ DECLARE_STL_ITERATORS(classname) \ #endif #endif // _COMPHELPER_STLTYPES_HXX_ <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: property.cxx,v $ * $Revision: 1.11 $ * * 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_comphelper.hxx" #include <comphelper/property.hxx> #include <comphelper/sequence.hxx> #include <comphelper/types.hxx> #include <osl/diagnose.h> #if OSL_DEBUG_LEVEL > 0 #ifndef _RTL_STRBUF_HXX_ #include <rtl/strbuf.hxx> #endif #ifndef _CPPUHELPER_EXC_HLP_HXX_ #include <cppuhelper/exc_hlp.hxx> #endif #ifndef _OSL_THREAD_H_ #include <osl/thread.h> #endif #endif #include <com/sun/star/beans/PropertyAttribute.hpp> #include <com/sun/star/lang/IllegalArgumentException.hpp> #include <com/sun/star/uno/genfunc.h> #include <algorithm> //......................................................................... namespace comphelper { /** === begin UNO using === **/ using ::com::sun::star::uno::Reference; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::beans::XPropertySetInfo; using ::com::sun::star::beans::Property; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::Any; using ::com::sun::star::uno::Type; using ::com::sun::star::uno::cpp_queryInterface; using ::com::sun::star::uno::cpp_acquire; using ::com::sun::star::uno::cpp_release; /** === end UNO using === **/ namespace PropertyAttribute = ::com::sun::star::beans::PropertyAttribute; //------------------------------------------------------------------ void copyProperties(const Reference<XPropertySet>& _rxSource, const Reference<XPropertySet>& _rxDest) { if (!_rxSource.is() || !_rxDest.is()) { OSL_ENSURE(sal_False, "copyProperties: invalid arguments !"); return; } Reference< XPropertySetInfo > xSourceProps = _rxSource->getPropertySetInfo(); Reference< XPropertySetInfo > xDestProps = _rxDest->getPropertySetInfo(); Sequence< Property > aSourceProps = xSourceProps->getProperties(); const Property* pSourceProps = aSourceProps.getConstArray(); Property aDestProp; for (sal_Int32 i=0; i<aSourceProps.getLength(); ++i, ++pSourceProps) { if ( xDestProps->hasPropertyByName(pSourceProps->Name) ) { try { aDestProp = xDestProps->getPropertyByName(pSourceProps->Name); if (0 == (aDestProp.Attributes & PropertyAttribute::READONLY)) _rxDest->setPropertyValue(pSourceProps->Name, _rxSource->getPropertyValue(pSourceProps->Name)); } catch (Exception&) { #if OSL_DEBUG_LEVEL > 0 ::rtl::OStringBuffer aBuffer; aBuffer.append( "::comphelper::copyProperties: could not copy property '" ); aBuffer.append( ::rtl::OString( pSourceProps->Name.getStr(), pSourceProps->Name.getLength(), RTL_TEXTENCODING_ASCII_US ) ); aBuffer.append( "' to the destination set.\n" ); Any aException( ::cppu::getCaughtException() ); aBuffer.append( "Caught an exception of type '" ); ::rtl::OUString sExceptionType( aException.getValueTypeName() ); aBuffer.append( ::rtl::OString( sExceptionType.getStr(), sExceptionType.getLength(), RTL_TEXTENCODING_ASCII_US ) ); aBuffer.append( "'" ); Exception aBaseException; if ( ( aException >>= aBaseException ) && aBaseException.Message.getLength() ) { aBuffer.append( ", saying '" ); aBuffer.append( ::rtl::OString( aBaseException.Message.getStr(), aBaseException.Message.getLength(), osl_getThreadTextEncoding() ) ); aBuffer.append( "'" ); } aBuffer.append( "." ); OSL_ENSURE( sal_False, aBuffer.getStr() ); #endif } } } } //------------------------------------------------------------------ sal_Bool hasProperty(const rtl::OUString& _rName, const Reference<XPropertySet>& _rxSet) { if (_rxSet.is()) { // XPropertySetInfoRef xInfo(rxSet->getPropertySetInfo()); return _rxSet->getPropertySetInfo()->hasPropertyByName(_rName); } return sal_False; } //------------------------------------------------------------------ void RemoveProperty(Sequence<Property>& _rProps, const rtl::OUString& _rPropName) { sal_Int32 nLen = _rProps.getLength(); // binaere Suche const Property* pProperties = _rProps.getConstArray(); const Property* pResult = ::std::lower_bound(pProperties, pProperties + nLen, _rPropName,PropertyStringLessFunctor()); // gefunden ? if ( pResult && (pResult != pProperties + nLen) && (pResult->Name == _rPropName) ) { OSL_ENSURE(pResult->Name.equals(_rPropName), "::RemoveProperty Properties nicht sortiert"); removeElementAt(_rProps, pResult - pProperties); } } //------------------------------------------------------------------ void ModifyPropertyAttributes(Sequence<Property>& seqProps, const ::rtl::OUString& sPropName, sal_Int16 nAddAttrib, sal_Int16 nRemoveAttrib) { sal_Int32 nLen = seqProps.getLength(); // binaere Suche Property* pProperties = seqProps.getArray(); Property* pResult = ::std::lower_bound(pProperties, pProperties + nLen,sPropName, PropertyStringLessFunctor()); // gefunden ? if ( pResult && (pResult != pProperties + nLen) && (pResult->Name == sPropName) ) { pResult->Attributes |= nAddAttrib; pResult->Attributes &= ~nRemoveAttrib; } } //------------------------------------------------------------------ sal_Bool tryPropertyValue(Any& _rConvertedValue, Any& _rOldValue, const Any& _rValueToSet, Any& _rCurrentValue, const Type& _rExpectedType) { sal_Bool bModified(sal_False); if (_rCurrentValue.getValue() != _rValueToSet.getValue()) { if ( _rValueToSet.hasValue() && ( !_rExpectedType.equals( _rValueToSet.getValueType() ) ) ) { _rConvertedValue = Any( NULL, _rExpectedType.getTypeLibType() ); if ( !uno_type_assignData( const_cast< void* >( _rConvertedValue.getValue() ), _rConvertedValue.getValueType().getTypeLibType(), const_cast< void* >( _rValueToSet.getValue() ), _rValueToSet.getValueType().getTypeLibType(), reinterpret_cast< uno_QueryInterfaceFunc >( cpp_queryInterface), reinterpret_cast< uno_AcquireFunc >(cpp_acquire), reinterpret_cast< uno_ReleaseFunc >(cpp_release) ) ) throw starlang::IllegalArgumentException(); } else _rConvertedValue = _rValueToSet; if ( _rCurrentValue != _rConvertedValue ) { _rOldValue = _rCurrentValue; bModified = sal_True; } } return bModified; } //......................................................................... } //......................................................................... <commit_msg>INTEGRATION: CWS canvas05 (1.10.20); FILE MERGED 2008/04/21 07:56:10 thb 1.10.20.2: RESYNC: (1.10-1.11); FILE MERGED 2007/10/01 13:50:40 thb 1.10.20.1: #i80285# Merge from CWS picom<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: property.cxx,v $ * $Revision: 1.12 $ * * 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_comphelper.hxx" #include <comphelper/property.hxx> #include <comphelper/sequence.hxx> #include <comphelper/types.hxx> #include <osl/diagnose.h> #if OSL_DEBUG_LEVEL > 0 #ifndef _RTL_STRBUF_HXX_ #include <rtl/strbuf.hxx> #endif #ifndef _CPPUHELPER_EXC_HLP_HXX_ #include <cppuhelper/exc_hlp.hxx> #endif #ifndef _OSL_THREAD_H_ #include <osl/thread.h> #endif #endif #include <com/sun/star/beans/PropertyAttribute.hpp> #include <com/sun/star/lang/IllegalArgumentException.hpp> #include <com/sun/star/uno/genfunc.h> #include <algorithm> #include <boost/bind.hpp> //......................................................................... namespace comphelper { /** === begin UNO using === **/ using ::com::sun::star::uno::Reference; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::beans::XPropertySetInfo; using ::com::sun::star::beans::Property; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::Any; using ::com::sun::star::uno::Type; using ::com::sun::star::uno::cpp_queryInterface; using ::com::sun::star::uno::cpp_acquire; using ::com::sun::star::uno::cpp_release; /** === end UNO using === **/ namespace PropertyAttribute = ::com::sun::star::beans::PropertyAttribute; //------------------------------------------------------------------ void copyProperties(const Reference<XPropertySet>& _rxSource, const Reference<XPropertySet>& _rxDest) { if (!_rxSource.is() || !_rxDest.is()) { OSL_ENSURE(sal_False, "copyProperties: invalid arguments !"); return; } Reference< XPropertySetInfo > xSourceProps = _rxSource->getPropertySetInfo(); Reference< XPropertySetInfo > xDestProps = _rxDest->getPropertySetInfo(); Sequence< Property > aSourceProps = xSourceProps->getProperties(); const Property* pSourceProps = aSourceProps.getConstArray(); Property aDestProp; for (sal_Int32 i=0; i<aSourceProps.getLength(); ++i, ++pSourceProps) { if ( xDestProps->hasPropertyByName(pSourceProps->Name) ) { try { aDestProp = xDestProps->getPropertyByName(pSourceProps->Name); if (0 == (aDestProp.Attributes & PropertyAttribute::READONLY)) _rxDest->setPropertyValue(pSourceProps->Name, _rxSource->getPropertyValue(pSourceProps->Name)); } catch (Exception&) { #if OSL_DEBUG_LEVEL > 0 ::rtl::OStringBuffer aBuffer; aBuffer.append( "::comphelper::copyProperties: could not copy property '" ); aBuffer.append( ::rtl::OString( pSourceProps->Name.getStr(), pSourceProps->Name.getLength(), RTL_TEXTENCODING_ASCII_US ) ); aBuffer.append( "' to the destination set.\n" ); Any aException( ::cppu::getCaughtException() ); aBuffer.append( "Caught an exception of type '" ); ::rtl::OUString sExceptionType( aException.getValueTypeName() ); aBuffer.append( ::rtl::OString( sExceptionType.getStr(), sExceptionType.getLength(), RTL_TEXTENCODING_ASCII_US ) ); aBuffer.append( "'" ); Exception aBaseException; if ( ( aException >>= aBaseException ) && aBaseException.Message.getLength() ) { aBuffer.append( ", saying '" ); aBuffer.append( ::rtl::OString( aBaseException.Message.getStr(), aBaseException.Message.getLength(), osl_getThreadTextEncoding() ) ); aBuffer.append( "'" ); } aBuffer.append( "." ); OSL_ENSURE( sal_False, aBuffer.getStr() ); #endif } } } } //------------------------------------------------------------------ sal_Bool hasProperty(const rtl::OUString& _rName, const Reference<XPropertySet>& _rxSet) { if (_rxSet.is()) { // XPropertySetInfoRef xInfo(rxSet->getPropertySetInfo()); return _rxSet->getPropertySetInfo()->hasPropertyByName(_rName); } return sal_False; } //------------------------------------------------------------------ bool findProperty(Property& o_rProp, Sequence<Property>& i_seqProps, const ::rtl::OUString& i_rPropName) { const Property* pAry(i_seqProps.getConstArray()); const sal_Int32 nLen(i_seqProps.getLength()); const Property* pRes( std::find_if(pAry,pAry+nLen, boost::bind(PropertyStringEqualFunctor(), _1, boost::cref(i_rPropName)))); if( pRes == pAry+nLen ) return false; o_rProp = *pRes; return true; } //------------------------------------------------------------------ void RemoveProperty(Sequence<Property>& _rProps, const rtl::OUString& _rPropName) { sal_Int32 nLen = _rProps.getLength(); // binaere Suche const Property* pProperties = _rProps.getConstArray(); const Property* pResult = ::std::lower_bound(pProperties, pProperties + nLen, _rPropName,PropertyStringLessFunctor()); // gefunden ? if ( pResult && (pResult != pProperties + nLen) && (pResult->Name == _rPropName) ) { OSL_ENSURE(pResult->Name.equals(_rPropName), "::RemoveProperty Properties nicht sortiert"); removeElementAt(_rProps, pResult - pProperties); } } //------------------------------------------------------------------ void ModifyPropertyAttributes(Sequence<Property>& seqProps, const ::rtl::OUString& sPropName, sal_Int16 nAddAttrib, sal_Int16 nRemoveAttrib) { sal_Int32 nLen = seqProps.getLength(); // binaere Suche Property* pProperties = seqProps.getArray(); Property* pResult = ::std::lower_bound(pProperties, pProperties + nLen,sPropName, PropertyStringLessFunctor()); // gefunden ? if ( pResult && (pResult != pProperties + nLen) && (pResult->Name == sPropName) ) { pResult->Attributes |= nAddAttrib; pResult->Attributes &= ~nRemoveAttrib; } } //------------------------------------------------------------------ sal_Bool tryPropertyValue(Any& _rConvertedValue, Any& _rOldValue, const Any& _rValueToSet, Any& _rCurrentValue, const Type& _rExpectedType) { sal_Bool bModified(sal_False); if (_rCurrentValue.getValue() != _rValueToSet.getValue()) { if ( _rValueToSet.hasValue() && ( !_rExpectedType.equals( _rValueToSet.getValueType() ) ) ) { _rConvertedValue = Any( NULL, _rExpectedType.getTypeLibType() ); if ( !uno_type_assignData( const_cast< void* >( _rConvertedValue.getValue() ), _rConvertedValue.getValueType().getTypeLibType(), const_cast< void* >( _rValueToSet.getValue() ), _rValueToSet.getValueType().getTypeLibType(), reinterpret_cast< uno_QueryInterfaceFunc >( cpp_queryInterface), reinterpret_cast< uno_AcquireFunc >(cpp_acquire), reinterpret_cast< uno_ReleaseFunc >(cpp_release) ) ) throw starlang::IllegalArgumentException(); } else _rConvertedValue = _rValueToSet; if ( _rCurrentValue != _rConvertedValue ) { _rOldValue = _rCurrentValue; bModified = sal_True; } } return bModified; } //......................................................................... } //......................................................................... <|endoftext|>
<commit_before>// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include "TestExternalTransport.h" #include "os/OsMutex.h" #include "os/OsTime.h" #include "sipXtapiTest.h" #include "tapi/sipXtapi.h" #include "tapi/sipXtapiEvents.h" #include "tapi/sipXtapiInternal.h" static OsMutex transportMutex(OsMutex::Q_FIFO); static void* gpData1; static size_t gnData1; static char gpUserData1[256]; static void* gpData2; static size_t gnData2; static char gpUserData2[256]; SIPX_TRANSPORT ghTransport1; SIPX_TRANSPORT ghTransport2; bool transportProc1(SIPX_TRANSPORT hTransport, const char* szDestinationIp, const int iDestPort, const char* szLocalIp, const int iLocalPort, const void* pData, const size_t nData, const void* pUserData) { transportMutex.acquire(); ghTransport1 = hTransport; gpData1 = malloc(nData); gnData1 = nData; memset(gpData1, 0, nData); memcpy(gpData1, pData, nData); strcpy(gpUserData1, (char*)pUserData); transportMutex.release(); return nData > 0; } bool transportProc2(SIPX_TRANSPORT hTransport, const char* szDestinationIp, const int iDestPort, const char* szLocalIp, const int iLocalPort, const void* pData, const size_t nData, const void* pUserData) { transportMutex.acquire(); ghTransport2 = hTransport; gpData2 = malloc(nData); gnData2 = nData; memset(gpData2, 0, nData); memcpy(gpData2, pData, nData); strcpy(gpUserData2, (char*)pUserData); transportMutex.release(); return nData > 0; } TransportTask::TransportTask(int id, const UtlString& name, void* pArg, const int priority, const int options, const int stackSize) : OsTask(name, pArg, priority, options, stackSize), mId(id) { } TransportTask::~TransportTask() { requestShutdown(); waitUntilShutDown(); } int TransportTask::run(void* pArg) { OsTime timeout(100); int bytesRead = 0; void* buffer = NULL; while (mState != SHUTTING_DOWN && mState != SHUT_DOWN ) { OsStatus rc = transportMutex.acquire(timeout); OsTask::delay(10) ; if (OS_SUCCESS == rc) { SIPX_TRANSPORT hTransport = NULL; if (1 == mId) { hTransport = ghTransport1; bytesRead = gnData2; buffer = gpData2; } else if (2 == mId) { hTransport = ghTransport2; bytesRead = gnData1; buffer = gpData1; } if (hTransport && buffer) { sipxConfigExternalTransportHandleMessage(hTransport, "127.0.0.1", -1, "127.0.0.1", -1, buffer, bytesRead); } if (1 == mId) { gpData2 = NULL; } else if (2 == mId) { gpData1 = NULL; } transportMutex.release(); } } return 0; } <commit_msg>Use SIPX_TRANSPORT_NULL instead of NULL to initialize variable of type SIPX_TRANSPORT in TransportTask::run() in TestExternalTransport.cpp.<commit_after>// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include "TestExternalTransport.h" #include "os/OsMutex.h" #include "os/OsTime.h" #include "sipXtapiTest.h" #include "tapi/sipXtapi.h" #include "tapi/sipXtapiEvents.h" #include "tapi/sipXtapiInternal.h" static OsMutex transportMutex(OsMutex::Q_FIFO); static void* gpData1; static size_t gnData1; static char gpUserData1[256]; static void* gpData2; static size_t gnData2; static char gpUserData2[256]; SIPX_TRANSPORT ghTransport1; SIPX_TRANSPORT ghTransport2; bool transportProc1(SIPX_TRANSPORT hTransport, const char* szDestinationIp, const int iDestPort, const char* szLocalIp, const int iLocalPort, const void* pData, const size_t nData, const void* pUserData) { transportMutex.acquire(); ghTransport1 = hTransport; gpData1 = malloc(nData); gnData1 = nData; memset(gpData1, 0, nData); memcpy(gpData1, pData, nData); strcpy(gpUserData1, (char*)pUserData); transportMutex.release(); return nData > 0; } bool transportProc2(SIPX_TRANSPORT hTransport, const char* szDestinationIp, const int iDestPort, const char* szLocalIp, const int iLocalPort, const void* pData, const size_t nData, const void* pUserData) { transportMutex.acquire(); ghTransport2 = hTransport; gpData2 = malloc(nData); gnData2 = nData; memset(gpData2, 0, nData); memcpy(gpData2, pData, nData); strcpy(gpUserData2, (char*)pUserData); transportMutex.release(); return nData > 0; } TransportTask::TransportTask(int id, const UtlString& name, void* pArg, const int priority, const int options, const int stackSize) : OsTask(name, pArg, priority, options, stackSize), mId(id) { } TransportTask::~TransportTask() { requestShutdown(); waitUntilShutDown(); } int TransportTask::run(void* pArg) { OsTime timeout(100); int bytesRead = 0; void* buffer = NULL; while (mState != SHUTTING_DOWN && mState != SHUT_DOWN ) { OsStatus rc = transportMutex.acquire(timeout); OsTask::delay(10) ; if (OS_SUCCESS == rc) { SIPX_TRANSPORT hTransport = SIPX_TRANSPORT_NULL; if (1 == mId) { hTransport = ghTransport1; bytesRead = gnData2; buffer = gpData2; } else if (2 == mId) { hTransport = ghTransport2; bytesRead = gnData1; buffer = gpData1; } if (hTransport && buffer) { sipxConfigExternalTransportHandleMessage(hTransport, "127.0.0.1", -1, "127.0.0.1", -1, buffer, bytesRead); } if (1 == mId) { gpData2 = NULL; } else if (2 == mId) { gpData1 = NULL; } transportMutex.release(); } } return 0; } <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2004-2007 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "factory.h" #include "factory_p.h" #include "backendinterface.h" #include "medianode_p.h" #include "audiooutput.h" #include "audiooutput_p.h" #include "globalstatic_p.h" #include "platformplugin.h" #include "phononnamespace_p.h" #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QLibrary> #include <QtCore/QList> #include <QtCore/QPluginLoader> #include <QtGui/QIcon> #ifndef QT_NO_DBUS #include <QtDBus/QtDBus> #endif namespace Phonon { PHONON_GLOBAL_STATIC(Phonon::FactoryPrivate, globalFactory) void Factory::setBackend(QObject *b) { Q_ASSERT(globalFactory->m_backendObject == 0); globalFactory->m_backendObject = b; } /*void Factory::createBackend(const QString &library, const QString &version) { Q_ASSERT(globalFactory->m_backendObject == 0); PlatformPlugin *f = globalFactory->platformPlugin(); if (f) { globalFactory->m_backendObject = f->createBackend(library, version); } }*/ bool FactoryPrivate::createBackend() { Q_ASSERT(m_backendObject == 0); PlatformPlugin *f = globalFactory->platformPlugin(); if (f) { m_backendObject = f->createBackend(); } if (!m_backendObject) { // could not load a backend through the platform plugin. Falling back to the default. #if defined(Q_WS_MAC) const QLatin1String pluginName("mac_qt7"); #elif defined(Q_WS_WIN) #if defined(QT_NO_DEBUG) const QLatin1String pluginName("phonon_ds9"); #else const QLatin1String pluginName("phonon_ds9d"); #endif #else const QLatin1String pluginName("xine"); #endif const QLatin1String suffix("/phonon_backend/"); foreach (QString libPath, QCoreApplication::libraryPaths()) { libPath += suffix; const QDir dir(libPath); if (!dir.exists()) { pDebug() << Q_FUNC_INFO << dir.absolutePath() << "does not exist"; continue; } QLibrary pluginLib(libPath + pluginName); if (pluginLib.load()) { pDebug() << Q_FUNC_INFO << "trying to load " << pluginLib.fileName(); QPluginLoader pluginLoader(pluginLib.fileName()); if (!pluginLoader.load()) { pDebug() << Q_FUNC_INFO << " load failed:" << pluginLoader.errorString(); continue; } pDebug() << pluginLoader.instance(); m_backendObject = pluginLoader.instance(); if (m_backendObject) { break; } } } if (!m_backendObject) { pDebug() << Q_FUNC_INFO << "phonon plugin could not be loaded:" << pluginName; return false; } } connect(m_backendObject, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)), SLOT(objectDescriptionChanged(ObjectDescriptionType))); return true; } FactoryPrivate::FactoryPrivate() : m_backendObject(0), m_platformPlugin(0), m_noPlatformPlugin(false) { // Add the post routine to make sure that all other global statics (especially the ones from Qt) // are still available. If the FactoryPrivate dtor is called too late many bad things can happen // as the whole backend might still be alive. qAddPostRoutine(globalFactory.destroy); #ifndef QT_NO_DBUS QDBusConnection::sessionBus().connect(QString(), QString(), "org.kde.Phonon.Factory", "phononBackendChanged", this, SLOT(phononBackendChanged())); #endif } FactoryPrivate::~FactoryPrivate() { foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->deleteBackendObject(); } if (objects.size() > 0) { pError() << "The backend objects are not deleted as was requested."; qDeleteAll(objects); } delete m_backendObject; delete m_platformPlugin; } void FactoryPrivate::objectDescriptionChanged(ObjectDescriptionType type) { #ifdef PHONON_METHODTEST Q_UNUSED(type); #else pDebug() << Q_FUNC_INFO << type; switch (type) { case AudioOutputDeviceType: emit availableAudioOutputDevicesChanged(); break; default: break; } //emit capabilitiesChanged(); #endif // PHONON_METHODTEST } Factory::Sender *Factory::sender() { return globalFactory; } bool Factory::isMimeTypeAvailable(const QString &mimeType) { PlatformPlugin *f = globalFactory->platformPlugin(); if (f) { return f->isMimeTypeAvailable(mimeType); } return true; // the MIME type might be supported, let BackendCapabilities find out } void Factory::registerFrontendObject(MediaNodePrivate *bp) { globalFactory->mediaNodePrivateList.prepend(bp); // inserted last => deleted first } void Factory::deregisterFrontendObject(MediaNodePrivate *bp) { // The Factory can already be cleaned up while there are other frontend objects still alive. // When those are deleted they'll call deregisterFrontendObject through ~BasePrivate if (!globalFactory.isDestroyed()) { globalFactory->mediaNodePrivateList.removeAll(bp); } } void FactoryPrivate::phononBackendChanged() { if (m_backendObject) { foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->deleteBackendObject(); } if (objects.size() > 0) { pDebug() << "WARNING: we were asked to change the backend but the application did\n" "not free all references to objects created by the factory. Therefore we can not\n" "change the backend without crashing. Now we have to wait for a restart to make\n" "backendswitching possible."; // in case there were objects deleted give 'em a chance to recreate // them now foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->createBackendObject(); } return; } delete m_backendObject; m_backendObject = 0; } createBackend(); foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->createBackendObject(); } emit backendChanged(); } //X void Factory::freeSoundcardDevices() //X { //X if (globalFactory->backend) { //X globalFactory->backend->freeSoundcardDevices(); //X } //X } void FactoryPrivate::objectDestroyed(QObject * obj) { //pDebug() << Q_FUNC_INFO << obj; objects.removeAll(obj); } #define FACTORY_IMPL(classname) \ QObject *Factory::create ## classname(QObject *parent) \ { \ if (backend()) { \ return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent)); \ } \ return 0; \ } #define FACTORY_IMPL_1ARG(classname) \ QObject *Factory::create ## classname(int arg1, QObject *parent) \ { \ if (backend()) { \ return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent, QList<QVariant>() << arg1)); \ } \ return 0; \ } FACTORY_IMPL(MediaObject) FACTORY_IMPL_1ARG(Effect) FACTORY_IMPL(VolumeFaderEffect) FACTORY_IMPL(AudioOutput) FACTORY_IMPL(AudioDataOutput) FACTORY_IMPL(Visualization) FACTORY_IMPL(VideoDataOutput) FACTORY_IMPL(VideoWidget) #undef FACTORY_IMPL PlatformPlugin *FactoryPrivate::platformPlugin() { if (!m_platformPlugin) { if (m_noPlatformPlugin) { return 0; } #ifndef QT_NO_DBUS if (!QCoreApplication::instance() || QCoreApplication::applicationName().isEmpty()) { pWarning() << "Phonon needs QCoreApplication::applicationName to be set to export audio output names through the DBUS interface"; } #endif const QString suffix(QLatin1String("/phonon_platform")); Q_ASSERT(QCoreApplication::instance()); foreach (QString libPath, QCoreApplication::libraryPaths()) { libPath += suffix; const QDir dir(libPath); if (!dir.exists()) { pDebug() << Q_FUNC_INFO << dir.absolutePath() << "does not exist"; continue; } QLibrary pluginLib(libPath + QLatin1String("/kde")); if (pluginLib.load()) { pDebug() << Q_FUNC_INFO << "trying to load " << pluginLib.fileName(); QPluginLoader pluginLoader(pluginLib.fileName()); Q_ASSERT_X(pluginLoader.load(), Q_FUNC_INFO, qPrintable(pluginLoader.errorString())); pDebug() << pluginLoader.instance(); m_platformPlugin = qobject_cast<PlatformPlugin *>(pluginLoader.instance()); pDebug() << m_platformPlugin; if (m_platformPlugin) { return m_platformPlugin; } } else { pDebug() << Q_FUNC_INFO << dir.absolutePath() << "exists but the KDE platform plugin was not loadable:" << pluginLib.errorString(); } } if (!m_platformPlugin) { pDebug() << Q_FUNC_INFO << "phonon_platform/kde plugin could not be loaded"; m_noPlatformPlugin = true; } } return m_platformPlugin; } PlatformPlugin *Factory::platformPlugin() { return globalFactory->platformPlugin(); } QObject *Factory::backend(bool createWhenNull) { if (globalFactory.isDestroyed()) { return 0; } if (createWhenNull && globalFactory->m_backendObject == 0) { globalFactory->createBackend(); // XXX: might create "reentrancy" problems: // a method calls this method and is called again because the // backendChanged signal is emitted emit globalFactory->backendChanged(); } return globalFactory->m_backendObject; } #define GET_STRING_PROPERTY(name) \ QString Factory::name() \ { \ if (globalFactory->m_backendObject) { \ return globalFactory->m_backendObject->property(#name).toString(); \ } \ return QString(); \ } \ GET_STRING_PROPERTY(identifier) GET_STRING_PROPERTY(backendName) GET_STRING_PROPERTY(backendComment) GET_STRING_PROPERTY(backendVersion) GET_STRING_PROPERTY(backendIcon) GET_STRING_PROPERTY(backendWebsite) QObject *Factory::registerQObject(QObject *o) { if (o) { QObject::connect(o, SIGNAL(destroyed(QObject *)), globalFactory, SLOT(objectDestroyed(QObject *)), Qt::DirectConnection); globalFactory->objects.append(o); } return o; } } //namespace Phonon #include "moc_factory.cpp" #include "moc_factory_p.cpp" // vim: sw=4 ts=4 <commit_msg>Don't hardcode the plugin names, but instead try and load them dynamically<commit_after>/* This file is part of the KDE project Copyright (C) 2004-2007 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "factory.h" #include "factory_p.h" #include "backendinterface.h" #include "medianode_p.h" #include "audiooutput.h" #include "audiooutput_p.h" #include "globalstatic_p.h" #include "platformplugin.h" #include "phononnamespace_p.h" #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QLibrary> #include <QtCore/QList> #include <QtCore/QPluginLoader> #include <QtGui/QIcon> #ifndef QT_NO_DBUS #include <QtDBus/QtDBus> #endif namespace Phonon { PHONON_GLOBAL_STATIC(Phonon::FactoryPrivate, globalFactory) void Factory::setBackend(QObject *b) { Q_ASSERT(globalFactory->m_backendObject == 0); globalFactory->m_backendObject = b; } /*void Factory::createBackend(const QString &library, const QString &version) { Q_ASSERT(globalFactory->m_backendObject == 0); PlatformPlugin *f = globalFactory->platformPlugin(); if (f) { globalFactory->m_backendObject = f->createBackend(library, version); } }*/ bool FactoryPrivate::createBackend() { Q_ASSERT(m_backendObject == 0); PlatformPlugin *f = globalFactory->platformPlugin(); if (f) { m_backendObject = f->createBackend(); } if (!m_backendObject) { // could not load a backend through the platform plugin. Falling back to the default // (finding the first loadable backend). const QLatin1String suffix("/phonon_backend/"); foreach (QString libPath, QCoreApplication::libraryPaths()) { libPath += suffix; const QDir dir(libPath); if (!dir.exists()) { pDebug() << Q_FUNC_INFO << dir.absolutePath() << "does not exist"; continue; } foreach (QString pluginName, dir.entryList(QDir::Files)) { QPluginLoader pluginLoader(libPath + pluginName); if (!pluginLoader.load()) { pDebug() << Q_FUNC_INFO << " load failed:" << pluginLoader.errorString(); continue; } pDebug() << pluginLoader.instance(); m_backendObject = pluginLoader.instance(); if (m_backendObject) { break; } // no backend found, don't leave an unused plugin in memory pluginLoader.unload(); } if (m_backendObject) { break; } } if (!m_backendObject) { pDebug() << Q_FUNC_INFO << "phonon backend plugin could not be loaded"; return false; } } connect(m_backendObject, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)), SLOT(objectDescriptionChanged(ObjectDescriptionType))); return true; } FactoryPrivate::FactoryPrivate() : m_backendObject(0), m_platformPlugin(0), m_noPlatformPlugin(false) { // Add the post routine to make sure that all other global statics (especially the ones from Qt) // are still available. If the FactoryPrivate dtor is called too late many bad things can happen // as the whole backend might still be alive. qAddPostRoutine(globalFactory.destroy); #ifndef QT_NO_DBUS QDBusConnection::sessionBus().connect(QString(), QString(), "org.kde.Phonon.Factory", "phononBackendChanged", this, SLOT(phononBackendChanged())); #endif } FactoryPrivate::~FactoryPrivate() { foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->deleteBackendObject(); } if (objects.size() > 0) { pError() << "The backend objects are not deleted as was requested."; qDeleteAll(objects); } delete m_backendObject; delete m_platformPlugin; } void FactoryPrivate::objectDescriptionChanged(ObjectDescriptionType type) { #ifdef PHONON_METHODTEST Q_UNUSED(type); #else pDebug() << Q_FUNC_INFO << type; switch (type) { case AudioOutputDeviceType: emit availableAudioOutputDevicesChanged(); break; default: break; } //emit capabilitiesChanged(); #endif // PHONON_METHODTEST } Factory::Sender *Factory::sender() { return globalFactory; } bool Factory::isMimeTypeAvailable(const QString &mimeType) { PlatformPlugin *f = globalFactory->platformPlugin(); if (f) { return f->isMimeTypeAvailable(mimeType); } return true; // the MIME type might be supported, let BackendCapabilities find out } void Factory::registerFrontendObject(MediaNodePrivate *bp) { globalFactory->mediaNodePrivateList.prepend(bp); // inserted last => deleted first } void Factory::deregisterFrontendObject(MediaNodePrivate *bp) { // The Factory can already be cleaned up while there are other frontend objects still alive. // When those are deleted they'll call deregisterFrontendObject through ~BasePrivate if (!globalFactory.isDestroyed()) { globalFactory->mediaNodePrivateList.removeAll(bp); } } void FactoryPrivate::phononBackendChanged() { if (m_backendObject) { foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->deleteBackendObject(); } if (objects.size() > 0) { pDebug() << "WARNING: we were asked to change the backend but the application did\n" "not free all references to objects created by the factory. Therefore we can not\n" "change the backend without crashing. Now we have to wait for a restart to make\n" "backendswitching possible."; // in case there were objects deleted give 'em a chance to recreate // them now foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->createBackendObject(); } return; } delete m_backendObject; m_backendObject = 0; } createBackend(); foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->createBackendObject(); } emit backendChanged(); } //X void Factory::freeSoundcardDevices() //X { //X if (globalFactory->backend) { //X globalFactory->backend->freeSoundcardDevices(); //X } //X } void FactoryPrivate::objectDestroyed(QObject * obj) { //pDebug() << Q_FUNC_INFO << obj; objects.removeAll(obj); } #define FACTORY_IMPL(classname) \ QObject *Factory::create ## classname(QObject *parent) \ { \ if (backend()) { \ return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent)); \ } \ return 0; \ } #define FACTORY_IMPL_1ARG(classname) \ QObject *Factory::create ## classname(int arg1, QObject *parent) \ { \ if (backend()) { \ return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent, QList<QVariant>() << arg1)); \ } \ return 0; \ } FACTORY_IMPL(MediaObject) FACTORY_IMPL_1ARG(Effect) FACTORY_IMPL(VolumeFaderEffect) FACTORY_IMPL(AudioOutput) FACTORY_IMPL(AudioDataOutput) FACTORY_IMPL(Visualization) FACTORY_IMPL(VideoDataOutput) FACTORY_IMPL(VideoWidget) #undef FACTORY_IMPL PlatformPlugin *FactoryPrivate::platformPlugin() { if (!m_platformPlugin) { if (m_noPlatformPlugin) { return 0; } #ifndef QT_NO_DBUS if (!QCoreApplication::instance() || QCoreApplication::applicationName().isEmpty()) { pWarning() << "Phonon needs QCoreApplication::applicationName to be set to export audio output names through the DBUS interface"; } #endif const QString suffix(QLatin1String("/phonon_platform")); Q_ASSERT(QCoreApplication::instance()); foreach (QString libPath, QCoreApplication::libraryPaths()) { libPath += suffix; const QDir dir(libPath); if (!dir.exists()) { pDebug() << Q_FUNC_INFO << dir.absolutePath() << "does not exist"; continue; } QPluginLoader pluginLoader(libPath + QLatin1String("/kde")); Q_ASSERT_X(pluginLoader.load(), Q_FUNC_INFO, qPrintable(pluginLoader.errorString())); pDebug() << pluginLoader.instance(); m_platformPlugin = qobject_cast<PlatformPlugin *>(pluginLoader.instance()); pDebug() << m_platformPlugin; if (m_platformPlugin) { return m_platformPlugin; } else { pDebug() << Q_FUNC_INFO << dir.absolutePath() << "exists but the KDE platform plugin was not loadable:" << pluginLoader.errorString(); pluginLoader.unload(); } } if (!m_platformPlugin) { pDebug() << Q_FUNC_INFO << "phonon_platform/kde plugin could not be loaded"; m_noPlatformPlugin = true; } } return m_platformPlugin; } PlatformPlugin *Factory::platformPlugin() { return globalFactory->platformPlugin(); } QObject *Factory::backend(bool createWhenNull) { if (globalFactory.isDestroyed()) { return 0; } if (createWhenNull && globalFactory->m_backendObject == 0) { globalFactory->createBackend(); // XXX: might create "reentrancy" problems: // a method calls this method and is called again because the // backendChanged signal is emitted emit globalFactory->backendChanged(); } return globalFactory->m_backendObject; } #define GET_STRING_PROPERTY(name) \ QString Factory::name() \ { \ if (globalFactory->m_backendObject) { \ return globalFactory->m_backendObject->property(#name).toString(); \ } \ return QString(); \ } \ GET_STRING_PROPERTY(identifier) GET_STRING_PROPERTY(backendName) GET_STRING_PROPERTY(backendComment) GET_STRING_PROPERTY(backendVersion) GET_STRING_PROPERTY(backendIcon) GET_STRING_PROPERTY(backendWebsite) QObject *Factory::registerQObject(QObject *o) { if (o) { QObject::connect(o, SIGNAL(destroyed(QObject *)), globalFactory, SLOT(objectDestroyed(QObject *)), Qt::DirectConnection); globalFactory->objects.append(o); } return o; } } //namespace Phonon #include "moc_factory.cpp" #include "moc_factory_p.cpp" // vim: sw=4 ts=4 <|endoftext|>
<commit_before>#ifndef __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_SIMPLEX_HPP__ #define __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_SIMPLEX_HPP__ #include <sstream> #include <stan/math/matrix/Eigen.hpp> #include <stan/meta/traits.hpp> #include <stan/math/error_handling/dom_err.hpp> #include <stan/math/error_handling/matrix/constraint_tolerance.hpp> namespace stan { namespace math { /** * Return <code>true</code> if the specified vector is simplex. * To be a simplex, all values must be greater than or equal to 0 * and the values must sum to 1. * * <p>The test that the values sum to 1 is done to within the * tolerance specified by <code>CONSTRAINT_TOLERANCE</code>. * * @param function * @param theta Vector to test. * @param name * @param result * @return <code>true</code> if the vector is a simplex. */ template <typename T_prob, typename T_result> bool check_simplex(const char* function, const Eigen::Matrix<T_prob,Eigen::Dynamic,1>& theta, const char* name, T_result* result) { typedef typename Eigen::Matrix<T_prob,Eigen::Dynamic,1>::size_type size_t; if (theta.size() == 0) { std::stringstream msg; msg << " is not a valid simplex. " << "length(" << name << ") = %1%"; std::string tmp(msg.str()); return dom_err(function,0,name, tmp.c_str(),"", result); } if (fabs(1.0 - theta.sum()) > CONSTRAINT_TOLERANCE) { std::stringstream msg; T_prob sum = theta.sum(); msg << " is not a valid simplex."; msg << " sum(" << name << ") = %1%, but should be 1"; std::string tmp(msg.str()); return dom_err(function,sum,name, tmp.c_str(),"", result); } for (size_t n = 0; n < theta.size(); n++) { if (!(theta[n] >= 0)) { std::ostringstream stream; stream << " is not a valid simplex. " << name << "[" << n + stan::error_index::value << "]" << " = %1%, but should be greater than or equal to 0"; std::string tmp(stream.str()); return dom_err(function,theta[n],name, tmp.c_str(),"", result); } } return true; } } } #endif <commit_msg>adding more precision to error message<commit_after>#ifndef __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_SIMPLEX_HPP__ #define __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_SIMPLEX_HPP__ #include <sstream> #include <stan/math/matrix/Eigen.hpp> #include <stan/meta/traits.hpp> #include <stan/math/error_handling/dom_err.hpp> #include <stan/math/error_handling/matrix/constraint_tolerance.hpp> namespace stan { namespace math { /** * Return <code>true</code> if the specified vector is simplex. * To be a simplex, all values must be greater than or equal to 0 * and the values must sum to 1. * * <p>The test that the values sum to 1 is done to within the * tolerance specified by <code>CONSTRAINT_TOLERANCE</code>. * * @param function * @param theta Vector to test. * @param name * @param result * @return <code>true</code> if the vector is a simplex. */ template <typename T_prob, typename T_result> bool check_simplex(const char* function, const Eigen::Matrix<T_prob,Eigen::Dynamic,1>& theta, const char* name, T_result* result) { typedef typename Eigen::Matrix<T_prob,Eigen::Dynamic,1>::size_type size_t; if (theta.size() == 0) { std::stringstream msg; msg << " is not a valid simplex. " << "length(" << name << ") = %1%"; std::string tmp(msg.str()); return dom_err(function,0,name, tmp.c_str(),"", result); } if (fabs(1.0 - theta.sum()) > CONSTRAINT_TOLERANCE) { std::stringstream msg; T_prob sum = theta.sum(); msg << " is not a valid simplex."; msg.precision(10); msg << " sum(" << name << ") = " << sum << ", but should be %1%"; std::string tmp(msg.str()); return dom_err(function,1.0,name, tmp.c_str(),"", result); } for (size_t n = 0; n < theta.size(); n++) { if (!(theta[n] >= 0)) { std::ostringstream stream; stream << " is not a valid simplex. " << name << "[" << n + stan::error_index::value << "]" << " = %1%, but should be greater than or equal to 0"; std::string tmp(stream.str()); return dom_err(function,theta[n],name, tmp.c_str(),"", result); } } return true; } } } #endif <|endoftext|>
<commit_before>/* * ReedSolomonDecoder.cpp * zxing * * Created by Christian Brunschen on 05/05/2008. * Copyright 2008 Google UK. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <memory> #include <zxing/common/reedsolomon/ReedSolomonDecoder.h> #include <zxing/common/reedsolomon/ReedSolomonException.h> #include <zxing/common/IllegalArgumentException.h> using namespace std; namespace zxing { ReedSolomonDecoder::ReedSolomonDecoder(Ref<GenericGF> fld) : field(fld) { } ReedSolomonDecoder::~ReedSolomonDecoder() { } void ReedSolomonDecoder::decode(ArrayRef<int> received, int twoS) { Ref<GenericGFPoly> poly(new GenericGFPoly(field, received)); /* #ifdef DEBUG cout << "decoding with poly " << *poly << endl; #endif */ ArrayRef<int> syndromeCoefficients(new Array<int> (twoS)); #ifdef DEBUG cout << "syndromeCoefficients array = " << syndromeCoefficients.array_ << endl; #endif bool dataMatrix = (field.object_ == GenericGF::DATA_MATRIX_FIELD_256.object_); bool noError = true; for (int i = 0; i < twoS; i++) { int eval = poly->evaluateAt(field->exp(dataMatrix ? i + 1 : i)); syndromeCoefficients[syndromeCoefficients->size() - 1 - i] = eval; if (eval != 0) { noError = false; } } if (noError) { return; } Ref<GenericGFPoly> syndrome(new GenericGFPoly(field, syndromeCoefficients)); Ref<GenericGFPoly> monomial = field->buildMonomial(twoS, 1); vector<Ref<GenericGFPoly> > sigmaOmega = runEuclideanAlgorithm(monomial, syndrome, twoS); ArrayRef<int> errorLocations = findErrorLocations(sigmaOmega[0]); ArrayRef<int> errorMagitudes = findErrorMagnitudes(sigmaOmega[1], errorLocations, dataMatrix); for (unsigned i = 0; i < errorLocations->size(); i++) { int position = received->size() - 1 - field->log(errorLocations[i]); //TODO: check why the position would be invalid if (position < 0 || (size_t)position >= received.size()) throw IllegalArgumentException("Invalid position (ReedSolomonDecoder)"); received[position] = GenericGF::addOrSubtract(received[position], errorMagitudes[i]); } } vector<Ref<GenericGFPoly> > ReedSolomonDecoder::runEuclideanAlgorithm(Ref<GenericGFPoly> a, Ref<GenericGFPoly> b, int R) { // Assume a's degree is >= b's if (a->getDegree() < b->getDegree()) { Ref<GenericGFPoly> tmp = a; a = b; b = tmp; } Ref<GenericGFPoly> rLast(a); Ref<GenericGFPoly> r(b); Ref<GenericGFPoly> sLast(field->getOne()); Ref<GenericGFPoly> s(field->getZero()); Ref<GenericGFPoly> tLast(field->getZero()); Ref<GenericGFPoly> t(field->getOne()); // Run Euclidean algorithm until r's degree is less than R/2 while (r->getDegree() >= R / 2) { Ref<GenericGFPoly> rLastLast(rLast); Ref<GenericGFPoly> sLastLast(sLast); Ref<GenericGFPoly> tLastLast(tLast); rLast = r; sLast = s; tLast = t; // Divide rLastLast by rLast, with quotient q and remainder r if (rLast->isZero()) { // Oops, Euclidean algorithm already terminated? throw ReedSolomonException("r_{i-1} was zero"); } r = rLastLast; Ref<GenericGFPoly> q(field->getZero()); int denominatorLeadingTerm = rLast->getCoefficient(rLast->getDegree()); int dltInverse = field->inverse(denominatorLeadingTerm); while (r->getDegree() >= rLast->getDegree() && !r->isZero()) { int degreeDiff = r->getDegree() - rLast->getDegree(); int scale = field->multiply(r->getCoefficient(r->getDegree()), dltInverse); q = q->addOrSubtract(field->buildMonomial(degreeDiff, scale)); r = r->addOrSubtract(rLast->multiplyByMonomial(degreeDiff, scale)); } s = q->multiply(sLast)->addOrSubtract(sLastLast); t = q->multiply(tLast)->addOrSubtract(tLastLast); } int sigmaTildeAtZero = t->getCoefficient(0); if (sigmaTildeAtZero == 0) { throw ReedSolomonException("sigmaTilde(0) was zero"); } int inverse = field->inverse(sigmaTildeAtZero); Ref<GenericGFPoly> sigma(t->multiply(inverse)); Ref<GenericGFPoly> omega(r->multiply(inverse)); /* #ifdef DEBUG cout << "t = " << *t << endl; cout << "r = " << *r << "\n"; cout << "sigma = " << *sigma << endl; cout << "omega = " << *omega << endl; #endif */ vector<Ref<GenericGFPoly> > result(2); result[0] = sigma; result[1] = omega; return result; } ArrayRef<int> ReedSolomonDecoder::findErrorLocations(Ref<GenericGFPoly> errorLocator) { // This is a direct application of Chien's search int numErrors = errorLocator->getDegree(); if (numErrors == 1) { // shortcut ArrayRef<int> result(new Array<int>(1)); result[0] = errorLocator->getCoefficient(1); return result; } ArrayRef<int> result(new Array<int>(numErrors)); int e = 0; for (int i = 1; i < field->getSize() && e < numErrors; i++) { // cout << "errorLocator(" << i << ") == " << errorLocator->evaluateAt(i) << endl; if (errorLocator->evaluateAt(i) == 0) { result[e] = field->inverse(i); e++; } } if (e != numErrors) { throw ReedSolomonException("Error locator degree does not match number of roots"); } return result; } ArrayRef<int> ReedSolomonDecoder::findErrorMagnitudes(Ref<GenericGFPoly> errorEvaluator, ArrayRef<int> errorLocations, bool dataMatrix) { // This is directly applying Forney's Formula int s = errorLocations.size(); ArrayRef<int> result(new Array<int>(s)); for (int i = 0; i < s; i++) { int xiInverse = field->inverse(errorLocations[i]); int denominator = 1; for (int j = 0; j < s; j++) { if (i != j) { denominator = field->multiply(denominator, GenericGF::addOrSubtract(1, field->multiply(errorLocations[j], xiInverse))); } } result[i] = field->multiply(errorEvaluator->evaluateAt(xiInverse), field->inverse(denominator)); if (dataMatrix) { result[i] = field->multiply(result[i], xiInverse); } } return result; } } <commit_msg>C++ changes for 2281<commit_after>/* * ReedSolomonDecoder.cpp * zxing * * Created by Christian Brunschen on 05/05/2008. * Copyright 2008 Google UK. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <memory> #include <zxing/common/reedsolomon/ReedSolomonDecoder.h> #include <zxing/common/reedsolomon/ReedSolomonException.h> #include <zxing/common/IllegalArgumentException.h> using namespace std; namespace zxing { ReedSolomonDecoder::ReedSolomonDecoder(Ref<GenericGF> fld) : field(fld) { } ReedSolomonDecoder::~ReedSolomonDecoder() { } void ReedSolomonDecoder::decode(ArrayRef<int> received, int twoS) { Ref<GenericGFPoly> poly(new GenericGFPoly(field, received)); /* #ifdef DEBUG cout << "decoding with poly " << *poly << endl; #endif */ ArrayRef<int> syndromeCoefficients(new Array<int> (twoS)); #ifdef DEBUG cout << "syndromeCoefficients array = " << syndromeCoefficients.array_ << endl; #endif bool dataMatrix = (field.object_ == GenericGF::DATA_MATRIX_FIELD_256.object_); bool noError = true; for (int i = 0; i < twoS; i++) { int eval = poly->evaluateAt(field->exp(dataMatrix ? i + 1 : i)); syndromeCoefficients[syndromeCoefficients->size() - 1 - i] = eval; if (eval != 0) { noError = false; } } if (noError) { return; } Ref<GenericGFPoly> syndrome(new GenericGFPoly(field, syndromeCoefficients)); Ref<GenericGFPoly> monomial = field->buildMonomial(twoS, 1); vector<Ref<GenericGFPoly> > sigmaOmega = runEuclideanAlgorithm(monomial, syndrome, twoS); ArrayRef<int> errorLocations = findErrorLocations(sigmaOmega[0]); ArrayRef<int> errorMagitudes = findErrorMagnitudes(sigmaOmega[1], errorLocations, dataMatrix); for (unsigned i = 0; i < errorLocations->size(); i++) { int position = received->size() - 1 - field->log(errorLocations[i]); //TODO: check why the position would be invalid if (position < 0 || (size_t)position >= received.size()) throw IllegalArgumentException("Invalid position (ReedSolomonDecoder)"); received[position] = GenericGF::addOrSubtract(received[position], errorMagitudes[i]); } } vector<Ref<GenericGFPoly> > ReedSolomonDecoder::runEuclideanAlgorithm(Ref<GenericGFPoly> a, Ref<GenericGFPoly> b, int R) { // Assume a's degree is >= b's if (a->getDegree() < b->getDegree()) { Ref<GenericGFPoly> tmp = a; a = b; b = tmp; } Ref<GenericGFPoly> rLast(a); Ref<GenericGFPoly> r(b); Ref<GenericGFPoly> tLast(field->getZero()); Ref<GenericGFPoly> t(field->getOne()); // Run Euclidean algorithm until r's degree is less than R/2 while (r->getDegree() >= R / 2) { Ref<GenericGFPoly> rLastLast(rLast); Ref<GenericGFPoly> tLastLast(tLast); rLast = r; tLast = t; // Divide rLastLast by rLast, with quotient q and remainder r if (rLast->isZero()) { // Oops, Euclidean algorithm already terminated? throw ReedSolomonException("r_{i-1} was zero"); } r = rLastLast; Ref<GenericGFPoly> q(field->getZero()); int denominatorLeadingTerm = rLast->getCoefficient(rLast->getDegree()); int dltInverse = field->inverse(denominatorLeadingTerm); while (r->getDegree() >= rLast->getDegree() && !r->isZero()) { int degreeDiff = r->getDegree() - rLast->getDegree(); int scale = field->multiply(r->getCoefficient(r->getDegree()), dltInverse); q = q->addOrSubtract(field->buildMonomial(degreeDiff, scale)); r = r->addOrSubtract(rLast->multiplyByMonomial(degreeDiff, scale)); } t = q->multiply(tLast)->addOrSubtract(tLastLast); } int sigmaTildeAtZero = t->getCoefficient(0); if (sigmaTildeAtZero == 0) { throw ReedSolomonException("sigmaTilde(0) was zero"); } int inverse = field->inverse(sigmaTildeAtZero); Ref<GenericGFPoly> sigma(t->multiply(inverse)); Ref<GenericGFPoly> omega(r->multiply(inverse)); /* #ifdef DEBUG cout << "t = " << *t << endl; cout << "r = " << *r << "\n"; cout << "sigma = " << *sigma << endl; cout << "omega = " << *omega << endl; #endif */ vector<Ref<GenericGFPoly> > result(2); result[0] = sigma; result[1] = omega; return result; } ArrayRef<int> ReedSolomonDecoder::findErrorLocations(Ref<GenericGFPoly> errorLocator) { // This is a direct application of Chien's search int numErrors = errorLocator->getDegree(); if (numErrors == 1) { // shortcut ArrayRef<int> result(new Array<int>(1)); result[0] = errorLocator->getCoefficient(1); return result; } ArrayRef<int> result(new Array<int>(numErrors)); int e = 0; for (int i = 1; i < field->getSize() && e < numErrors; i++) { // cout << "errorLocator(" << i << ") == " << errorLocator->evaluateAt(i) << endl; if (errorLocator->evaluateAt(i) == 0) { result[e] = field->inverse(i); e++; } } if (e != numErrors) { throw ReedSolomonException("Error locator degree does not match number of roots"); } return result; } ArrayRef<int> ReedSolomonDecoder::findErrorMagnitudes(Ref<GenericGFPoly> errorEvaluator, ArrayRef<int> errorLocations, bool dataMatrix) { // This is directly applying Forney's Formula int s = errorLocations.size(); ArrayRef<int> result(new Array<int>(s)); for (int i = 0; i < s; i++) { int xiInverse = field->inverse(errorLocations[i]); int denominator = 1; for (int j = 0; j < s; j++) { if (i != j) { denominator = field->multiply(denominator, GenericGF::addOrSubtract(1, field->multiply(errorLocations[j], xiInverse))); } } result[i] = field->multiply(errorEvaluator->evaluateAt(xiInverse), field->inverse(denominator)); if (dataMatrix) { result[i] = field->multiply(result[i], xiInverse); } } return result; } } <|endoftext|>
<commit_before>#include <SFML/Graphics.hpp> #include <fstream> #include <iostream> #include <string> #include "Map.h" #pragma once using namespace std; //Loads the map. Map::Map(){ size = 20; int blocks[][20] = { {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,4,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,4,1}, {1,0,1,1,0,1,0,1,1,1,1,1,1,0,1,0,1,1,0,1}, {1,0,1,0,0,0,0,0,0,1,4,0,0,0,0,0,0,1,0,1}, {1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1}, {1,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1}, {1,0,1,0,1,1,0,1,1,1,1,1,1,0,1,1,0,1,0,1}, {1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1}, {1,0,1,1,0,1,1,1,1,2,2,1,1,1,1,0,1,1,0,1}, {1,0,0,0,0,1,2,2,3,2,2,3,2,2,1,0,0,0,0,1}, {1,0,0,0,0,1,2,2,2,3,3,2,2,2,1,0,0,0,0,1}, {1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1}, {1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1}, {1,0,1,0,1,1,0,1,1,5,1,1,1,0,1,1,0,1,0,1}, {1,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1}, {1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1}, {1,0,1,0,0,0,0,0,0,4,1,0,0,0,0,0,0,1,0,1}, {1,0,1,1,0,1,0,1,1,1,1,1,1,0,1,0,1,1,0,1}, {1,4,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,4,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1} }; for(int i = 0; i < size; i++){ for(int j = 0; j < size; j++){ mapBlocks[i][j] = blocks[i][j]; sf::RectangleShape b; b.setSize(sf::Vector2f(30,30)); //TODO: TILE_WIDTH b.setPosition((float)(i*30),(float)(j*30)); //TODO: TILE_WIDTH if (mapBlocks[i][j]) { b.setFillColor(sf::Color::Blue); } else { b.setFillColor(sf::Color::Black); } mapShapes[i][j] = b; } } } /* * Get that memory back!! */ Map::~Map(){ delete(mapBlocks); delete(mapShapes); } /* * Returns an id for the given block. * 0 = Free space with food item * 1 = wall * 2 = Free space * 3 = Ghost * 4 = Powerup * 5 = Pacman */ int Map::getBlock(int x, int y){ return mapBlocks[x][y]; } /* * Returns the maps length in blocks. */ int Map::mapSize(){ return size; } /* * Returns the shape for the given block */ sf::RectangleShape Map::getShape(int x, int y){ return mapShapes[x][y]; } <commit_msg>Changed x and y axes for the map<commit_after>#include <SFML/Graphics.hpp> #include <fstream> #include <iostream> #include <string> #include "Map.h" #pragma once using namespace std; //Loads the map. Map::Map(){ size = 20; int blocks[][20] = { {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,4,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,4,1}, {1,0,1,1,0,1,0,1,1,1,1,1,1,0,1,0,1,1,0,1}, {1,0,1,0,0,0,0,0,0,1,4,0,0,0,0,0,0,1,0,1}, {1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1}, {1,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1}, {1,0,1,0,1,1,0,1,1,1,1,1,1,0,1,1,0,1,0,1}, {1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1}, {1,0,1,1,0,1,1,1,1,2,2,1,1,1,1,0,1,1,0,1}, {1,0,0,0,0,1,2,2,3,2,2,3,2,2,1,0,0,0,0,1}, {1,0,0,0,0,1,2,2,2,3,3,2,2,2,1,0,0,0,0,1}, {1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1}, {1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1}, {1,0,1,0,1,1,0,1,1,5,1,1,1,0,1,1,0,1,0,1}, {1,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1}, {1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1}, {1,0,1,0,0,0,0,0,0,4,1,0,0,0,0,0,0,1,0,1}, {1,0,1,1,0,1,0,1,1,1,1,1,1,0,1,0,1,1,0,1}, {1,4,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,4,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1} }; for(int i = 0; i < size; i++){ for(int j = 0; j < size; j++){ mapBlocks[i][j] = blocks[j][i]; sf::RectangleShape b; b.setSize(sf::Vector2f(30,30)); //TODO: TILE_WIDTH b.setPosition((float)(i*30),(float)(j*30)); //TODO: TILE_WIDTH if (mapBlocks[i][j]) { b.setFillColor(sf::Color::Blue); } else { b.setFillColor(sf::Color::Black); } mapShapes[i][j] = b; } } } /* * Get that memory back!! */ Map::~Map(){ delete(mapBlocks); delete(mapShapes); } /* * Returns an id for the given block. * 0 = Free space with food item * 1 = wall * 2 = Free space * 3 = Ghost * 4 = Powerup * 5 = Pacman */ int Map::getBlock(int x, int y){ return mapBlocks[x][y]; } /* * Returns the maps length in blocks. */ int Map::mapSize(){ return size; } /* * Returns the shape for the given block */ sf::RectangleShape Map::getShape(int x, int y){ return mapShapes[x][y]; } <|endoftext|>
<commit_before>/*********************************************************************** created: Sat Jul 19 2014 author: Timotei Dolean <timotei21@gmail.com> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/widgets/ListWidget.h" namespace CEGUI { //----------------------------------------------------------------------------// ListWidgetItem& indexToWidgetItem(const ModelIndex& index) { return *(static_cast<ListWidgetItem*>(index.d_modelData)); } //----------------------------------------------------------------------------// const String ListWidget::EventNamespace("ListWidget"); const String ListWidget::WidgetTypeName("CEGUI/ListWidget"); //----------------------------------------------------------------------------// ListWidget::ListWidget(const String& type, const String& name) : ListView(type, name) { } //----------------------------------------------------------------------------// ListWidget::~ListWidget() { } //----------------------------------------------------------------------------// ListWidgetItem::ListWidgetItem() { } //----------------------------------------------------------------------------// ListWidgetItem::~ListWidgetItem() { } //----------------------------------------------------------------------------// bool ListWidgetItem::operator==(const ListWidgetItem& other) const { return getText() == other.getText(); } //----------------------------------------------------------------------------// bool ListWidgetItem::operator<(const ListWidgetItem& other) const { return getText() < other.getText(); } //----------------------------------------------------------------------------// bool ListWidget::isValidIndex(const ModelIndex& model_index) const { return model_index.d_modelData != 0 && getChildId(model_index) != -1; } //----------------------------------------------------------------------------// ModelIndex ListWidget::makeIndex(size_t child, const ModelIndex& parent_index) { if (child >= d_widgetItems.size()) return ModelIndex(); return ModelIndex(&d_widgetItems[child]); } //----------------------------------------------------------------------------// bool ListWidget::areIndicesEqual(const ModelIndex& index1, const ModelIndex& index2) const { return compareIndices(index1, index2) == 0; } //----------------------------------------------------------------------------// int ListWidget::compareIndices(const ModelIndex& index1, const ModelIndex& index2) const { if (!isValidIndex(index1) || !isValidIndex(index2)) return false; return indexToWidgetItem(index1) < indexToWidgetItem(index2); } //----------------------------------------------------------------------------// ModelIndex ListWidget::getParentIndex(const ModelIndex& model_index) const { return getRootIndex(); } //----------------------------------------------------------------------------// int ListWidget::getChildId(const ModelIndex& model_index) const { std::vector<ListWidgetItem>::const_iterator itor = std::find(d_widgetItems.begin(), d_widgetItems.end(), indexToWidgetItem(model_index)); if (itor == d_widgetItems.end()) return -1; return std::distance(d_widgetItems.begin(), itor); } //----------------------------------------------------------------------------// ModelIndex ListWidget::getRootIndex() const { return ModelIndex(); } //----------------------------------------------------------------------------// size_t ListWidget::getChildCount(const ModelIndex& model_index) const { return d_widgetItems.size(); } //----------------------------------------------------------------------------// String ListWidget::getData(const ModelIndex& model_index, ItemDataRole role /*= IDR_Text*/) { if (!isValidIndex(model_index)) return ""; return indexToWidgetItem(model_index).getText(); } //----------------------------------------------------------------------------// void ListWidget::addItem(String text) { ListWidgetItem item; item.setText(text); addItem(item); } //----------------------------------------------------------------------------// void ListWidget::addItem(const ListWidgetItem& item) { d_widgetItems.push_back(item); notifyChildrenAdded(getRootIndex(), d_widgetItems.size() - 1, 1); } //----------------------------------------------------------------------------// void ListWidget::initialiseComponents() { ListView::initialiseComponents(); setModel(this); } } <commit_msg>Properly implement 'compareIndices' for ListWidget<commit_after>/*********************************************************************** created: Sat Jul 19 2014 author: Timotei Dolean <timotei21@gmail.com> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/widgets/ListWidget.h" namespace CEGUI { //----------------------------------------------------------------------------// ListWidgetItem& indexToWidgetItem(const ModelIndex& index) { return *(static_cast<ListWidgetItem*>(index.d_modelData)); } //----------------------------------------------------------------------------// const String ListWidget::EventNamespace("ListWidget"); const String ListWidget::WidgetTypeName("CEGUI/ListWidget"); //----------------------------------------------------------------------------// ListWidget::ListWidget(const String& type, const String& name) : ListView(type, name) { } //----------------------------------------------------------------------------// ListWidget::~ListWidget() { } //----------------------------------------------------------------------------// ListWidgetItem::ListWidgetItem() { } //----------------------------------------------------------------------------// ListWidgetItem::~ListWidgetItem() { } //----------------------------------------------------------------------------// bool ListWidgetItem::operator==(const ListWidgetItem& other) const { return getText() == other.getText(); } //----------------------------------------------------------------------------// bool ListWidgetItem::operator<(const ListWidgetItem& other) const { return getText() < other.getText(); } //----------------------------------------------------------------------------// bool ListWidget::isValidIndex(const ModelIndex& model_index) const { return model_index.d_modelData != 0 && getChildId(model_index) != -1; } //----------------------------------------------------------------------------// ModelIndex ListWidget::makeIndex(size_t child, const ModelIndex& parent_index) { if (child >= d_widgetItems.size()) return ModelIndex(); return ModelIndex(&d_widgetItems[child]); } //----------------------------------------------------------------------------// bool ListWidget::areIndicesEqual(const ModelIndex& index1, const ModelIndex& index2) const { return compareIndices(index1, index2) == 0; } //----------------------------------------------------------------------------// int ListWidget::compareIndices(const ModelIndex& index1, const ModelIndex& index2) const { if (!isValidIndex(index1) || !isValidIndex(index2)) return false; if (indexToWidgetItem(index1) < indexToWidgetItem(index2)) return -1; return indexToWidgetItem(index1) == indexToWidgetItem(index2) ? 0 : 1; } //----------------------------------------------------------------------------// ModelIndex ListWidget::getParentIndex(const ModelIndex& model_index) const { return getRootIndex(); } //----------------------------------------------------------------------------// int ListWidget::getChildId(const ModelIndex& model_index) const { std::vector<ListWidgetItem>::const_iterator itor = std::find(d_widgetItems.begin(), d_widgetItems.end(), indexToWidgetItem(model_index)); if (itor == d_widgetItems.end()) return -1; return std::distance(d_widgetItems.begin(), itor); } //----------------------------------------------------------------------------// ModelIndex ListWidget::getRootIndex() const { return ModelIndex(); } //----------------------------------------------------------------------------// size_t ListWidget::getChildCount(const ModelIndex& model_index) const { return d_widgetItems.size(); } //----------------------------------------------------------------------------// String ListWidget::getData(const ModelIndex& model_index, ItemDataRole role /*= IDR_Text*/) { if (!isValidIndex(model_index)) return ""; return indexToWidgetItem(model_index).getText(); } //----------------------------------------------------------------------------// void ListWidget::addItem(String text) { ListWidgetItem item; item.setText(text); addItem(item); } //----------------------------------------------------------------------------// void ListWidget::addItem(const ListWidgetItem& item) { d_widgetItems.push_back(item); notifyChildrenAdded(getRootIndex(), d_widgetItems.size() - 1, 1); } //----------------------------------------------------------------------------// void ListWidget::initialiseComponents() { ListView::initialiseComponents(); setModel(this); } } <|endoftext|>
<commit_before>/** * PWM.hpp * * This header file contains the function definitions for the PWM class in * libbbbpwm. This class encapsulates the fileops needed to activate the PWM * interface on the BeagleBone Black running the 3.8 kernel. * * Copyright (C) 2014 Nathan Hui <ntlhui@gmail.com> (408.838.5393) * * 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 deistributed 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 */ namespace PWM{ class PWM{ public: PWM(const uint8_t header, const uint8_t pin, const uint32_t frequency); ~PWM(); int setDuty(const float dutyPercentage); int setPeriod(const uint32_t period); int setPolarity(const bool polarity); int setOnTime(const uint32_t onTime); } } <commit_msg>Fixed spelling error in license section in top doc comment<commit_after>/** * PWM.hpp * * This header file contains the function definitions for the PWM class in * libbbbpwm. This class encapsulates the fileops needed to activate the PWM * interface on the BeagleBone Black running the 3.8 kernel. * * Copyright (C) 2014 Nathan Hui <ntlhui@gmail.com> (408.838.5393) * * 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 */ namespace PWM{ class PWM{ public: PWM(const uint8_t header, const uint8_t pin, const uint32_t frequency); ~PWM(); int setDuty(const float dutyPercentage); int setPeriod(const uint32_t period); int setPolarity(const bool polarity); int setOnTime(const uint32_t onTime); } } <|endoftext|>
<commit_before>//-------------------------------------------------------------------------- // // QUESO - a library to support the Quantification of Uncertainty // for Estimation, Simulation and Optimization // // Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- #include <queso/InfiniteDimensionalMCMCSamplerOptions.h> // ODV = option default value #define UQ_INF_DATA_OUTPUT_DIR_NAME_ODV "chain" #define UQ_INF_DATA_OUTPUT_FILE_NAME_ODV "out.h5" #define UQ_INF_NUM_ITERS_ODV 1000 #define UQ_INF_SAVE_FREQ_ODV 1 #define UQ_INF_RWMH_STEP_ODV 1e-2 namespace QUESO { InfiniteDimensionalMCMCSamplerOptions::InfiniteDimensionalMCMCSamplerOptions( const BaseEnvironment& env, const char * prefix) : BaseInputOptions(&env), m_prefix((std::string)(prefix) + "infmcmc_"), m_env(env), m_option_help(m_prefix + "help"), m_option_dataOutputDirName(m_prefix + "dataOutputDirName"), m_option_dataOutputFileName(m_prefix + "dataOutputFileName"), m_option_num_iters(m_prefix + "num_iters"), m_option_save_freq(m_prefix + "save_freq"), m_option_rwmh_step(m_prefix + "rwmh_step") { UQ_FATAL_TEST_MACRO(m_env.optionsInputFileName() == "", m_env.worldRank(), "InfiniteDimensionalMCMCSamplerOptions::constructor(1)", "this constructor is incompatible with the abscense of an options input file"); } InfiniteDimensionalMCMCSamplerOptions::~InfiniteDimensionalMCMCSamplerOptions() { } void InfiniteDimensionalMCMCSamplerOptions::defineOptions() { (*m_optionsDescription).add_options() (m_option_help.c_str(), "produce help message for infinite dimensional sampler") (m_option_dataOutputDirName.c_str(), po::value<std::string>()->default_value(UQ_INF_DATA_OUTPUT_DIR_NAME_ODV), "name of data output dir") (m_option_dataOutputFileName.c_str(), po::value<std::string>()->default_value(UQ_INF_DATA_OUTPUT_FILE_NAME_ODV), "name of data output file (HDF5)") (m_option_num_iters.c_str(), po::value<int>()->default_value(UQ_INF_NUM_ITERS_ODV), "number of mcmc iterations to do") (m_option_save_freq.c_str(), po::value<int>()->default_value(UQ_INF_SAVE_FREQ_ODV), "the frequency at which to save the chain state") (m_option_rwmh_step.c_str(), po::value<double>()->default_value(UQ_INF_RWMH_STEP_ODV), "the step-size in the random-walk Metropolis proposal"); return; } void InfiniteDimensionalMCMCSamplerOptions::getOptionValues() { if (m_env.allOptionsMap().count(m_option_help)) { if (m_env.subDisplayFile()) { *m_env.subDisplayFile() << (*m_optionsDescription) << std::endl; } } if (m_env.allOptionsMap().count(m_option_dataOutputDirName)) { this->m_dataOutputDirName = ((const po::variable_value&) m_env.allOptionsMap()[m_option_dataOutputDirName]).as<std::string>(); } if (m_env.allOptionsMap().count(m_option_dataOutputFileName)) { this->m_dataOutputFileName = ((const po::variable_value&) m_env.allOptionsMap()[m_option_dataOutputFileName]).as<std::string>(); } if (m_env.allOptionsMap().count(m_option_num_iters)) { this->m_num_iters = ((const po::variable_value&) m_env.allOptionsMap()[m_option_num_iters]).as<int>(); } if (m_env.allOptionsMap().count(m_option_save_freq)) { this->m_save_freq = ((const po::variable_value&) m_env.allOptionsMap()[m_option_save_freq]).as<int>(); } if (m_env.allOptionsMap().count(m_option_rwmh_step)) { this->m_rwmh_step = ((const po::variable_value&) m_env.allOptionsMap()[m_option_rwmh_step]).as<double>(); } return; } void InfiniteDimensionalMCMCSamplerOptions::print(std::ostream & os) const { os << "\n" << this->m_option_dataOutputDirName << " = " << this->m_dataOutputDirName; os << "\n" << this->m_option_dataOutputFileName << " = " << this->m_dataOutputFileName; os << "\n" << this->m_option_num_iters << " = " << this->m_num_iters; os << "\n" << this->m_option_save_freq << " = " << this->m_save_freq; os << "\n" << this->m_option_rwmh_step << " = " << this->m_rwmh_step; os << std::endl; return; } std::ostream & operator<<(std::ostream & os, const InfiniteDimensionalMCMCSamplerOptions & obj) { obj.print(os); return os; } const BaseEnvironment& InfiniteDimensionalMCMCSamplerOptions::env() const { return this->m_env; } } // End namespace QUESO <commit_msg>Add defaults for options<commit_after>//-------------------------------------------------------------------------- // // QUESO - a library to support the Quantification of Uncertainty // for Estimation, Simulation and Optimization // // Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- #include <queso/InfiniteDimensionalMCMCSamplerOptions.h> // ODV = option default value #define UQ_INF_DATA_OUTPUT_DIR_NAME_ODV "chain" #define UQ_INF_DATA_OUTPUT_FILE_NAME_ODV "out.h5" #define UQ_INF_NUM_ITERS_ODV 1000 #define UQ_INF_SAVE_FREQ_ODV 1 #define UQ_INF_RWMH_STEP_ODV 1e-2 namespace QUESO { InfiniteDimensionalMCMCSamplerOptions::InfiniteDimensionalMCMCSamplerOptions( const BaseEnvironment& env, const char * prefix) : BaseInputOptions(&env), m_prefix((std::string)(prefix) + "infmcmc_"), m_dataOutputDirName(UQ_INF_DATA_OUTPUT_DIR_NAME_ODV), m_dataOutputFileName(UQ_INF_DATA_OUTPUT_FILE_NAME_ODV), m_num_iters(UQ_INF_NUM_ITERS_ODV), m_save_freq(UQ_INF_SAVE_FREQ_ODV), m_rwmh_step(UQ_INF_RWMH_STEP_ODV), m_env(env), m_option_help(m_prefix + "help"), m_option_dataOutputDirName(m_prefix + "dataOutputDirName"), m_option_dataOutputFileName(m_prefix + "dataOutputFileName"), m_option_num_iters(m_prefix + "num_iters"), m_option_save_freq(m_prefix + "save_freq"), m_option_rwmh_step(m_prefix + "rwmh_step") { UQ_FATAL_TEST_MACRO(m_env.optionsInputFileName() == "", m_env.worldRank(), "InfiniteDimensionalMCMCSamplerOptions::constructor(1)", "this constructor is incompatible with the abscense of an options input file"); } InfiniteDimensionalMCMCSamplerOptions::~InfiniteDimensionalMCMCSamplerOptions() { } void InfiniteDimensionalMCMCSamplerOptions::defineOptions() { (*m_optionsDescription).add_options() (m_option_help.c_str(), "produce help message for infinite dimensional sampler") (m_option_dataOutputDirName.c_str(), po::value<std::string>()->default_value(UQ_INF_DATA_OUTPUT_DIR_NAME_ODV), "name of data output dir") (m_option_dataOutputFileName.c_str(), po::value<std::string>()->default_value(UQ_INF_DATA_OUTPUT_FILE_NAME_ODV), "name of data output file (HDF5)") (m_option_num_iters.c_str(), po::value<int>()->default_value(UQ_INF_NUM_ITERS_ODV), "number of mcmc iterations to do") (m_option_save_freq.c_str(), po::value<int>()->default_value(UQ_INF_SAVE_FREQ_ODV), "the frequency at which to save the chain state") (m_option_rwmh_step.c_str(), po::value<double>()->default_value(UQ_INF_RWMH_STEP_ODV), "the step-size in the random-walk Metropolis proposal"); } void InfiniteDimensionalMCMCSamplerOptions::getOptionValues() { if (m_env.allOptionsMap().count(m_option_help)) { if (m_env.subDisplayFile()) { *m_env.subDisplayFile() << (*m_optionsDescription) << std::endl; } } if (m_env.allOptionsMap().count(m_option_dataOutputDirName)) { this->m_dataOutputDirName = ((const po::variable_value&) m_env.allOptionsMap()[m_option_dataOutputDirName]).as<std::string>(); } if (m_env.allOptionsMap().count(m_option_dataOutputFileName)) { this->m_dataOutputFileName = ((const po::variable_value&) m_env.allOptionsMap()[m_option_dataOutputFileName]).as<std::string>(); } if (m_env.allOptionsMap().count(m_option_num_iters)) { this->m_num_iters = ((const po::variable_value&) m_env.allOptionsMap()[m_option_num_iters]).as<int>(); } if (m_env.allOptionsMap().count(m_option_save_freq)) { this->m_save_freq = ((const po::variable_value&) m_env.allOptionsMap()[m_option_save_freq]).as<int>(); } if (m_env.allOptionsMap().count(m_option_rwmh_step)) { this->m_rwmh_step = ((const po::variable_value&) m_env.allOptionsMap()[m_option_rwmh_step]).as<double>(); } return; } void InfiniteDimensionalMCMCSamplerOptions::print(std::ostream & os) const { os << "\n" << this->m_option_dataOutputDirName << " = " << this->m_dataOutputDirName; os << "\n" << this->m_option_dataOutputFileName << " = " << this->m_dataOutputFileName; os << "\n" << this->m_option_num_iters << " = " << this->m_num_iters; os << "\n" << this->m_option_save_freq << " = " << this->m_save_freq; os << "\n" << this->m_option_rwmh_step << " = " << this->m_rwmh_step; os << std::endl; return; } std::ostream & operator<<(std::ostream & os, const InfiniteDimensionalMCMCSamplerOptions & obj) { obj.print(os); return os; } const BaseEnvironment& InfiniteDimensionalMCMCSamplerOptions::env() const { return this->m_env; } } // End namespace QUESO <|endoftext|>
<commit_before>/* * $Id$ * * Copyright(C) 1998-2004 Satoshi Nakamura * All rights reserved. * */ #include <qsencoder.h> #include <qsstl.h> #include <qstextutil.h> using namespace qs; /**************************************************************************** * * TextUtil * */ wxstring_ptr qs::TextUtil::fold(const WCHAR* pwszText, size_t nLen, size_t nLineWidth, const WCHAR* pwszQuote, size_t nQuoteLen, size_t nTabWidth) { assert(pwszText); if (nLen == -1) nLen = wcslen(pwszText); size_t nQuoteWidth = 0; for (size_t n = 0; n < nQuoteLen; ++n) nQuoteWidth += isHalfWidth(*(pwszQuote + n)) ? 1 : 2; if (nLineWidth > nQuoteWidth) { nLineWidth -= nQuoteWidth; if (nLineWidth < 10) nLineWidth = 10; } else { nLineWidth = 10; } XStringBuffer<WXSTRING> buf; size_t nCurrentLen = 0; const WCHAR* pLine = pwszText; const WCHAR* pBreak = 0; const WCHAR* p = pwszText; while (p < pwszText + nLen) { WCHAR c = *p; size_t nCharLen = 1; if (c == L'\t') nCharLen = nTabWidth - nCurrentLen%nTabWidth; else if (!isHalfWidth(c)) nCharLen = 2; if (p != pLine && (isBreakSelf(c) || isBreakBefore(c))) pBreak = p; bool bFlushed = true; if (c == L'\n') { if (!buf.append(pwszQuote, nQuoteLen) || !buf.append(pLine, p - pLine + 1)) return 0; nCurrentLen = 0; pLine = p + 1; pBreak = 0; } else if (nCurrentLen + nCharLen > nLineWidth) { if (!pBreak) { if (pwszQuote) { if (!buf.append(pwszQuote, nQuoteLen)) return 0; } if (!buf.append(pLine, p - pLine) || !buf.append(L'\n')) return 0; nCurrentLen = nCharLen; pLine = p; } else { WCHAR cBreak = *pBreak; const WCHAR* pEnd = pBreak; const WCHAR* pNext = pBreak; if (isBreakSelf(cBreak)) { ++pNext; } else if (isBreakAfter(cBreak) && (pBreak != p || nCurrentLen + nCharLen <= nLineWidth)) { ++pEnd; ++pNext; } else if (isBreakBefore(cBreak)) { ; } else { assert(false); } if (pwszQuote) { if (!buf.append(pwszQuote, nQuoteLen)) return 0; } if (!buf.append(pLine, pEnd - pLine) || !buf.append(L'\n')) return 0; pLine = pNext; nCurrentLen = 0; pBreak = 0; p = pNext - 1; } } else { nCurrentLen += nCharLen; bFlushed = false; } if (!bFlushed && isBreakChar(c) && p != pLine) pBreak = p; ++p; } if (p != pLine) { if (pwszQuote) { if (!buf.append(pwszQuote, nQuoteLen)) return 0; } if (!buf.append(pLine, p - pLine)) return 0; } return buf.getXString(); } std::pair<size_t, size_t> qs::TextUtil::findURL(const WCHAR* pwszText, size_t nLen, const WCHAR* const* ppwszSchemas, size_t nSchemaCount) { assert(pwszText); std::pair<size_t, size_t> url(-1, 0); if (nSchemaCount != 0) { const WCHAR* p = pwszText; while (nLen > 0) { if (p == pwszText || !isURLChar(*(p - 1))) { bool bFound = false; for (size_t n = 0; n < nSchemaCount; ++n) { if (ppwszSchemas[n][0] == *p) { size_t nSchemaLen = wcslen(ppwszSchemas[n]); if (nLen > nSchemaLen && wcsncmp(p, ppwszSchemas[n], nSchemaLen) == 0 && *(p + nSchemaLen) == L':') { bFound = true; break; } } } if (bFound) break; } else if (*p == L'@' && p != pwszText && isURLChar(*(p - 1)) && nLen > 1 && isURLChar(*(p + 1))) { while (p >= pwszText && isURLChar(*p)) { --p; ++nLen; } ++p; --nLen; break; } --nLen; ++p; } if (nLen > 0) { url.first = p - pwszText; while (nLen > 0 && isURLChar(*p)) { --nLen; ++p; } url.second = p - (pwszText + url.first); } } return url; } bool qs::TextUtil::isURLChar(WCHAR c) { return (L'A' <= c && c <= L'Z') || (L'a' <= c && c <= L'z') || (L'0' <= c && c <= L'9') || c == L'.' || c == L':' || c == L'/' || c == L'?' || c == L'%' || c == L'&' || c == L'@' || c == L'!' || c == L'#' || c == L'$' || c == L'~' || c == L'*' || c == L'=' || c == L'+' || c == L'-' || c == L'_' || c == L';' || c == L',' || c == L'(' || c == L')'; } wstring_ptr qs::TextUtil::encodePassword(const WCHAR* pwsz) { assert(pwsz); Base64Encoder encoder(false); malloc_size_ptr<unsigned char> encoded(encoder.encode( reinterpret_cast<const unsigned char*>(pwsz), wcslen(pwsz)*sizeof(WCHAR))); if (!encoded.get()) return 0; const unsigned char* p = encoded.get(); wstring_ptr wstr(allocWString(encoded.size()*2 + 1)); WCHAR* pDst = wstr.get(); for (size_t n = 0; n < encoded.size(); ++n) { swprintf(pDst, L"%02x", *(p + n) ^ 'q'); pDst += 2; } *pDst = L'\0'; return wstr; } wstring_ptr qs::TextUtil::decodePassword(const WCHAR* pwsz) { assert(pwsz); size_t nLen = wcslen(pwsz); auto_ptr_array<unsigned char> pBuf(new unsigned char[nLen/2 + 1]); unsigned char* p = pBuf.get(); for (size_t n = 0; n < nLen; n += 2) { WCHAR wsz[3] = L""; wcsncpy(wsz, pwsz + n, 2); unsigned int m = 0; swscanf(wsz, L"%02x", &m); *p++ = m ^= 'q'; } Base64Encoder encoder(false); malloc_size_ptr<unsigned char> decoded( encoder.decode(pBuf.get(), p - pBuf.get())); if (!decoded.get()) return 0; return allocWString(reinterpret_cast<WCHAR*>(decoded.get()), decoded.size()/sizeof(WCHAR)); } <commit_msg>If the end of an URL is . , ; or ), strip it from the URL.<commit_after>/* * $Id$ * * Copyright(C) 1998-2004 Satoshi Nakamura * All rights reserved. * */ #include <qsencoder.h> #include <qsstl.h> #include <qstextutil.h> using namespace qs; /**************************************************************************** * * TextUtil * */ wxstring_ptr qs::TextUtil::fold(const WCHAR* pwszText, size_t nLen, size_t nLineWidth, const WCHAR* pwszQuote, size_t nQuoteLen, size_t nTabWidth) { assert(pwszText); if (nLen == -1) nLen = wcslen(pwszText); size_t nQuoteWidth = 0; for (size_t n = 0; n < nQuoteLen; ++n) nQuoteWidth += isHalfWidth(*(pwszQuote + n)) ? 1 : 2; if (nLineWidth > nQuoteWidth) { nLineWidth -= nQuoteWidth; if (nLineWidth < 10) nLineWidth = 10; } else { nLineWidth = 10; } XStringBuffer<WXSTRING> buf; size_t nCurrentLen = 0; const WCHAR* pLine = pwszText; const WCHAR* pBreak = 0; const WCHAR* p = pwszText; while (p < pwszText + nLen) { WCHAR c = *p; size_t nCharLen = 1; if (c == L'\t') nCharLen = nTabWidth - nCurrentLen%nTabWidth; else if (!isHalfWidth(c)) nCharLen = 2; if (p != pLine && (isBreakSelf(c) || isBreakBefore(c))) pBreak = p; bool bFlushed = true; if (c == L'\n') { if (!buf.append(pwszQuote, nQuoteLen) || !buf.append(pLine, p - pLine + 1)) return 0; nCurrentLen = 0; pLine = p + 1; pBreak = 0; } else if (nCurrentLen + nCharLen > nLineWidth) { if (!pBreak) { if (pwszQuote) { if (!buf.append(pwszQuote, nQuoteLen)) return 0; } if (!buf.append(pLine, p - pLine) || !buf.append(L'\n')) return 0; nCurrentLen = nCharLen; pLine = p; } else { WCHAR cBreak = *pBreak; const WCHAR* pEnd = pBreak; const WCHAR* pNext = pBreak; if (isBreakSelf(cBreak)) { ++pNext; } else if (isBreakAfter(cBreak) && (pBreak != p || nCurrentLen + nCharLen <= nLineWidth)) { ++pEnd; ++pNext; } else if (isBreakBefore(cBreak)) { ; } else { assert(false); } if (pwszQuote) { if (!buf.append(pwszQuote, nQuoteLen)) return 0; } if (!buf.append(pLine, pEnd - pLine) || !buf.append(L'\n')) return 0; pLine = pNext; nCurrentLen = 0; pBreak = 0; p = pNext - 1; } } else { nCurrentLen += nCharLen; bFlushed = false; } if (!bFlushed && isBreakChar(c) && p != pLine) pBreak = p; ++p; } if (p != pLine) { if (pwszQuote) { if (!buf.append(pwszQuote, nQuoteLen)) return 0; } if (!buf.append(pLine, p - pLine)) return 0; } return buf.getXString(); } std::pair<size_t, size_t> qs::TextUtil::findURL(const WCHAR* pwszText, size_t nLen, const WCHAR* const* ppwszSchemas, size_t nSchemaCount) { assert(pwszText); std::pair<size_t, size_t> url(-1, 0); if (nSchemaCount != 0) { bool bEmail = false; const WCHAR* p = pwszText; while (nLen > 0) { if (p == pwszText || !isURLChar(*(p - 1))) { bool bFound = false; for (size_t n = 0; n < nSchemaCount; ++n) { if (ppwszSchemas[n][0] == *p) { size_t nSchemaLen = wcslen(ppwszSchemas[n]); if (nLen > nSchemaLen && wcsncmp(p, ppwszSchemas[n], nSchemaLen) == 0 && *(p + nSchemaLen) == L':') { bFound = true; break; } } } if (bFound) break; } else if (*p == L'@' && p != pwszText && isURLChar(*(p - 1)) && nLen > 1 && isURLChar(*(p + 1))) { while (p >= pwszText && isURLChar(*p) && *p != L'(') { --p; ++nLen; } ++p; --nLen; bEmail = true; break; } --nLen; ++p; } if (nLen > 0) { url.first = p - pwszText; while (nLen > 0 && isURLChar(*p)) { --nLen; ++p; } if (p != pwszText + url.first) { WCHAR c = *(p - 1); if (c == L'.' || c == L',' || (bEmail && (c == L';' || c == L')'))) --p; } url.second = p - (pwszText + url.first); } } return url; } bool qs::TextUtil::isURLChar(WCHAR c) { return (L'A' <= c && c <= L'Z') || (L'a' <= c && c <= L'z') || (L'0' <= c && c <= L'9') || c == L'.' || c == L':' || c == L'/' || c == L'?' || c == L'%' || c == L'&' || c == L'@' || c == L'!' || c == L'#' || c == L'$' || c == L'~' || c == L'*' || c == L'=' || c == L'+' || c == L'-' || c == L'_' || c == L';' || c == L',' || c == L'(' || c == L')'; } wstring_ptr qs::TextUtil::encodePassword(const WCHAR* pwsz) { assert(pwsz); Base64Encoder encoder(false); malloc_size_ptr<unsigned char> encoded(encoder.encode( reinterpret_cast<const unsigned char*>(pwsz), wcslen(pwsz)*sizeof(WCHAR))); if (!encoded.get()) return 0; const unsigned char* p = encoded.get(); wstring_ptr wstr(allocWString(encoded.size()*2 + 1)); WCHAR* pDst = wstr.get(); for (size_t n = 0; n < encoded.size(); ++n) { swprintf(pDst, L"%02x", *(p + n) ^ 'q'); pDst += 2; } *pDst = L'\0'; return wstr; } wstring_ptr qs::TextUtil::decodePassword(const WCHAR* pwsz) { assert(pwsz); size_t nLen = wcslen(pwsz); auto_ptr_array<unsigned char> pBuf(new unsigned char[nLen/2 + 1]); unsigned char* p = pBuf.get(); for (size_t n = 0; n < nLen; n += 2) { WCHAR wsz[3] = L""; wcsncpy(wsz, pwsz + n, 2); unsigned int m = 0; swscanf(wsz, L"%02x", &m); *p++ = m ^= 'q'; } Base64Encoder encoder(false); malloc_size_ptr<unsigned char> decoded( encoder.decode(pBuf.get(), p - pBuf.get())); if (!decoded.get()) return 0; return allocWString(reinterpret_cast<WCHAR*>(decoded.get()), decoded.size()/sizeof(WCHAR)); } <|endoftext|>
<commit_before>// infoware - C++ System information Library // // Written in 2017 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/> #ifdef __APPLE__ #include "infoware/cpu.hpp" #include "infoware/detail/scope.hpp" #include <cstring> #include <sstream> #include <stdio.h> #include <string> #include <unistd.h> iware::cpu::quantities_t iware::cpu::quantities() { iware::cpu::quantities_t ret{}; ret.logical = sysconf(_SC_NPROCESSORS_ONLN); // TODO rest of fields return ret; } // This is hell // // https://github.com/ThePhD/infoware/issues/12#issuecomment-495782115 // // TODO: couldn't find a good way to get the associativity (default 0) or the type (default unified) iware::cpu::cache_t iware::cpu::cache(unsigned int level) { const auto sysctl_output = popen("sysctl hw", "r"); if(!sysctl_output) return {}; iware::detail::quickscope_wrapper sysctl_closer{[&]() { pclose(sysctl_output); }}; cache_t ret{}; bool full_line = false; std::string line; char buf[32]{}; for(bool have_data = true; have_data;) { have_data = fgets(buf, sizeof(buf), sysctl_output); if(full_line) line = buf; else line += buf; full_line = line.back() == '\n'; if(full_line) { std::size_t* data = nullptr; if(line.find("hw.cachelinesize") == 0) data = &ret.line_size; else if(line.find("hw.l") == 0 && line.find(std::to_string(level)) == 4 && [&]() { const auto idx = line.find("cachesize"); return idx == 5 || // e.g. hw.l2cachesize idx == 6; // e.g. hw.l1icachesize }()) data = &ret.size; if(data) { std::size_t tmp; std::istringstream(line.c_str() + line.find(':') + 1) >> tmp; *data += tmp; } } } return ret; } #endif <commit_msg>Add sysctl-based CPU quantities acquisition for Darwin<commit_after>// infoware - C++ System information Library // // Written in 2017 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/> #ifdef __APPLE__ #include "infoware/cpu.hpp" #include "infoware/detail/scope.hpp" #include <cstdlib> #include <cstring> #include <sstream> #include <stdio.h> #include <string> // https://github.com/ThePhD/infoware/issues/12#issuecomment-495291650 // // Assuming there's only ever gonna be 1 package because the sysctl outputs I've seen so far haven't provided any way to read if there were more? // // Parses `machdep.cpu.cores_per_package` and `machdep.cpu.logical_per_package`. iware::cpu::quantities_t iware::cpu::quantities() { const auto sysctl_output = popen("sysctl machdep.cpu", "r"); if(!sysctl_output) return {}; iware::detail::quickscope_wrapper sysctl_closer{[&]() { pclose(sysctl_output); }}; iware::cpu::quantities_t ret{}; char buf[48]{}; while(fgets(buf, sizeof(buf), sysctl_output)) { const auto len = std::strlen(buf); if(len < 31 + 2 || buf[len - 1] != '\n') continue; // Skipping all lines that don't fit in the buffer because the ones we're after do and the ones shorter than the ones we're after if(std::strncmp(buf + 12, "cores_per_package: ", 29 - 12) == 0) ret.physical = std::strtoul(buf + 29 + 2, nullptr, 10); else if(std::strncmp(buf + 12, "logical_per_package: ", 31 - 12) == 0) ret.logical = std::strtoul(buf + 31 + 2, nullptr, 10); } ret.packages = 1; return ret; } // This is hell // // https://github.com/ThePhD/infoware/issues/12#issuecomment-495782115 // // TODO: couldn't find a good way to get the associativity (default 0) or the type (default unified) iware::cpu::cache_t iware::cpu::cache(unsigned int level) { const auto sysctl_output = popen("sysctl hw", "r"); if(!sysctl_output) return {}; iware::detail::quickscope_wrapper sysctl_closer{[&]() { pclose(sysctl_output); }}; iware::cpu::cache_t ret{}; bool full_line = false; std::string line; char buf[32]{}; while(fgets(buf, sizeof(buf), sysctl_output)) { if(full_line) line = buf; else line += buf; full_line = line.back() == '\n'; if(full_line) { std::size_t* data = nullptr; if(line.find("hw.cachelinesize") == 0) data = &ret.line_size; else if(line.find("hw.l") == 0 && line.find(std::to_string(level)) == 4 && [&]() { const auto idx = line.find("cachesize"); return idx == 5 || // e.g. hw.l2cachesize idx == 6; // e.g. hw.l1icachesize }()) data = &ret.size; if(data) { std::size_t tmp; std::istringstream(line.c_str() + line.find(':') + 1) >> tmp; *data += tmp; } } } return ret; } #endif <|endoftext|>
<commit_before>/* * SessionFilesListingMonitor.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionFilesListingMonitor.hpp" #include <algorithm> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <core/Error.hpp> #include <core/Log.hpp> #include <core/FileInfo.hpp> #include <core/FilePath.hpp> #include <core/json/JsonRpc.hpp> #include <core/system/FileMonitor.hpp> #include <core/system/FileChangeEvent.hpp> #include <session/SessionModuleContext.hpp> #include "SessionVCS.hpp" using namespace core ; namespace session { namespace modules { namespace files { Error FilesListingMonitor::start(const FilePath& filePath, json::Array* pJsonFiles) { // always stop existing stop(); // scan the directory (populates pJsonFiles out parameter) std::vector<FilePath> files; Error error = listFiles(filePath, &files, pJsonFiles); if (error) return error; // copy the file listing into a vector of FileInfo which we will order so that it can // be compared with the initial scan of the file montor for changes std::vector<FileInfo> prevFiles; std::transform(files.begin(), files.end(), std::back_inserter(prevFiles), core::toFileInfo); // kickoff new monitor core::system::file_monitor::Callbacks cb; cb.onRegistered = boost::bind(&FilesListingMonitor::onRegistered, this, _1, filePath, prevFiles, _2); cb.onRegistrationError = boost::bind(core::log::logError, _1, ERROR_LOCATION); cb.onFilesChanged = boost::bind(module_context::enqueFileChangedEvents, filePath, _1); cb.onMonitoringError = boost::bind(core::log::logError, _1, ERROR_LOCATION); cb.onUnregistered = boost::bind(&FilesListingMonitor::onUnregistered, this, _1); core::system::file_monitor::registerMonitor(filePath, false, module_context::fileListingFilter, cb); return Success(); } void FilesListingMonitor::stop() { // reset monitored path and unregister any existing handle currentPath_ = FilePath(); if (!currentHandle_.empty()) { core::system::file_monitor::unregisterMonitor(currentHandle_); currentHandle_ = core::system::file_monitor::Handle(); } } const FilePath& FilesListingMonitor::currentMonitoredPath() const { return currentPath_; } void FilesListingMonitor::onRegistered(core::system::file_monitor::Handle handle, const FilePath& filePath, const std::vector<FileInfo>& prevFiles, const tree<core::FileInfo>& files) { // set path and current handle currentPath_ = filePath; currentHandle_ = handle; // compare the previously returned listing with the initial scan to see if any // file changes occurred between listings std::vector<core::system::FileChangeEvent> events; core::system::collectFileChangeEvents(prevFiles.begin(), prevFiles.end(), files.begin(files.begin()), files.end(files.begin()), module_context::fileListingFilter, &events); // enque any events we discovered if (!events.empty()) module_context::enqueFileChangedEvents(filePath, events); } void FilesListingMonitor::onUnregistered(core::system::file_monitor::Handle handle) { // typically we clear our internal state explicitly when a new registration // comes in. however, it is possible that our monitor could be unregistered // as a result of an error which occurs during monitoring. in this case // we clear our state explicitly here as well if (currentHandle_ == handle) { currentPath_ = FilePath(); currentHandle_ = core::system::file_monitor::Handle(); } } Error FilesListingMonitor::listFiles(const FilePath& rootPath, std::vector<FilePath>* pFiles, json::Array* pJsonFiles) { // enumerate the files pFiles->clear(); core::Error error = rootPath.children(pFiles) ; if (error) return error; using namespace source_control; boost::shared_ptr<FileDecorationContext> pCtx = source_control::fileDecorationContext(rootPath); // sort the files by name std::sort(pFiles->begin(), pFiles->end(), core::compareAbsolutePathNoCase); // produce json listing BOOST_FOREACH( core::FilePath& filePath, *pFiles) { // files which may have been deleted after the listing or which // are not end-user visible if (filePath.exists() && module_context::fileListingFilter(core::FileInfo(filePath))) { core::json::Object fileObject = module_context::createFileSystemItem(filePath); pCtx->decorateFile(filePath, &fileObject); pJsonFiles->push_back(fileObject) ; } } return Success(); } } // namepsace files } // namespace modules } // namesapce session <commit_msg>ensure that spurious file removed/added events aren't generated for symlinks<commit_after>/* * SessionFilesListingMonitor.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionFilesListingMonitor.hpp" #include <algorithm> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <core/Error.hpp> #include <core/Log.hpp> #include <core/FileInfo.hpp> #include <core/FilePath.hpp> #include <core/json/JsonRpc.hpp> #include <core/system/FileMonitor.hpp> #include <core/system/FileChangeEvent.hpp> #include <session/SessionModuleContext.hpp> #include "SessionVCS.hpp" using namespace core ; namespace session { namespace modules { namespace files { Error FilesListingMonitor::start(const FilePath& filePath, json::Array* pJsonFiles) { // always stop existing stop(); // scan the directory (populates pJsonFiles out parameter) std::vector<FilePath> files; Error error = listFiles(filePath, &files, pJsonFiles); if (error) return error; // copy the file listing into a vector of FileInfo which we will order so that it can // be compared with the initial scan of the file montor for changes std::vector<FileInfo> prevFiles; std::transform(files.begin(), files.end(), std::back_inserter(prevFiles), core::toFileInfo); // kickoff new monitor core::system::file_monitor::Callbacks cb; cb.onRegistered = boost::bind(&FilesListingMonitor::onRegistered, this, _1, filePath, prevFiles, _2); cb.onRegistrationError = boost::bind(core::log::logError, _1, ERROR_LOCATION); cb.onFilesChanged = boost::bind(module_context::enqueFileChangedEvents, filePath, _1); cb.onMonitoringError = boost::bind(core::log::logError, _1, ERROR_LOCATION); cb.onUnregistered = boost::bind(&FilesListingMonitor::onUnregistered, this, _1); core::system::file_monitor::registerMonitor(filePath, false, module_context::fileListingFilter, cb); return Success(); } void FilesListingMonitor::stop() { // reset monitored path and unregister any existing handle currentPath_ = FilePath(); if (!currentHandle_.empty()) { core::system::file_monitor::unregisterMonitor(currentHandle_); currentHandle_ = core::system::file_monitor::Handle(); } } const FilePath& FilesListingMonitor::currentMonitoredPath() const { return currentPath_; } namespace { // Convert fileInfo returned from file monitor into a normalized path which // will traverse a symlink if necessary. this addresses the following concern: // // - Our core file listing code calls FilePath::children which traverses // symblinks to list the actual underlying file or directory linked to // // - Our file monitoring code however treats symlinks literally (to avoid // recursive or otherwise very long traversals) // // - The above two behaviors intersect to cause a pair of add/remove events // for symliniks within onRegistered (because the initial snapshot // was taken with FilePath::children and the file monitor enumeration // is taken using core::scanFiles). When propagated to the client this // results in symlinked directories appearing as documents and not // being traversable in the files pane // // - We could fix this by changing the behavior of core::scanFiles and/or // another layer in the file listing / monitoring code however we // are making the fix late in the cycle and therefore want to treat // only the symptom (it's not clear that this isn't the best fix anyway, // but just want to note that other fixes were not considered and // might be superior) // FileInfo normalizeFileScannerPath(const FileInfo& fileInfo) { FilePath filePath(fileInfo.absolutePath()); return FileInfo(filePath); } } // anonymous namespace void FilesListingMonitor::onRegistered(core::system::file_monitor::Handle handle, const FilePath& filePath, const std::vector<FileInfo>& prevFiles, const tree<core::FileInfo>& files) { // set path and current handle currentPath_ = filePath; currentHandle_ = handle; // normalize scanned file paths (see comment above for explanation) std::vector<FileInfo> currFiles; std::transform(files.begin(files.begin()), files.end(files.begin()), std::back_inserter(currFiles), normalizeFileScannerPath); // compare the previously returned listing with the initial scan to see if any // file changes occurred between listings std::vector<core::system::FileChangeEvent> events; core::system::collectFileChangeEvents(prevFiles.begin(), prevFiles.end(), currFiles.begin(), currFiles.end(), module_context::fileListingFilter, &events); // enque any events we discovered if (!events.empty()) module_context::enqueFileChangedEvents(filePath, events); } void FilesListingMonitor::onUnregistered(core::system::file_monitor::Handle handle) { // typically we clear our internal state explicitly when a new registration // comes in. however, it is possible that our monitor could be unregistered // as a result of an error which occurs during monitoring. in this case // we clear our state explicitly here as well if (currentHandle_ == handle) { currentPath_ = FilePath(); currentHandle_ = core::system::file_monitor::Handle(); } } Error FilesListingMonitor::listFiles(const FilePath& rootPath, std::vector<FilePath>* pFiles, json::Array* pJsonFiles) { // enumerate the files pFiles->clear(); core::Error error = rootPath.children(pFiles) ; if (error) return error; using namespace source_control; boost::shared_ptr<FileDecorationContext> pCtx = source_control::fileDecorationContext(rootPath); // sort the files by name std::sort(pFiles->begin(), pFiles->end(), core::compareAbsolutePathNoCase); // produce json listing BOOST_FOREACH( core::FilePath& filePath, *pFiles) { // files which may have been deleted after the listing or which // are not end-user visible if (filePath.exists() && module_context::fileListingFilter(core::FileInfo(filePath))) { core::json::Object fileObject = module_context::createFileSystemItem(filePath); pCtx->decorateFile(filePath, &fileObject); pJsonFiles->push_back(fileObject) ; } } return Success(); } } // namepsace files } // namespace modules } // namesapce session <|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 "src/core/uuid4.h" #include <ctime> #include <random> #include <sstream> namespace falken { namespace core { namespace { // UUIDGens are seeded by system time. In case system time-resolution is too // low there could be collisions when UUIDGens are created close together. We // therefore factor the number of counters into the seed. int rng_counter = 0; } void UUIDGen::GenerateRandomHexNibbles(std::stringstream& out, int number_of_nibbles, int override_mask, int override) { for (int i = 0; i < number_of_nibbles; ++i) { int nibble = ((random_int_(rng_) & 0xF) & ~override_mask); nibble |= (override_mask & override); out << std::hex << nibble; } } // Returns a random UUID v4. // See spec at: // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random) std::string UUIDGen::RandUUID4() { std::stringstream ss; GenerateRandomHexNibbles(ss, 8); ss << "-"; GenerateRandomHexNibbles(ss, 4); ss << "-" << "4"; // 13th digit is always 4. GenerateRandomHexNibbles(ss, 3); ss << "-"; // 17th digit is either 8, 9, a or b GenerateRandomHexNibbles(ss, 1, (1 << 3) | (1 << 2), (1 << 3)); GenerateRandomHexNibbles(ss, 3); ss << "-"; GenerateRandomHexNibbles(ss, 12); return ss.str(); } // Create seed by combining current time, number of rngs, and input str. uint64_t UUIDGen::GetFreshSeed(const std::string& seed_str, uint64_t time) { if (!time) { time = std::time(nullptr); } std::string full_seed_str = ( seed_str + std::to_string(time) + std::to_string(rng_counter++)); std::seed_seq seed_seq(full_seed_str.begin(), full_seed_str.end()); uint64_t seed; seed_seq.generate(&seed, &seed+ 1); return seed; } UUIDGen::UUIDGen(const std::string& seed_helper) : rng_(GetFreshSeed(seed_helper)) {} std::string RandUUID4(const std::string& seed_helper) { return UUIDGen(seed_helper).RandUUID4(); } } // namespace core } // namespace falken <commit_msg>Fix warning in uuid4.cc on Windows platforms<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 "src/core/uuid4.h" #include <array> #include <ctime> #include <random> #include <sstream> namespace falken { namespace core { namespace { // UUIDGens are seeded by system time. In case system time-resolution is too // low there could be collisions when UUIDGens are created close together. We // therefore factor the number of counters into the seed. int rng_counter = 0; } void UUIDGen::GenerateRandomHexNibbles(std::stringstream& out, int number_of_nibbles, int override_mask, int override) { for (int i = 0; i < number_of_nibbles; ++i) { int nibble = ((random_int_(rng_) & 0xF) & ~override_mask); nibble |= (override_mask & override); out << std::hex << nibble; } } // Returns a random UUID v4. // See spec at: // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random) std::string UUIDGen::RandUUID4() { std::stringstream ss; GenerateRandomHexNibbles(ss, 8); ss << "-"; GenerateRandomHexNibbles(ss, 4); ss << "-" << "4"; // 13th digit is always 4. GenerateRandomHexNibbles(ss, 3); ss << "-"; // 17th digit is either 8, 9, a or b GenerateRandomHexNibbles(ss, 1, (1 << 3) | (1 << 2), (1 << 3)); GenerateRandomHexNibbles(ss, 3); ss << "-"; GenerateRandomHexNibbles(ss, 12); return ss.str(); } // Create seed by combining current time, number of rngs, and input str. uint64_t UUIDGen::GetFreshSeed(const std::string& seed_str, uint64_t time) { if (!time) { time = std::time(nullptr); } std::string full_seed_str = ( seed_str + std::to_string(time) + std::to_string(rng_counter++)); std::seed_seq seed_seq(full_seed_str.begin(), full_seed_str.end()); std::array<uint32_t, 2> seed; seed_seq.generate(seed.begin(), seed.end()); return static_cast<uint64_t>(seed[0]) | (static_cast<uint64_t>(seed[1]) << 32); } UUIDGen::UUIDGen(const std::string& seed_helper) : rng_(GetFreshSeed(seed_helper)) {} std::string RandUUID4(const std::string& seed_helper) { return UUIDGen(seed_helper).RandUUID4(); } } // namespace core } // namespace falken <|endoftext|>
<commit_before>/** * baseConvert.cpp * * Author: Patrick Rummage (patrickbrummage@gmail.com) * * Takes a positive number in decimal, binary, hex, or octal form and * converts the number to the other 3 forms. */ #include <iostream> using std::cin; using std::cout; int convertToDecimal(int base); void baseConvert(int number, int base); int findNearestPower(int number, int base); int main(int argc, char *argv[]) { char mode; cout << "Choose input mode. [d]ecimal, [o]ctal, [h]ex, [b]inary: "; mode = cin.get(); cin.ignore(1); //ignore ENTER int decimalNum; switch(mode) { case 'd': //decimal cout << "Enter number: "; cin >> decimalNum; cout << "Binary: "; baseConvert(decimalNum, 2); cout << "Octal: "; baseConvert(decimalNum, 8); cout << "Hexadecimal: "; baseConvert(decimalNum, 16); break; case 'b': //binary decimalNum = convertToDecimal(2); cout << "Decimal: " << decimalNum << "\n"; cout << "Octal: "; baseConvert(decimalNum, 8); cout << "Hexadecimal: "; baseConvert(decimalNum, 16); break; case 'o': //octal decimalNum = convertToDecimal(8); cout << "Decimal: " << decimalNum << "\n"; cout << "Binary: "; baseConvert(decimalNum, 2); cout << "Hexadecimal: "; baseConvert(decimalNum, 16); break; case 'h': //hex decimalNum = convertToDecimal(16); cout << "Decimal: " << decimalNum << "\n"; cout << "Binary: "; baseConvert(decimalNum, 2); cout << "Octal: "; baseConvert(decimalNum, 8); break; } return 0; } int convertToDecimal(int base) { char digit; int decimalNum = 0; cout << "Enter number: "; digit = cin.get(); while (digit != 10) { decimalNum *= base; if (digit >= 'a') //hex lowercase { decimalNum += (digit - 87); } else if (digit >= 'A') //hex uppercase { decimalNum += (digit - 55); } else decimalNum += (digit - '0'); digit = cin.get(); } return decimalNum; } void baseConvert(int number, int base) { int nearestPower = findNearestPower(number, base); int subtract; int nextChar; char outputChar; while (nearestPower >= 1) { subtract = number - nearestPower; if (subtract >= 0) { nextChar = (number / nearestPower) % base; if (nextChar >= 10) //handle hex chars { outputChar = nextChar + 55; } else outputChar = nextChar + '0'; number = subtract; nearestPower /= base; } else { outputChar = '0'; nearestPower /= base; } cout << outputChar; } cout << "\n"; } int findNearestPower(int number, int base) { int power = 1; while (power < number) { power *= base; } if (power > number) { return power / base; } else return power; } <commit_msg>added comments for functions<commit_after>/** * baseConvert.cpp * * Author: Patrick Rummage (patrickbrummage@gmail.com) * * Takes a positive number in decimal, binary, hex, or octal form and * converts the number to the other 3 forms. */ #include <iostream> using std::cin; using std::cout; int convertToDecimal(int base); void baseConvert(int number, int base); int findNearestPower(int number, int base); int main(int argc, char *argv[]) { char mode; cout << "Choose input mode. [d]ecimal, [o]ctal, [h]ex, [b]inary: "; mode = cin.get(); cin.ignore(1); //ignore ENTER int decimalNum; switch(mode) { case 'd': //decimal cout << "Enter number: "; cin >> decimalNum; cout << "Binary: "; baseConvert(decimalNum, 2); cout << "Octal: "; baseConvert(decimalNum, 8); cout << "Hexadecimal: "; baseConvert(decimalNum, 16); break; case 'b': //binary decimalNum = convertToDecimal(2); cout << "Decimal: " << decimalNum << "\n"; cout << "Octal: "; baseConvert(decimalNum, 8); cout << "Hexadecimal: "; baseConvert(decimalNum, 16); break; case 'o': //octal decimalNum = convertToDecimal(8); cout << "Decimal: " << decimalNum << "\n"; cout << "Binary: "; baseConvert(decimalNum, 2); cout << "Hexadecimal: "; baseConvert(decimalNum, 16); break; case 'h': //hex decimalNum = convertToDecimal(16); cout << "Decimal: " << decimalNum << "\n"; cout << "Binary: "; baseConvert(decimalNum, 2); cout << "Octal: "; baseConvert(decimalNum, 8); break; } return 0; } // Takes input in hex, oct, or binary (one char at a time) and returns decimal form int convertToDecimal(int base) { char digit; int decimalNum = 0; cout << "Enter number: "; digit = cin.get(); while (digit != 10) { decimalNum *= base; if (digit >= 'a') //hex lowercase { decimalNum += (digit - 87); } else if (digit >= 'A') //hex uppercase { decimalNum += (digit - 55); } else decimalNum += (digit - '0'); digit = cin.get(); } return decimalNum; } //Takes decimal int and converts to binary, oct, or hex. Prints the result. void baseConvert(int number, int base) { int nearestPower = findNearestPower(number, base); int subtract; int nextChar; char outputChar; while (nearestPower >= 1) { subtract = number - nearestPower; if (subtract >= 0) { nextChar = (number / nearestPower) % base; if (nextChar >= 10) //handle hex chars { outputChar = nextChar + 55; } else outputChar = nextChar + '0'; number = subtract; nearestPower /= base; } else { outputChar = '0'; nearestPower /= base; } cout << outputChar; } cout << "\n"; } /* * Returns the closest multiple of a base below a given number. Needed to print * out the converted number HO first. * EX: * (64, 2) -> 64 * (270, 16) -> 256 */ int findNearestPower(int number, int base) { int power = 1; while (power < number) { power *= base; } if (power > number) { return power / base; } else return power; } <|endoftext|>
<commit_before>// // Created by jannis on 01.09.18. // #include "../../platform.hpp" #ifdef NOVA_LINUX #include "x11_window.hpp" namespace nova { x11_window::x11_window(uint32_t width, uint32_t height) { display = XOpenDisplay(nullptr); if(display == nullptr) { throw window_creation_error("Failed to open XDisplay"); } // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) int screen = DefaultScreen(display); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) window = XCreateSimpleWindow(display, RootWindow(display, screen), 50, 50, width, height, 1, BlackPixel(display, screen), WhitePixel(display, screen)); wm_protocols = XInternAtom(display, "WM_PROTOCOLS", 0); wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", 0); XSetWMProtocols(display, window, &wm_delete_window, 1); XSelectInput(display, window, ExposureMask | ButtonPressMask | KeyPressMask); XMapWindow(display, window); } x11_window::~x11_window() { XUnmapWindow(display, window); XDestroyWindow(display, window); XCloseDisplay(display); } Window &x11_window::get_x11_window() { return window; } Display *x11_window::get_display() { return display; } void x11_window::on_frame_end() { XEvent event; while(XPending(display) != 0) { XNextEvent(display, &event); switch(event.type) { case ClientMessage: { if(event.xclient.message_type == wm_protocols && event.xclient.data.l[0] == static_cast<long>(wm_delete_window)) { should_window_close = true; } break; } default: break; } } } bool x11_window::should_close() const { return should_window_close; } glm::uvec2 x11_window::get_window_size() const { Window root_window; int x_pos; int y_pos; uint32_t width; uint32_t height; uint32_t border_width; uint32_t depth; XGetGeometry(display, window, &root_window, &x_pos, &y_pos, &width, &height, &border_width, &depth); return {width, height}; } } // namespace nova #endif <commit_msg>clang-tidy: cppcoreguidelines-pro-type-cstyle-cast<commit_after>// // Created by jannis on 01.09.18. // #include "../../platform.hpp" #ifdef NOVA_LINUX #include "x11_window.hpp" namespace nova { x11_window::x11_window(uint32_t width, uint32_t height) { display = XOpenDisplay(nullptr); if(display == nullptr) { throw window_creation_error("Failed to open XDisplay"); } // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) int screen = DefaultScreen(display); window = XCreateSimpleWindow(display, RootWindow(display, screen), // NOLINT(cppcoreguidelines-pro-type-cstyle-cast) 50, 50, width, height, 1, BlackPixel(display, screen), // NOLINT(cppcoreguidelines-pro-type-cstyle-cast) WhitePixel(display, screen)); wm_protocols = XInternAtom(display, "WM_PROTOCOLS", 0); wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", 0); XSetWMProtocols(display, window, &wm_delete_window, 1); XSelectInput(display, window, ExposureMask | ButtonPressMask | KeyPressMask); XMapWindow(display, window); } x11_window::~x11_window() { XUnmapWindow(display, window); XDestroyWindow(display, window); XCloseDisplay(display); } Window &x11_window::get_x11_window() { return window; } Display *x11_window::get_display() { return display; } void x11_window::on_frame_end() { XEvent event; while(XPending(display) != 0) { XNextEvent(display, &event); switch(event.type) { case ClientMessage: { if(event.xclient.message_type == wm_protocols && event.xclient.data.l[0] == static_cast<long>(wm_delete_window)) { should_window_close = true; } break; } default: break; } } } bool x11_window::should_close() const { return should_window_close; } glm::uvec2 x11_window::get_window_size() const { Window root_window; int x_pos; int y_pos; uint32_t width; uint32_t height; uint32_t border_width; uint32_t depth; XGetGeometry(display, window, &root_window, &x_pos, &y_pos, &width, &height, &border_width, &depth); return {width, height}; } } // namespace nova #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/trace_processor/dynamic/thread_state_generator.h" #include <memory> #include <set> #include "src/trace_processor/containers/row_map.h" #include "src/trace_processor/types/trace_processor_context.h" namespace perfetto { namespace trace_processor { ThreadStateGenerator::ThreadStateGenerator(TraceProcessorContext* context) : running_string_id_(context->storage->InternString("Running")), runnable_string_id_(context->storage->InternString("R")), context_(context) {} ThreadStateGenerator::~ThreadStateGenerator() = default; util::Status ThreadStateGenerator::ValidateConstraints( const QueryConstraints&) { return util::OkStatus(); } std::unique_ptr<Table> ThreadStateGenerator::ComputeTable( const std::vector<Constraint>&, const std::vector<Order>&) { if (!unsorted_thread_state_table_) { int64_t trace_end_ts = context_->storage->GetTraceTimestampBoundsNs().second; unsorted_thread_state_table_ = ComputeThreadStateTable(trace_end_ts); // We explicitly sort by ts here as ComputeThreadStateTable does not insert // rows in sorted order but we expect our clients to always want to sort // on ts. Writing ComputeThreadStateTable to insert in sorted order is // more trouble than its worth. sorted_thread_state_table_ = unsorted_thread_state_table_->Sort( {unsorted_thread_state_table_->ts().ascending()}); } PERFETTO_CHECK(sorted_thread_state_table_); return std::unique_ptr<Table>(new Table(sorted_thread_state_table_->Copy())); } std::unique_ptr<tables::ThreadStateTable> ThreadStateGenerator::ComputeThreadStateTable(int64_t trace_end_ts) { std::unique_ptr<tables::ThreadStateTable> table(new tables::ThreadStateTable( context_->storage->mutable_string_pool(), nullptr)); const auto& raw_sched = context_->storage->sched_slice_table(); const auto& instants = context_->storage->instant_table(); // In both tables, exclude utid == 0 which represents the idle thread. Table sched = raw_sched.Filter({raw_sched.utid().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); Table waking = instants.Filter( {instants.name().eq("sched_waking"), instants.ref().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); // We prefer to use waking if at all possible and fall back to wakeup if not // available. if (waking.row_count() == 0) { waking = instants.Filter( {instants.name().eq("sched_wakeup"), instants.ref().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); } Table sched_blocked_reason = instants.Filter( {instants.name().eq("sched_blocked_reason"), instants.ref().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); const auto& sched_ts_col = sched.GetTypedColumnByName<int64_t>("ts"); const auto& waking_ts_col = waking.GetTypedColumnByName<int64_t>("ts"); const auto& blocked_ts_col = sched_blocked_reason.GetTypedColumnByName<int64_t>("ts"); uint32_t sched_idx = 0; uint32_t waking_idx = 0; uint32_t blocked_idx = 0; std::unordered_map<UniqueTid, ThreadSchedInfo> state_map; while (sched_idx < sched.row_count() || waking_idx < waking.row_count() || blocked_idx < sched_blocked_reason.row_count()) { int64_t sched_ts = sched_idx < sched.row_count() ? sched_ts_col[sched_idx] : std::numeric_limits<int64_t>::max(); int64_t waking_ts = waking_idx < waking.row_count() ? waking_ts_col[waking_idx] : std::numeric_limits<int64_t>::max(); int64_t blocked_ts = blocked_idx < sched_blocked_reason.row_count() ? blocked_ts_col[blocked_idx] : std::numeric_limits<int64_t>::max(); // We go through all tables, picking the earliest timestamp from any // to process that event. int64_t min_ts = std::min({sched_ts, waking_ts, blocked_ts}); if (min_ts == sched_ts) { AddSchedEvent(sched, sched_idx++, state_map, trace_end_ts, table.get()); } else if (min_ts == waking_ts) { AddWakingEvent(waking, waking_idx++, state_map); } else /* (min_ts == blocked_ts) */ { AddBlockedReasonEvent(sched_blocked_reason, blocked_idx++, state_map); } } // At the end, go through and flush any remaining pending events. for (const auto& utid_to_pending_info : state_map) { UniqueTid utid = utid_to_pending_info.first; const ThreadSchedInfo& pending_info = utid_to_pending_info.second; FlushPendingEventsForThread(utid, pending_info, table.get(), base::nullopt); } return table; } void ThreadStateGenerator::AddSchedEvent( const Table& sched, uint32_t sched_idx, std::unordered_map<UniqueTid, ThreadSchedInfo>& state_map, int64_t trace_end_ts, tables::ThreadStateTable* table) { int64_t ts = sched.GetTypedColumnByName<int64_t>("ts")[sched_idx]; UniqueTid utid = sched.GetTypedColumnByName<uint32_t>("utid")[sched_idx]; ThreadSchedInfo* info = &state_map[utid]; // Due to races in the kernel, it is possible for the same thread to be // scheduled on different CPUs at the same time. This will manifest itself // here by having |info->desched_ts| in the future of this scheduling slice // (i.e. there was a scheduling slice in the past which ended after the start // of the current scheduling slice). // // We work around this problem by truncating the previous slice to the start // of this slice and not adding the descheduled slice (i.e. we don't call // |FlushPendingEventsForThread| which adds this slice). // // See b/186509316 for details and an example on when this happens. if (info->desched_ts && info->desched_ts.value() > ts) { uint32_t prev_sched_row = info->scheduled_row.value(); int64_t prev_sched_start = table->ts()[prev_sched_row]; // Just a double check that descheduling slice would have started at the // same time the scheduling slice would have ended. PERFETTO_DCHECK(prev_sched_start + table->dur()[prev_sched_row] == info->desched_ts.value()); // Truncate the duration of the old slice to end at the start of this // scheduling slice. table->mutable_dur()->Set(prev_sched_row, ts - prev_sched_start); } else { FlushPendingEventsForThread(utid, *info, table, ts); } // Reset so we don't have any leftover data on the next round. *info = {}; // Undo the expansion of the final sched slice for each CPU to the end of the // trace by setting the duration back to -1. This counteracts the code in // SchedEventTracker::FlushPendingEvents // TODO(lalitm): remove this hack when we stop expanding the last slice to the // end of the trace. int64_t dur = sched.GetTypedColumnByName<int64_t>("dur")[sched_idx]; if (ts + dur == trace_end_ts) { dur = -1; } // Now add the sched slice itself as "Running" with the other fields // unchanged. tables::ThreadStateTable::Row sched_row; sched_row.ts = ts; sched_row.dur = dur; sched_row.cpu = sched.GetTypedColumnByName<uint32_t>("cpu")[sched_idx]; sched_row.state = running_string_id_; sched_row.utid = utid; auto id_and_row = table->Insert(sched_row); // If the sched row had a negative duration, don't add any descheduled slice // because it would be meaningless. if (sched_row.dur == -1) { return; } // This will be flushed to the table on the next sched slice (or the very end // of the big loop). info->desched_ts = ts + dur; info->desched_end_state = sched.GetTypedColumnByName<StringId>("end_state")[sched_idx]; info->scheduled_row = id_and_row.row; } void ThreadStateGenerator::AddWakingEvent( const Table& waking, uint32_t waking_idx, std::unordered_map<UniqueTid, ThreadSchedInfo>& state_map) { int64_t ts = waking.GetTypedColumnByName<int64_t>("ts")[waking_idx]; UniqueTid utid = static_cast<UniqueTid>( waking.GetTypedColumnByName<int64_t>("ref")[waking_idx]); ThreadSchedInfo* info = &state_map[utid]; // Occasionally, it is possible to get a waking event for a thread // which is already in a runnable state. When this happens, we just // ignore the waking event. // See b/186509316 for details and an example on when this happens. if (info->desched_end_state && *info->desched_end_state == runnable_string_id_) { return; } // As counter-intuitive as it seems, occasionally we can get a waking // event for a thread which is currently running. // // There are two cases when this can happen: // 1. The kernel legitimately send a waking event for a "running" thread // because the thread was woken up before the kernel switched away // from it. In this case, the waking timestamp will be in the past // because we added the descheduled slice when we processed the sched // event. // 2. We're close to the end of the trace or had data-loss and we missed // the switch out event for a thread but we see a waking after. // Case 1 described above. In this situation, we should drop the waking // entirely. if (info->desched_ts && *info->desched_ts > ts) { return; } // For case 2 and otherwise, we should just note the fact that the thread // became runnable at this time. Note that we cannot check if runnable is // already not set because we could have data-loss which leads to us getting // back to back waking for a single thread. info->runnable_ts = ts; } Table::Schema ThreadStateGenerator::CreateSchema() { auto schema = tables::ThreadStateTable::Schema(); // Because we expect our users to generally want ordered by ts, we set the // ordering for the schema to match our forced sort pass in ComputeTable. auto ts_it = std::find_if( schema.columns.begin(), schema.columns.end(), [](const Table::Schema::Column& col) { return col.name == "ts"; }); ts_it->is_sorted = true; auto id_it = std::find_if( schema.columns.begin(), schema.columns.end(), [](const Table::Schema::Column& col) { return col.name == "id"; }); id_it->is_sorted = false; return schema; } void ThreadStateGenerator::FlushPendingEventsForThread( UniqueTid utid, const ThreadSchedInfo& info, tables::ThreadStateTable* table, base::Optional<int64_t> end_ts) { // First, let's flush the descheduled period (if any) to the table. if (info.desched_ts) { PERFETTO_DCHECK(info.desched_end_state); int64_t dur; if (end_ts) { int64_t desched_end_ts = info.runnable_ts ? *info.runnable_ts : *end_ts; dur = desched_end_ts - *info.desched_ts; } else { dur = -1; } tables::ThreadStateTable::Row row; row.ts = *info.desched_ts; row.dur = dur; row.state = *info.desched_end_state; row.utid = utid; row.io_wait = info.io_wait; row.blocked_function = info.blocked_function; table->Insert(row); } // Next, flush the runnable period (if any) to the table. if (info.runnable_ts) { tables::ThreadStateTable::Row row; row.ts = *info.runnable_ts; row.dur = end_ts ? *end_ts - row.ts : -1; row.state = runnable_string_id_; row.utid = utid; table->Insert(row); } } void ThreadStateGenerator::AddBlockedReasonEvent( const Table& blocked_reason, uint32_t blocked_idx, std::unordered_map<UniqueTid, ThreadSchedInfo>& state_map) { const auto& utid_col = blocked_reason.GetTypedColumnByName<int64_t>("ref"); const auto& arg_set_id_col = blocked_reason.GetTypedColumnByName<uint32_t>("arg_set_id"); UniqueTid utid = static_cast<UniqueTid>(utid_col[blocked_idx]); uint32_t arg_set_id = arg_set_id_col[blocked_idx]; ThreadSchedInfo& info = state_map[utid]; base::Optional<Variadic> opt_value; util::Status status = context_->storage->ExtractArg(arg_set_id, "io_wait", &opt_value); // We can't do anything better than ignoring any errors here. // TODO(lalitm): see if there's a better way to handle this. if (status.ok() && opt_value) { PERFETTO_CHECK(opt_value->type == Variadic::Type::kBool); info.io_wait = opt_value->bool_value; } status = context_->storage->ExtractArg(arg_set_id, "function", &opt_value); if (status.ok() && opt_value) { PERFETTO_CHECK(opt_value->type == Variadic::Type::kString); info.blocked_function = opt_value->string_value; } } std::string ThreadStateGenerator::TableName() { return "thread_state"; } uint32_t ThreadStateGenerator::EstimateRowCount() { return context_->storage->sched_slice_table().row_count(); } } // namespace trace_processor } // namespace perfetto <commit_msg>tp: fix compile am: 82b99102e5<commit_after>/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/trace_processor/dynamic/thread_state_generator.h" #include <memory> #include <set> #include "src/trace_processor/types/trace_processor_context.h" namespace perfetto { namespace trace_processor { ThreadStateGenerator::ThreadStateGenerator(TraceProcessorContext* context) : running_string_id_(context->storage->InternString("Running")), runnable_string_id_(context->storage->InternString("R")), context_(context) {} ThreadStateGenerator::~ThreadStateGenerator() = default; util::Status ThreadStateGenerator::ValidateConstraints( const QueryConstraints&) { return util::OkStatus(); } std::unique_ptr<Table> ThreadStateGenerator::ComputeTable( const std::vector<Constraint>&, const std::vector<Order>&) { if (!unsorted_thread_state_table_) { int64_t trace_end_ts = context_->storage->GetTraceTimestampBoundsNs().second; unsorted_thread_state_table_ = ComputeThreadStateTable(trace_end_ts); // We explicitly sort by ts here as ComputeThreadStateTable does not insert // rows in sorted order but we expect our clients to always want to sort // on ts. Writing ComputeThreadStateTable to insert in sorted order is // more trouble than its worth. sorted_thread_state_table_ = unsorted_thread_state_table_->Sort( {unsorted_thread_state_table_->ts().ascending()}); } PERFETTO_CHECK(sorted_thread_state_table_); return std::unique_ptr<Table>(new Table(sorted_thread_state_table_->Copy())); } std::unique_ptr<tables::ThreadStateTable> ThreadStateGenerator::ComputeThreadStateTable(int64_t trace_end_ts) { std::unique_ptr<tables::ThreadStateTable> table(new tables::ThreadStateTable( context_->storage->mutable_string_pool(), nullptr)); const auto& raw_sched = context_->storage->sched_slice_table(); const auto& instants = context_->storage->instant_table(); // In both tables, exclude utid == 0 which represents the idle thread. Table sched = raw_sched.Filter({raw_sched.utid().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); Table waking = instants.Filter( {instants.name().eq("sched_waking"), instants.ref().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); // We prefer to use waking if at all possible and fall back to wakeup if not // available. if (waking.row_count() == 0) { waking = instants.Filter( {instants.name().eq("sched_wakeup"), instants.ref().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); } Table sched_blocked_reason = instants.Filter( {instants.name().eq("sched_blocked_reason"), instants.ref().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); const auto& sched_ts_col = sched.GetTypedColumnByName<int64_t>("ts"); const auto& waking_ts_col = waking.GetTypedColumnByName<int64_t>("ts"); const auto& blocked_ts_col = sched_blocked_reason.GetTypedColumnByName<int64_t>("ts"); uint32_t sched_idx = 0; uint32_t waking_idx = 0; uint32_t blocked_idx = 0; std::unordered_map<UniqueTid, ThreadSchedInfo> state_map; while (sched_idx < sched.row_count() || waking_idx < waking.row_count() || blocked_idx < sched_blocked_reason.row_count()) { int64_t sched_ts = sched_idx < sched.row_count() ? sched_ts_col[sched_idx] : std::numeric_limits<int64_t>::max(); int64_t waking_ts = waking_idx < waking.row_count() ? waking_ts_col[waking_idx] : std::numeric_limits<int64_t>::max(); int64_t blocked_ts = blocked_idx < sched_blocked_reason.row_count() ? blocked_ts_col[blocked_idx] : std::numeric_limits<int64_t>::max(); // We go through all tables, picking the earliest timestamp from any // to process that event. int64_t min_ts = std::min({sched_ts, waking_ts, blocked_ts}); if (min_ts == sched_ts) { AddSchedEvent(sched, sched_idx++, state_map, trace_end_ts, table.get()); } else if (min_ts == waking_ts) { AddWakingEvent(waking, waking_idx++, state_map); } else /* (min_ts == blocked_ts) */ { AddBlockedReasonEvent(sched_blocked_reason, blocked_idx++, state_map); } } // At the end, go through and flush any remaining pending events. for (const auto& utid_to_pending_info : state_map) { UniqueTid utid = utid_to_pending_info.first; const ThreadSchedInfo& pending_info = utid_to_pending_info.second; FlushPendingEventsForThread(utid, pending_info, table.get(), base::nullopt); } return table; } void ThreadStateGenerator::AddSchedEvent( const Table& sched, uint32_t sched_idx, std::unordered_map<UniqueTid, ThreadSchedInfo>& state_map, int64_t trace_end_ts, tables::ThreadStateTable* table) { int64_t ts = sched.GetTypedColumnByName<int64_t>("ts")[sched_idx]; UniqueTid utid = sched.GetTypedColumnByName<uint32_t>("utid")[sched_idx]; ThreadSchedInfo* info = &state_map[utid]; // Due to races in the kernel, it is possible for the same thread to be // scheduled on different CPUs at the same time. This will manifest itself // here by having |info->desched_ts| in the future of this scheduling slice // (i.e. there was a scheduling slice in the past which ended after the start // of the current scheduling slice). // // We work around this problem by truncating the previous slice to the start // of this slice and not adding the descheduled slice (i.e. we don't call // |FlushPendingEventsForThread| which adds this slice). // // See b/186509316 for details and an example on when this happens. if (info->desched_ts && info->desched_ts.value() > ts) { uint32_t prev_sched_row = info->scheduled_row.value(); int64_t prev_sched_start = table->ts()[prev_sched_row]; // Just a double check that descheduling slice would have started at the // same time the scheduling slice would have ended. PERFETTO_DCHECK(prev_sched_start + table->dur()[prev_sched_row] == info->desched_ts.value()); // Truncate the duration of the old slice to end at the start of this // scheduling slice. table->mutable_dur()->Set(prev_sched_row, ts - prev_sched_start); } else { FlushPendingEventsForThread(utid, *info, table, ts); } // Reset so we don't have any leftover data on the next round. *info = {}; // Undo the expansion of the final sched slice for each CPU to the end of the // trace by setting the duration back to -1. This counteracts the code in // SchedEventTracker::FlushPendingEvents // TODO(lalitm): remove this hack when we stop expanding the last slice to the // end of the trace. int64_t dur = sched.GetTypedColumnByName<int64_t>("dur")[sched_idx]; if (ts + dur == trace_end_ts) { dur = -1; } // Now add the sched slice itself as "Running" with the other fields // unchanged. tables::ThreadStateTable::Row sched_row; sched_row.ts = ts; sched_row.dur = dur; sched_row.cpu = sched.GetTypedColumnByName<uint32_t>("cpu")[sched_idx]; sched_row.state = running_string_id_; sched_row.utid = utid; auto id_and_row = table->Insert(sched_row); // If the sched row had a negative duration, don't add any descheduled slice // because it would be meaningless. if (sched_row.dur == -1) { return; } // This will be flushed to the table on the next sched slice (or the very end // of the big loop). info->desched_ts = ts + dur; info->desched_end_state = sched.GetTypedColumnByName<StringId>("end_state")[sched_idx]; info->scheduled_row = id_and_row.row; } void ThreadStateGenerator::AddWakingEvent( const Table& waking, uint32_t waking_idx, std::unordered_map<UniqueTid, ThreadSchedInfo>& state_map) { int64_t ts = waking.GetTypedColumnByName<int64_t>("ts")[waking_idx]; UniqueTid utid = static_cast<UniqueTid>( waking.GetTypedColumnByName<int64_t>("ref")[waking_idx]); ThreadSchedInfo* info = &state_map[utid]; // Occasionally, it is possible to get a waking event for a thread // which is already in a runnable state. When this happens, we just // ignore the waking event. // See b/186509316 for details and an example on when this happens. if (info->desched_end_state && *info->desched_end_state == runnable_string_id_) { return; } // As counter-intuitive as it seems, occasionally we can get a waking // event for a thread which is currently running. // // There are two cases when this can happen: // 1. The kernel legitimately send a waking event for a "running" thread // because the thread was woken up before the kernel switched away // from it. In this case, the waking timestamp will be in the past // because we added the descheduled slice when we processed the sched // event. // 2. We're close to the end of the trace or had data-loss and we missed // the switch out event for a thread but we see a waking after. // Case 1 described above. In this situation, we should drop the waking // entirely. if (info->desched_ts && *info->desched_ts > ts) { return; } // For case 2 and otherwise, we should just note the fact that the thread // became runnable at this time. Note that we cannot check if runnable is // already not set because we could have data-loss which leads to us getting // back to back waking for a single thread. info->runnable_ts = ts; } Table::Schema ThreadStateGenerator::CreateSchema() { auto schema = tables::ThreadStateTable::Schema(); // Because we expect our users to generally want ordered by ts, we set the // ordering for the schema to match our forced sort pass in ComputeTable. auto ts_it = std::find_if( schema.columns.begin(), schema.columns.end(), [](const Table::Schema::Column& col) { return col.name == "ts"; }); ts_it->is_sorted = true; auto id_it = std::find_if( schema.columns.begin(), schema.columns.end(), [](const Table::Schema::Column& col) { return col.name == "id"; }); id_it->is_sorted = false; return schema; } void ThreadStateGenerator::FlushPendingEventsForThread( UniqueTid utid, const ThreadSchedInfo& info, tables::ThreadStateTable* table, base::Optional<int64_t> end_ts) { // First, let's flush the descheduled period (if any) to the table. if (info.desched_ts) { PERFETTO_DCHECK(info.desched_end_state); int64_t dur; if (end_ts) { int64_t desched_end_ts = info.runnable_ts ? *info.runnable_ts : *end_ts; dur = desched_end_ts - *info.desched_ts; } else { dur = -1; } tables::ThreadStateTable::Row row; row.ts = *info.desched_ts; row.dur = dur; row.state = *info.desched_end_state; row.utid = utid; row.io_wait = info.io_wait; row.blocked_function = info.blocked_function; table->Insert(row); } // Next, flush the runnable period (if any) to the table. if (info.runnable_ts) { tables::ThreadStateTable::Row row; row.ts = *info.runnable_ts; row.dur = end_ts ? *end_ts - row.ts : -1; row.state = runnable_string_id_; row.utid = utid; table->Insert(row); } } void ThreadStateGenerator::AddBlockedReasonEvent( const Table& blocked_reason, uint32_t blocked_idx, std::unordered_map<UniqueTid, ThreadSchedInfo>& state_map) { const auto& utid_col = blocked_reason.GetTypedColumnByName<int64_t>("ref"); const auto& arg_set_id_col = blocked_reason.GetTypedColumnByName<uint32_t>("arg_set_id"); UniqueTid utid = static_cast<UniqueTid>(utid_col[blocked_idx]); uint32_t arg_set_id = arg_set_id_col[blocked_idx]; ThreadSchedInfo& info = state_map[utid]; base::Optional<Variadic> opt_value; util::Status status = context_->storage->ExtractArg(arg_set_id, "io_wait", &opt_value); // We can't do anything better than ignoring any errors here. // TODO(lalitm): see if there's a better way to handle this. if (status.ok() && opt_value) { PERFETTO_CHECK(opt_value->type == Variadic::Type::kBool); info.io_wait = opt_value->bool_value; } status = context_->storage->ExtractArg(arg_set_id, "function", &opt_value); if (status.ok() && opt_value) { PERFETTO_CHECK(opt_value->type == Variadic::Type::kString); info.blocked_function = opt_value->string_value; } } std::string ThreadStateGenerator::TableName() { return "thread_state"; } uint32_t ThreadStateGenerator::EstimateRowCount() { return context_->storage->sched_slice_table().row_count(); } } // namespace trace_processor } // namespace perfetto <|endoftext|>
<commit_before> /* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE ptref_companies_test #include <boost/test/unit_test.hpp> #include "ptreferential/ptreferential.h" #include "ptreferential/reflexion.h" #include "ptreferential/ptref_graph.h" #include "ed/build_helper.h" #include <boost/graph/strong_components.hpp> #include <boost/graph/connected_components.hpp> #include "type/pt_data.h" namespace navitia{namespace ptref { template<typename T> std::vector<type::idx_t> get_indexes(Filter filter, Type_e requested_type, const type::Data & d); }} using namespace navitia::ptref; struct logger_initialized { logger_initialized() { init_logger(); } }; BOOST_GLOBAL_FIXTURE( logger_initialized ) class Params{ public: navitia::type::Data data; navitia::type::Company* current_company; navitia::type::Network* current_network; navitia::type::Line* current_line; navitia::type::Route* current_route; void add_network(const std::string& network_name){ current_network = new navitia::type::Network(); current_network->uri = network_name; current_network->name = network_name; current_network->idx = data.pt_data->networks.size(); data.pt_data->networks.push_back(current_network); } void add_company(const std::string& company_name){ current_company = new navitia::type::Company(); current_company->uri = company_name; current_company->name = company_name; current_company->idx = data.pt_data->companies.size(); data.pt_data->companies.push_back(current_company); } void add_line(const std::string& line_name){ current_line = new navitia::type::Line(); current_line->uri = line_name; current_line->name = line_name; current_line->idx = data.pt_data->lines.size(); data.pt_data->lines.push_back(current_line); } void add_route(const std::string& route_name){ current_route = new navitia::type::Route(); current_route->uri = route_name; current_route->name = route_name; current_route->idx = data.pt_data->routes.size(); data.pt_data->routes.push_back(current_route); } Params(){ add_network("N1"); add_company("C1"); add_line("C1-L1"); current_company->line_list.push_back(current_line); current_line->company_list.push_back(current_company); current_line->network = current_network; current_network->line_list.push_back(current_line); current_route->line = current_line; current_line->route_list.push_back(current_route); add_line("C1-L2"); current_company->line_list.push_back(current_line); current_line->company_list.push_back(current_company); current_line->network = current_network; current_network->line_list.push_back(current_line); add_network("N2"); add_company("C2"); add_line("C2-L1"); add_route("C2-L1-R1"); current_company->line_list.push_back(current_line); current_line->company_list.push_back(current_company); current_line->network = current_network; current_network->line_list.push_back(current_line); current_line->route_list.push_back(current_route); current_route->line = current_line; add_line("C2-L2"); add_route("C2-L1-R2"); current_company->line_list.push_back(current_line); current_line->company_list.push_back(current_company); current_line->network = current_network; current_network->line_list.push_back(current_line); current_line->route_list.push_back(current_route); current_route->line = current_line; add_line("C2-L3"); current_company->line_list.push_back(current_line); current_line->company_list.push_back(current_company); current_line->network = current_network; current_network->line_list.push_back(current_line); add_network("N3"); data.pt_data->build_uri(); } }; BOOST_FIXTURE_TEST_SUITE(companies_test, Params) BOOST_AUTO_TEST_CASE(comanies_list) { auto indexes = make_query(navitia::type::Type_e::Company, "", data); BOOST_CHECK_EQUAL(indexes.size(), 2); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[0]]->uri, "C1"); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[1]]->uri, "C2"); } BOOST_AUTO_TEST_CASE(comany_by_uri) { auto indexes = make_query(navitia::type::Type_e::Company, "company.uri=C1", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[0]]->uri, "C1"); } BOOST_AUTO_TEST_CASE(lines_by_company) { auto indexes = make_query(navitia::type::Type_e::Line, "company.uri=C1", data); BOOST_CHECK_EQUAL(indexes.size(), 2); BOOST_CHECK_EQUAL(data.pt_data->lines[indexes[0]]->uri, "C1-L1"); BOOST_CHECK_EQUAL(data.pt_data->lines[indexes[1]]->uri, "C1-L2"); indexes = make_query(navitia::type::Type_e::Line, "company.uri=C2", data); BOOST_CHECK_EQUAL(indexes.size(), 3); BOOST_CHECK_EQUAL(data.pt_data->lines[indexes[0]]->uri, "C2-L1"); BOOST_CHECK_EQUAL(data.pt_data->lines[indexes[1]]->uri, "C2-L2"); BOOST_CHECK_EQUAL(data.pt_data->lines[indexes[2]]->uri, "C2-L3"); } BOOST_AUTO_TEST_CASE(comanies_by_line) { auto indexes = make_query(navitia::type::Type_e::Company, "line.uri=C1-L1", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[0]]->uri, "C1"); } BOOST_AUTO_TEST_CASE(networks_by_company) { auto indexes = make_query(navitia::type::Type_e::Network, "company.uri=C1", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->networks[indexes.front()]->uri, "N1"); indexes = make_query(navitia::type::Type_e::Network, "company.uri=C2", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->networks[indexes.front()]->uri, "N2"); } BOOST_AUTO_TEST_CASE(companies_by_network) { auto indexes = make_query(navitia::type::Type_e::Company, "network.uri=N1", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[0]]->uri, "C1"); indexes = make_query(navitia::type::Type_e::Company, "network.uri=N2", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[0]]->uri, "C2"); BOOST_CHECK_THROW(make_query(navitia::type::Type_e::Company, "network.uri=N3", data), ptref_error); } BOOST_AUTO_TEST_CASE(routes_by_company) { BOOST_CHECK_THROW(make_query(navitia::type::Type_e::Route, "company.uri=C1", data), ptref_error); auto indexes = make_query(navitia::type::Type_e::Route, "company.uri=C2", data); BOOST_CHECK_EQUAL(indexes.size(), 2); BOOST_CHECK_EQUAL(data.pt_data->routes[indexes[0]]->uri, "C2-L1-R1"); BOOST_CHECK_EQUAL(data.pt_data->routes[indexes[1]]->uri, "C2-L1-R2"); } BOOST_AUTO_TEST_CASE(companies_by_route) { auto indexes = make_query(navitia::type::Type_e::Company, "route.uri=C2-L1-R1", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[0]]->uri, "C2"); indexes = make_query(navitia::type::Type_e::Company, "route.uri=C2-L1-R2", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[0]]->uri, "C2"); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>kraken: get_indexes unused<commit_after> /* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE ptref_companies_test #include <boost/test/unit_test.hpp> #include "ptreferential/ptreferential.h" #include "ptreferential/reflexion.h" #include "ptreferential/ptref_graph.h" #include "ed/build_helper.h" #include <boost/graph/strong_components.hpp> #include <boost/graph/connected_components.hpp> #include "type/pt_data.h" using namespace navitia::ptref; struct logger_initialized { logger_initialized() { init_logger(); } }; BOOST_GLOBAL_FIXTURE( logger_initialized ) class Params{ public: navitia::type::Data data; navitia::type::Company* current_company; navitia::type::Network* current_network; navitia::type::Line* current_line; navitia::type::Route* current_route; void add_network(const std::string& network_name){ current_network = new navitia::type::Network(); current_network->uri = network_name; current_network->name = network_name; current_network->idx = data.pt_data->networks.size(); data.pt_data->networks.push_back(current_network); } void add_company(const std::string& company_name){ current_company = new navitia::type::Company(); current_company->uri = company_name; current_company->name = company_name; current_company->idx = data.pt_data->companies.size(); data.pt_data->companies.push_back(current_company); } void add_line(const std::string& line_name){ current_line = new navitia::type::Line(); current_line->uri = line_name; current_line->name = line_name; current_line->idx = data.pt_data->lines.size(); data.pt_data->lines.push_back(current_line); } void add_route(const std::string& route_name){ current_route = new navitia::type::Route(); current_route->uri = route_name; current_route->name = route_name; current_route->idx = data.pt_data->routes.size(); data.pt_data->routes.push_back(current_route); } Params(){ add_network("N1"); add_company("C1"); add_line("C1-L1"); current_company->line_list.push_back(current_line); current_line->company_list.push_back(current_company); current_line->network = current_network; current_network->line_list.push_back(current_line); add_line("C1-L2"); current_company->line_list.push_back(current_line); current_line->company_list.push_back(current_company); current_line->network = current_network; current_network->line_list.push_back(current_line); add_network("N2"); add_company("C2"); add_line("C2-L1"); add_route("C2-L1-R1"); current_company->line_list.push_back(current_line); current_line->company_list.push_back(current_company); current_line->network = current_network; current_network->line_list.push_back(current_line); current_line->route_list.push_back(current_route); current_route->line = current_line; add_line("C2-L2"); add_route("C2-L1-R2"); current_company->line_list.push_back(current_line); current_line->company_list.push_back(current_company); current_line->network = current_network; current_network->line_list.push_back(current_line); current_line->route_list.push_back(current_route); current_route->line = current_line; add_line("C2-L3"); current_company->line_list.push_back(current_line); current_line->company_list.push_back(current_company); current_line->network = current_network; current_network->line_list.push_back(current_line); add_network("N3"); data.pt_data->build_uri(); } }; BOOST_FIXTURE_TEST_SUITE(companies_test, Params) BOOST_AUTO_TEST_CASE(comanies_list) { auto indexes = make_query(navitia::type::Type_e::Company, "", data); BOOST_CHECK_EQUAL(indexes.size(), 2); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[0]]->uri, "C1"); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[1]]->uri, "C2"); } BOOST_AUTO_TEST_CASE(comany_by_uri) { auto indexes = make_query(navitia::type::Type_e::Company, "company.uri=C1", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[0]]->uri, "C1"); } BOOST_AUTO_TEST_CASE(lines_by_company) { auto indexes = make_query(navitia::type::Type_e::Line, "company.uri=C1", data); BOOST_CHECK_EQUAL(indexes.size(), 2); BOOST_CHECK_EQUAL(data.pt_data->lines[indexes[0]]->uri, "C1-L1"); BOOST_CHECK_EQUAL(data.pt_data->lines[indexes[1]]->uri, "C1-L2"); indexes = make_query(navitia::type::Type_e::Line, "company.uri=C2", data); BOOST_CHECK_EQUAL(indexes.size(), 3); BOOST_CHECK_EQUAL(data.pt_data->lines[indexes[0]]->uri, "C2-L1"); BOOST_CHECK_EQUAL(data.pt_data->lines[indexes[1]]->uri, "C2-L2"); BOOST_CHECK_EQUAL(data.pt_data->lines[indexes[2]]->uri, "C2-L3"); } BOOST_AUTO_TEST_CASE(comanies_by_line) { auto indexes = make_query(navitia::type::Type_e::Company, "line.uri=C1-L1", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[0]]->uri, "C1"); } BOOST_AUTO_TEST_CASE(networks_by_company) { auto indexes = make_query(navitia::type::Type_e::Network, "company.uri=C1", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->networks[indexes.front()]->uri, "N1"); indexes = make_query(navitia::type::Type_e::Network, "company.uri=C2", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->networks[indexes.front()]->uri, "N2"); } BOOST_AUTO_TEST_CASE(companies_by_network) { auto indexes = make_query(navitia::type::Type_e::Company, "network.uri=N1", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[0]]->uri, "C1"); indexes = make_query(navitia::type::Type_e::Company, "network.uri=N2", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[0]]->uri, "C2"); BOOST_CHECK_THROW(make_query(navitia::type::Type_e::Company, "network.uri=N3", data), ptref_error); } BOOST_AUTO_TEST_CASE(routes_by_company) { BOOST_CHECK_THROW(make_query(navitia::type::Type_e::Route, "company.uri=C1", data), ptref_error); auto indexes = make_query(navitia::type::Type_e::Route, "company.uri=C2", data); BOOST_CHECK_EQUAL(indexes.size(), 2); BOOST_CHECK_EQUAL(data.pt_data->routes[indexes[0]]->uri, "C2-L1-R1"); BOOST_CHECK_EQUAL(data.pt_data->routes[indexes[1]]->uri, "C2-L1-R2"); } BOOST_AUTO_TEST_CASE(companies_by_route) { auto indexes = make_query(navitia::type::Type_e::Company, "route.uri=C2-L1-R1", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[0]]->uri, "C2"); indexes = make_query(navitia::type::Type_e::Company, "route.uri=C2-L1-R2", data); BOOST_CHECK_EQUAL(indexes.size(), 1); BOOST_CHECK_EQUAL(data.pt_data->companies[indexes[0]]->uri, "C2"); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/memory_details.h" #include "app/l10n_util.h" #include "base/file_version_info.h" #include "base/metrics/histogram.h" #include "base/process_util.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_child_process_host.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/renderer_host/backing_store_manager.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/navigation_entry.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/bindings_policy.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/url_constants.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #if defined(OS_LINUX) #include "chrome/browser/zygote_host_linux.h" #include "chrome/browser/renderer_host/render_sandbox_host_linux.h" #endif ProcessMemoryInformation::ProcessMemoryInformation() : pid(0), num_processes(0), is_diagnostics(false), type(ChildProcessInfo::UNKNOWN_PROCESS), renderer_type(ChildProcessInfo::RENDERER_UNKNOWN) { } ProcessMemoryInformation::~ProcessMemoryInformation() {} ProcessData::ProcessData() {} ProcessData::ProcessData(const ProcessData& rhs) : name(rhs.name), process_name(rhs.process_name), processes(rhs.processes) { } ProcessData::~ProcessData() {} ProcessData& ProcessData::operator=(const ProcessData& rhs) { name = rhs.name; process_name = rhs.process_name; processes = rhs.processes; return *this; } // About threading: // // This operation will hit no fewer than 3 threads. // // The ChildProcessInfo::Iterator can only be accessed from the IO thread. // // The RenderProcessHostIterator can only be accessed from the UI thread. // // This operation can take 30-100ms to complete. We never want to have // one task run for that long on the UI or IO threads. So, we run the // expensive parts of this operation over on the file thread. // void MemoryDetails::StartFetch() { DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::FILE)); // In order to process this request, we need to use the plugin information. // However, plugin process information is only available from the IO thread. BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &MemoryDetails::CollectChildInfoOnIOThread)); } MemoryDetails::~MemoryDetails() {} void MemoryDetails::CollectChildInfoOnIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); std::vector<ProcessMemoryInformation> child_info; // Collect the list of child processes. for (BrowserChildProcessHost::Iterator iter; !iter.Done(); ++iter) { ProcessMemoryInformation info; info.pid = base::GetProcId(iter->handle()); if (!info.pid) continue; info.type = iter->type(); info.renderer_type = iter->renderer_type(); info.titles.push_back(WideToUTF16Hack(iter->name())); child_info.push_back(info); } // Now go do expensive memory lookups from the file thread. BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &MemoryDetails::CollectProcessData, child_info)); } void MemoryDetails::CollectChildInfoOnUIThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); #if defined(OS_LINUX) const pid_t zygote_pid = ZygoteHost::GetInstance()->pid(); const pid_t sandbox_helper_pid = RenderSandboxHostLinux::GetInstance()->pid(); #endif ProcessData* const chrome_browser = ChromeBrowser(); // Get more information about the process. for (size_t index = 0; index < chrome_browser->processes.size(); index++) { // Check if it's a renderer, if so get the list of page titles in it and // check if it's a diagnostics-related process. We skip about:memory pages. // Iterate the RenderProcessHosts to find the tab contents. ProcessMemoryInformation& process = chrome_browser->processes[index]; for (RenderProcessHost::iterator renderer_iter( RenderProcessHost::AllHostsIterator()); !renderer_iter.IsAtEnd(); renderer_iter.Advance()) { RenderProcessHost* render_process_host = renderer_iter.GetCurrentValue(); DCHECK(render_process_host); // Ignore processes that don't have a connection, such as crashed tabs. if (!render_process_host->HasConnection() || process.pid != base::GetProcId(render_process_host->GetHandle())) { continue; } process.type = ChildProcessInfo::RENDER_PROCESS; // The RenderProcessHost may host multiple TabContents. Any // of them which contain diagnostics information make the whole // process be considered a diagnostics process. // // NOTE: This is a bit dangerous. We know that for now, listeners // are always RenderWidgetHosts. But in theory, they don't // have to be. RenderProcessHost::listeners_iterator iter( render_process_host->ListenersIterator()); for (; !iter.IsAtEnd(); iter.Advance()) { const RenderWidgetHost* widget = static_cast<const RenderWidgetHost*>(iter.GetCurrentValue()); DCHECK(widget); if (!widget || !widget->IsRenderView()) continue; const RenderViewHost* host = static_cast<const RenderViewHost*>(widget); RenderViewHostDelegate* host_delegate = host->delegate(); GURL url = host_delegate->GetURL(); ViewType::Type type = host_delegate->GetRenderViewType(); if (host->enabled_bindings() & BindingsPolicy::DOM_UI) { // TODO(erikkay) the type for devtools doesn't actually appear to // be set. if (type == ViewType::DEV_TOOLS_UI) process.renderer_type = ChildProcessInfo::RENDERER_DEVTOOLS; else process.renderer_type = ChildProcessInfo::RENDERER_CHROME; } else if (host->enabled_bindings() & BindingsPolicy::EXTENSION) { process.renderer_type = ChildProcessInfo::RENDERER_EXTENSION; } TabContents* contents = NULL; if (host_delegate) contents = host_delegate->GetAsTabContents(); if (!contents) { if (host->is_extension_process()) { // TODO(erikkay) should we just add GetAsExtensionHost to // TabContents? ExtensionHost* eh = static_cast<ExtensionHost*>(host_delegate); string16 title = UTF8ToUTF16(eh->extension()->name()); process.titles.push_back(title); } else if (process.renderer_type == ChildProcessInfo::RENDERER_UNKNOWN) { process.titles.push_back(UTF8ToUTF16(url.spec())); switch (type) { case ViewType::BACKGROUND_CONTENTS: process.renderer_type = ChildProcessInfo::RENDERER_BACKGROUND_APP; break; case ViewType::INTERSTITIAL_PAGE: process.renderer_type = ChildProcessInfo::RENDERER_INTERSTITIAL; break; case ViewType::NOTIFICATION: process.renderer_type = ChildProcessInfo::RENDERER_NOTIFICATION; break; default: process.renderer_type = ChildProcessInfo::RENDERER_UNKNOWN; break; } } continue; } // Since We have a TabContents and and the renderer type hasn't been // set yet, it must be a normal tabbed renderer. if (process.renderer_type == ChildProcessInfo::RENDERER_UNKNOWN) process.renderer_type = ChildProcessInfo::RENDERER_NORMAL; string16 title = contents->GetTitle(); if (!title.length()) title = l10n_util::GetStringUTF16(IDS_DEFAULT_TAB_TITLE); process.titles.push_back(title); // We need to check the pending entry as well as the virtual_url to // see if it's an about:memory URL (we don't want to count these in the // total memory usage of the browser). // // When we reach here, about:memory will be the pending entry since we // haven't responded with any data such that it would be committed. If // you have another about:memory tab open (which would be committed), // we don't want to count it either, so we also check the last committed // entry. // // Either the pending or last committed entries can be NULL. const NavigationEntry* pending_entry = contents->controller().pending_entry(); const NavigationEntry* last_committed_entry = contents->controller().GetLastCommittedEntry(); if ((last_committed_entry && LowerCaseEqualsASCII(last_committed_entry->virtual_url().spec(), chrome::kAboutMemoryURL)) || (pending_entry && LowerCaseEqualsASCII(pending_entry->virtual_url().spec(), chrome::kAboutMemoryURL))) process.is_diagnostics = true; } } #if defined(OS_LINUX) if (process.pid == zygote_pid) { process.type = ChildProcessInfo::ZYGOTE_PROCESS; } else if (process.pid == sandbox_helper_pid) { process.type = ChildProcessInfo::SANDBOX_HELPER_PROCESS; } #endif } // Get rid of other Chrome processes that are from a different profile. for (size_t index = 0; index < chrome_browser->processes.size(); index++) { if (chrome_browser->processes[index].type == ChildProcessInfo::UNKNOWN_PROCESS) { chrome_browser->processes.erase( chrome_browser->processes.begin() + index); index--; } } UpdateHistograms(); OnDetailsAvailable(); } void MemoryDetails::UpdateHistograms() { // Reports a set of memory metrics to UMA. // Memory is measured in KB. const ProcessData& browser = *ChromeBrowser(); size_t aggregate_memory = 0; int chrome_count = 0; int extension_count = 0; int plugin_count = 0; int renderer_count = 0; int other_count = 0; int worker_count = 0; for (size_t index = 0; index < browser.processes.size(); index++) { int sample = static_cast<int>(browser.processes[index].working_set.priv); aggregate_memory += sample; switch (browser.processes[index].type) { case ChildProcessInfo::BROWSER_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.Browser", sample); break; case ChildProcessInfo::RENDER_PROCESS: { ChildProcessInfo::RendererProcessType renderer_type = browser.processes[index].renderer_type; switch (renderer_type) { case ChildProcessInfo::RENDERER_EXTENSION: UMA_HISTOGRAM_MEMORY_KB("Memory.Extension", sample); extension_count++; break; case ChildProcessInfo::RENDERER_CHROME: UMA_HISTOGRAM_MEMORY_KB("Memory.Chrome", sample); chrome_count++; break; case ChildProcessInfo::RENDERER_UNKNOWN: NOTREACHED() << "Unknown renderer process type."; break; case ChildProcessInfo::RENDERER_NORMAL: default: // TODO(erikkay): Should we bother splitting out the other subtypes? UMA_HISTOGRAM_MEMORY_KB("Memory.Renderer", sample); renderer_count++; break; } break; } case ChildProcessInfo::PLUGIN_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.Plugin", sample); plugin_count++; break; case ChildProcessInfo::WORKER_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.Worker", sample); worker_count++; break; case ChildProcessInfo::UTILITY_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.Utility", sample); other_count++; break; case ChildProcessInfo::ZYGOTE_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.Zygote", sample); other_count++; break; case ChildProcessInfo::SANDBOX_HELPER_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.SandboxHelper", sample); other_count++; break; case ChildProcessInfo::NACL_LOADER_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.NativeClient", sample); other_count++; break; case ChildProcessInfo::NACL_BROKER_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.NativeClientBroker", sample); other_count++; break; case ChildProcessInfo::GPU_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.Gpu", sample); other_count++; break; default: NOTREACHED(); } } UMA_HISTOGRAM_MEMORY_KB("Memory.BackingStore", BackingStoreManager::MemorySize() / 1024); UMA_HISTOGRAM_COUNTS_100("Memory.ProcessCount", static_cast<int>(browser.processes.size())); UMA_HISTOGRAM_COUNTS_100("Memory.ChromeProcessCount", chrome_count); UMA_HISTOGRAM_COUNTS_100("Memory.ExtensionProcessCount", extension_count); UMA_HISTOGRAM_COUNTS_100("Memory.OtherProcessCount", other_count); UMA_HISTOGRAM_COUNTS_100("Memory.PluginProcessCount", plugin_count); UMA_HISTOGRAM_COUNTS_100("Memory.RendererProcessCount", renderer_count); UMA_HISTOGRAM_COUNTS_100("Memory.WorkerProcessCount", worker_count); // TODO(viettrungluu): Do we want separate counts for the other // (platform-specific) process types? int total_sample = static_cast<int>(aggregate_memory / 1000); UMA_HISTOGRAM_MEMORY_MB("Memory.Total", total_sample); } <commit_msg>Fix crasher caused by non-ExtensionHost-based RenderViewHostDelegates in extension processes (notifications or sidebars currently) when viewing about:memory.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/memory_details.h" #include "app/l10n_util.h" #include "base/file_version_info.h" #include "base/metrics/histogram.h" #include "base/process_util.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_child_process_host.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/backing_store_manager.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/navigation_entry.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/bindings_policy.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/url_constants.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #if defined(OS_LINUX) #include "chrome/browser/zygote_host_linux.h" #include "chrome/browser/renderer_host/render_sandbox_host_linux.h" #endif ProcessMemoryInformation::ProcessMemoryInformation() : pid(0), num_processes(0), is_diagnostics(false), type(ChildProcessInfo::UNKNOWN_PROCESS), renderer_type(ChildProcessInfo::RENDERER_UNKNOWN) { } ProcessMemoryInformation::~ProcessMemoryInformation() {} ProcessData::ProcessData() {} ProcessData::ProcessData(const ProcessData& rhs) : name(rhs.name), process_name(rhs.process_name), processes(rhs.processes) { } ProcessData::~ProcessData() {} ProcessData& ProcessData::operator=(const ProcessData& rhs) { name = rhs.name; process_name = rhs.process_name; processes = rhs.processes; return *this; } // About threading: // // This operation will hit no fewer than 3 threads. // // The ChildProcessInfo::Iterator can only be accessed from the IO thread. // // The RenderProcessHostIterator can only be accessed from the UI thread. // // This operation can take 30-100ms to complete. We never want to have // one task run for that long on the UI or IO threads. So, we run the // expensive parts of this operation over on the file thread. // void MemoryDetails::StartFetch() { DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::FILE)); // In order to process this request, we need to use the plugin information. // However, plugin process information is only available from the IO thread. BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &MemoryDetails::CollectChildInfoOnIOThread)); } MemoryDetails::~MemoryDetails() {} void MemoryDetails::CollectChildInfoOnIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); std::vector<ProcessMemoryInformation> child_info; // Collect the list of child processes. for (BrowserChildProcessHost::Iterator iter; !iter.Done(); ++iter) { ProcessMemoryInformation info; info.pid = base::GetProcId(iter->handle()); if (!info.pid) continue; info.type = iter->type(); info.renderer_type = iter->renderer_type(); info.titles.push_back(WideToUTF16Hack(iter->name())); child_info.push_back(info); } // Now go do expensive memory lookups from the file thread. BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &MemoryDetails::CollectProcessData, child_info)); } void MemoryDetails::CollectChildInfoOnUIThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); #if defined(OS_LINUX) const pid_t zygote_pid = ZygoteHost::GetInstance()->pid(); const pid_t sandbox_helper_pid = RenderSandboxHostLinux::GetInstance()->pid(); #endif ProcessData* const chrome_browser = ChromeBrowser(); // Get more information about the process. for (size_t index = 0; index < chrome_browser->processes.size(); index++) { // Check if it's a renderer, if so get the list of page titles in it and // check if it's a diagnostics-related process. We skip about:memory pages. // Iterate the RenderProcessHosts to find the tab contents. ProcessMemoryInformation& process = chrome_browser->processes[index]; for (RenderProcessHost::iterator renderer_iter( RenderProcessHost::AllHostsIterator()); !renderer_iter.IsAtEnd(); renderer_iter.Advance()) { RenderProcessHost* render_process_host = renderer_iter.GetCurrentValue(); DCHECK(render_process_host); // Ignore processes that don't have a connection, such as crashed tabs. if (!render_process_host->HasConnection() || process.pid != base::GetProcId(render_process_host->GetHandle())) { continue; } process.type = ChildProcessInfo::RENDER_PROCESS; Profile* profile = render_process_host->profile(); ExtensionService* extension_service = profile->GetExtensionService(); // The RenderProcessHost may host multiple TabContents. Any // of them which contain diagnostics information make the whole // process be considered a diagnostics process. // // NOTE: This is a bit dangerous. We know that for now, listeners // are always RenderWidgetHosts. But in theory, they don't // have to be. RenderProcessHost::listeners_iterator iter( render_process_host->ListenersIterator()); for (; !iter.IsAtEnd(); iter.Advance()) { const RenderWidgetHost* widget = static_cast<const RenderWidgetHost*>(iter.GetCurrentValue()); DCHECK(widget); if (!widget || !widget->IsRenderView()) continue; const RenderViewHost* host = static_cast<const RenderViewHost*>(widget); RenderViewHostDelegate* host_delegate = host->delegate(); GURL url = host_delegate->GetURL(); ViewType::Type type = host_delegate->GetRenderViewType(); if (host->enabled_bindings() & BindingsPolicy::DOM_UI) { // TODO(erikkay) the type for devtools doesn't actually appear to // be set. if (type == ViewType::DEV_TOOLS_UI) process.renderer_type = ChildProcessInfo::RENDERER_DEVTOOLS; else process.renderer_type = ChildProcessInfo::RENDERER_CHROME; } else if (host->enabled_bindings() & BindingsPolicy::EXTENSION) { process.renderer_type = ChildProcessInfo::RENDERER_EXTENSION; } TabContents* contents = NULL; if (host_delegate) contents = host_delegate->GetAsTabContents(); if (!contents) { if (host->is_extension_process()) { const Extension* extension = extension_service->GetExtensionByURL(url); if (extension) { string16 title = UTF8ToUTF16(extension->name()); process.titles.push_back(title); } } else if (process.renderer_type == ChildProcessInfo::RENDERER_UNKNOWN) { process.titles.push_back(UTF8ToUTF16(url.spec())); switch (type) { case ViewType::BACKGROUND_CONTENTS: process.renderer_type = ChildProcessInfo::RENDERER_BACKGROUND_APP; break; case ViewType::INTERSTITIAL_PAGE: process.renderer_type = ChildProcessInfo::RENDERER_INTERSTITIAL; break; case ViewType::NOTIFICATION: process.renderer_type = ChildProcessInfo::RENDERER_NOTIFICATION; break; default: process.renderer_type = ChildProcessInfo::RENDERER_UNKNOWN; break; } } continue; } // Since We have a TabContents and and the renderer type hasn't been // set yet, it must be a normal tabbed renderer. if (process.renderer_type == ChildProcessInfo::RENDERER_UNKNOWN) process.renderer_type = ChildProcessInfo::RENDERER_NORMAL; string16 title = contents->GetTitle(); if (!title.length()) title = l10n_util::GetStringUTF16(IDS_DEFAULT_TAB_TITLE); process.titles.push_back(title); // We need to check the pending entry as well as the virtual_url to // see if it's an about:memory URL (we don't want to count these in the // total memory usage of the browser). // // When we reach here, about:memory will be the pending entry since we // haven't responded with any data such that it would be committed. If // you have another about:memory tab open (which would be committed), // we don't want to count it either, so we also check the last committed // entry. // // Either the pending or last committed entries can be NULL. const NavigationEntry* pending_entry = contents->controller().pending_entry(); const NavigationEntry* last_committed_entry = contents->controller().GetLastCommittedEntry(); if ((last_committed_entry && LowerCaseEqualsASCII(last_committed_entry->virtual_url().spec(), chrome::kAboutMemoryURL)) || (pending_entry && LowerCaseEqualsASCII(pending_entry->virtual_url().spec(), chrome::kAboutMemoryURL))) process.is_diagnostics = true; } } #if defined(OS_LINUX) if (process.pid == zygote_pid) { process.type = ChildProcessInfo::ZYGOTE_PROCESS; } else if (process.pid == sandbox_helper_pid) { process.type = ChildProcessInfo::SANDBOX_HELPER_PROCESS; } #endif } // Get rid of other Chrome processes that are from a different profile. for (size_t index = 0; index < chrome_browser->processes.size(); index++) { if (chrome_browser->processes[index].type == ChildProcessInfo::UNKNOWN_PROCESS) { chrome_browser->processes.erase( chrome_browser->processes.begin() + index); index--; } } UpdateHistograms(); OnDetailsAvailable(); } void MemoryDetails::UpdateHistograms() { // Reports a set of memory metrics to UMA. // Memory is measured in KB. const ProcessData& browser = *ChromeBrowser(); size_t aggregate_memory = 0; int chrome_count = 0; int extension_count = 0; int plugin_count = 0; int renderer_count = 0; int other_count = 0; int worker_count = 0; for (size_t index = 0; index < browser.processes.size(); index++) { int sample = static_cast<int>(browser.processes[index].working_set.priv); aggregate_memory += sample; switch (browser.processes[index].type) { case ChildProcessInfo::BROWSER_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.Browser", sample); break; case ChildProcessInfo::RENDER_PROCESS: { ChildProcessInfo::RendererProcessType renderer_type = browser.processes[index].renderer_type; switch (renderer_type) { case ChildProcessInfo::RENDERER_EXTENSION: UMA_HISTOGRAM_MEMORY_KB("Memory.Extension", sample); extension_count++; break; case ChildProcessInfo::RENDERER_CHROME: UMA_HISTOGRAM_MEMORY_KB("Memory.Chrome", sample); chrome_count++; break; case ChildProcessInfo::RENDERER_UNKNOWN: NOTREACHED() << "Unknown renderer process type."; break; case ChildProcessInfo::RENDERER_NORMAL: default: // TODO(erikkay): Should we bother splitting out the other subtypes? UMA_HISTOGRAM_MEMORY_KB("Memory.Renderer", sample); renderer_count++; break; } break; } case ChildProcessInfo::PLUGIN_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.Plugin", sample); plugin_count++; break; case ChildProcessInfo::WORKER_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.Worker", sample); worker_count++; break; case ChildProcessInfo::UTILITY_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.Utility", sample); other_count++; break; case ChildProcessInfo::ZYGOTE_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.Zygote", sample); other_count++; break; case ChildProcessInfo::SANDBOX_HELPER_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.SandboxHelper", sample); other_count++; break; case ChildProcessInfo::NACL_LOADER_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.NativeClient", sample); other_count++; break; case ChildProcessInfo::NACL_BROKER_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.NativeClientBroker", sample); other_count++; break; case ChildProcessInfo::GPU_PROCESS: UMA_HISTOGRAM_MEMORY_KB("Memory.Gpu", sample); other_count++; break; default: NOTREACHED(); } } UMA_HISTOGRAM_MEMORY_KB("Memory.BackingStore", BackingStoreManager::MemorySize() / 1024); UMA_HISTOGRAM_COUNTS_100("Memory.ProcessCount", static_cast<int>(browser.processes.size())); UMA_HISTOGRAM_COUNTS_100("Memory.ChromeProcessCount", chrome_count); UMA_HISTOGRAM_COUNTS_100("Memory.ExtensionProcessCount", extension_count); UMA_HISTOGRAM_COUNTS_100("Memory.OtherProcessCount", other_count); UMA_HISTOGRAM_COUNTS_100("Memory.PluginProcessCount", plugin_count); UMA_HISTOGRAM_COUNTS_100("Memory.RendererProcessCount", renderer_count); UMA_HISTOGRAM_COUNTS_100("Memory.WorkerProcessCount", worker_count); // TODO(viettrungluu): Do we want separate counts for the other // (platform-specific) process types? int total_sample = static_cast<int>(aggregate_memory / 1000); UMA_HISTOGRAM_MEMORY_MB("Memory.Total", total_sample); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/memory_details.h" #include <psapi.h> #include "base/file_version_info.h" #include "base/histogram.h" #include "base/image_util.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_trial.h" #include "chrome/browser/plugin_process_host.h" #include "chrome/browser/plugin_service.h" #include "chrome/browser/render_process_host.h" #include "chrome/browser/render_view_host.h" #include "chrome/browser/tab_contents.h" #include "chrome/browser/web_contents.h" class RenderViewHostDelegate; // Template of static data we use for finding browser process information. // These entries must match the ordering for MemoryDetails::BrowserProcess. static ProcessData g_process_template[] = { { L"Chromium", L"chrome.exe", }, { L"IE", L"iexplore.exe", }, { L"Firefox", L"firefox.exe", }, { L"Opera", L"opera.exe", }, { L"Safari", L"safari.exe", }, }; // About threading: // // This operation will hit no fewer than 3 threads. // // The PluginHostIterator can only be accessed from the IO thread. // // The RenderProcessHostIterator can only be accessed from the UI thread. // // This operation can take 30-100ms to complete. We never want to have // one task run for that long on the UI or IO threads. So, we run the // expensive parts of this operation over on the file thread. // MemoryDetails::MemoryDetails() : ui_loop_(NULL) { for (int index = 0; index < arraysize(g_process_template); ++index) { process_data_[index].name = g_process_template[index].name; process_data_[index].process_name = g_process_template[index].process_name; } } void MemoryDetails::StartFetch() { ui_loop_ = MessageLoop::current(); DCHECK(ui_loop_ != g_browser_process->io_thread()->message_loop()); DCHECK(ui_loop_ != g_browser_process->file_thread()->message_loop()); // In order to process this request, we need to use the plugin information. // However, plugin process information is only available from the IO thread. g_browser_process->io_thread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &MemoryDetails::CollectPluginInformation)); } void MemoryDetails::CollectPluginInformation() { DCHECK(MessageLoop::current() == ChromeThread::GetMessageLoop(ChromeThread::IO)); // Collect the list of plugins. for (PluginProcessHostIterator plugin_iter; !plugin_iter.Done(); ++plugin_iter) { PluginProcessHost* plugin = const_cast<PluginProcessHost*>(*plugin_iter); DCHECK(plugin); if (!plugin || !plugin->process()) continue; PluginProcessInformation info; info.pid = process_util::GetProcId(plugin->process()); if (info.pid != 0) { info.dll_path = plugin->dll_path(); plugins_.push_back(info); } } // Now go do expensive memory lookups from the file thread. ChromeThread::GetMessageLoop(ChromeThread::FILE)->PostTask(FROM_HERE, NewRunnableMethod(this, &MemoryDetails::CollectProcessData)); } void MemoryDetails::CollectProcessData() { DCHECK(MessageLoop::current() == ChromeThread::GetMessageLoop(ChromeThread::FILE)); int array_size = 32; DWORD* process_list = NULL; DWORD bytes_used = 0; do { array_size *= 2; process_list = static_cast<DWORD*>( realloc(process_list, sizeof(*process_list) * array_size)); // EnumProcesses doesn't return an error if the array is too small. // We have to check if the return buffer is full, and if so, call it // again. See msdn docs for more info. if (!EnumProcesses(process_list, array_size * sizeof(*process_list), &bytes_used)) { LOG(ERROR) << "EnumProcesses failed: " << GetLastError(); return; } } while (bytes_used == (array_size * sizeof(*process_list))); int num_processes = bytes_used / sizeof(*process_list); // Clear old data. for (int index = 0; index < arraysize(g_process_template); index++) process_data_[index].processes.clear(); for (int index = 0; index < num_processes; index++) { HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_list[index]); if (handle) { TCHAR name[MAX_PATH]; if (GetModuleBaseName(handle, NULL, name, MAX_PATH-1)) { for (int index2 = 0; index2 < arraysize(g_process_template); index2++) { if (_wcsicmp(process_data_[index2].process_name, name) == 0) { // Get Memory Information. ProcessMemoryInformation info; info.pid = process_list[index]; scoped_ptr<process_util::ProcessMetrics> metrics; metrics.reset( process_util::ProcessMetrics::CreateProcessMetrics(handle)); metrics->GetCommittedKBytes(&info.committed); metrics->GetWorkingSetKBytes(&info.working_set); // Get Version Information. if (index2 == 0) { // Chrome scoped_ptr<FileVersionInfo> version_info( FileVersionInfo::CreateFileVersionInfoForCurrentModule()); if (version_info != NULL) info.version = version_info->file_version(); } else if (GetModuleFileNameEx(handle, NULL, name, MAX_PATH-1)) { std::wstring str_name(name); scoped_ptr<FileVersionInfo> version_info( FileVersionInfo::CreateFileVersionInfo(str_name)); if (version_info != NULL) { info.version = version_info->product_version(); info.product_name = version_info->product_name(); } } // Add the process info to our list. process_data_[index2].processes.push_back(info); break; } } } CloseHandle(handle); } } free(process_list); // Finally return to the browser thread. ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(this, &MemoryDetails::CollectRenderHostInformation)); } void MemoryDetails::CollectRenderHostInformation() { DCHECK(MessageLoop::current() == ui_loop_); // Determine if this is a diagnostics-related process. We skip all // diagnostics pages (e.g. "about:xxx" URLs). Iterate the RenderProcessHosts // to find the tab contents. If it is of type TAB_CONTENTS_ABOUT_UI, mark // the process as diagnostics related. for (size_t index = 0; index < process_data_[CHROME_BROWSER].processes.size(); index++) { RenderProcessHost::iterator renderer_iter; for (renderer_iter = RenderProcessHost::begin(); renderer_iter != RenderProcessHost::end(); ++renderer_iter) { DCHECK(renderer_iter->second); if (process_data_[CHROME_BROWSER].processes[index].pid == renderer_iter->second->pid()) { // The RenderProcessHost may host multiple TabContents. Any // of them which contain diagnostics information make the whole // process be considered a diagnostics process. // // NOTE: This is a bit dangerous. We know that for now, listeners // are always RenderWidgetHosts. But in theory, they don't // have to be. RenderProcessHost::listeners_iterator iter; for (iter = renderer_iter->second->listeners_begin(); iter != renderer_iter->second->listeners_end(); ++iter) { RenderWidgetHost* widget = static_cast<RenderWidgetHost*>(iter->second); DCHECK(widget); if (!widget || !widget->IsRenderView()) continue; RenderViewHost* host = static_cast<RenderViewHost*>(widget); TabContents* contents = static_cast<WebContents*>(host->delegate()); DCHECK(contents); if (!contents) continue; if (contents->type() == TAB_CONTENTS_ABOUT_UI) process_data_[CHROME_BROWSER].processes[index].is_diagnostics = true; } } } } UpdateHistograms(); OnDetailsAvailable(); } void MemoryDetails::UpdateHistograms() { // Reports a set of memory metrics to UMA. // Memory is measured in units of 10KB. // If field trial is active, report results in special histograms. static scoped_refptr<FieldTrial> trial( FieldTrialList::Find(BrowserTrial::kMemoryModelFieldTrial)); DWORD browser_pid = GetCurrentProcessId(); ProcessData browser = process_data_[CHROME_BROWSER]; size_t aggregate_memory = 0; for (size_t index = 0; index < browser.processes.size(); index++) { int sample = static_cast<int>(browser.processes[index].working_set.priv); aggregate_memory += sample; if (browser.processes[index].pid == browser_pid) { if (trial.get()) { if (trial->boolean_value()) UMA_HISTOGRAM_MEMORY_KB(L"Memory.Browser_trial_high_memory", sample); else UMA_HISTOGRAM_MEMORY_KB(L"Memory.Browser_trial_med_memory", sample); } else { UMA_HISTOGRAM_MEMORY_KB(L"Memory.Browser", sample); } } else { bool is_plugin_process = false; for (size_t index2 = 0; index2 < plugins_.size(); index2++) { if (browser.processes[index].pid == plugins_[index2].pid) { UMA_HISTOGRAM_MEMORY_KB(L"Memory.Plugin", sample); is_plugin_process = true; break; } } if (!is_plugin_process) { if (trial.get()) { if (trial->boolean_value()) UMA_HISTOGRAM_MEMORY_KB(L"Memory.Renderer_high_memory", sample); else UMA_HISTOGRAM_MEMORY_KB(L"Memory.Renderer_med_memory", sample); } else { UMA_HISTOGRAM_MEMORY_KB(L"Memory.Renderer", sample); } } } } UMA_HISTOGRAM_COUNTS_100(L"Memory.ProcessCount", static_cast<int>(browser.processes.size())); UMA_HISTOGRAM_COUNTS_100(L"Memory.PluginProcessCount", static_cast<int>(plugins_.size())); int total_sample = static_cast<int>(aggregate_memory / 1000); if (trial.get()) { if (trial->boolean_value()) UMA_HISTOGRAM_MEMORY_MB(L"Memory.Total_trial_high_memory", total_sample); else UMA_HISTOGRAM_MEMORY_MB(L"Memory.Total_trial_med_memory", total_sample); } else { UMA_HISTOGRAM_MEMORY_MB(L"Memory.Total", total_sample); } } <commit_msg>Correct typo in histogram name (I left out the word trial)<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/memory_details.h" #include <psapi.h> #include "base/file_version_info.h" #include "base/histogram.h" #include "base/image_util.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_trial.h" #include "chrome/browser/plugin_process_host.h" #include "chrome/browser/plugin_service.h" #include "chrome/browser/render_process_host.h" #include "chrome/browser/render_view_host.h" #include "chrome/browser/tab_contents.h" #include "chrome/browser/web_contents.h" class RenderViewHostDelegate; // Template of static data we use for finding browser process information. // These entries must match the ordering for MemoryDetails::BrowserProcess. static ProcessData g_process_template[] = { { L"Chromium", L"chrome.exe", }, { L"IE", L"iexplore.exe", }, { L"Firefox", L"firefox.exe", }, { L"Opera", L"opera.exe", }, { L"Safari", L"safari.exe", }, }; // About threading: // // This operation will hit no fewer than 3 threads. // // The PluginHostIterator can only be accessed from the IO thread. // // The RenderProcessHostIterator can only be accessed from the UI thread. // // This operation can take 30-100ms to complete. We never want to have // one task run for that long on the UI or IO threads. So, we run the // expensive parts of this operation over on the file thread. // MemoryDetails::MemoryDetails() : ui_loop_(NULL) { for (int index = 0; index < arraysize(g_process_template); ++index) { process_data_[index].name = g_process_template[index].name; process_data_[index].process_name = g_process_template[index].process_name; } } void MemoryDetails::StartFetch() { ui_loop_ = MessageLoop::current(); DCHECK(ui_loop_ != g_browser_process->io_thread()->message_loop()); DCHECK(ui_loop_ != g_browser_process->file_thread()->message_loop()); // In order to process this request, we need to use the plugin information. // However, plugin process information is only available from the IO thread. g_browser_process->io_thread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &MemoryDetails::CollectPluginInformation)); } void MemoryDetails::CollectPluginInformation() { DCHECK(MessageLoop::current() == ChromeThread::GetMessageLoop(ChromeThread::IO)); // Collect the list of plugins. for (PluginProcessHostIterator plugin_iter; !plugin_iter.Done(); ++plugin_iter) { PluginProcessHost* plugin = const_cast<PluginProcessHost*>(*plugin_iter); DCHECK(plugin); if (!plugin || !plugin->process()) continue; PluginProcessInformation info; info.pid = process_util::GetProcId(plugin->process()); if (info.pid != 0) { info.dll_path = plugin->dll_path(); plugins_.push_back(info); } } // Now go do expensive memory lookups from the file thread. ChromeThread::GetMessageLoop(ChromeThread::FILE)->PostTask(FROM_HERE, NewRunnableMethod(this, &MemoryDetails::CollectProcessData)); } void MemoryDetails::CollectProcessData() { DCHECK(MessageLoop::current() == ChromeThread::GetMessageLoop(ChromeThread::FILE)); int array_size = 32; DWORD* process_list = NULL; DWORD bytes_used = 0; do { array_size *= 2; process_list = static_cast<DWORD*>( realloc(process_list, sizeof(*process_list) * array_size)); // EnumProcesses doesn't return an error if the array is too small. // We have to check if the return buffer is full, and if so, call it // again. See msdn docs for more info. if (!EnumProcesses(process_list, array_size * sizeof(*process_list), &bytes_used)) { LOG(ERROR) << "EnumProcesses failed: " << GetLastError(); return; } } while (bytes_used == (array_size * sizeof(*process_list))); int num_processes = bytes_used / sizeof(*process_list); // Clear old data. for (int index = 0; index < arraysize(g_process_template); index++) process_data_[index].processes.clear(); for (int index = 0; index < num_processes; index++) { HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_list[index]); if (handle) { TCHAR name[MAX_PATH]; if (GetModuleBaseName(handle, NULL, name, MAX_PATH-1)) { for (int index2 = 0; index2 < arraysize(g_process_template); index2++) { if (_wcsicmp(process_data_[index2].process_name, name) == 0) { // Get Memory Information. ProcessMemoryInformation info; info.pid = process_list[index]; scoped_ptr<process_util::ProcessMetrics> metrics; metrics.reset( process_util::ProcessMetrics::CreateProcessMetrics(handle)); metrics->GetCommittedKBytes(&info.committed); metrics->GetWorkingSetKBytes(&info.working_set); // Get Version Information. if (index2 == 0) { // Chrome scoped_ptr<FileVersionInfo> version_info( FileVersionInfo::CreateFileVersionInfoForCurrentModule()); if (version_info != NULL) info.version = version_info->file_version(); } else if (GetModuleFileNameEx(handle, NULL, name, MAX_PATH-1)) { std::wstring str_name(name); scoped_ptr<FileVersionInfo> version_info( FileVersionInfo::CreateFileVersionInfo(str_name)); if (version_info != NULL) { info.version = version_info->product_version(); info.product_name = version_info->product_name(); } } // Add the process info to our list. process_data_[index2].processes.push_back(info); break; } } } CloseHandle(handle); } } free(process_list); // Finally return to the browser thread. ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(this, &MemoryDetails::CollectRenderHostInformation)); } void MemoryDetails::CollectRenderHostInformation() { DCHECK(MessageLoop::current() == ui_loop_); // Determine if this is a diagnostics-related process. We skip all // diagnostics pages (e.g. "about:xxx" URLs). Iterate the RenderProcessHosts // to find the tab contents. If it is of type TAB_CONTENTS_ABOUT_UI, mark // the process as diagnostics related. for (size_t index = 0; index < process_data_[CHROME_BROWSER].processes.size(); index++) { RenderProcessHost::iterator renderer_iter; for (renderer_iter = RenderProcessHost::begin(); renderer_iter != RenderProcessHost::end(); ++renderer_iter) { DCHECK(renderer_iter->second); if (process_data_[CHROME_BROWSER].processes[index].pid == renderer_iter->second->pid()) { // The RenderProcessHost may host multiple TabContents. Any // of them which contain diagnostics information make the whole // process be considered a diagnostics process. // // NOTE: This is a bit dangerous. We know that for now, listeners // are always RenderWidgetHosts. But in theory, they don't // have to be. RenderProcessHost::listeners_iterator iter; for (iter = renderer_iter->second->listeners_begin(); iter != renderer_iter->second->listeners_end(); ++iter) { RenderWidgetHost* widget = static_cast<RenderWidgetHost*>(iter->second); DCHECK(widget); if (!widget || !widget->IsRenderView()) continue; RenderViewHost* host = static_cast<RenderViewHost*>(widget); TabContents* contents = static_cast<WebContents*>(host->delegate()); DCHECK(contents); if (!contents) continue; if (contents->type() == TAB_CONTENTS_ABOUT_UI) process_data_[CHROME_BROWSER].processes[index].is_diagnostics = true; } } } } UpdateHistograms(); OnDetailsAvailable(); } void MemoryDetails::UpdateHistograms() { // Reports a set of memory metrics to UMA. // Memory is measured in units of 10KB. // If field trial is active, report results in special histograms. static scoped_refptr<FieldTrial> trial( FieldTrialList::Find(BrowserTrial::kMemoryModelFieldTrial)); DWORD browser_pid = GetCurrentProcessId(); ProcessData browser = process_data_[CHROME_BROWSER]; size_t aggregate_memory = 0; for (size_t index = 0; index < browser.processes.size(); index++) { int sample = static_cast<int>(browser.processes[index].working_set.priv); aggregate_memory += sample; if (browser.processes[index].pid == browser_pid) { if (trial.get()) { if (trial->boolean_value()) UMA_HISTOGRAM_MEMORY_KB(L"Memory.Browser_trial_high_memory", sample); else UMA_HISTOGRAM_MEMORY_KB(L"Memory.Browser_trial_med_memory", sample); } else { UMA_HISTOGRAM_MEMORY_KB(L"Memory.Browser", sample); } } else { bool is_plugin_process = false; for (size_t index2 = 0; index2 < plugins_.size(); index2++) { if (browser.processes[index].pid == plugins_[index2].pid) { UMA_HISTOGRAM_MEMORY_KB(L"Memory.Plugin", sample); is_plugin_process = true; break; } } if (!is_plugin_process) { if (trial.get()) { if (trial->boolean_value()) UMA_HISTOGRAM_MEMORY_KB(L"Memory.Renderer_trial_high_memory", sample); else UMA_HISTOGRAM_MEMORY_KB(L"Memory.Renderer_trial_med_memory", sample); } else { UMA_HISTOGRAM_MEMORY_KB(L"Memory.Renderer", sample); } } } } UMA_HISTOGRAM_COUNTS_100(L"Memory.ProcessCount", static_cast<int>(browser.processes.size())); UMA_HISTOGRAM_COUNTS_100(L"Memory.PluginProcessCount", static_cast<int>(plugins_.size())); int total_sample = static_cast<int>(aggregate_memory / 1000); if (trial.get()) { if (trial->boolean_value()) UMA_HISTOGRAM_MEMORY_MB(L"Memory.Total_trial_high_memory", total_sample); else UMA_HISTOGRAM_MEMORY_MB(L"Memory.Total_trial_med_memory", total_sample); } else { UMA_HISTOGRAM_MEMORY_MB(L"Memory.Total", total_sample); } } <|endoftext|>
<commit_before>#include <TSR.h> #include <Eigen/Geometry> #include <ompl/util/RandomNumbers.h> #include <vector> using namespace or_ompl; TSR::TSR() : _initialized(false) { } TSR::TSR(const Eigen::Affine3d &T0_w, const Eigen::Affine3d &Tw_e, const Eigen::Matrix<double, 6, 2> &Bw) : _T0_w(T0_w), _Tw_e(Tw_e), _Bw(Bw), _initialized(true) { _T0_w_inv = _T0_w.inverse(); _Tw_e_inv = _Tw_e.inverse(); } bool TSR::deserialize(std::stringstream &ss) { // TODO: Do we need this stuff? int manipind_ignored; ss >> manipind_ignored; std::string relativebodyname_ignored; ss >> relativebodyname_ignored; if( relativebodyname_ignored != "NULL" ) { std::string relativelinkname_ignored; ss >> relativelinkname_ignored; } // Read in the T0_w matrix - serialized as OpenRAVE // q.x, q.y, q.z, q.w - switch it the the // Eigen convention double or_x, or_y, or_z, or_w; ss >> or_x; ss >> or_y; ss >> or_z; ss >> or_w; Eigen::Quaterniond T0_w_quat(or_w, or_x, or_y, or_z); std::cout << "Quat: " << T0_w_quat.matrix() << std::endl; ss >> or_x; ss >> or_y; ss >> or_z; Eigen::Vector3d T0_w_trans(or_x, or_y, or_z); std::cout << "Trans: " << T0_w_trans << std::endl; _T0_w = Eigen::Translation<double,3>(T0_w_trans) * T0_w_quat; ss >> or_x; ss >> or_y; ss >> or_z; ss >> or_w; Eigen::Quaterniond Tw_e_quat(or_w, or_x, or_y, or_z); ss >> or_x; ss >> or_y; ss >> or_z; Eigen::Vector3d Tw_e_trans(or_x, or_y, or_z); _T0_w = Eigen::Translation<double,3>(Tw_e_trans) * Tw_e_quat; ss >> _Bw(0,0); ss >> _Bw(0,1); ss >> _Bw(1,0); ss >> _Bw(1,1); ss >> _Bw(2,0); ss >> _Bw(2,1); ss >> _Bw(3,0); ss >> _Bw(3,1); ss >> _Bw(4,0); ss >> _Bw(4,1); ss >> _Bw(5,0); ss >> _Bw(5,1); _T0_w_inv = _T0_w.inverse(); _Tw_e_inv = _Tw_e.inverse(); _initialized = true; std::cout << "T0_w: " << _T0_w.matrix() << std::endl; std::cout << "Tw_e: " << _Tw_e.matrix() << std::endl; std::cout << "Bw: " << _Bw.matrix() << std::endl; return _initialized; } Eigen::Matrix<double, 6, 1> TSR::distance(const Eigen::Affine3d &ee_pose) const { Eigen::Matrix<double, 6, 1> dist = Eigen::Matrix<double, 6, 1>::Zero(); // First compute the pose of the w frame in world coordinates, given the ee_pose Eigen::Affine3d w_in_world = ee_pose * _Tw_e_inv; // Next compute the pose of the w frame relative to its original pose (as specified by T0_w) Eigen::Affine3d w_offset = _T0_w_inv * w_in_world; // Now compute the elements of the distance matrix dist(0,0) = w_offset.translation()(0); dist(1,0) = w_offset.translation()(1); dist(2,0) = w_offset.translation()(2); dist(3,0) = atan2(w_offset.rotation()(2,1), w_offset.rotation()(2,2)); dist(4,0) = -asin(w_offset.rotation()(2,0)); dist(5,0) = atan2(w_offset.rotation()(1,0), w_offset.rotation()(0,0)); return dist; } Eigen::Matrix<double, 6, 1> TSR::displacement(const Eigen::Affine3d &ee_pose) const { Eigen::Matrix<double, 6, 1> dist = distance(ee_pose); Eigen::Matrix<double, 6, 1> disp = Eigen::Matrix<double, 6, 1>::Zero(); for(unsigned int idx=0; idx < 6; idx++){ if(dist(idx,0) < _Bw(idx,0)){ disp(idx,0) = dist(idx,0) - _Bw(idx,0); }else if(dist(idx,0) > _Bw(idx,1)){ disp(idx,0) = dist(idx,0) - _Bw(idx,1); } } return disp; } Eigen::Affine3d TSR::sample(void) const { // First sample uniformly betwee each of the bounds of Bw std::vector<double> d_sample(6); ompl::RNG rng; for(unsigned int idx=0; idx < d_sample.size(); idx++){ if(_Bw(idx,1) > _Bw(idx,0)){ d_sample[idx] = rng.uniformReal(_Bw(idx,0), _Bw(idx,1)); } } Eigen::Affine3d return_tf; return_tf.translation() << d_sample[0], d_sample[1], d_sample[2]; // Convert to a transform matrix double roll = d_sample[3]; double pitch = d_sample[4]; double yaw = d_sample[5]; double A = cos(yaw); double B = sin(yaw); double C = cos(pitch); double D = sin(pitch); double E = cos(roll); double F = sin(roll); return_tf.linear() << A*C, A*D*F - B*E, B*F + A*D*E, B*C, A*E + B*D*F, B*D*E - A*F, -D, C*F, C*E; return _T0_w * return_tf * _Tw_e; } <commit_msg>Deserialization working<commit_after>#include <TSR.h> #include <Eigen/Geometry> #include <ompl/util/RandomNumbers.h> #include <vector> using namespace or_ompl; TSR::TSR() : _initialized(false) { } TSR::TSR(const Eigen::Affine3d &T0_w, const Eigen::Affine3d &Tw_e, const Eigen::Matrix<double, 6, 2> &Bw) : _T0_w(T0_w), _Tw_e(Tw_e), _Bw(Bw), _initialized(true) { _T0_w_inv = _T0_w.inverse(); _Tw_e_inv = _Tw_e.inverse(); } bool TSR::deserialize(std::stringstream &ss) { // TODO: Do we need this stuff? int manipind_ignored; ss >> manipind_ignored; std::string relativebodyname_ignored; ss >> relativebodyname_ignored; if( relativebodyname_ignored != "NULL" ) { std::string relativelinkname_ignored; ss >> relativelinkname_ignored; } // Read in the T0_w matrix double tmp; for(unsigned int c=0; c < 3; c++){ for(unsigned int r=0; r < 3; r++){ ss >> tmp; _T0_w.matrix()(r,c) = tmp; } } for(unsigned int idx=0; idx < 3; idx++){ ss >> tmp; _T0_w.translation()(idx) = tmp; } // Read in the Tw_e matrix for(unsigned int c=0; c < 3; c++){ for(unsigned int r=0; r < 3; r++){ ss >> tmp; _Tw_e.matrix()(r,c) = tmp; } } for(unsigned int idx=0; idx < 3; idx++){ ss >> tmp; _Tw_e.translation()(idx) = tmp; } // Read in the Bw matrix for(unsigned int r=0; r < 6; r++){ for(unsigned int c=0; c < 2; c++){ ss >> tmp; _Bw(r,c) = tmp; } } _T0_w_inv = _T0_w.inverse(); _Tw_e_inv = _Tw_e.inverse(); _initialized = true; return _initialized; } Eigen::Matrix<double, 6, 1> TSR::distance(const Eigen::Affine3d &ee_pose) const { Eigen::Matrix<double, 6, 1> dist = Eigen::Matrix<double, 6, 1>::Zero(); // First compute the pose of the w frame in world coordinates, given the ee_pose Eigen::Affine3d w_in_world = ee_pose * _Tw_e_inv; // Next compute the pose of the w frame relative to its original pose (as specified by T0_w) Eigen::Affine3d w_offset = _T0_w_inv * w_in_world; // Now compute the elements of the distance matrix dist(0,0) = w_offset.translation()(0); dist(1,0) = w_offset.translation()(1); dist(2,0) = w_offset.translation()(2); dist(3,0) = atan2(w_offset.rotation()(2,1), w_offset.rotation()(2,2)); dist(4,0) = -asin(w_offset.rotation()(2,0)); dist(5,0) = atan2(w_offset.rotation()(1,0), w_offset.rotation()(0,0)); return dist; } Eigen::Matrix<double, 6, 1> TSR::displacement(const Eigen::Affine3d &ee_pose) const { Eigen::Matrix<double, 6, 1> dist = distance(ee_pose); Eigen::Matrix<double, 6, 1> disp = Eigen::Matrix<double, 6, 1>::Zero(); for(unsigned int idx=0; idx < 6; idx++){ if(dist(idx,0) < _Bw(idx,0)){ disp(idx,0) = dist(idx,0) - _Bw(idx,0); }else if(dist(idx,0) > _Bw(idx,1)){ disp(idx,0) = dist(idx,0) - _Bw(idx,1); } } return disp; } Eigen::Affine3d TSR::sample(void) const { // First sample uniformly betwee each of the bounds of Bw std::vector<double> d_sample(6); ompl::RNG rng; for(unsigned int idx=0; idx < d_sample.size(); idx++){ if(_Bw(idx,1) > _Bw(idx,0)){ d_sample[idx] = rng.uniformReal(_Bw(idx,0), _Bw(idx,1)); } } Eigen::Affine3d return_tf; return_tf.translation() << d_sample[0], d_sample[1], d_sample[2]; // Convert to a transform matrix double roll = d_sample[3]; double pitch = d_sample[4]; double yaw = d_sample[5]; double A = cos(yaw); double B = sin(yaw); double C = cos(pitch); double D = sin(pitch); double E = cos(roll); double F = sin(roll); return_tf.linear() << A*C, A*D*F - B*E, B*F + A*D*E, B*C, A*E + B*D*F, B*D*E - A*F, -D, C*F, C*E; return _T0_w * return_tf * _Tw_e; } <|endoftext|>
<commit_before>/* RTcmix - Copyright (C) 2004 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ /* Write a basic .rtcmixrc file in the user's home directory. -JGG, 7/1/04 */ #include <Option.h> #include <stdio.h> #include <unistd.h> #include "../src/control/midi/portmidi/pm_common/portmidi.h" /* We make our own warn function so that we don't have to pull in more RTcmix code. This must have the same signature as the real one in message.c. It doesn't print WARNING ***, though. */ #include <stdarg.h> #define BUFSIZE 1024 extern "C" { void warn(const char *inst_name, const char *format, ...) { // ignore inst_name char buf[BUFSIZE]; va_list args; va_start(args, format); vsnprintf(buf, BUFSIZE, format, args); va_end(args); fprintf(stderr, "\n%s\n\n", buf); } } // extern "C" int chooseMIDIDevice() { int status = 0; #if defined(MACOSX) || defined(ALSA) Pm_Initialize(); const int numdev = Pm_CountDevices(); bool hasinputdev = false; for (int id = 0; id < numdev; id++) { const PmDeviceInfo *info = Pm_GetDeviceInfo(id); if (info->input) { hasinputdev = true; break; } } if (hasinputdev) { printf("\nHere are the names of MIDI input devices in your system...\n\n" "\tID\tName\n" "----------------------------------------------------------\n"); for (int id = 0; id < numdev; id++) { const PmDeviceInfo *info = Pm_GetDeviceInfo(id); if (info->input) printf("\t%d\t\"%s\"\n", id, info->name); } printf("\nEnter the ID number of one of the listed devices...\n"); bool trying = true; while (trying) { int chosenID; if (scanf("%d", &chosenID) == 1) { const PmDeviceInfo *info = Pm_GetDeviceInfo(chosenID); if (info != NULL && info->input) { Option::midiInDevice(info->name); trying = false; } else printf("The number you typed was not one of the listed ID " "numbers. Try again...\n"); } else { trying = false; } } } else printf("NOTE: Your system appears to have no MIDI input devices.\n"); Pm_Terminate(); #else // !defined(MACOSX) && !defined(ALSA) printf("NOTE: MIDI not supported on your platform.\n"); #endif return status; } int main() { Option::init(); if (chooseMIDIDevice() != 0) exit(1); if (Option::writeConfigFile(Option::rcName()) != 0) return -1; printf("Configuration file \"%s\" successfully written.\n", Option::rcName()); return 0; } <commit_msg>Reorg; add future MIDI output dev support; prepare for audio dev support.<commit_after>/* RTcmix - Copyright (C) 2005 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ // Write a basic .rtcmixrc file in the user's home directory. // -JGG, 7/1/04; rev. for MIDI/audio devices, 7/29/05. #include <Option.h> #include <stdio.h> #include "../src/control/midi/portmidi/pm_common/portmidi.h" // We make our own warn function so that we don't have to pull in more // RTcmix code. This must have the same signature as the real one in // message.c. It doesn't print WARNING ***, though. #include <stdarg.h> #define BUFSIZE 1024 extern "C" { void warn(const char *inst_name, const char *format, ...) { // ignore inst_name char buf[BUFSIZE]; va_list args; va_start(args, format); vsnprintf(buf, BUFSIZE, format, args); va_end(args); fprintf(stderr, "\n%s\n\n", buf); } } // extern "C" int chooseAudioDevices() { return 0; } #if defined(MACOSX) || defined(ALSA) void makeMIDIChoice(const PmDeviceInfo *info[], const int numDevices, const bool input) { const char *direction = input ? "input" : "output"; printf("\nHere are the names of MIDI %s devices in your system...\n\n" "\tID\tName\n" "----------------------------------------------------------\n", direction); for (int id = 0; id < numDevices; id++) { if (info[id] != NULL) { if ((input && info[id]->input) || (!input && info[id]->output)) printf("\t%d\t\"%s\"\n", id, info[id]->name); } } printf("\nEnter the ID number of one of the listed devices...\n"); bool trying = true; while (trying) { int chosenID; if (scanf("%d", &chosenID) == 1) { if (chosenID >= 0 && chosenID < numDevices && info[chosenID] != NULL) { if (input && info[chosenID]->input) { Option::midiInDevice(info[chosenID]->name); trying = false; } else if (!input && info[chosenID]->output) { Option::midiOutDevice(info[chosenID]->name); trying = false; } } else printf("The number you typed was not one of the listed ID " "numbers. Try again...\n"); } else { trying = false; } } } int chooseMIDIDevices() { int status = 0; Pm_Initialize(); const int numdev = Pm_CountDevices(); const PmDeviceInfo *info[numdev]; bool hasinputdev = false; bool hasoutputdev = false; for (int id = 0; id < numdev; id++) { info[id] = Pm_GetDeviceInfo(id); if (info[id] != NULL) { if (info[id]->input) hasinputdev = true; else if (info[id]->output) hasoutputdev = true; } } if (hasinputdev) makeMIDIChoice(info, numdev, true); else printf("NOTE: Your system appears to have no MIDI input devices.\n"); #ifdef NOTYET // XXX we don't support MIDI output yet if (hasoutputdev) makeMIDIChoice(info, numdev, false); else printf("NOTE: Your system appears to have no MIDI output devices.\n"); #endif Pm_Terminate(); return status; } #else // !defined(MACOSX) && !defined(ALSA) int chooseMIDIDevices() { printf("NOTE: MIDI not supported on your platform.\n"); return 0; } #endif int main() { Option::init(); if (chooseAudioDevices() != 0) return -1; if (chooseMIDIDevices() != 0) return -1; if (Option::writeConfigFile(Option::rcName()) != 0) return -1; printf("Configuration file \"%s\" successfully written.\n", Option::rcName()); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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. // This file provides the embedder's side of random webkit glue functions. #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #include <wininet.h> #endif #include "base/clipboard.h" #include "base/command_line.h" #include "base/scoped_clipboard_writer.h" #include "base/string_util.h" #include "chrome/renderer/net/render_dns_master.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/resource_bundle.h" #include "chrome/common/render_messages.h" #include "chrome/plugin/npobject_util.h" #include "chrome/renderer/render_view.h" #include "chrome/renderer/visitedlink_slave.h" #include "googleurl/src/url_util.h" #include "net/base/mime_util.h" #include "net/base/net_errors.h" #include "webkit/glue/scoped_clipboard_writer_glue.h" #include "webkit/glue/webframe.h" #include "webkit/glue/webkit_glue.h" #include <vector> #include "SkBitmap.h" #if defined(OS_WIN) #include <strsafe.h> // note: per msdn docs, this must *follow* other includes #endif template <typename T, size_t stack_capacity> class ResizableStackArray { public: ResizableStackArray() : cur_buffer_(stack_buffer_), cur_capacity_(stack_capacity) { } ~ResizableStackArray() { FreeHeap(); } T* get() const { return cur_buffer_; } T& operator[](size_t i) { return cur_buffer_[i]; } size_t capacity() const { return cur_capacity_; } void Resize(size_t new_size) { if (new_size < cur_capacity_) return; // already big enough FreeHeap(); cur_capacity_ = new_size; cur_buffer_ = new T[new_size]; } private: // Resets the heap buffer, if any void FreeHeap() { if (cur_buffer_ != stack_buffer_) { delete[] cur_buffer_; cur_buffer_ = stack_buffer_; cur_capacity_ = stack_capacity; } } T stack_buffer_[stack_capacity]; T* cur_buffer_; size_t cur_capacity_; }; #if defined(OS_WIN) // This definition of WriteBitmap uses shared memory to communicate across // processes. void ScopedClipboardWriterGlue::WriteBitmap(const SkBitmap& bitmap) { // do not try to write a bitmap more than once if (shared_buf_) return; size_t buf_size = bitmap.getSize(); gfx::Size size(bitmap.width(), bitmap.height()); // Allocate a shared memory buffer to hold the bitmap bits shared_buf_ = RenderProcess::AllocSharedMemory(buf_size); if (!shared_buf_ || !shared_buf_->Map(buf_size)) { NOTREACHED(); return; } // Copy the bits into shared memory SkAutoLockPixels bitmap_lock(bitmap); memcpy(shared_buf_->memory(), bitmap.getPixels(), buf_size); shared_buf_->Unmap(); Clipboard::ObjectMapParam param1, param2; base::SharedMemoryHandle smh = shared_buf_->handle(); const char* shared_handle = reinterpret_cast<const char*>(&smh); for (size_t i = 0; i < sizeof base::SharedMemoryHandle; i++) param1.push_back(shared_handle[i]); const char* size_data = reinterpret_cast<const char*>(&size); for (size_t i = 0; i < sizeof gfx::Size; i++) param2.push_back(size_data[i]); Clipboard::ObjectMapParams params; params.push_back(param1); params.push_back(param2); objects_[Clipboard::CBF_SMBITMAP] = params; } #endif // Define a destructor that makes IPCs to flush the contents to the // system clipboard. ScopedClipboardWriterGlue::~ScopedClipboardWriterGlue() { if (objects_.empty()) return; #if defined(OS_WIN) if (shared_buf_) { g_render_thread->Send( new ViewHostMsg_ClipboardWriteObjectsSync(objects_)); RenderProcess::FreeSharedMemory(shared_buf_); return; } #endif g_render_thread->Send( new ViewHostMsg_ClipboardWriteObjectsAsync(objects_)); } namespace webkit_glue { bool IsMediaPlayerAvailable() { return CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableVideo); } void PrefetchDns(const std::string& hostname) { if (!hostname.empty()) DnsPrefetchCString(hostname.c_str(), hostname.length()); } void PrecacheUrl(const wchar_t* url, int url_length) { // TBD: jar: Need implementation that loads the targetted URL into our cache. // For now, at least prefetch DNS lookup GURL parsed_url(WideToUTF8(std::wstring(url, url_length))); PrefetchDns(parsed_url.host()); } void AppendToLog(const char* file, int line, const char* msg) { logging::LogMessage(file, line).stream() << msg; } bool GetMimeTypeFromExtension(const std::wstring &ext, std::string *mime_type) { if (IsPluginProcess()) return net::GetMimeTypeFromExtension(ext, mime_type); // The sandbox restricts our access to the registry, so we need to proxy // these calls over to the browser process. DCHECK(mime_type->empty()); g_render_thread->Send( new ViewHostMsg_GetMimeTypeFromExtension(ext, mime_type)); return !mime_type->empty(); } bool GetMimeTypeFromFile(const std::wstring &file_path, std::string *mime_type) { if (IsPluginProcess()) return net::GetMimeTypeFromFile(file_path, mime_type); // The sandbox restricts our access to the registry, so we need to proxy // these calls over to the browser process. DCHECK(mime_type->empty()); g_render_thread->Send( new ViewHostMsg_GetMimeTypeFromFile(file_path, mime_type)); return !mime_type->empty(); } bool GetPreferredExtensionForMimeType(const std::string& mime_type, std::wstring* ext) { if (IsPluginProcess()) return net::GetPreferredExtensionForMimeType(mime_type, ext); // The sandbox restricts our access to the registry, so we need to proxy // these calls over to the browser process. DCHECK(ext->empty()); g_render_thread->Send( new ViewHostMsg_GetPreferredExtensionForMimeType(mime_type, ext)); return !ext->empty(); } std::string GetDataResource(int resource_id) { return ResourceBundle::GetSharedInstance().GetDataResource(resource_id); } SkBitmap* GetBitmapResource(int resource_id) { return ResourceBundle::GetSharedInstance().GetBitmapNamed(resource_id); } #if defined(OS_WIN) HCURSOR LoadCursor(int cursor_id) { return ResourceBundle::GetSharedInstance().LoadCursor(cursor_id); } #endif // Clipboard glue Clipboard* ClipboardGetClipboard(){ return NULL; } #if defined(OS_LINUX) // TODO(port): This should replace the method below (the unsigned int is a // windows type). We may need to convert the type of format so it can be sent // over IPC. bool ClipboardIsFormatAvailable(Clipboard::FormatType format) { NOTIMPLEMENTED(); return false; } #endif bool ClipboardIsFormatAvailable(unsigned int format) { bool result; g_render_thread->Send( new ViewHostMsg_ClipboardIsFormatAvailable(format, &result)); return result; } void ClipboardReadText(std::wstring* result) { g_render_thread->Send(new ViewHostMsg_ClipboardReadText(result)); } void ClipboardReadAsciiText(std::string* result) { g_render_thread->Send(new ViewHostMsg_ClipboardReadAsciiText(result)); } void ClipboardReadHTML(std::wstring* markup, GURL* url) { g_render_thread->Send(new ViewHostMsg_ClipboardReadHTML(markup, url)); } GURL GetInspectorURL() { return GURL("chrome-ui://inspector/inspector.html"); } std::string GetUIResourceProtocol() { return "chrome"; } bool GetPlugins(bool refresh, std::vector<WebPluginInfo>* plugins) { return g_render_thread->Send( new ViewHostMsg_GetPlugins(refresh, plugins)); } #if defined(OS_WIN) bool EnsureFontLoaded(HFONT font) { LOGFONT logfont; GetObject(font, sizeof(LOGFONT), &logfont); return g_render_thread->Send(new ViewHostMsg_LoadFont(logfont)); } #endif webkit_glue::ScreenInfo GetScreenInfo(gfx::NativeViewId window) { webkit_glue::ScreenInfo results; g_render_thread->Send( new ViewHostMsg_GetScreenInfo(window, &results)); return results; } uint64 VisitedLinkHash(const char* canonical_url, size_t length) { return g_render_thread->visited_link_slave()->ComputeURLFingerprint( canonical_url, length); } bool IsLinkVisited(uint64 link_hash) { return g_render_thread->visited_link_slave()->IsVisited(link_hash); } int ResolveProxyFromRenderThread(const GURL& url, std::string* proxy_result) { // Send a synchronous IPC from renderer process to the browser process to // resolve the proxy. (includes --single-process case). int net_error; bool ipc_ok = g_render_thread->Send( new ViewHostMsg_ResolveProxy(url, &net_error, proxy_result)); return ipc_ok ? net_error : net::ERR_UNEXPECTED; } #ifndef USING_SIMPLE_RESOURCE_LOADER_BRIDGE // Each RenderView has a ResourceDispatcher. In unit tests, this function may // not work properly since there may be a ResourceDispatcher w/o a RenderView. // The WebView's delegate may be null, which typically happens as a WebView is // being closed (but it is also possible that it could be null at other times // since WebView has a SetDelegate method). static ResourceDispatcher* GetResourceDispatcher(WebFrame* frame) { WebViewDelegate* d = frame->GetView()->GetDelegate(); return d ? static_cast<RenderView*>(d)->resource_dispatcher() : NULL; } // static factory function ResourceLoaderBridge* ResourceLoaderBridge::Create( WebFrame* webframe, const std::string& method, const GURL& url, const GURL& policy_url, const GURL& referrer, const std::string& headers, int load_flags, int origin_pid, ResourceType::Type resource_type, bool mixed_content) { // TODO(darin): we need to eliminate the webframe parameter because webkit // does not always supply it (see ResourceHandle::loadResourceSynchronously). // Instead we should add context to ResourceRequest, which will be easy to do // once we merge to the latest WebKit (r23806 at least). if (!webframe) { NOTREACHED() << "no webframe"; return NULL; } ResourceDispatcher* dispatcher = GetResourceDispatcher(webframe); if (!dispatcher) { DLOG(WARNING) << "no resource dispatcher"; return NULL; } return dispatcher->CreateBridge(method, url, policy_url, referrer, headers, load_flags, origin_pid, resource_type, mixed_content, 0); } void SetCookie(const GURL& url, const GURL& policy_url, const std::string& cookie) { g_render_thread->Send(new ViewHostMsg_SetCookie(url, policy_url, cookie)); } std::string GetCookies(const GURL& url, const GURL& policy_url) { std::string cookies; g_render_thread->Send(new ViewHostMsg_GetCookies(url, policy_url, &cookies)); return cookies; } void NotifyCacheStats() { // Update the browser about our cache // NOTE: Since this can be called from the plugin process, we might not have // a RenderThread. Do nothing in that case. if (g_render_thread) g_render_thread->InformHostOfCacheStatsLater(); } #endif // !USING_SIMPLE_RESOURCE_LOADER_BRIDGE } // namespace webkit_glue <commit_msg>POSIX: fix renderer crash<commit_after>// Copyright (c) 2006-2008 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. // This file provides the embedder's side of random webkit glue functions. #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #include <wininet.h> #endif #include "base/clipboard.h" #include "base/command_line.h" #include "base/scoped_clipboard_writer.h" #include "base/string_util.h" #include "chrome/renderer/net/render_dns_master.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/resource_bundle.h" #include "chrome/common/render_messages.h" #include "chrome/plugin/npobject_util.h" #include "chrome/renderer/render_view.h" #include "chrome/renderer/visitedlink_slave.h" #include "googleurl/src/url_util.h" #include "net/base/mime_util.h" #include "net/base/net_errors.h" #include "webkit/glue/scoped_clipboard_writer_glue.h" #include "webkit/glue/webframe.h" #include "webkit/glue/webkit_glue.h" #include <vector> #include "SkBitmap.h" #if defined(OS_WIN) #include <strsafe.h> // note: per msdn docs, this must *follow* other includes #endif template <typename T, size_t stack_capacity> class ResizableStackArray { public: ResizableStackArray() : cur_buffer_(stack_buffer_), cur_capacity_(stack_capacity) { } ~ResizableStackArray() { FreeHeap(); } T* get() const { return cur_buffer_; } T& operator[](size_t i) { return cur_buffer_[i]; } size_t capacity() const { return cur_capacity_; } void Resize(size_t new_size) { if (new_size < cur_capacity_) return; // already big enough FreeHeap(); cur_capacity_ = new_size; cur_buffer_ = new T[new_size]; } private: // Resets the heap buffer, if any void FreeHeap() { if (cur_buffer_ != stack_buffer_) { delete[] cur_buffer_; cur_buffer_ = stack_buffer_; cur_capacity_ = stack_capacity; } } T stack_buffer_[stack_capacity]; T* cur_buffer_; size_t cur_capacity_; }; #if defined(OS_WIN) // This definition of WriteBitmap uses shared memory to communicate across // processes. void ScopedClipboardWriterGlue::WriteBitmap(const SkBitmap& bitmap) { // do not try to write a bitmap more than once if (shared_buf_) return; size_t buf_size = bitmap.getSize(); gfx::Size size(bitmap.width(), bitmap.height()); // Allocate a shared memory buffer to hold the bitmap bits shared_buf_ = RenderProcess::AllocSharedMemory(buf_size); if (!shared_buf_ || !shared_buf_->Map(buf_size)) { NOTREACHED(); return; } // Copy the bits into shared memory SkAutoLockPixels bitmap_lock(bitmap); memcpy(shared_buf_->memory(), bitmap.getPixels(), buf_size); shared_buf_->Unmap(); Clipboard::ObjectMapParam param1, param2; base::SharedMemoryHandle smh = shared_buf_->handle(); const char* shared_handle = reinterpret_cast<const char*>(&smh); for (size_t i = 0; i < sizeof base::SharedMemoryHandle; i++) param1.push_back(shared_handle[i]); const char* size_data = reinterpret_cast<const char*>(&size); for (size_t i = 0; i < sizeof gfx::Size; i++) param2.push_back(size_data[i]); Clipboard::ObjectMapParams params; params.push_back(param1); params.push_back(param2); objects_[Clipboard::CBF_SMBITMAP] = params; } #endif // Define a destructor that makes IPCs to flush the contents to the // system clipboard. ScopedClipboardWriterGlue::~ScopedClipboardWriterGlue() { if (objects_.empty()) return; #if defined(OS_WIN) if (shared_buf_) { g_render_thread->Send( new ViewHostMsg_ClipboardWriteObjectsSync(objects_)); RenderProcess::FreeSharedMemory(shared_buf_); return; } #endif g_render_thread->Send( new ViewHostMsg_ClipboardWriteObjectsAsync(objects_)); } namespace webkit_glue { bool IsMediaPlayerAvailable() { return CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableVideo); } void PrefetchDns(const std::string& hostname) { if (!hostname.empty()) DnsPrefetchCString(hostname.c_str(), hostname.length()); } void PrecacheUrl(const wchar_t* url, int url_length) { // TBD: jar: Need implementation that loads the targetted URL into our cache. // For now, at least prefetch DNS lookup GURL parsed_url(WideToUTF8(std::wstring(url, url_length))); PrefetchDns(parsed_url.host()); } void AppendToLog(const char* file, int line, const char* msg) { logging::LogMessage(file, line).stream() << msg; } bool GetMimeTypeFromExtension(const std::wstring &ext, std::string *mime_type) { if (IsPluginProcess()) return net::GetMimeTypeFromExtension(ext, mime_type); // The sandbox restricts our access to the registry, so we need to proxy // these calls over to the browser process. DCHECK(mime_type->empty()); g_render_thread->Send( new ViewHostMsg_GetMimeTypeFromExtension(ext, mime_type)); return !mime_type->empty(); } bool GetMimeTypeFromFile(const std::wstring &file_path, std::string *mime_type) { if (IsPluginProcess()) return net::GetMimeTypeFromFile(file_path, mime_type); // The sandbox restricts our access to the registry, so we need to proxy // these calls over to the browser process. DCHECK(mime_type->empty()); g_render_thread->Send( new ViewHostMsg_GetMimeTypeFromFile(file_path, mime_type)); return !mime_type->empty(); } bool GetPreferredExtensionForMimeType(const std::string& mime_type, std::wstring* ext) { if (IsPluginProcess()) return net::GetPreferredExtensionForMimeType(mime_type, ext); // The sandbox restricts our access to the registry, so we need to proxy // these calls over to the browser process. DCHECK(ext->empty()); g_render_thread->Send( new ViewHostMsg_GetPreferredExtensionForMimeType(mime_type, ext)); return !ext->empty(); } std::string GetDataResource(int resource_id) { return ResourceBundle::GetSharedInstance().GetDataResource(resource_id); } SkBitmap* GetBitmapResource(int resource_id) { return ResourceBundle::GetSharedInstance().GetBitmapNamed(resource_id); } #if defined(OS_WIN) HCURSOR LoadCursor(int cursor_id) { return ResourceBundle::GetSharedInstance().LoadCursor(cursor_id); } #endif // Clipboard glue Clipboard* ClipboardGetClipboard(){ return NULL; } #if defined(OS_LINUX) // TODO(port): This should replace the method below (the unsigned int is a // windows type). We may need to convert the type of format so it can be sent // over IPC. bool ClipboardIsFormatAvailable(Clipboard::FormatType format) { NOTIMPLEMENTED(); return false; } #endif bool ClipboardIsFormatAvailable(unsigned int format) { bool result; g_render_thread->Send( new ViewHostMsg_ClipboardIsFormatAvailable(format, &result)); return result; } void ClipboardReadText(std::wstring* result) { g_render_thread->Send(new ViewHostMsg_ClipboardReadText(result)); } void ClipboardReadAsciiText(std::string* result) { g_render_thread->Send(new ViewHostMsg_ClipboardReadAsciiText(result)); } void ClipboardReadHTML(std::wstring* markup, GURL* url) { g_render_thread->Send(new ViewHostMsg_ClipboardReadHTML(markup, url)); } GURL GetInspectorURL() { return GURL("chrome-ui://inspector/inspector.html"); } std::string GetUIResourceProtocol() { return "chrome"; } bool GetPlugins(bool refresh, std::vector<WebPluginInfo>* plugins) { return g_render_thread->Send( new ViewHostMsg_GetPlugins(refresh, plugins)); } #if defined(OS_WIN) bool EnsureFontLoaded(HFONT font) { LOGFONT logfont; GetObject(font, sizeof(LOGFONT), &logfont); return g_render_thread->Send(new ViewHostMsg_LoadFont(logfont)); } #endif webkit_glue::ScreenInfo GetScreenInfo(gfx::NativeViewId window) { webkit_glue::ScreenInfo results; g_render_thread->Send( new ViewHostMsg_GetScreenInfo(window, &results)); return results; } uint64 VisitedLinkHash(const char* canonical_url, size_t length) { return g_render_thread->visited_link_slave()->ComputeURLFingerprint( canonical_url, length); } bool IsLinkVisited(uint64 link_hash) { #if defined(OS_WIN) return g_render_thread->visited_link_slave()->IsVisited(link_hash); #elif defined(OS_POSIX) // TODO(port): Currently we don't have a HistoryService. This stops the // VisitiedLinkMaster from sucessfully calling Init(). In that case, no // message is ever sent to the renderer with the VisitiedLink shared memory // region and we end up crashing with SIGFPE as we try to hash by taking a // fingerprint mod 0. return false; #endif } int ResolveProxyFromRenderThread(const GURL& url, std::string* proxy_result) { // Send a synchronous IPC from renderer process to the browser process to // resolve the proxy. (includes --single-process case). int net_error; bool ipc_ok = g_render_thread->Send( new ViewHostMsg_ResolveProxy(url, &net_error, proxy_result)); return ipc_ok ? net_error : net::ERR_UNEXPECTED; } #ifndef USING_SIMPLE_RESOURCE_LOADER_BRIDGE // Each RenderView has a ResourceDispatcher. In unit tests, this function may // not work properly since there may be a ResourceDispatcher w/o a RenderView. // The WebView's delegate may be null, which typically happens as a WebView is // being closed (but it is also possible that it could be null at other times // since WebView has a SetDelegate method). static ResourceDispatcher* GetResourceDispatcher(WebFrame* frame) { WebViewDelegate* d = frame->GetView()->GetDelegate(); return d ? static_cast<RenderView*>(d)->resource_dispatcher() : NULL; } // static factory function ResourceLoaderBridge* ResourceLoaderBridge::Create( WebFrame* webframe, const std::string& method, const GURL& url, const GURL& policy_url, const GURL& referrer, const std::string& headers, int load_flags, int origin_pid, ResourceType::Type resource_type, bool mixed_content) { // TODO(darin): we need to eliminate the webframe parameter because webkit // does not always supply it (see ResourceHandle::loadResourceSynchronously). // Instead we should add context to ResourceRequest, which will be easy to do // once we merge to the latest WebKit (r23806 at least). if (!webframe) { NOTREACHED() << "no webframe"; return NULL; } ResourceDispatcher* dispatcher = GetResourceDispatcher(webframe); if (!dispatcher) { DLOG(WARNING) << "no resource dispatcher"; return NULL; } return dispatcher->CreateBridge(method, url, policy_url, referrer, headers, load_flags, origin_pid, resource_type, mixed_content, 0); } void SetCookie(const GURL& url, const GURL& policy_url, const std::string& cookie) { g_render_thread->Send(new ViewHostMsg_SetCookie(url, policy_url, cookie)); } std::string GetCookies(const GURL& url, const GURL& policy_url) { std::string cookies; g_render_thread->Send(new ViewHostMsg_GetCookies(url, policy_url, &cookies)); return cookies; } void NotifyCacheStats() { // Update the browser about our cache // NOTE: Since this can be called from the plugin process, we might not have // a RenderThread. Do nothing in that case. if (g_render_thread) g_render_thread->InformHostOfCacheStatsLater(); } #endif // !USING_SIMPLE_RESOURCE_LOADER_BRIDGE } // namespace webkit_glue <|endoftext|>
<commit_before>/*========================================================================= * * Copyright David Doria 2012 daviddoria@gmail.com * * 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.txt * * 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 PatchHelpers_HPP #define PatchHelpers_HPP #include "PatchHelpers.h" // Submodules #include <ITKHelpers/ITKHelpers.h> #include <ITKQtHelpers/ITKQtHelpers.h> // STL #include <cassert> #include <stdexcept> // Qt #include <QApplication> #include <QColor> #include <QPainter> namespace PatchHelpers { template <typename TNodeQueue, typename TPriorityMap> void WriteValidQueueNodesLocationsImage(TNodeQueue nodeQueue, const TPriorityMap propertyMap, const itk::ImageRegion<2>& fullRegion, const std::string& fileName) { typedef itk::Image<unsigned char, 2> ImageType; ImageType::Pointer image = ImageType::New(); image->SetRegions(fullRegion); image->Allocate(); image->FillBuffer(0); while(!nodeQueue.empty()) { typename TNodeQueue::value_type queuedNode = nodeQueue.top(); bool valid = get(propertyMap, queuedNode); if(valid) { itk::Index<2> index = Helpers::ConvertFrom<itk::Index<2>, typename TNodeQueue::value_type>(queuedNode); image->SetPixel(index, 255); } nodeQueue.pop(); } ITKHelpers::WriteImage(image.GetPointer(), fileName); } template <typename TNodeQueue, typename TBoundaryStatusMap, typename TPriorityMap> void WriteValidQueueNodesPrioritiesImage(TNodeQueue nodeQueue, const TBoundaryStatusMap boundaryStatusMap, const TPriorityMap priorityMap, const itk::ImageRegion<2>& fullRegion, const std::string& fileName) { typedef itk::Image<float, 2> ImageType; ImageType::Pointer image = ImageType::New(); image->SetRegions(fullRegion); image->Allocate(); image->FillBuffer(0); while(!nodeQueue.empty()) { typename TNodeQueue::value_type queuedNode = nodeQueue.top(); bool valid = get(boundaryStatusMap, queuedNode); if(valid) { itk::Index<2> index = Helpers::ConvertFrom<itk::Index<2>, typename TNodeQueue::value_type>(queuedNode); // image->SetPixel(index, get(nodeQueue.keys(), queuedNode)); image->SetPixel(index, get(priorityMap, queuedNode)); } nodeQueue.pop(); } ITKHelpers::WriteImage(image.GetPointer(), fileName); } template <typename TNodeQueue, typename TBoundaryStatusMap, typename TPriorityMap> void DumpQueue(TNodeQueue nodeQueue, const TBoundaryStatusMap boundaryStatusMap, const TPriorityMap priorityMap) { while(!nodeQueue.empty()) { typename TNodeQueue::value_type queuedNode = nodeQueue.top(); bool valid = get(boundaryStatusMap, queuedNode); if(valid) { float priority = get(priorityMap, queuedNode); std::cout << "(" << queuedNode[0] << ", " << queuedNode[1] << ") : " << priority << std::endl; } nodeQueue.pop(); } } template <class TPriorityQueue> void WritePriorityQueue(TPriorityQueue q, const std::string& fileName) { std::ofstream fout(fileName.c_str()); while(!q.empty()) { float priority = get(q.keys(), q.top()); fout << priority << std::endl; q.pop(); } } template <typename TImage> QImage GetQImageCombinedPatch(const TImage* const image, const itk::ImageRegion<2>& sourceRegion, const itk::ImageRegion<2>& targetRegion, const Mask* const mask) { assert(sourceRegion.GetSize() == targetRegion.GetSize()); QImage qimage(sourceRegion.GetSize()[0], sourceRegion.GetSize()[1], QImage::Format_RGB888); typedef itk::RegionOfInterestImageFilter<TImage, TImage> RegionOfInterestImageFilterType; typename RegionOfInterestImageFilterType::Pointer sourcePatchExtractor = RegionOfInterestImageFilterType::New(); sourcePatchExtractor->SetRegionOfInterest(sourceRegion); sourcePatchExtractor->SetInput(image); sourcePatchExtractor->Update(); typename RegionOfInterestImageFilterType::Pointer targetPatchExtractor = RegionOfInterestImageFilterType::New(); targetPatchExtractor->SetRegionOfInterest(targetRegion); targetPatchExtractor->SetInput(image); targetPatchExtractor->Update(); typedef itk::RegionOfInterestImageFilter<Mask, Mask> RegionOfInterestMaskFilterType; typename RegionOfInterestMaskFilterType::Pointer regionOfInterestMaskFilter = RegionOfInterestMaskFilterType::New(); regionOfInterestMaskFilter->SetRegionOfInterest(targetRegion); regionOfInterestMaskFilter->SetInput(mask); regionOfInterestMaskFilter->Update(); itk::ImageRegionIterator<TImage> sourcePatchIterator(sourcePatchExtractor->GetOutput(), sourcePatchExtractor->GetOutput()->GetLargestPossibleRegion()); itk::ImageRegionIterator<TImage> targetPatchIterator(targetPatchExtractor->GetOutput(), targetPatchExtractor->GetOutput()->GetLargestPossibleRegion()); while(!sourcePatchIterator.IsAtEnd()) { itk::Index<2> index = targetPatchIterator.GetIndex(); typename TImage::PixelType pixel; if(regionOfInterestMaskFilter->GetOutput()->IsHole(index)) { pixel = sourcePatchIterator.Get(); } else { pixel = targetPatchIterator.Get(); } QColor pixelColor(static_cast<int>(pixel[0]), static_cast<int>(pixel[1]), static_cast<int>(pixel[2])); qimage.setPixel(index[0], index[1], pixelColor.rgb()); ++targetPatchIterator; ++sourcePatchIterator; } // std::cout << "There were " << numberOfHolePixels << " hole pixels." << std::endl; //return qimage; // The actual image region return qimage.mirrored(false, true); // The flipped image region } template <class TImage> void CopyRegion(const TImage* sourceImage, TImage* targetImage, const itk::Index<2>& sourcePosition, const itk::Index<2>& targetPosition, const unsigned int radius) { // Copy a patch of radius 'radius' centered at 'sourcePosition' from 'sourceImage' to 'targetImage' centered at 'targetPosition' typedef itk::RegionOfInterestImageFilter<TImage, TImage> ExtractFilterType; typename ExtractFilterType::Pointer extractFilter = ExtractFilterType::New(); extractFilter->SetRegionOfInterest(ITKHelpers::GetRegionInRadiusAroundPixel(sourcePosition, radius)); extractFilter->SetInput(sourceImage); extractFilter->Update(); CopyPatchIntoImage<TImage>(extractFilter->GetOutput(), targetImage, targetPosition); } template <class TImage> void CopyPatchIntoImage(const TImage* const patch, TImage* const image, const Mask* const mask, const itk::Index<2>& position) { // This function copies 'patch' into 'image' centered at 'position' only where the 'mask' is non-zero // 'Mask' must be the same size as 'image' if(mask->GetLargestPossibleRegion().GetSize() != image->GetLargestPossibleRegion().GetSize()) { throw std::runtime_error("mask and image must be the same size!"); } // The PasteFilter expects the lower left corner of the destination position, but we have passed the center pixel. position[0] -= patch->GetLargestPossibleRegion().GetSize()[0]/2; position[1] -= patch->GetLargestPossibleRegion().GetSize()[1]/2; itk::ImageRegion<2> region = GetRegionInRadiusAroundPixel(position, patch->GetLargestPossibleRegion().GetSize()[0]/2); itk::ImageRegionConstIterator<TImage> patchIterator(patch,patch->GetLargestPossibleRegion()); itk::ImageRegionConstIterator<Mask> maskIterator(mask,region); itk::ImageRegionIterator<TImage> imageIterator(image, region); while(!patchIterator.IsAtEnd()) { if(mask->IsHole(maskIterator.GetIndex())) // we are in the target region { imageIterator.Set(patchIterator.Get()); } ++imageIterator; ++maskIterator; ++patchIterator; } } template <class TImage> void CopyPatchIntoImage(const TImage* patch, TImage* const image, const itk::Index<2>& centerPixel) { // This function copies 'patch' into 'image' centered at 'position'. // The PasteFilter expects the lower left corner of the destination position, but we have passed the center pixel. itk::Index<2> cornerPixel; cornerPixel[0] = centerPixel[0] - patch->GetLargestPossibleRegion().GetSize()[0]/2; cornerPixel[1] = centerPixel[1] - patch->GetLargestPossibleRegion().GetSize()[1]/2; typedef itk::PasteImageFilter <TImage, TImage> PasteImageFilterType; typename PasteImageFilterType::Pointer pasteFilter = PasteImageFilterType::New(); pasteFilter->SetInput(0, image); pasteFilter->SetInput(1, patch); pasteFilter->SetSourceRegion(patch->GetLargestPossibleRegion()); pasteFilter->SetDestinationIndex(cornerPixel); pasteFilter->InPlaceOn(); pasteFilter->Update(); image->Graft(pasteFilter->GetOutput()); } template <typename TIterator, typename TImage, typename TPropertyMap> void WriteTopPatches(TImage* const image, TPropertyMap propertyMap, const TIterator first, const TIterator last, const std::string& prefix, const unsigned int iteration) { itk::Size<2> patchSize = get(propertyMap, *first).GetRegion().GetSize(); unsigned int patchSideLength = patchSize[0]; // Assumes square patches unsigned int numberOfTopPatches = last - first; // std::cout << "WriteTopPatches:numberOfTopPatches = " << numberOfTopPatches << std::endl; itk::Index<2> topPatchesImageCorner = {{0,0}}; itk::Size<2> topPatchesImageSize = {{patchSideLength * 2, patchSideLength * numberOfTopPatches + numberOfTopPatches - 1}}; // Make space for all the patches and a colored line dividing them (and the -1 is so there is no dividing line at the bottom) itk::ImageRegion<2> topPatchesImageRegion(topPatchesImageCorner, topPatchesImageSize); // std::cout << "topPatchesImageRegion: " << topPatchesImageRegion << std::endl; typename TImage::Pointer topPatchesImage = TImage::New(); topPatchesImage->SetRegions(topPatchesImageRegion); topPatchesImage->Allocate(); topPatchesImage->FillBuffer(itk::NumericTraits<typename TImage::PixelType>::Zero); typename TImage::PixelType green; green.Fill(0); green[1] = 255; QApplication* app = 0; if(!QApplication::instance()) { int fakeargc = 1; const char* fakeArgv[1]; fakeArgv[0] = "FakeQApplication"; app = new QApplication(fakeargc, const_cast<char**>(fakeArgv)); } QPixmap pixmap(patchSideLength, patchSideLength); QPainter painter(&pixmap); QFont font("", 6); // arbitrary (default) font, size 6 painter.setFont(font); painter.drawText(QPointF(10,10), "test"); // bottom left corner of the text seems to start at this point typename TImage::Pointer numberImage = TImage::New(); QColor qtwhite(255,255,255); for(TIterator currentPatch = first; currentPatch != last; ++currentPatch) { unsigned int currentPatchId = currentPatch - first; pixmap.fill(qtwhite); std::stringstream ssNumber; ssNumber << currentPatchId; painter.drawText(QPointF(10,10), ssNumber.str().c_str()); // bottom left corner of the text seems to start at this point ITKQtHelpers::QImageToITKImage(pixmap.toImage(), numberImage.GetPointer()); // The extra + currentPatchId is to skip the extra dividing lines that have been drawn itk::Index<2> topPatchesImageNumberCorner = {{static_cast<itk::Index<2>::IndexValueType>(patchSideLength), static_cast<itk::Index<2>::IndexValueType>(patchSideLength * currentPatchId + currentPatchId)}}; itk::ImageRegion<2> topPatchesImageNumberRegion(topPatchesImageNumberCorner, patchSize); ITKHelpers::CopyRegion(numberImage.GetPointer(), topPatchesImage.GetPointer(), numberImage->GetLargestPossibleRegion(), topPatchesImageNumberRegion); // The extra + currentPatchId is to skip the extra dividing lines that have been drawn itk::Index<2> topPatchesImageCorner = {{0, static_cast<itk::Index<2>::IndexValueType>(patchSideLength * currentPatchId + currentPatchId)}}; itk::ImageRegion<2> currentTopPatchesImageRegion(topPatchesImageCorner, patchSize); itk::ImageRegion<2> currentRegion = get(propertyMap, *currentPatch).GetRegion(); ITKHelpers::CopyRegion(image, topPatchesImage.GetPointer(), currentRegion, currentTopPatchesImageRegion); if(currentPatchId != numberOfTopPatches - 1) { // std::cout << "CurrentPatchId " << currentPatchId << " numberOfPatches " << numberOfPatches << std::endl; itk::Index<2> dividingLineCorner = {{0, static_cast<itk::Index<2>::IndexValueType>(topPatchesImageCorner[1] + patchSideLength)}}; itk::Size<2> dividingLineSize = {{patchSideLength, 1}}; itk::ImageRegion<2> dividingLine(dividingLineCorner, dividingLineSize); // std::cout << "Dividing line: " << dividingLine << std::endl; ITKHelpers::SetRegionToConstant(topPatchesImage.GetPointer(), dividingLine, green); } } ITKHelpers::WriteRGBImage(topPatchesImage.GetPointer(), Helpers::GetSequentialFileName(prefix, iteration,"png",3)); delete app; } } // end namespace #endif <commit_msg>Prevent patches that are not inside the image from being included in the list.<commit_after>/*========================================================================= * * Copyright David Doria 2012 daviddoria@gmail.com * * 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.txt * * 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 PatchHelpers_HPP #define PatchHelpers_HPP #include "PatchHelpers.h" // Submodules #include <ITKHelpers/ITKHelpers.h> #include <ITKQtHelpers/ITKQtHelpers.h> // STL #include <cassert> #include <stdexcept> // Qt #include <QApplication> #include <QColor> #include <QPainter> namespace PatchHelpers { template <typename TNodeQueue, typename TPriorityMap> void WriteValidQueueNodesLocationsImage(TNodeQueue nodeQueue, const TPriorityMap propertyMap, const itk::ImageRegion<2>& fullRegion, const std::string& fileName) { typedef itk::Image<unsigned char, 2> ImageType; ImageType::Pointer image = ImageType::New(); image->SetRegions(fullRegion); image->Allocate(); image->FillBuffer(0); while(!nodeQueue.empty()) { typename TNodeQueue::value_type queuedNode = nodeQueue.top(); bool valid = get(propertyMap, queuedNode); if(valid) { itk::Index<2> index = Helpers::ConvertFrom<itk::Index<2>, typename TNodeQueue::value_type>(queuedNode); image->SetPixel(index, 255); } nodeQueue.pop(); } ITKHelpers::WriteImage(image.GetPointer(), fileName); } template <typename TNodeQueue, typename TBoundaryStatusMap, typename TPriorityMap> void WriteValidQueueNodesPrioritiesImage(TNodeQueue nodeQueue, const TBoundaryStatusMap boundaryStatusMap, const TPriorityMap priorityMap, const itk::ImageRegion<2>& fullRegion, const std::string& fileName) { typedef itk::Image<float, 2> ImageType; ImageType::Pointer image = ImageType::New(); image->SetRegions(fullRegion); image->Allocate(); image->FillBuffer(0); while(!nodeQueue.empty()) { typename TNodeQueue::value_type queuedNode = nodeQueue.top(); bool valid = get(boundaryStatusMap, queuedNode); if(valid) { itk::Index<2> index = Helpers::ConvertFrom<itk::Index<2>, typename TNodeQueue::value_type>(queuedNode); // image->SetPixel(index, get(nodeQueue.keys(), queuedNode)); image->SetPixel(index, get(priorityMap, queuedNode)); } nodeQueue.pop(); } ITKHelpers::WriteImage(image.GetPointer(), fileName); } template <typename TNodeQueue, typename TBoundaryStatusMap, typename TPriorityMap> void DumpQueue(TNodeQueue nodeQueue, const TBoundaryStatusMap boundaryStatusMap, const TPriorityMap priorityMap) { while(!nodeQueue.empty()) { typename TNodeQueue::value_type queuedNode = nodeQueue.top(); bool valid = get(boundaryStatusMap, queuedNode); if(valid) { float priority = get(priorityMap, queuedNode); std::cout << "(" << queuedNode[0] << ", " << queuedNode[1] << ") : " << priority << std::endl; } nodeQueue.pop(); } } template <class TPriorityQueue> void WritePriorityQueue(TPriorityQueue q, const std::string& fileName) { std::ofstream fout(fileName.c_str()); while(!q.empty()) { float priority = get(q.keys(), q.top()); fout << priority << std::endl; q.pop(); } } template <typename TImage> QImage GetQImageCombinedPatch(const TImage* const image, const itk::ImageRegion<2>& sourceRegion, const itk::ImageRegion<2>& targetRegion, const Mask* const mask) { assert(sourceRegion.GetSize() == targetRegion.GetSize()); QImage qimage(sourceRegion.GetSize()[0], sourceRegion.GetSize()[1], QImage::Format_RGB888); typedef itk::RegionOfInterestImageFilter<TImage, TImage> RegionOfInterestImageFilterType; typename RegionOfInterestImageFilterType::Pointer sourcePatchExtractor = RegionOfInterestImageFilterType::New(); sourcePatchExtractor->SetRegionOfInterest(sourceRegion); sourcePatchExtractor->SetInput(image); sourcePatchExtractor->Update(); typename RegionOfInterestImageFilterType::Pointer targetPatchExtractor = RegionOfInterestImageFilterType::New(); targetPatchExtractor->SetRegionOfInterest(targetRegion); targetPatchExtractor->SetInput(image); targetPatchExtractor->Update(); typedef itk::RegionOfInterestImageFilter<Mask, Mask> RegionOfInterestMaskFilterType; typename RegionOfInterestMaskFilterType::Pointer regionOfInterestMaskFilter = RegionOfInterestMaskFilterType::New(); regionOfInterestMaskFilter->SetRegionOfInterest(targetRegion); regionOfInterestMaskFilter->SetInput(mask); regionOfInterestMaskFilter->Update(); itk::ImageRegionIterator<TImage> sourcePatchIterator(sourcePatchExtractor->GetOutput(), sourcePatchExtractor->GetOutput()->GetLargestPossibleRegion()); itk::ImageRegionIterator<TImage> targetPatchIterator(targetPatchExtractor->GetOutput(), targetPatchExtractor->GetOutput()->GetLargestPossibleRegion()); while(!sourcePatchIterator.IsAtEnd()) { itk::Index<2> index = targetPatchIterator.GetIndex(); typename TImage::PixelType pixel; if(regionOfInterestMaskFilter->GetOutput()->IsHole(index)) { pixel = sourcePatchIterator.Get(); } else { pixel = targetPatchIterator.Get(); } QColor pixelColor(static_cast<int>(pixel[0]), static_cast<int>(pixel[1]), static_cast<int>(pixel[2])); qimage.setPixel(index[0], index[1], pixelColor.rgb()); ++targetPatchIterator; ++sourcePatchIterator; } // std::cout << "There were " << numberOfHolePixels << " hole pixels." << std::endl; //return qimage; // The actual image region return qimage.mirrored(false, true); // The flipped image region } template <class TImage> void CopyRegion(const TImage* sourceImage, TImage* targetImage, const itk::Index<2>& sourcePosition, const itk::Index<2>& targetPosition, const unsigned int radius) { // Copy a patch of radius 'radius' centered at 'sourcePosition' from 'sourceImage' to 'targetImage' centered at 'targetPosition' typedef itk::RegionOfInterestImageFilter<TImage, TImage> ExtractFilterType; typename ExtractFilterType::Pointer extractFilter = ExtractFilterType::New(); extractFilter->SetRegionOfInterest(ITKHelpers::GetRegionInRadiusAroundPixel(sourcePosition, radius)); extractFilter->SetInput(sourceImage); extractFilter->Update(); CopyPatchIntoImage<TImage>(extractFilter->GetOutput(), targetImage, targetPosition); } template <class TImage> void CopyPatchIntoImage(const TImage* const patch, TImage* const image, const Mask* const mask, const itk::Index<2>& position) { // This function copies 'patch' into 'image' centered at 'position' only where the 'mask' is non-zero // 'Mask' must be the same size as 'image' if(mask->GetLargestPossibleRegion().GetSize() != image->GetLargestPossibleRegion().GetSize()) { throw std::runtime_error("mask and image must be the same size!"); } // The PasteFilter expects the lower left corner of the destination position, but we have passed the center pixel. position[0] -= patch->GetLargestPossibleRegion().GetSize()[0]/2; position[1] -= patch->GetLargestPossibleRegion().GetSize()[1]/2; itk::ImageRegion<2> region = GetRegionInRadiusAroundPixel(position, patch->GetLargestPossibleRegion().GetSize()[0]/2); itk::ImageRegionConstIterator<TImage> patchIterator(patch,patch->GetLargestPossibleRegion()); itk::ImageRegionConstIterator<Mask> maskIterator(mask,region); itk::ImageRegionIterator<TImage> imageIterator(image, region); while(!patchIterator.IsAtEnd()) { if(mask->IsHole(maskIterator.GetIndex())) // we are in the target region { imageIterator.Set(patchIterator.Get()); } ++imageIterator; ++maskIterator; ++patchIterator; } } template <class TImage> void CopyPatchIntoImage(const TImage* patch, TImage* const image, const itk::Index<2>& centerPixel) { // This function copies 'patch' into 'image' centered at 'position'. // The PasteFilter expects the lower left corner of the destination position, but we have passed the center pixel. itk::Index<2> cornerPixel; cornerPixel[0] = centerPixel[0] - patch->GetLargestPossibleRegion().GetSize()[0]/2; cornerPixel[1] = centerPixel[1] - patch->GetLargestPossibleRegion().GetSize()[1]/2; typedef itk::PasteImageFilter <TImage, TImage> PasteImageFilterType; typename PasteImageFilterType::Pointer pasteFilter = PasteImageFilterType::New(); pasteFilter->SetInput(0, image); pasteFilter->SetInput(1, patch); pasteFilter->SetSourceRegion(patch->GetLargestPossibleRegion()); pasteFilter->SetDestinationIndex(cornerPixel); pasteFilter->InPlaceOn(); pasteFilter->Update(); image->Graft(pasteFilter->GetOutput()); } template <typename TIterator, typename TImage, typename TPropertyMap> void WriteTopPatches(TImage* const image, TPropertyMap propertyMap, const TIterator first, const TIterator last, const std::string& prefix, const unsigned int iteration) { itk::Size<2> patchSize = get(propertyMap, *first).GetRegion().GetSize(); unsigned int patchSideLength = patchSize[0]; // Assumes square patches unsigned int numberOfTopPatches = last - first; // std::cout << "WriteTopPatches:numberOfTopPatches = " << numberOfTopPatches << std::endl; itk::Index<2> topPatchesImageCorner = {{0,0}}; itk::Size<2> topPatchesImageSize = {{patchSideLength * 2, patchSideLength * numberOfTopPatches + numberOfTopPatches - 1}}; // Make space for all the patches and a colored line dividing them (and the -1 is so there is no dividing line at the bottom) itk::ImageRegion<2> topPatchesImageRegion(topPatchesImageCorner, topPatchesImageSize); // std::cout << "topPatchesImageRegion: " << topPatchesImageRegion << std::endl; typename TImage::Pointer topPatchesImage = TImage::New(); topPatchesImage->SetRegions(topPatchesImageRegion); topPatchesImage->Allocate(); topPatchesImage->FillBuffer(itk::NumericTraits<typename TImage::PixelType>::Zero); typename TImage::PixelType green; green.Fill(0); green[1] = 255; QApplication* app = 0; if(!QApplication::instance()) { int fakeargc = 1; const char* fakeArgv[1]; fakeArgv[0] = "FakeQApplication"; app = new QApplication(fakeargc, const_cast<char**>(fakeArgv)); } QPixmap pixmap(patchSideLength, patchSideLength); QPainter painter(&pixmap); QFont font("", 6); // arbitrary (default) font, size 6 painter.setFont(font); painter.drawText(QPointF(10,10), "test"); // bottom left corner of the text seems to start at this point typename TImage::Pointer numberImage = TImage::New(); QColor qtwhite(255,255,255); for(TIterator currentPatch = first; currentPatch != last; ++currentPatch) { unsigned int currentPatchId = currentPatch - first; pixmap.fill(qtwhite); std::stringstream ssNumber; ssNumber << currentPatchId; painter.drawText(QPointF(10,10), ssNumber.str().c_str()); // bottom left corner of the text seems to start at this point ITKQtHelpers::QImageToITKImage(pixmap.toImage(), numberImage.GetPointer()); // The extra + currentPatchId is to skip the extra dividing lines that have been drawn itk::Index<2> topPatchesImageNumberCorner = {{static_cast<itk::Index<2>::IndexValueType>(patchSideLength), static_cast<itk::Index<2>::IndexValueType>(patchSideLength * currentPatchId + currentPatchId)}}; itk::ImageRegion<2> topPatchesImageNumberRegion(topPatchesImageNumberCorner, patchSize); ITKHelpers::CopyRegion(numberImage.GetPointer(), topPatchesImage.GetPointer(), numberImage->GetLargestPossibleRegion(), topPatchesImageNumberRegion); // The extra + currentPatchId is to skip the extra dividing lines that have been drawn itk::Index<2> topPatchesImageCorner = {{0, static_cast<itk::Index<2>::IndexValueType>(patchSideLength * currentPatchId + currentPatchId)}}; itk::ImageRegion<2> currentTopPatchesImageRegion(topPatchesImageCorner, patchSize); itk::ImageRegion<2> currentRegion = get(propertyMap, *currentPatch).GetRegion(); // The patches passed to this function aren't necessarily inside the image. If they are not, we cannot write them into the list of top patches, // and we simply leave the patch blank. if(image->GetLargestPossibleRegion().IsInside(currentRegion)) { ITKHelpers::CopyRegion(image, topPatchesImage.GetPointer(), currentRegion, currentTopPatchesImageRegion); } if(currentPatchId != numberOfTopPatches - 1) { // std::cout << "CurrentPatchId " << currentPatchId << " numberOfPatches " << numberOfPatches << std::endl; itk::Index<2> dividingLineCorner = {{0, static_cast<itk::Index<2>::IndexValueType>(topPatchesImageCorner[1] + patchSideLength)}}; itk::Size<2> dividingLineSize = {{patchSideLength, 1}}; itk::ImageRegion<2> dividingLine(dividingLineCorner, dividingLineSize); // std::cout << "Dividing line: " << dividingLine << std::endl; ITKHelpers::SetRegionToConstant(topPatchesImage.GetPointer(), dividingLine, green); } } ITKHelpers::WriteRGBImage(topPatchesImage.GetPointer(), Helpers::GetSequentialFileName(prefix, iteration,"png",3)); delete app; // c++ allows null pointers to be deleted } } // end namespace #endif <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/lib/p9_avsbus_lib.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_avsbus_lib.H /// @brief Library functions for AVSBus /// /// *HW Owner : Sudheendra K Srivathsa <sudheendraks@in.ibm.com> /// *FW Owner : Sangeetha T S <sangeet2@in.ibm.com> /// *Team : PM /// *Consumed by : HB /// *Level : 2 /// /// @todo (to be considered in L2/L3 development) AVSBus timing parameters /// as attributes or not. They were hardcoded in P8. #ifndef __P9_AVSBUS_LIB_H__ #define __P9_AVSBUS_LIB_H__ #include <fapi2.H> namespace p9avslib { enum avsRails { VDD, VDN, VCS }; enum avsBusNum { AVSBUSVDD = 0, AVSBUSVDN = 1, AVSBUSVCS = 0 }; union avsMasterFrame { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t StartCode : 2; uint32_t Cmd : 2; uint32_t CmdGroup : 1; uint32_t CmdDataType: 4; uint32_t Select : 4; uint32_t CmdData : 16; uint32_t CRC : 3; #else uint32_t CRC : 3; uint32_t CmdData : 16; uint32_t Select : 4; uint32_t CmdDataType: 4; uint32_t CmdGroup : 1; uint32_t Cmd : 2; uint32_t StartCode : 2; #endif // _BIG_ENDIAN } fields; }; union avsSlaveFrame { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t SlaveAck : 2; uint32_t reserved1 : 1; uint32_t StatusResp : 5; uint32_t CmdData : 16; uint32_t reserved5 : 5; uint32_t CRC : 3; #else uint32_t CRC : 3; uint32_t reserved5 : 5; uint32_t CmdData : 16; uint32_t StatusResp : 5; uint32_t reserved1 : 1; uint32_t SlaveAck : 2; #endif // _BIG_ENDIAN } fields; }; union avsStatus { uint16_t value; struct { #ifdef _BIG_ENDIAN uint16_t VDone : 1; // Voltage done uint16_t OCW : 1; // IOUT_OC_WARNING (Output over-current) uint16_t UCW : 1; // VOUT_UV_WARNING (Output under-voltage) uint16_t OTW : 1; // IOUT_OT_WARNING (Over-temperature) uint16_t OPW : 1; // POUT_OP_WARNING (Output over-power) uint16_t Reserved_3 : 3; uint16_t MfrSpcfc_8 : 8; // Mfg Specific defined by the AVSBus Slave #else uint16_t MfrSpcfc_8 : 8; // Mfg Specific defined by the AVSBus Slave uint16_t Reserved_3 : 3; uint16_t OPW : 1; // POUT_OP_WARNING (Output over-power) uint16_t OTW : 1; // IOUT_OT_WARNING (Over-temperature) uint16_t UCW : 1; // VOUT_UV_WARNING (Output under-voltage) uint16_t OCW : 1; // IOUT_OC_WARNING (Output over-current) uint16_t VDone : 1; // Voltage done #endif // _BIG_ENDIAN } fields; }; enum avslibconstants { // @todo: This should be calculated based on time (eg 100ms) and the projected // time that a SCOM poll will take. // const uint32_t MAX_POLL_COUNT_AVS = 0x1000; // AVSBUS_FREQUENCY specified in Khz, Default value 10 MHz MAX_POLL_COUNT_AVS = 0x1000, AVS_CRC_DATA_MASK = 0xfffffff8, O2S_FRAME_SIZE = 0x20, O2S_IN_DELAY1 = 0x3F, AVSBUS_FREQUENCY = 0x2710 }; // Constant definitions //const uint64_t O2S_FRAME_SIZE = 0x20; // OIMR Mask Values const uint32_t OCB_OIMR1_MASK_VALUES[2][2] = { 0xFFFFFBFF, //bit 21 0xFFFFFCFF, //bit 22 0xFFFFFBFF, //bit 23 0xFFFFFEFF //bit 24 }; //const uint64_t OCB_O2SST_MASK = 0x8000000000000000; } //end of p9avslib namespace ///@brief Generates a 3 bit CRC value for 29 bit data ///@param[i] i_data ///@return 3 bit CRC result (right aligned) uint32_t avsCRCcalc(uint32_t i_data); ///@brief Initialize an O2S bridge for AVSBus usage ///@param[i] i_target Chip target ///@param[i] i_avsBusNum AVSBus Number (0 or 1) ///@param[i] i_o2sBridgeNum O2S Bridge Number (0 or 1) ///@return FAPI2::ReturnCode defined in XML fapi2::ReturnCode avsInitExtVoltageControl(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint8_t i_avsBusNum, const uint8_t i_o2sBridgeNum); ///@brief Polls OCB status register O2SST for o2s_ongoing=0 ///@param[i] i_target Chip target ///@param[i] i_avsBusNum AVSBus Number (0 or 1) ///@param[i] i_o2sBridgeNum O2S Bridge Number (0 or 1) ///@return FAPI2::SUCCESS ///@return FAPI2::RC_PROCPM_AVSBUS_TIMEOUT fapi2::ReturnCode avsPollVoltageTransDone(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint8_t i_avsBusNum, const uint8_t i_o2sBridgeNum); ///@brief Drives a downstream command to a select bus via a selected bridge ///@param[i] i_target Chip target ///@param[i] i_avsBusNum AVSBus Number (0 or 1) ///@param[i] i_o2sBridgeNum O2S Bridge Number (0 or 1) ///@param[i] i_RailSelect Rail Select (value depends on the system implementation) ///@param[i] i_CmdType Defined by AVSBus spec (4b, right justified) ///@param[i] i_CmdGroup Defined by AVSBus spec (0 = AVSBus defined; 1 = Mfg defined) ///@param[i] i_CmdData Defined by AVSBus spec and command dependent (16b, right justified) ///@return FAPI2::SUCCESS ///@return FAPI2::RC_PROCPM_AVSBUS_TIMEOUT fapi2::ReturnCode avsDriveCommand(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint8_t i_avsBusNum, const uint8_t i_o2sBridgeNum, const uint32_t i_RailSelect, const uint32_t i_CmdType, const uint32_t i_CmdGroup, const uint32_t i_CmdDataType, const uint32_t i_CmdData); ///@brief Perform an AVS read transaction ///@param[i] i_target Chip target ///@param[i] i_avsBusNum AVSBus Number (0 or 1) ///@param[i] i_o2sBridgeNum O2S Bridge Number (0 or 1) ///@param[i] i_RailSelect Rail Select (value depends on the system implementation) ///@param[o] o_CmdData Defined by AVSBus spec and command dependent (16b, right justified) ///@return FAPI2::SUCCESS ///@return FAPI2::RC_PROCPM_AVSBUS_TIMEOUT fapi2::ReturnCode avsVoltageRead(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint8_t i_avsBusNum, const uint8_t i_o2sBridgeNum, const uint32_t i_RailSelect, uint32_t& o_Voltage); ///@brief Perform an AVS write transaction ///@param[i] i_target Chip target ///@param[i] i_avsBusNum AVSBus Number (0 or 1) ///@param[i] i_o2sBridgeNum O2S Bridge Number (0 or 1) ///@param[i] i_RailSelect Rail Select (value depends on the system implementation) ///@param[i] i_CmdData Defined by AVSBus spec and command dependent (16b, right justified) ///@return FAPI2::SUCCESS ///@return FAPI2::RC_PROCPM_AVSBUS_TIMEOUT fapi2::ReturnCode avsVoltageWrite(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint8_t i_avsBusNum, const uint8_t i_o2sBridgeNum, const uint32_t i_RailSelect, const uint32_t o_Voltage); ///@brief Drive an Idle Frame on an AVSBus ///@param[i] i_target Chip target ///@param[i] i_avsBusNum AVSBus Number (0 or 1) ///@param[i] i_o2sBridgeNum O2S Bridge Number (0 or 1) ///@return FAPI2::SUCCESS fapi2::ReturnCode avsIdleFrame(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint8_t i_avsBusNum, const uint8_t i_o2sBridgeNum); #endif // __P9_AVSBUS_LIB_H__ <commit_msg>AVSBus current,temperature and slew rate commands, add CRC Checking<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/lib/p9_avsbus_lib.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_avsbus_lib.H /// @brief Library functions for AVSBus /// /// *HW Owner : Sudheendra K Srivathsa <sudheendraks@in.ibm.com> /// *FW Owner : Sangeetha T S <sangeet2@in.ibm.com> /// *Team : PM /// *Consumed by : HB /// *Level : 2 /// /// @todo (to be considered in L2/L3 development) AVSBus timing parameters /// as attributes or not. They were hardcoded in P8. #ifndef __P9_AVSBUS_LIB_H__ #define __P9_AVSBUS_LIB_H__ #include <fapi2.H> namespace p9avslib { enum avsRails { VDD, VDN, VCS }; enum avsBusNum { AVSBUSVDD = 0, AVSBUSVDN = 1, AVSBUSVCS = 0 }; union avsMasterFrame { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t StartCode : 2; uint32_t Cmd : 2; uint32_t CmdGroup : 1; uint32_t CmdDataType: 4; uint32_t Select : 4; uint32_t CmdData : 16; uint32_t CRC : 3; #else uint32_t CRC : 3; uint32_t CmdData : 16; uint32_t Select : 4; uint32_t CmdDataType: 4; uint32_t CmdGroup : 1; uint32_t Cmd : 2; uint32_t StartCode : 2; #endif // _BIG_ENDIAN } fields; }; union avsSlaveFrame { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t SlaveAck : 2; uint32_t reserved1 : 1; uint32_t StatusResp : 5; uint32_t CmdData : 16; uint32_t reserved5 : 5; uint32_t CRC : 3; #else uint32_t CRC : 3; uint32_t reserved5 : 5; uint32_t CmdData : 16; uint32_t StatusResp : 5; uint32_t reserved1 : 1; uint32_t SlaveAck : 2; #endif // _BIG_ENDIAN } fields; }; union avsStatus { uint16_t value; struct { #ifdef _BIG_ENDIAN uint16_t VDone : 1; // Voltage done uint16_t OCW : 1; // IOUT_OC_WARNING (Output over-current) uint16_t UCW : 1; // VOUT_UV_WARNING (Output under-voltage) uint16_t OTW : 1; // IOUT_OT_WARNING (Over-temperature) uint16_t OPW : 1; // POUT_OP_WARNING (Output over-power) uint16_t Reserved_3 : 3; uint16_t MfrSpcfc_8 : 8; // Mfg Specific defined by the AVSBus Slave #else uint16_t MfrSpcfc_8 : 8; // Mfg Specific defined by the AVSBus Slave uint16_t Reserved_3 : 3; uint16_t OPW : 1; // POUT_OP_WARNING (Output over-power) uint16_t OTW : 1; // IOUT_OT_WARNING (Over-temperature) uint16_t UCW : 1; // VOUT_UV_WARNING (Output under-voltage) uint16_t OCW : 1; // IOUT_OC_WARNING (Output over-current) uint16_t VDone : 1; // Voltage done #endif // _BIG_ENDIAN } fields; }; enum avslibconstants { // @todo: This should be calculated based on time (eg 100ms) and the projected // time that a SCOM poll will take. // const uint32_t MAX_POLL_COUNT_AVS = 0x1000; // AVSBUS_FREQUENCY specified in Khz, Default value 10 MHz MAX_POLL_COUNT_AVS = 0x1000, AVS_CRC_DATA_MASK = 0xfffffff8, O2S_FRAME_SIZE = 0x20, O2S_IN_DELAY1 = 0x3F, AVSBUS_FREQUENCY = 0x2710 }; // Constant definitions //const uint64_t O2S_FRAME_SIZE = 0x20; // OIMR Mask Values const uint32_t OCB_OIMR1_MASK_VALUES[2][2] = { 0xFFFFFBFF, //bit 21 0xFFFFFCFF, //bit 22 0xFFFFFBFF, //bit 23 0xFFFFFEFF //bit 24 }; //const uint64_t OCB_O2SST_MASK = 0x8000000000000000; } //end of p9avslib namespace ///@brief Generates a 3 bit CRC value for 29 bit data ///@param[i] i_data ///@return 3 bit CRC result (right aligned) uint32_t avsCRCcalc(uint32_t i_data); ///@brief Initialize an O2S bridge for AVSBus usage ///@param[i] i_target Chip target ///@param[i] i_avsBusNum AVSBus Number (0 or 1) ///@param[i] i_o2sBridgeNum O2S Bridge Number (0 or 1) ///@return FAPI2::ReturnCode defined in XML fapi2::ReturnCode avsInitExtVoltageControl(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint8_t i_avsBusNum, const uint8_t i_o2sBridgeNum); ///@brief Polls OCB status register O2SST for o2s_ongoing=0 ///@param[i] i_target Chip target ///@param[i] i_avsBusNum AVSBus Number (0 or 1) ///@param[i] i_o2sBridgeNum O2S Bridge Number (0 or 1) ///@return FAPI2::SUCCESS ///@return FAPI2::RC_PROCPM_AVSBUS_TIMEOUT fapi2::ReturnCode avsPollVoltageTransDone(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint8_t i_avsBusNum, const uint8_t i_o2sBridgeNum); ///@brief Drives a downstream command to a select bus via a selected bridge ///@param[i] i_target Chip target ///@param[i] i_avsBusNum AVSBus Number (0 or 1) ///@param[i] i_o2sBridgeNum O2S Bridge Number (0 or 1) ///@param[i] i_RailSelect Rail Select (value depends on the system implementation) ///@param[i] i_CmdType Defined by AVSBus spec (4b, right justified) ///@param[i] i_CmdGroup Defined by AVSBus spec (0 = AVSBus defined; 1 = Mfg defined) ///@param[i] i_CmdData Defined by AVSBus spec and command dependent (16b, right justified) ///@return FAPI2::SUCCESS ///@return FAPI2::RC_PROCPM_AVSBUS_TIMEOUT fapi2::ReturnCode avsDriveCommand(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint8_t i_avsBusNum, const uint8_t i_o2sBridgeNum, const uint32_t i_RailSelect, const uint32_t i_CmdType, const uint32_t i_CmdGroup, const uint32_t i_CmdDataType, const uint32_t i_CmdData); ///@brief Perform an AVS read transaction ///@param[i] i_target Chip target ///@param[i] i_avsBusNum AVSBus Number (0 or 1) ///@param[i] i_o2sBridgeNum O2S Bridge Number (0 or 1) ///@param[i] i_RailSelect Rail Select (value depends on the system implementation) ///@param[o] o_CmdData Defined by AVSBus spec and command dependent (16b, right justified) ///@return FAPI2::SUCCESS ///@return FAPI2::RC_PROCPM_AVSBUS_TIMEOUT fapi2::ReturnCode avsVoltageRead(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint8_t i_avsBusNum, const uint8_t i_o2sBridgeNum, const uint32_t i_RailSelect, uint32_t& o_Voltage); ///@brief Perform an AVS write transaction ///@param[i] i_target Chip target ///@param[i] i_avsBusNum AVSBus Number (0 or 1) ///@param[i] i_o2sBridgeNum O2S Bridge Number (0 or 1) ///@param[i] i_RailSelect Rail Select (value depends on the system implementation) ///@param[i] i_CmdData Defined by AVSBus spec and command dependent (16b, right justified) ///@return FAPI2::SUCCESS ///@return FAPI2::RC_PROCPM_AVSBUS_TIMEOUT fapi2::ReturnCode avsVoltageWrite(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint8_t i_avsBusNum, const uint8_t i_o2sBridgeNum, const uint32_t i_RailSelect, const uint32_t o_Voltage); ///@brief Drive an Idle Frame on an AVSBus ///@param[i] i_target Chip target ///@param[i] i_avsBusNum AVSBus Number (0 or 1) ///@param[i] i_o2sBridgeNum O2S Bridge Number (0 or 1) ///@return FAPI2::SUCCESS fapi2::ReturnCode avsIdleFrame(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint8_t i_avsBusNum, const uint8_t i_o2sBridgeNum); ///@brief Validate the AVSBUS slave response ///@param[i] i_target Chip target ///@param[i] i_avsBusNum AVSBus Number (0 or 1) ///@param[i] i_o2sBridgeNum O2S Bridge Number (0 or 1) ///@param[i] i_throwAssert Should this routine throw an assert ///@param[o] o_goodResponse Was the response valid fapi2::ReturnCode avsValidateResponse(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint8_t i_avsBusNum, const uint8_t i_o2sBridgeNum, const uint8_t i_throwAssert, uint8_t& o_goodResponse); #endif // __P9_AVSBUS_LIB_H__ <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2011-2012 Denis Shienkov <denis.shienkov@gmail.com> ** Copyright (C) 2011 Sergey Belyashov <Sergey.Belyashov@gmail.com> ** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org> ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtSerialPort module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qserialportinfo.h" #include "qserialportinfo_p.h" #include "qttylocker_unix_p.h" #include "qserialport_unix_p.h" #include <QtCore/qfile.h> #ifndef Q_OS_MAC #if defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV) extern "C" { #include <libudev.h> } #else #include <QtCore/qdir.h> #include <QtCore/qstringlist.h> #endif #endif // Q_OS_MAC QT_BEGIN_NAMESPACE #ifndef Q_OS_MAC #if !(defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV)) static inline const QStringList& filtersOfDevices() { static const QStringList deviceFileNameFilterList = QStringList() # ifdef Q_OS_LINUX << QLatin1String("ttyS*") // Standart UART 8250 and etc. << QLatin1String("ttyUSB*") // Usb/serial converters PL2303 and etc. << QLatin1String("ttyACM*") // CDC_ACM converters (i.e. Mobile Phones). << QLatin1String("ttyGS*") // Gadget serial device (i.e. Mobile Phones with gadget serial driver). << QLatin1String("ttyMI*") // MOXA pci/serial converters. << QLatin1String("ttyAMA*") // AMBA serial device for embedded platform on ARM (i.e. Raspberry Pi). << QLatin1String("rfcomm*") // Bluetooth serial device. << QLatin1String("ircomm*"); // IrDA serial device. # elif defined (Q_OS_FREEBSD) << QLatin1String("cu*"); # else ; // Here for other *nix OS. # endif return deviceFileNameFilterList; } #endif QList<QSerialPortInfo> QSerialPortInfo::availablePorts() { QList<QSerialPortInfo> serialPortInfoList; #if defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV) // White list for devices without a parent static const QString rfcommDeviceName(QLatin1String("rfcomm")); struct ::udev *udev = ::udev_new(); if (udev) { struct ::udev_enumerate *enumerate = ::udev_enumerate_new(udev); if (enumerate) { ::udev_enumerate_add_match_subsystem(enumerate, "tty"); ::udev_enumerate_scan_devices(enumerate); struct ::udev_list_entry *devices = ::udev_enumerate_get_list_entry(enumerate); struct ::udev_list_entry *dev_list_entry; udev_list_entry_foreach(dev_list_entry, devices) { struct ::udev_device *dev = ::udev_device_new_from_syspath(udev, ::udev_list_entry_get_name(dev_list_entry)); if (dev) { QSerialPortInfo serialPortInfo; serialPortInfo.d_ptr->device = QLatin1String(::udev_device_get_devnode(dev)); serialPortInfo.d_ptr->portName = QLatin1String(::udev_device_get_sysname(dev)); struct ::udev_device *parentdev = ::udev_device_get_parent(dev); bool canAppendToList = true; if (parentdev) { QLatin1String subsys(::udev_device_get_subsystem(parentdev)); if (subsys == QLatin1String("usb-serial") || subsys == QLatin1String("usb")) { // USB bus type // Append this devices and try get additional information about them. serialPortInfo.d_ptr->description = QString( QLatin1String(::udev_device_get_property_value(dev, "ID_MODEL"))).replace('_', ' '); serialPortInfo.d_ptr->manufacturer = QString( QLatin1String(::udev_device_get_property_value(dev, "ID_VENDOR"))).replace('_', ' '); serialPortInfo.d_ptr->vendorIdentifier = QString::fromLatin1(::udev_device_get_property_value(dev, "ID_VENDOR_ID")).toInt(&serialPortInfo.d_ptr->hasVendorIdentifier, 16); serialPortInfo.d_ptr->productIdentifier = QString::fromLatin1(::udev_device_get_property_value(dev, "ID_MODEL_ID")).toInt(&serialPortInfo.d_ptr->hasProductIdentifier, 16); } else if (subsys == QLatin1String("pnp")) { // PNP bus type // Append this device. // FIXME: How to get additional information about serial devices // with this subsystem? } else if (subsys == QLatin1String("platform")) { // Platform 'pseudo' bus for legacy device. // Skip this devices because this type of subsystem does // not include a real physical serial device. canAppendToList = false; } else { // Others types of subsystems. // Append this devices because we believe that any other types of // subsystems provide a real serial devices. For example, for devices // such as ttyGSx, its driver provide an empty subsystem name, but it // devices is a real physical serial devices. // FIXME: How to get additional information about serial devices // with this subsystems? } } else { // Devices without a parent if (serialPortInfo.d_ptr->portName.startsWith(rfcommDeviceName)) { // Bluetooth device bool ok; // Check for an unsigned decimal integer at the end of the device name: "rfcomm0", "rfcomm15" // devices with negative and invalid numbers in the name are rejected int portNumber = serialPortInfo.d_ptr->portName.mid(rfcommDeviceName.length()).toInt(&ok); if (!ok || (portNumber < 0) || (portNumber > 255)) { canAppendToList = false; } } else { canAppendToList = false; } } if (canAppendToList) serialPortInfoList.append(serialPortInfo); ::udev_device_unref(dev); } } ::udev_enumerate_unref(enumerate); } ::udev_unref(udev); } #elif defined (Q_OS_FREEBSD) && defined (HAVE_LIBUSB) // TODO: Implement me. #else QDir devDir(QLatin1String("/dev")); if (devDir.exists()) { devDir.setNameFilters(filtersOfDevices()); devDir.setFilter(QDir::Files | QDir::System | QDir::NoSymLinks); QStringList foundDevices; // Found devices list. foreach (const QFileInfo &deviceFileInfo, devDir.entryInfoList()) { QString deviceFilePath = deviceFileInfo.absoluteFilePath(); if (!foundDevices.contains(deviceFilePath)) { foundDevices.append(deviceFilePath); QSerialPortInfo serialPortInfo; serialPortInfo.d_ptr->device = deviceFilePath; serialPortInfo.d_ptr->portName = QSerialPortPrivate::portNameFromSystemLocation(deviceFilePath); // Get description, manufacturer, vendor identifier, product // identifier are not supported. serialPortInfoList.append(serialPortInfo); } } } #endif return serialPortInfoList; } #endif // Q_OS_MAC // common part QList<qint32> QSerialPortInfo::standardBaudRates() { return QSerialPortPrivate::standardBaudRates(); } bool QSerialPortInfo::isBusy() const { bool currentPid = false; return QTtyLocker::isLocked(portName().toLocal8Bit().constData(), &currentPid); } bool QSerialPortInfo::isValid() const { QFile f(systemLocation()); return f.exists(); } QT_END_NAMESPACE <commit_msg>Linux: Added enumeration of Motorola IMX serial ports<commit_after>/**************************************************************************** ** ** Copyright (C) 2011-2012 Denis Shienkov <denis.shienkov@gmail.com> ** Copyright (C) 2011 Sergey Belyashov <Sergey.Belyashov@gmail.com> ** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org> ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtSerialPort module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qserialportinfo.h" #include "qserialportinfo_p.h" #include "qttylocker_unix_p.h" #include "qserialport_unix_p.h" #include <QtCore/qfile.h> #ifndef Q_OS_MAC #if defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV) extern "C" { #include <libudev.h> } #else #include <QtCore/qdir.h> #include <QtCore/qstringlist.h> #endif #endif // Q_OS_MAC QT_BEGIN_NAMESPACE #ifndef Q_OS_MAC #if !(defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV)) static inline const QStringList& filtersOfDevices() { static const QStringList deviceFileNameFilterList = QStringList() # ifdef Q_OS_LINUX << QLatin1String("ttyS*") // Standart UART 8250 and etc. << QLatin1String("ttyUSB*") // Usb/serial converters PL2303 and etc. << QLatin1String("ttyACM*") // CDC_ACM converters (i.e. Mobile Phones). << QLatin1String("ttyGS*") // Gadget serial device (i.e. Mobile Phones with gadget serial driver). << QLatin1String("ttyMI*") // MOXA pci/serial converters. << QLatin1String("ttymxc*") // Motorola IMX serial ports (i.e. Freescale i.MX). << QLatin1String("ttyAMA*") // AMBA serial device for embedded platform on ARM (i.e. Raspberry Pi). << QLatin1String("rfcomm*") // Bluetooth serial device. << QLatin1String("ircomm*"); // IrDA serial device. # elif defined (Q_OS_FREEBSD) << QLatin1String("cu*"); # else ; // Here for other *nix OS. # endif return deviceFileNameFilterList; } #endif QList<QSerialPortInfo> QSerialPortInfo::availablePorts() { QList<QSerialPortInfo> serialPortInfoList; #if defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV) // White list for devices without a parent static const QString rfcommDeviceName(QLatin1String("rfcomm")); struct ::udev *udev = ::udev_new(); if (udev) { struct ::udev_enumerate *enumerate = ::udev_enumerate_new(udev); if (enumerate) { ::udev_enumerate_add_match_subsystem(enumerate, "tty"); ::udev_enumerate_scan_devices(enumerate); struct ::udev_list_entry *devices = ::udev_enumerate_get_list_entry(enumerate); struct ::udev_list_entry *dev_list_entry; udev_list_entry_foreach(dev_list_entry, devices) { struct ::udev_device *dev = ::udev_device_new_from_syspath(udev, ::udev_list_entry_get_name(dev_list_entry)); if (dev) { QSerialPortInfo serialPortInfo; serialPortInfo.d_ptr->device = QLatin1String(::udev_device_get_devnode(dev)); serialPortInfo.d_ptr->portName = QLatin1String(::udev_device_get_sysname(dev)); struct ::udev_device *parentdev = ::udev_device_get_parent(dev); bool canAppendToList = true; if (parentdev) { QLatin1String subsys(::udev_device_get_subsystem(parentdev)); if (subsys == QLatin1String("usb-serial") || subsys == QLatin1String("usb")) { // USB bus type // Append this devices and try get additional information about them. serialPortInfo.d_ptr->description = QString( QLatin1String(::udev_device_get_property_value(dev, "ID_MODEL"))).replace('_', ' '); serialPortInfo.d_ptr->manufacturer = QString( QLatin1String(::udev_device_get_property_value(dev, "ID_VENDOR"))).replace('_', ' '); serialPortInfo.d_ptr->vendorIdentifier = QString::fromLatin1(::udev_device_get_property_value(dev, "ID_VENDOR_ID")).toInt(&serialPortInfo.d_ptr->hasVendorIdentifier, 16); serialPortInfo.d_ptr->productIdentifier = QString::fromLatin1(::udev_device_get_property_value(dev, "ID_MODEL_ID")).toInt(&serialPortInfo.d_ptr->hasProductIdentifier, 16); } else if (subsys == QLatin1String("pnp")) { // PNP bus type // Append this device. // FIXME: How to get additional information about serial devices // with this subsystem? } else if (subsys == QLatin1String("platform")) { // Platform 'pseudo' bus for legacy device. // Skip this devices because this type of subsystem does // not include a real physical serial device. canAppendToList = false; } else { // Others types of subsystems. // Append this devices because we believe that any other types of // subsystems provide a real serial devices. For example, for devices // such as ttyGSx, its driver provide an empty subsystem name, but it // devices is a real physical serial devices. // FIXME: How to get additional information about serial devices // with this subsystems? } } else { // Devices without a parent if (serialPortInfo.d_ptr->portName.startsWith(rfcommDeviceName)) { // Bluetooth device bool ok; // Check for an unsigned decimal integer at the end of the device name: "rfcomm0", "rfcomm15" // devices with negative and invalid numbers in the name are rejected int portNumber = serialPortInfo.d_ptr->portName.mid(rfcommDeviceName.length()).toInt(&ok); if (!ok || (portNumber < 0) || (portNumber > 255)) { canAppendToList = false; } } else { canAppendToList = false; } } if (canAppendToList) serialPortInfoList.append(serialPortInfo); ::udev_device_unref(dev); } } ::udev_enumerate_unref(enumerate); } ::udev_unref(udev); } #elif defined (Q_OS_FREEBSD) && defined (HAVE_LIBUSB) // TODO: Implement me. #else QDir devDir(QLatin1String("/dev")); if (devDir.exists()) { devDir.setNameFilters(filtersOfDevices()); devDir.setFilter(QDir::Files | QDir::System | QDir::NoSymLinks); QStringList foundDevices; // Found devices list. foreach (const QFileInfo &deviceFileInfo, devDir.entryInfoList()) { QString deviceFilePath = deviceFileInfo.absoluteFilePath(); if (!foundDevices.contains(deviceFilePath)) { foundDevices.append(deviceFilePath); QSerialPortInfo serialPortInfo; serialPortInfo.d_ptr->device = deviceFilePath; serialPortInfo.d_ptr->portName = QSerialPortPrivate::portNameFromSystemLocation(deviceFilePath); // Get description, manufacturer, vendor identifier, product // identifier are not supported. serialPortInfoList.append(serialPortInfo); } } } #endif return serialPortInfoList; } #endif // Q_OS_MAC // common part QList<qint32> QSerialPortInfo::standardBaudRates() { return QSerialPortPrivate::standardBaudRates(); } bool QSerialPortInfo::isBusy() const { bool currentPid = false; return QTtyLocker::isLocked(portName().toLocal8Bit().constData(), &currentPid); } bool QSerialPortInfo::isValid() const { QFile f(systemLocation()); return f.exists(); } QT_END_NAMESPACE <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_start_cbs.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_start_cbs.C /// /// @brief Start CBS : Trigger CBS //------------------------------------------------------------------------------ // *HWP HW Owner : Abhishek Agarwal <abagarw8@in.ibm.com> // *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com> // *HWP FW Owner : sunil kumar <skumar8j@in.ibm.com> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : SE:HB //------------------------------------------------------------------------------ //## auto_generated #include "p9_start_cbs.H" #include <p9_perv_scom_addresses.H> #include <p9_perv_scom_addresses_fld.H> enum P9_START_CBS_Private_Constants { P9_CFAM_CBS_POLL_COUNT = 600, // Observed Number of times CBS read for CBS_INTERNAL_STATE_VECTOR CBS_IDLE_VALUE = 0x002, // Read the value of CBS_CS_INTERNAL_STATE_VECTOR P9_CBS_IDLE_HW_NS_DELAY = 100000, // unit is nano seconds P9_CBS_IDLE_SIM_CYCLE_DELAY = 250000 // unit is sim cycles }; fapi2::ReturnCode p9_start_cbs(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_target_chip, const bool i_sbe_start) { bool l_sbe_start_value = false; fapi2::buffer<uint32_t> l_data32; fapi2::buffer<uint32_t> l_data32_cbs_cs; int l_timeout = 0; FAPI_INF("Entering ..."); l_sbe_start_value = !i_sbe_start; FAPI_DBG("Configuring Prevent SBE start option"); FAPI_IMP("SBE start value : %d", l_sbe_start_value); //Setting CBS_CS register value FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI, l_data32_cbs_cs)); //CFAM.CBS_CS.CBS_CS_PREVENT_SBE_START = l_sbe_start_value l_data32_cbs_cs.writeBit<3>(l_sbe_start_value); FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI, l_data32_cbs_cs)); FAPI_DBG("Resetting CFAM Boot Sequencer (CBS) to flush value"); //Setting CBS_CS register value FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI, l_data32_cbs_cs)); l_data32_cbs_cs.clearBit<0>(); //CFAM.CBS_CS.CBS_CS_START_BOOT_SEQUENCER = 0 FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI, l_data32_cbs_cs)); // HW319150 - pervSoA: cbs_start is implemented as pulse 0 -> 1 FAPI_DBG("Triggering CFAM Boot Sequencer (CBS) to start"); //Setting CBS_CS register value l_data32_cbs_cs.setBit<0>(); //CFAM.CBS_CS.CBS_CS_START_BOOT_SEQUENCER = 1 FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI, l_data32_cbs_cs)); FAPI_DBG("Check cbs_cs_internal_state_vector"); l_timeout = P9_CFAM_CBS_POLL_COUNT; //UNTIL CBS_CS.CBS_CS_INTERNAL_STATE_VECTOR == CBS_IDLE_VALUE while (l_timeout != 0) { //Getting CBS_CS register value FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI, l_data32_cbs_cs)); uint32_t l_poll_data = 0; //uint32_t l_poll_data = CFAM.CBS_CS.CBS_CS_INTERNAL_STATE_VECTOR l_data32_cbs_cs.extractToRight<16, 16>(l_poll_data); if (l_poll_data == CBS_IDLE_VALUE) { break; } fapi2::delay(P9_CBS_IDLE_HW_NS_DELAY, P9_CBS_IDLE_SIM_CYCLE_DELAY); --l_timeout; } FAPI_DBG("Loop Count :%d", l_timeout); FAPI_ASSERT(l_timeout > 0, fapi2::CBS_CS_INTERNAL_STATE(), "ERROR:STATE NOT SET , CBS_CS BIT 30 NOT SET"); FAPI_INF("Exiting ..."); fapi_try_exit: return fapi2::current_err; } <commit_msg>Level 2 Hwp for p9_start_cbs<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_start_cbs.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_start_cbs.C /// /// @brief Start CBS : Trigger CBS //------------------------------------------------------------------------------ // *HWP HW Owner : Abhishek Agarwal <abagarw8@in.ibm.com> // *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com> // *HWP FW Owner : sunil kumar <skumar8j@in.ibm.com> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : SE:HB //------------------------------------------------------------------------------ //## auto_generated #include "p9_start_cbs.H" //## auto_generated #include "p9_const_common.H" #include <p9_perv_scom_addresses.H> #include <p9_perv_scom_addresses_fld.H> #include <p9_perv_scom_addresses_fixes.H> #include <p9_perv_scom_addresses_fld_fixes.H> enum P9_START_CBS_Private_Constants { P9_CFAM_CBS_POLL_COUNT = 600, // Observed Number of times CBS read for CBS_INTERNAL_STATE_VECTOR CBS_IDLE_VALUE = 0x002, // Read the value of CBS_CS_INTERNAL_STATE_VECTOR P9_CBS_IDLE_HW_NS_DELAY = 100000, // unit is nano seconds P9_CBS_IDLE_SIM_CYCLE_DELAY = 250000 // unit is sim cycles }; fapi2::ReturnCode p9_start_cbs(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_target_chip, const bool i_sbe_start) { fapi2::buffer<uint32_t> l_read_reg ; bool l_read_vdn_pgood_status = false; bool l_sbe_start_value = false; bool l_fsi2pib_status = false; fapi2::buffer<uint32_t> l_data32; fapi2::buffer<uint32_t> l_data32_cbs_cs; int l_timeout = 0; FAPI_INF("Entering ..."); l_sbe_start_value = !i_sbe_start; FAPI_DBG("Configuring Prevent SBE start option"); FAPI_IMP("SBE start value : %d", l_sbe_start_value); //Setting CBS_CS register value FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI, l_data32_cbs_cs)); //CFAM.CBS_CS.CBS_CS_PREVENT_SBE_START = l_sbe_start_value l_data32_cbs_cs.writeBit<3>(l_sbe_start_value); FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI, l_data32_cbs_cs)); FAPI_DBG("check for VDN_PGOOD"); //Getting PERV_CBS_ENVSTAT register value FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_ENVSTAT_FSI, l_data32)); l_read_vdn_pgood_status = l_data32.getBit<PERV_CBS_ENVSTAT_C4_VDN_GPOOD>(); //l_read_vdn_pgood_status = PERV_CBS_ENVSTAT.PERV_CBS_ENVSTAT_C4_VDN_GPOOD FAPI_ASSERT(l_read_vdn_pgood_status, fapi2::VDN_PGOOD_NOT_SET(), "ERROR:VDN PGOOD OFF, CBS_ENVSTAT BIT 2 NOT SET"); FAPI_DBG("Resetting CFAM Boot Sequencer (CBS) to flush value"); //Setting CBS_CS register value FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI, l_data32_cbs_cs)); l_data32_cbs_cs.clearBit<0>(); //CFAM.CBS_CS.CBS_CS_START_BOOT_SEQUENCER = 0 FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI, l_data32_cbs_cs)); // HW319150 - pervSoA: cbs_start is implemented as pulse 0 -> 1 FAPI_DBG("Triggering CFAM Boot Sequencer (CBS) to start"); //Setting CBS_CS register value l_data32_cbs_cs.setBit<0>(); //CFAM.CBS_CS.CBS_CS_START_BOOT_SEQUENCER = 1 FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI, l_data32_cbs_cs)); FAPI_DBG("Check cbs_cs_internal_state_vector"); l_timeout = P9_CFAM_CBS_POLL_COUNT; //UNTIL CBS_CS.CBS_CS_INTERNAL_STATE_VECTOR == CBS_IDLE_VALUE while (l_timeout != 0) { //Getting CBS_CS register value FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI, l_data32_cbs_cs)); uint32_t l_poll_data = 0; //uint32_t l_poll_data = CFAM.CBS_CS.CBS_CS_INTERNAL_STATE_VECTOR l_data32_cbs_cs.extractToRight<16, 16>(l_poll_data); if (l_poll_data == CBS_IDLE_VALUE) { break; } fapi2::delay(P9_CBS_IDLE_HW_NS_DELAY, P9_CBS_IDLE_SIM_CYCLE_DELAY); --l_timeout; } FAPI_DBG("Loop Count :%d", l_timeout); FAPI_ASSERT(l_timeout > 0, fapi2::CBS_CS_INTERNAL_STATE(), "ERROR: CBS_CS_INTERNAL_STATE_VECTOR HAS NOT REACHED IDLE STATE VALUE 0x002 "); FAPI_DBG("check for VDD status"); //Getting FSI2PIB_STATUS register value FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_FSI2PIB_STATUS_FSI, l_data32)); //l_fsi2pib_status = CFAM.FSI2PIB_STATUS.VDD_NEST_OBSERVE l_fsi2pib_status = l_data32.getBit<PERV_FSI2PIB_STATUS_VDD_NEST_OBSERVE>(); FAPI_ASSERT(l_fsi2pib_status, fapi2::VDD_NEST_OBSERVE(), "ERROR:VDD OFF, FSI2PIB BIT 16 NOT SET"); FAPI_INF("Exiting ..."); fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef ROCPRIM_DETAIL_VARIOUS_HPP_ #define ROCPRIM_DETAIL_VARIOUS_HPP_ #include <type_traits> #include "../config.hpp" #include "../types.hpp" #include "../type_traits.hpp" // TODO: Refactor when it gets crowded BEGIN_ROCPRIM_NAMESPACE namespace detail { struct empty_storage_type { }; template<class T> ROCPRIM_HOST_DEVICE inline constexpr bool is_power_of_two(const T x) { static_assert(::rocprim::is_integral<T>::value, "T must be integer type"); return (x > 0) && ((x & (x - 1)) == 0); } template<class T> ROCPRIM_HOST_DEVICE inline constexpr T next_power_of_two(const T x, const T acc = 1) { static_assert(::rocprim::is_unsigned<T>::value, "T must be unsigned type"); return acc >= x ? acc : next_power_of_two(x, 2 * acc); } template<class T> ROCPRIM_HOST_DEVICE inline constexpr auto ceiling_div(T a, T b) -> typename std::enable_if<::rocprim::is_integral<T>::value, T>::type { return (a + b - 1) / b; } ROCPRIM_HOST_DEVICE inline size_t align_size(size_t size, size_t alignment = 256) { return ceiling_div(size, alignment) * alignment; } // Select the minimal warp size for block of size block_size, it's // useful for blocks smaller than maximal warp size. template<class T> ROCPRIM_HOST_DEVICE inline constexpr T get_min_warp_size(const T block_size, const T max_warp_size) { static_assert(::rocprim::is_unsigned<T>::value, "T must be unsigned type"); return block_size >= max_warp_size ? max_warp_size : next_power_of_two(block_size); } template<unsigned int WarpSize> struct is_warpsize_shuffleable { static const bool value = detail::is_power_of_two(WarpSize); }; // Selects an appropriate vector_type based on the input T and size N. // The byte size is calculated and used to select an appropriate vector_type. template<class T, unsigned int N> struct match_vector_type { static constexpr unsigned int size = sizeof(T) * N; using vector_base_type = typename std::conditional< sizeof(T) >= 4, int, typename std::conditional< sizeof(T) >= 2, short, char >::type >::type; using vector_4 = typename make_vector_type<vector_base_type, 4>::type; using vector_2 = typename make_vector_type<vector_base_type, 2>::type; using vector_1 = typename make_vector_type<vector_base_type, 1>::type; using type = typename std::conditional< size % sizeof(vector_4) == 0, vector_4, typename std::conditional< size % sizeof(vector_2) == 0, vector_2, vector_1 >::type >::type; }; // Checks if Items is odd and ensures that size of T is smaller than vector_type. template<class T, unsigned int Items> ROCPRIM_HOST_DEVICE constexpr bool is_vectorizable() { return (Items % 2 == 0) && (sizeof(T) < sizeof(typename match_vector_type<T, Items>::type)); } // Returns the number of LDS (local data share) banks. ROCPRIM_HOST_DEVICE constexpr unsigned int get_lds_banks_no() { // Currently all devices supported by ROCm have 32 banks (4 bytes each) return 32; } // Finds biggest fundamental type for type T that sizeof(T) is // a multiple of that type's size. template<class T> struct match_fundamental_type { using type = typename std::conditional< sizeof(T)%8 == 0, unsigned long long, typename std::conditional< sizeof(T)%4 == 0, unsigned int, typename std::conditional< sizeof(T)%2 == 0, unsigned short, unsigned char >::type >::type >::type; }; template<class T> ROCPRIM_DEVICE inline auto store_volatile(T * output, T value) -> typename std::enable_if<std::is_fundamental<T>::value>::type { *const_cast<volatile T*>(output) = value; } template<class T> ROCPRIM_DEVICE inline auto store_volatile(T * output, T value) -> typename std::enable_if<!std::is_fundamental<T>::value>::type { using fundamental_type = typename match_fundamental_type<T>::type; constexpr unsigned int n = sizeof(T) / sizeof(fundamental_type); auto input_ptr = reinterpret_cast<volatile fundamental_type*>(&value); auto output_ptr = reinterpret_cast<volatile fundamental_type*>(output); #pragma unroll for(unsigned int i = 0; i < n; i++) { output_ptr[i] = input_ptr[i]; } } template<class T> ROCPRIM_DEVICE inline auto load_volatile(T * input) -> typename std::enable_if<std::is_fundamental<T>::value, T>::type { T retval = *const_cast<volatile T*>(input); return retval; } template<class T> ROCPRIM_DEVICE inline auto load_volatile(T * input) -> typename std::enable_if<!std::is_fundamental<T>::value, T>::type { using fundamental_type = typename match_fundamental_type<T>::type; constexpr unsigned int n = sizeof(T) / sizeof(fundamental_type); T retval; auto output_ptr = reinterpret_cast<volatile fundamental_type*>(&retval); auto input_ptr = reinterpret_cast<volatile fundamental_type*>(input); #pragma unroll for(unsigned int i = 0; i < n; i++) { output_ptr[i] = input_ptr[i]; } return retval; } // A storage-backing wrapper that allows types with non-trivial constructors to be aliased in unions template <typename T> struct raw_storage { // Biggest memory-access word that T is a whole multiple of and is not larger than the alignment of T typedef typename detail::match_fundamental_type<T>::type device_word; // Backing storage device_word storage[sizeof(T) / sizeof(device_word)]; // Alias ROCPRIM_HOST_DEVICE T& get() { return reinterpret_cast<T&>(*this); } }; // Checks if two iterators have the same type and value template<class Iterator1, class Iterator2> inline bool are_iterators_equal(Iterator1, Iterator2) { return false; } template<class Iterator> inline bool are_iterators_equal(Iterator iter1, Iterator iter2) { return iter1 == iter2; } } // end namespace detail END_ROCPRIM_NAMESPACE #endif // ROCPRIM_DETAIL_VARIOUS_HPP_ <commit_msg>Add half-overload for load/store-volatile<commit_after>// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef ROCPRIM_DETAIL_VARIOUS_HPP_ #define ROCPRIM_DETAIL_VARIOUS_HPP_ #include <type_traits> #include "../config.hpp" #include "../types.hpp" #include "../type_traits.hpp" // TODO: Refactor when it gets crowded BEGIN_ROCPRIM_NAMESPACE namespace detail { struct empty_storage_type { }; template<class T> ROCPRIM_HOST_DEVICE inline constexpr bool is_power_of_two(const T x) { static_assert(::rocprim::is_integral<T>::value, "T must be integer type"); return (x > 0) && ((x & (x - 1)) == 0); } template<class T> ROCPRIM_HOST_DEVICE inline constexpr T next_power_of_two(const T x, const T acc = 1) { static_assert(::rocprim::is_unsigned<T>::value, "T must be unsigned type"); return acc >= x ? acc : next_power_of_two(x, 2 * acc); } template<class T> ROCPRIM_HOST_DEVICE inline constexpr auto ceiling_div(T a, T b) -> typename std::enable_if<::rocprim::is_integral<T>::value, T>::type { return (a + b - 1) / b; } ROCPRIM_HOST_DEVICE inline size_t align_size(size_t size, size_t alignment = 256) { return ceiling_div(size, alignment) * alignment; } // Select the minimal warp size for block of size block_size, it's // useful for blocks smaller than maximal warp size. template<class T> ROCPRIM_HOST_DEVICE inline constexpr T get_min_warp_size(const T block_size, const T max_warp_size) { static_assert(::rocprim::is_unsigned<T>::value, "T must be unsigned type"); return block_size >= max_warp_size ? max_warp_size : next_power_of_two(block_size); } template<unsigned int WarpSize> struct is_warpsize_shuffleable { static const bool value = detail::is_power_of_two(WarpSize); }; // Selects an appropriate vector_type based on the input T and size N. // The byte size is calculated and used to select an appropriate vector_type. template<class T, unsigned int N> struct match_vector_type { static constexpr unsigned int size = sizeof(T) * N; using vector_base_type = typename std::conditional< sizeof(T) >= 4, int, typename std::conditional< sizeof(T) >= 2, short, char >::type >::type; using vector_4 = typename make_vector_type<vector_base_type, 4>::type; using vector_2 = typename make_vector_type<vector_base_type, 2>::type; using vector_1 = typename make_vector_type<vector_base_type, 1>::type; using type = typename std::conditional< size % sizeof(vector_4) == 0, vector_4, typename std::conditional< size % sizeof(vector_2) == 0, vector_2, vector_1 >::type >::type; }; // Checks if Items is odd and ensures that size of T is smaller than vector_type. template<class T, unsigned int Items> ROCPRIM_HOST_DEVICE constexpr bool is_vectorizable() { return (Items % 2 == 0) && (sizeof(T) < sizeof(typename match_vector_type<T, Items>::type)); } // Returns the number of LDS (local data share) banks. ROCPRIM_HOST_DEVICE constexpr unsigned int get_lds_banks_no() { // Currently all devices supported by ROCm have 32 banks (4 bytes each) return 32; } // Finds biggest fundamental type for type T that sizeof(T) is // a multiple of that type's size. template<class T> struct match_fundamental_type { using type = typename std::conditional< sizeof(T)%8 == 0, unsigned long long, typename std::conditional< sizeof(T)%4 == 0, unsigned int, typename std::conditional< sizeof(T)%2 == 0, unsigned short, unsigned char >::type >::type >::type; }; template<class T> ROCPRIM_DEVICE inline auto store_volatile(T * output, T value) -> typename std::enable_if<std::is_fundamental<T>::value>::type { *const_cast<volatile T*>(output) = value; } template<class T> ROCPRIM_DEVICE inline auto store_volatile(T * output, T value) -> typename std::enable_if<!std::is_fundamental<T>::value>::type { using fundamental_type = typename match_fundamental_type<T>::type; constexpr unsigned int n = sizeof(T) / sizeof(fundamental_type); auto input_ptr = reinterpret_cast<volatile fundamental_type*>(&value); auto output_ptr = reinterpret_cast<volatile fundamental_type*>(output); #pragma unroll for(unsigned int i = 0; i < n; i++) { output_ptr[i] = input_ptr[i]; } } ROCPRIM_DEVICE inline void store_volatile(half * output, half value) { *reinterpret_cast<volatile _Float16*>(output) = value; } template<class T> ROCPRIM_DEVICE inline auto load_volatile(T * input) -> typename std::enable_if<std::is_fundamental<T>::value, T>::type { T retval = *const_cast<volatile T*>(input); return retval; } template<class T> ROCPRIM_DEVICE inline auto load_volatile(T * input) -> typename std::enable_if<!std::is_fundamental<T>::value, T>::type { using fundamental_type = typename match_fundamental_type<T>::type; constexpr unsigned int n = sizeof(T) / sizeof(fundamental_type); T retval; auto output_ptr = reinterpret_cast<volatile fundamental_type*>(&retval); auto input_ptr = reinterpret_cast<volatile fundamental_type*>(input); #pragma unroll for(unsigned int i = 0; i < n; i++) { output_ptr[i] = input_ptr[i]; } return retval; } ROCPRIM_DEVICE inline half load_volatile(half * input) { half retval = *reinterpret_cast<volatile _Float16*>(input); return retval; } // A storage-backing wrapper that allows types with non-trivial constructors to be aliased in unions template <typename T> struct raw_storage { // Biggest memory-access word that T is a whole multiple of and is not larger than the alignment of T typedef typename detail::match_fundamental_type<T>::type device_word; // Backing storage device_word storage[sizeof(T) / sizeof(device_word)]; // Alias ROCPRIM_HOST_DEVICE T& get() { return reinterpret_cast<T&>(*this); } }; // Checks if two iterators have the same type and value template<class Iterator1, class Iterator2> inline bool are_iterators_equal(Iterator1, Iterator2) { return false; } template<class Iterator> inline bool are_iterators_equal(Iterator iter1, Iterator iter2) { return iter1 == iter2; } } // end namespace detail END_ROCPRIM_NAMESPACE #endif // ROCPRIM_DETAIL_VARIOUS_HPP_ <|endoftext|>
<commit_before> #include "temoto/preplanned_sequences/enable_compliance.h" // Enable compliance int enable_compliance::enable_compliance() { // Put the robot in force mode // This will be compliant in all directions with a target wrench of 0 std::vector<float> force_frame {0., 0., 0., 0., 0., 0.}; // A pose std::vector<int> selection_vector {1, 1, 1, 1, 1, 1}; // Compliant in all directions std::vector<int> target_wrench {0, 0, 0, 0, 0, 0}; int type = 1; // Force frame transform std::vector<float> limits {0.8, 0.8, 0.8, 1.571, 1.571, 1.571}; // Displacement limits ur_script_compliance right_arm("/right_ur5_controller/right_ur5_URScript"); right_arm.enable_force_mode_( force_frame, selection_vector, target_wrench, type, limits ); return 0; } <commit_msg>Update for ur_script_interface.<commit_after> #include "temoto/preplanned_sequences/enable_compliance.h" // Enable compliance int enable_compliance::enable_compliance() { // Put the robot in force mode // This will be compliant in all directions with a target wrench of 0 std::vector<float> force_frame {0., 0., 0., 0., 0., 0.}; // A pose std::vector<int> selection_vector {1, 1, 1, 1, 1, 1}; // Compliant in all directions std::vector<int> target_wrench {0, 0, 0, 0, 0, 0}; int type = 1; // Force frame transform std::vector<float> limits {0.8, 0.8, 0.8, 1.571, 1.571, 1.571}; // Displacement limits ur_script_interface right_arm("/right_ur5_controller/right_ur5_URScript"); right_arm.enable_force_mode_( force_frame, selection_vector, target_wrench, type, limits ); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: datasourceconnector.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2005-01-21 17:20:22 $ * * 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_DATASOURCECONNECTOR_HXX_ #include "datasourceconnector.hxx" #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef DBACCESS_SHARED_DBUSTRINGS_HRC #include "dbustrings.hrc" #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_SDB_XCOMPLETEDCONNECTION_HPP_ #include <com/sun/star/sdb/XCompletedConnection.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_ #include <com/sun/star/task/XInteractionHandler.hpp> #endif #ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_ #include <com/sun/star/sdb/SQLContext.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_ #include <com/sun/star/sdbc/SQLWarning.hpp> #endif #ifndef _OSL_THREAD_H_ #include <osl/thread.h> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif #ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_ #include <com/sun/star/sdbc/XDataSource.hpp> #endif #ifndef DBAUI_TOOLS_HXX #include "UITools.hxx" #endif #ifndef _VCL_STDTEXT_HXX #include <vcl/stdtext.hxx> #endif #ifndef SVTOOLS_FILENOTATION_HXX #include <svtools/filenotation.hxx> #endif #ifndef _DBU_MISC_HRC_ #include "dbu_misc.hrc" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif //......................................................................... namespace dbaui { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::sdb; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::task; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::dbtools; using ::svt::OFileNotation; //===================================================================== //= ODatasourceConnector //===================================================================== //--------------------------------------------------------------------- ODatasourceConnector::ODatasourceConnector(const Reference< XMultiServiceFactory >& _rxORB, Window* _pMessageParent) :m_xORB(_rxORB) ,m_pErrorMessageParent(_pMessageParent) { implConstruct(); } //--------------------------------------------------------------------- ODatasourceConnector::ODatasourceConnector( const Reference< XMultiServiceFactory >& _rxORB, Window* _pMessageParent, const ::rtl::OUString& _rContextInformation, const ::rtl::OUString& _rContextDetails ) :m_xORB(_rxORB) ,m_pErrorMessageParent(_pMessageParent) ,m_sContextInformation( _rContextInformation ) ,m_sContextDetails( _rContextDetails ) { implConstruct(); } //--------------------------------------------------------------------- void ODatasourceConnector::implConstruct() { OSL_ENSURE(m_xORB.is(), "ODatasourceConnector::implConstruct: invalid ORB!"); if (m_xORB.is()) { try { Reference< XInterface > xContext = m_xORB->createInstance(SERVICE_SDB_DATABASECONTEXT); OSL_ENSURE(xContext.is(), "ODatasourceConnector::implConstruct: got no data source context!"); m_xDatabaseContext.set(xContext,UNO_QUERY); OSL_ENSURE(m_xDatabaseContext.is() || !xContext.is(), "ODatasourceConnector::ODatasourceConnector: missing the XNameAccess interface on the data source context!"); } catch(const Exception&) { OSL_ENSURE(sal_False, "ODatasourceConnector::implConstruct: caught an exception while creating the data source context!"); } } } //--------------------------------------------------------------------- Reference< XConnection > ODatasourceConnector::connect(const ::rtl::OUString& _rDataSourceName, sal_Bool _bShowError) const { Reference< XConnection > xConnection; OSL_ENSURE(isValid(), "ODatasourceConnector::connect: invalid object!"); if (!isValid()) return xConnection; // get the data source Reference< XDataSource > xDatasource( getDataSourceByName_displayError( m_xDatabaseContext, _rDataSourceName, m_pErrorMessageParent, m_xORB, _bShowError ), UNO_QUERY ); if ( xDatasource.is() ) xConnection = connect( xDatasource, _bShowError ); return xConnection; } //--------------------------------------------------------------------- Reference< XConnection > ODatasourceConnector::connect(const Reference< XDataSource>& _xDataSource, sal_Bool _bShowError) const { Reference< XConnection > xConnection; OSL_ENSURE(isValid(), "ODatasourceConnector::connect: invalid object!"); if (!isValid()) return xConnection; if (!_xDataSource.is()) { OSL_ENSURE(sal_False, "ODatasourceConnector::connect: could not retrieve the data source!"); return xConnection; } // get user/password ::rtl::OUString sPassword, sUser; sal_Bool bPwdRequired = sal_False; Reference<XPropertySet> xProp(_xDataSource,UNO_QUERY); try { xProp->getPropertyValue(PROPERTY_PASSWORD) >>= sPassword; xProp->getPropertyValue(PROPERTY_ISPASSWORDREQUIRED) >>= bPwdRequired; xProp->getPropertyValue(PROPERTY_USER) >>= sUser; } catch(Exception&) { OSL_ENSURE(sal_False, "ODatasourceConnector::connect: error while retrieving data source properties!"); } // try to connect SQLExceptionInfo aInfo; try { if (bPwdRequired && !sPassword.getLength()) { // password required, but empty -> connect using an interaction handler Reference< XCompletedConnection > xConnectionCompletion(_xDataSource, UNO_QUERY); if (!xConnectionCompletion.is()) { OSL_ENSURE(sal_False, "ODatasourceConnector::connect: missing an interface ... need an error message here!"); } else { // instantiate the default SDB interaction handler Reference< XInteractionHandler > xHandler(m_xORB->createInstance(SERVICE_SDB_INTERACTION_HANDLER), UNO_QUERY); if (!xHandler.is()) { ShowServiceNotAvailableError(m_pErrorMessageParent, String(SERVICE_SDB_INTERACTION_HANDLER), sal_True); } else { xConnection = xConnectionCompletion->connectWithCompletion(xHandler); } } } else { xConnection = _xDataSource->getConnection(sUser, sPassword); } } catch(SQLContext& e) { aInfo = SQLExceptionInfo(e); } catch(SQLWarning& e) { aInfo = SQLExceptionInfo(e); } catch(SQLException& e) { aInfo = SQLExceptionInfo(e); } catch(Exception&) { OSL_ENSURE(sal_False, "SbaTableQueryBrowser::OnExpandEntry: could not connect - unknown exception!"); } // display the error (if any) if ( _bShowError && aInfo.isValid() ) { if ( m_sContextInformation.getLength() ) { SQLContext aContext; aContext.Message = m_sContextInformation; aContext.Details = m_sContextDetails; aContext.NextException = aInfo.get(); aInfo = aContext; } showError(aInfo, m_pErrorMessageParent, m_xORB); } return xConnection; } //......................................................................... } // namespace dbaui //......................................................................... <commit_msg>INTEGRATION: CWS ooo19126 (1.6.142); FILE MERGED 2005/09/05 17:35:17 rt 1.6.142.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: datasourceconnector.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-08 16:12:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _DBAUI_DATASOURCECONNECTOR_HXX_ #include "datasourceconnector.hxx" #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef DBACCESS_SHARED_DBUSTRINGS_HRC #include "dbustrings.hrc" #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_SDB_XCOMPLETEDCONNECTION_HPP_ #include <com/sun/star/sdb/XCompletedConnection.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_ #include <com/sun/star/task/XInteractionHandler.hpp> #endif #ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_ #include <com/sun/star/sdb/SQLContext.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_ #include <com/sun/star/sdbc/SQLWarning.hpp> #endif #ifndef _OSL_THREAD_H_ #include <osl/thread.h> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif #ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_ #include <com/sun/star/sdbc/XDataSource.hpp> #endif #ifndef DBAUI_TOOLS_HXX #include "UITools.hxx" #endif #ifndef _VCL_STDTEXT_HXX #include <vcl/stdtext.hxx> #endif #ifndef SVTOOLS_FILENOTATION_HXX #include <svtools/filenotation.hxx> #endif #ifndef _DBU_MISC_HRC_ #include "dbu_misc.hrc" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif //......................................................................... namespace dbaui { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::sdb; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::task; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::dbtools; using ::svt::OFileNotation; //===================================================================== //= ODatasourceConnector //===================================================================== //--------------------------------------------------------------------- ODatasourceConnector::ODatasourceConnector(const Reference< XMultiServiceFactory >& _rxORB, Window* _pMessageParent) :m_xORB(_rxORB) ,m_pErrorMessageParent(_pMessageParent) { implConstruct(); } //--------------------------------------------------------------------- ODatasourceConnector::ODatasourceConnector( const Reference< XMultiServiceFactory >& _rxORB, Window* _pMessageParent, const ::rtl::OUString& _rContextInformation, const ::rtl::OUString& _rContextDetails ) :m_xORB(_rxORB) ,m_pErrorMessageParent(_pMessageParent) ,m_sContextInformation( _rContextInformation ) ,m_sContextDetails( _rContextDetails ) { implConstruct(); } //--------------------------------------------------------------------- void ODatasourceConnector::implConstruct() { OSL_ENSURE(m_xORB.is(), "ODatasourceConnector::implConstruct: invalid ORB!"); if (m_xORB.is()) { try { Reference< XInterface > xContext = m_xORB->createInstance(SERVICE_SDB_DATABASECONTEXT); OSL_ENSURE(xContext.is(), "ODatasourceConnector::implConstruct: got no data source context!"); m_xDatabaseContext.set(xContext,UNO_QUERY); OSL_ENSURE(m_xDatabaseContext.is() || !xContext.is(), "ODatasourceConnector::ODatasourceConnector: missing the XNameAccess interface on the data source context!"); } catch(const Exception&) { OSL_ENSURE(sal_False, "ODatasourceConnector::implConstruct: caught an exception while creating the data source context!"); } } } //--------------------------------------------------------------------- Reference< XConnection > ODatasourceConnector::connect(const ::rtl::OUString& _rDataSourceName, sal_Bool _bShowError) const { Reference< XConnection > xConnection; OSL_ENSURE(isValid(), "ODatasourceConnector::connect: invalid object!"); if (!isValid()) return xConnection; // get the data source Reference< XDataSource > xDatasource( getDataSourceByName_displayError( m_xDatabaseContext, _rDataSourceName, m_pErrorMessageParent, m_xORB, _bShowError ), UNO_QUERY ); if ( xDatasource.is() ) xConnection = connect( xDatasource, _bShowError ); return xConnection; } //--------------------------------------------------------------------- Reference< XConnection > ODatasourceConnector::connect(const Reference< XDataSource>& _xDataSource, sal_Bool _bShowError) const { Reference< XConnection > xConnection; OSL_ENSURE(isValid(), "ODatasourceConnector::connect: invalid object!"); if (!isValid()) return xConnection; if (!_xDataSource.is()) { OSL_ENSURE(sal_False, "ODatasourceConnector::connect: could not retrieve the data source!"); return xConnection; } // get user/password ::rtl::OUString sPassword, sUser; sal_Bool bPwdRequired = sal_False; Reference<XPropertySet> xProp(_xDataSource,UNO_QUERY); try { xProp->getPropertyValue(PROPERTY_PASSWORD) >>= sPassword; xProp->getPropertyValue(PROPERTY_ISPASSWORDREQUIRED) >>= bPwdRequired; xProp->getPropertyValue(PROPERTY_USER) >>= sUser; } catch(Exception&) { OSL_ENSURE(sal_False, "ODatasourceConnector::connect: error while retrieving data source properties!"); } // try to connect SQLExceptionInfo aInfo; try { if (bPwdRequired && !sPassword.getLength()) { // password required, but empty -> connect using an interaction handler Reference< XCompletedConnection > xConnectionCompletion(_xDataSource, UNO_QUERY); if (!xConnectionCompletion.is()) { OSL_ENSURE(sal_False, "ODatasourceConnector::connect: missing an interface ... need an error message here!"); } else { // instantiate the default SDB interaction handler Reference< XInteractionHandler > xHandler(m_xORB->createInstance(SERVICE_SDB_INTERACTION_HANDLER), UNO_QUERY); if (!xHandler.is()) { ShowServiceNotAvailableError(m_pErrorMessageParent, String(SERVICE_SDB_INTERACTION_HANDLER), sal_True); } else { xConnection = xConnectionCompletion->connectWithCompletion(xHandler); } } } else { xConnection = _xDataSource->getConnection(sUser, sPassword); } } catch(SQLContext& e) { aInfo = SQLExceptionInfo(e); } catch(SQLWarning& e) { aInfo = SQLExceptionInfo(e); } catch(SQLException& e) { aInfo = SQLExceptionInfo(e); } catch(Exception&) { OSL_ENSURE(sal_False, "SbaTableQueryBrowser::OnExpandEntry: could not connect - unknown exception!"); } // display the error (if any) if ( _bShowError && aInfo.isValid() ) { if ( m_sContextInformation.getLength() ) { SQLContext aContext; aContext.Message = m_sContextInformation; aContext.Details = m_sContextDetails; aContext.NextException = aInfo.get(); aInfo = aContext; } showError(aInfo, m_pErrorMessageParent, m_xORB); } return xConnection; } //......................................................................... } // namespace dbaui //......................................................................... <|endoftext|>
<commit_before>#include "generator.h" #include "opcodes.h" #include "sections.h" #include <iostream> namespace ceos { std::stringstream &Generator::generate() { generateProgram(m_ast); m_output.seekg(0); return m_output; } void Generator::generateNode(std::shared_ptr<AST> node) { switch (node->type) { case AST::Type::Call: generateCall(std::static_pointer_cast<AST::Call>(node)); break; case AST::Type::Number: generateNumber(std::static_pointer_cast<AST::Number>(node)); break; case AST::Type::ID: generateID(std::static_pointer_cast<AST::ID>(node)); break; case AST::Type::String: generateString(std::static_pointer_cast<AST::String>(node)); break; case AST::Type::FunctionArgument: generateFunctionArgument(std::static_pointer_cast<AST::FunctionArgument>(node)); break; default: throw "Unhandled Type"; } } bool Generator::handleSpecialCall(std::shared_ptr<AST::Call> call) { if (call->arguments[0]->type == AST::Type::ID) { std::string callee = AST::asID(call->arguments[0])->name; if (callee == "defn") { m_ast->functions.push_back(call); return true; } else if (callee == "if") { generateIf(call); return true; } } return false; } void Generator::write(int data) { m_output.write(reinterpret_cast<char *>(&data), sizeof(data)); } void Generator::write(const std::string &data) { m_output << data; m_output.put('\0'); } void Generator::emitOpcode(Opcode::Type opcode) { write(opcode); } void Generator::emitJmp(Opcode::Type jmpType, std::shared_ptr<AST> &node) { emitJmp(jmpType, node, false); } void Generator::emitJmp(Opcode::Type jmpType, std::shared_ptr<AST> &node, bool skipNextJump) { emitOpcode(jmpType); unsigned beforePos = m_output.tellp(); write(0); // placeholder generateNode(node); unsigned afterPos = m_output.tellp(); m_output.seekp(beforePos); write((afterPos - beforePos) - 4 // sizeof the jump offset + (skipNextJump ? 8 : 0) // special case for if with else ); m_output.seekp(afterPos); } void Generator::generateCall(std::shared_ptr<AST::Call> call) { if (handleSpecialCall(call)) { return; } for (unsigned i = call->arguments.size(); i > 0;) { generateNode(call->arguments[--i]); } emitOpcode(Opcode::push); write(call->arguments.size()); emitOpcode(Opcode::call); } void Generator::generateNumber(std::shared_ptr<AST::Number> number) { emitOpcode(Opcode::push); write(number->value); } void Generator::generateID(std::shared_ptr<AST::ID> id) { auto v = m_currentScope->get(id->name); if (v) { generateNode(v); } else { emitOpcode(Opcode::lookup); write(id->uid); } } void Generator::generateString(std::shared_ptr<AST::String> str) { emitOpcode(Opcode::load_string); write(str->uid); } void Generator::generateFunctionArgument(std::shared_ptr<AST::FunctionArgument> arg) { emitOpcode(Opcode::push_arg); write(arg->index); } void Generator::generateFunction(std::shared_ptr<AST::Call> fn) { write(AST::asID(fn->arguments[1])->name); write(AST::asCall(fn->arguments[2])->arguments.size()); Scope s(this); int index = 0; for (auto arg : AST::asCall(fn->arguments[2])->arguments) { s.variables[AST::asID(arg)->name] = std::make_shared<AST::FunctionArgument>(index++); } generateNode(fn->arguments[3]); write(Opcode::ret); } void Generator::generateIf(std::shared_ptr<AST::Call> iff) { unsigned size = iff->arguments.size(); assert(size == 3 || size == 4); generateNode(iff->arguments[1]); emitJmp(Opcode::jz, iff->arguments[2], size == 4 ? 2 : 0); if (size == 4) { emitJmp(Opcode::jmp, iff->arguments[3]); } } void Generator::generateProgram(std::shared_ptr<AST::Program> program) { for (auto node : program->nodes()) { generateNode(node); } auto text = m_output.str(); m_output = std::stringstream(); if (program->strings.size()) { write(Section::Header); write(Section::Strings); for (auto string : program->strings) { write(string); } } if (program->functions.size()) { write(Section::Header); write(Section::Functions); for (auto fn : program->functions) { write(Section::FunctionHeader); generateFunction(fn); } } if (text.length()) { write(Section::Header); write(Section::Text); m_output << text; } } void Generator::disassemble(std::stringstream &bytecode) { #define WRITE(...) std::cout << __VA_ARGS__ << "\n" read_section: READ_INT(bytecode, ceos); assert(ceos == 0xCE05); READ_INT(bytecode, section); switch (section) { case Section::Strings: WRITE("section STRINGS:"); goto section_strings; break; case Section::Functions: WRITE("section FUNCTIONS:"); goto section_functions; break; case Section::Text: WRITE("section TEXT:"); goto section_code; break; } section_strings: while (true) { READ_INT(bytecode, ceos); bytecode.seekg(-4, bytecode.cur); if (ceos == 0xCE05) { goto read_section; } READ_STR(bytecode, str); WRITE(str); } section_functions: { READ_INT(bytecode, fn_header); assert(fn_header == Section::FunctionHeader); READ_STR(bytecode, fn_name); READ_INT(bytecode, arg_count); WRITE("fn " << fn_name << "(" << arg_count << "):"); while (true) { READ_INT(bytecode, header); bytecode.seekg(-4, bytecode.cur); if (header == Section::FunctionHeader) { goto section_functions; } else if (header == Section::Header) { goto read_section; } READ_INT(bytecode, opcode); printOpcode(bytecode, static_cast<Opcode::Type>(opcode)); } } section_code: while (true) { READ_INT(bytecode, opcode); printOpcode(bytecode, static_cast<Opcode::Type>(opcode)); } goto read_section; } void Generator::printOpcode(std::stringstream &bytecode, Opcode::Type opcode) { switch (opcode) { case Opcode::push: { READ_INT(bytecode, value); WRITE("push $" << value); break; } case Opcode::call: { WRITE("call"); break; } case Opcode::load_string: { READ_INT(bytecode, stringID); WRITE("load_string $" << stringID); break; } case Opcode::lookup: { READ_INT(bytecode, id); WRITE("lookup $" << id); break; } case Opcode::jmp: { READ_INT(bytecode, target); WRITE("jmp " << target); break; } case Opcode::jz: { READ_INT(bytecode, target); WRITE("jz " << target); break; } case Opcode::push_arg: { READ_INT(bytecode, arg); WRITE("push_arg $" << arg); break; } case Opcode::ret: { WRITE("ret"); break; } default: std::cerr << "Unhandled opcode: " << Opcode::typeName(static_cast<Opcode::Type>(opcode)) << "\n"; throw; } } #undef WRITE } <commit_msg>Show offset in the bytecode dump<commit_after>#include "generator.h" #include "opcodes.h" #include "sections.h" #include <iostream> #include <iomanip> namespace ceos { std::stringstream &Generator::generate() { generateProgram(m_ast); m_output.seekg(0); return m_output; } void Generator::generateNode(std::shared_ptr<AST> node) { switch (node->type) { case AST::Type::Call: generateCall(std::static_pointer_cast<AST::Call>(node)); break; case AST::Type::Number: generateNumber(std::static_pointer_cast<AST::Number>(node)); break; case AST::Type::ID: generateID(std::static_pointer_cast<AST::ID>(node)); break; case AST::Type::String: generateString(std::static_pointer_cast<AST::String>(node)); break; case AST::Type::FunctionArgument: generateFunctionArgument(std::static_pointer_cast<AST::FunctionArgument>(node)); break; default: throw "Unhandled Type"; } } bool Generator::handleSpecialCall(std::shared_ptr<AST::Call> call) { if (call->arguments[0]->type == AST::Type::ID) { std::string callee = AST::asID(call->arguments[0])->name; if (callee == "defn") { m_ast->functions.push_back(call); return true; } else if (callee == "if") { generateIf(call); return true; } } return false; } void Generator::write(int data) { m_output.write(reinterpret_cast<char *>(&data), sizeof(data)); } void Generator::write(const std::string &data) { m_output << data; m_output.put('\0'); } void Generator::emitOpcode(Opcode::Type opcode) { write(opcode); } void Generator::emitJmp(Opcode::Type jmpType, std::shared_ptr<AST> &node) { emitJmp(jmpType, node, false); } void Generator::emitJmp(Opcode::Type jmpType, std::shared_ptr<AST> &node, bool skipNextJump) { emitOpcode(jmpType); unsigned beforePos = m_output.tellp(); write(0); // placeholder generateNode(node); unsigned afterPos = m_output.tellp(); m_output.seekp(beforePos); write((afterPos - beforePos) - 4 // sizeof the jump offset + (skipNextJump ? 8 : 0) // special case for if with else ); m_output.seekp(afterPos); } void Generator::generateCall(std::shared_ptr<AST::Call> call) { if (handleSpecialCall(call)) { return; } for (unsigned i = call->arguments.size(); i > 0;) { generateNode(call->arguments[--i]); } emitOpcode(Opcode::push); write(call->arguments.size()); emitOpcode(Opcode::call); } void Generator::generateNumber(std::shared_ptr<AST::Number> number) { emitOpcode(Opcode::push); write(number->value); } void Generator::generateID(std::shared_ptr<AST::ID> id) { auto v = m_currentScope->get(id->name); if (v) { generateNode(v); } else { emitOpcode(Opcode::lookup); write(id->uid); } } void Generator::generateString(std::shared_ptr<AST::String> str) { emitOpcode(Opcode::load_string); write(str->uid); } void Generator::generateFunctionArgument(std::shared_ptr<AST::FunctionArgument> arg) { emitOpcode(Opcode::push_arg); write(arg->index); } void Generator::generateFunction(std::shared_ptr<AST::Call> fn) { write(AST::asID(fn->arguments[1])->name); write(AST::asCall(fn->arguments[2])->arguments.size()); Scope s(this); int index = 0; for (auto arg : AST::asCall(fn->arguments[2])->arguments) { s.variables[AST::asID(arg)->name] = std::make_shared<AST::FunctionArgument>(index++); } generateNode(fn->arguments[3]); write(Opcode::ret); } void Generator::generateIf(std::shared_ptr<AST::Call> iff) { unsigned size = iff->arguments.size(); assert(size == 3 || size == 4); generateNode(iff->arguments[1]); emitJmp(Opcode::jz, iff->arguments[2], size == 4 ? 2 : 0); if (size == 4) { emitJmp(Opcode::jmp, iff->arguments[3]); } } void Generator::generateProgram(std::shared_ptr<AST::Program> program) { for (auto node : program->nodes()) { generateNode(node); } auto text = m_output.str(); m_output = std::stringstream(); if (program->strings.size()) { write(Section::Header); write(Section::Strings); for (auto string : program->strings) { write(string); } } if (program->functions.size()) { write(Section::Header); write(Section::Functions); for (auto fn : program->functions) { write(Section::FunctionHeader); generateFunction(fn); } } if (text.length()) { write(Section::Header); write(Section::Text); m_output << text; } } void Generator::disassemble(std::stringstream &bytecode) { size_t size = bytecode.str().length(); size_t width = std::ceil(std::log10(size + 1)) + 1; #define WRITE(...) \ std::cout << "[" \ << std::setfill(' ') << std::setw(width) << bytecode.tellg() \ << "] " << __VA_ARGS__ << "\n" read_section: READ_INT(bytecode, ceos); assert(ceos == 0xCE05); READ_INT(bytecode, section); switch (section) { case Section::Strings: WRITE("section STRINGS:"); goto section_strings; break; case Section::Functions: WRITE("section FUNCTIONS:"); goto section_functions; break; case Section::Text: WRITE("section TEXT:"); goto section_code; break; } section_strings: while (true) { READ_INT(bytecode, ceos); bytecode.seekg(-4, bytecode.cur); if (ceos == 0xCE05) { goto read_section; } READ_STR(bytecode, str); WRITE(str); } section_functions: { READ_INT(bytecode, fn_header); assert(fn_header == Section::FunctionHeader); READ_STR(bytecode, fn_name); READ_INT(bytecode, arg_count); WRITE("fn " << fn_name << "(" << arg_count << "):"); while (true) { READ_INT(bytecode, header); bytecode.seekg(-4, bytecode.cur); if (header == Section::FunctionHeader) { goto section_functions; } else if (header == Section::Header) { goto read_section; } READ_INT(bytecode, opcode); printOpcode(bytecode, static_cast<Opcode::Type>(opcode)); } } section_code: while (true) { READ_INT(bytecode, opcode); printOpcode(bytecode, static_cast<Opcode::Type>(opcode)); } goto read_section; } void Generator::printOpcode(std::stringstream &bytecode, Opcode::Type opcode) { size_t size = bytecode.str().length(); size_t width = std::ceil(std::log10(size + 1)) + 1; switch (opcode) { case Opcode::push: { READ_INT(bytecode, value); WRITE("push $" << value); break; } case Opcode::call: { WRITE("call"); break; } case Opcode::load_string: { READ_INT(bytecode, stringID); WRITE("load_string $" << stringID); break; } case Opcode::lookup: { READ_INT(bytecode, id); WRITE("lookup $" << id); break; } case Opcode::jmp: { READ_INT(bytecode, target); WRITE("jmp " << target); break; } case Opcode::jz: { READ_INT(bytecode, target); WRITE("jz " << target); break; } case Opcode::push_arg: { READ_INT(bytecode, arg); WRITE("push_arg $" << arg); break; } case Opcode::ret: { WRITE("ret"); break; } default: std::cerr << "Unhandled opcode: " << Opcode::typeName(static_cast<Opcode::Type>(opcode)) << "\n"; throw; } } #undef WRITE } <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #define LIMIT (unsigned int) 1E9 using namespace std; struct Task { unsigned int start; unsigned int end; double res; }; void *PartialLeibniz(void *task) { Task *myTask = (Task *) task; myTask->res = 0.0; for (auto i = myTask->start; i < myTask->end; i++) { if (i % 2 == 0) myTask->res += 1.0 / ((i << 1) + 1); else myTask->res -= 1.0 / ((i << 1) + 1); } return nullptr; } int main() { int taskpipe[2], respipe[2]; if (pipe(taskpipe) == -1 || pipe(respipe)) { cerr << "pipe() failed" << endl; exit(EXIT_FAILURE); } pid_t pid = fork(); if (pid == 0) { // Child Task myTask; read(taskpipe[0], &myTask, sizeof(Task)); PartialLeibniz(&myTask); write(respipe[1], &myTask, sizeof(Task)); } else if (pid > 0) { // Parent Task task; task.start = 0; task.end = LIMIT; write(taskpipe[1], &task, sizeof(Task)); read(respipe[0], &task, sizeof(Task)); cout << "Sum\t" << task.res << endl; cout << "PI\t" << task.res * 4.0 << endl; } else { // Error cerr << "fork() failed" << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }<commit_msg>PIFork with variable number of processes.<commit_after>#include <iostream> #include <unistd.h> #define LIMIT (unsigned long) 1E10 #define PROCESSES 8 using namespace std; struct Task { unsigned long start; unsigned long end; double res; }; void *PartialLeibniz(void *task) { Task *myTask = (Task *) task; myTask->res = 0.0; for (auto i = myTask->start; i < myTask->end; ++i) { if (i % 2 == 0) myTask->res += 1.0 / ((i << 1) + 1); else myTask->res -= 1.0 / ((i << 1) + 1); } return nullptr; } int main() { int taskpipe[2], respipe[2]; if (pipe(taskpipe) == -1 || pipe(respipe)) { cerr << "pipe() failed" << endl; exit(EXIT_FAILURE); } for (auto i = 0u; i < PROCESSES; ++i) { Task task; task.start = LIMIT / PROCESSES * i; task.end = LIMIT / PROCESSES * (i + 1); write(taskpipe[1], &task, sizeof(Task)); } for (auto i = 0u; i < PROCESSES; ++i) { pid_t pid = fork(); if (pid == 0) { // Child Task myTask; read(taskpipe[0], &myTask, sizeof(Task)); PartialLeibniz(&myTask); write(respipe[1], &myTask, sizeof(Task)); return EXIT_SUCCESS; } else if (pid > 0) { // Parent } else { // Error cerr << "fork() failed" << endl; return EXIT_FAILURE; } } double sum = 0.0; for (auto i = 0u; i < PROCESSES; ++i) { Task res; read(respipe[0], &res, sizeof(Task)); sum += res.res; } cout << "Sum\t" << sum << endl; cout << "PI\t" << sum * 4.0 << endl; return EXIT_SUCCESS; }<|endoftext|>
<commit_before>/** * @license * Copyright 2021 William Silvermsith * 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. */ /* * Connected Components for 2D images. * Author: William Silversmith * Affiliation: Seung Lab, Princeton University * Date: August 2018 - June 2019, June 2021 * * ---- * Notes on the license: * * This is a special reduced feature version of cc3d * that includes only the logic needed for CCL 4-connected * and 6-connected. It is also modified to treat black as * foreground and black as background. * * cc3d is ordinarily licensed as GPL v3. * Get the full version of cc3d here: * * https://github.com/seung-lab/connected-components-3d */ #ifndef CC3D_SPECIAL_4_HPP #define CC3D_SPECIAL_4_HPP #include <algorithm> #include <cmath> #include <cstdint> #include <stdexcept> namespace cc3d { static size_t _dummy_N; template <typename T> class DisjointSet { public: T *ids; size_t length; DisjointSet () { length = 65536; // 2^16, some "reasonable" starting size ids = new T[length](); } DisjointSet (size_t len) { length = len; ids = new T[length](); } DisjointSet (const DisjointSet &cpy) { length = cpy.length; ids = new T[length](); for (int i = 0; i < length; i++) { ids[i] = cpy.ids[i]; } } ~DisjointSet () { delete []ids; } T root (T n) { T i = ids[n]; while (i != ids[i]) { ids[i] = ids[ids[i]]; // path compression i = ids[i]; } return i; } bool find (T p, T q) { return root(p) == root(q); } void add(T p) { if (ids[p] == 0) { ids[p] = p; } } void unify (T p, T q) { if (p == q) { return; } T i = root(p); T j = root(q); if (i == 0) { add(p); i = p; } if (j == 0) { add(q); j = q; } ids[i] = j; } // would be easy to write remove. // Will be O(n). }; // This is the second raster pass of the two pass algorithm family. // The input array (output_labels) has been assigned provisional // labels and this resolves them into their final labels. We // modify this pass to also ensure that the output labels are // numbered from 1 sequentially. template <typename OUT = uint32_t> OUT* relabel( OUT* out_labels, const int64_t voxels, const int64_t num_labels, DisjointSet<uint32_t> &equivalences, size_t &N = _dummy_N, OUT start_label = 1 ) { OUT label; OUT* renumber = new OUT[num_labels + 1](); OUT next_label = start_label; for (int64_t i = 1; i <= num_labels; i++) { label = equivalences.root(i); if (renumber[label] == 0) { renumber[label] = next_label; renumber[i] = next_label; next_label++; } else { renumber[i] = renumber[label]; } } // Raster Scan 2: Write final labels based on equivalences N = next_label - start_label; if (N < static_cast<size_t>(num_labels) || start_label != 1) { for (int64_t loc = 0; loc < voxels; loc++) { out_labels[loc] = renumber[out_labels[loc]]; } } delete[] renumber; return out_labels; } template <typename OUT = uint32_t> OUT* connected_components2d_4( bool* in_labels, const int64_t sx, const int64_t sy, const int64_t sz, size_t max_labels, OUT *out_labels = NULL, size_t &N = _dummy_N, OUT start_label = 1 ) { const int64_t sxy = sx * sy; const int64_t voxels = sx * sy * sz; max_labels++; max_labels = std::min(max_labels, static_cast<size_t>(voxels) + 1); // + 1L for an array with no zeros max_labels = std::min(max_labels, static_cast<size_t>(std::numeric_limits<OUT>::max())); DisjointSet<uint32_t> equivalences(max_labels); if (out_labels == NULL) { out_labels = new OUT[voxels](); } /* Layout of forward pass mask. A is the current location. D C B A */ // const int64_t A = 0; const int64_t B = -1; const int64_t C = -sx; const int64_t D = -1-sx; int64_t loc = 0; OUT next_label = 0; // Raster Scan 1: Set temporary labels and // record equivalences in a disjoint set. bool cur = 0; for (int64_t z = 0; z < sz; z++) { for (int64_t y = 0; y < sy; y++) { for (int64_t x = 0; x < sx; x++) { loc = x + sx * y + sxy * z; cur = in_labels[loc]; if (cur) { continue; } if (x > 0 && !in_labels[loc + B]) { out_labels[loc] = out_labels[loc + B]; if (y > 0 && in_labels[loc + D] && !in_labels[loc + C]) { equivalences.unify(out_labels[loc], out_labels[loc + C]); } } else if (y > 0 && !in_labels[loc + C]) { out_labels[loc] = out_labels[loc + C]; } else { next_label++; out_labels[loc] = next_label; equivalences.add(out_labels[loc]); } } } } return relabel<OUT>(out_labels, voxels, next_label, equivalences, N, start_label); } template <typename OUT = uint32_t> OUT* connected_components3d_6( bool* in_labels, const int64_t sx, const int64_t sy, const int64_t sz, size_t max_labels, OUT *out_labels = NULL, size_t &N = _dummy_N ) { const int64_t sxy = sx * sy; const int64_t voxels = sxy * sz; if (out_labels == NULL) { out_labels = new OUT[voxels](); } if (max_labels == 0) { return out_labels; } max_labels++; // corrects Cython estimation max_labels = std::min(max_labels, static_cast<size_t>(voxels) + 1); // + 1L for an array with no zeros max_labels = std::min(max_labels, static_cast<size_t>(std::numeric_limits<OUT>::max())); DisjointSet<OUT> equivalences(max_labels); /* Layout of forward pass mask (which faces backwards). N is the current location. z = -1 z = 0 A B C J K L y = -1 D E F M N y = 0 G H I y = +1 -1 0 +1 -1 0 <-- x axis */ // Z - 1 const int64_t B = -sx - sxy; const int64_t E = -sxy; const int64_t D = -1 - sxy; // Current Z const int64_t K = -sx; const int64_t M = -1; const int64_t J = -1 - sx; // N = 0; int64_t loc = 0; OUT next_label = 0; // Raster Scan 1: Set temporary labels and // record equivalences in a disjoint set. for (int64_t z = 0; z < sz; z++) { for (int64_t y = 0; y < sy; y++) { for (int64_t x = 0; x < sx; x++) { loc = x + sx * (y + sy * z); const bool cur = in_labels[loc]; if (cur) { continue; } if (x > 0 && !in_labels[loc + M]) { out_labels[loc] = out_labels[loc + M]; if (y > 0 && !in_labels[loc + K] && in_labels[loc + J]) { equivalences.unify(out_labels[loc], out_labels[loc + K]); if (z > 0 && !in_labels[loc + E]) { if (in_labels[loc + D] && in_labels[loc + B]) { equivalences.unify(out_labels[loc], out_labels[loc + E]); } } } else if (z > 0 && !in_labels[loc + E] && in_labels[loc + D]) { equivalences.unify(out_labels[loc], out_labels[loc + E]); } } else if (y > 0 && !in_labels[loc + K]) { out_labels[loc] = out_labels[loc + K]; if (z > 0 && !in_labels[loc + E] && in_labels[loc + B]) { equivalences.unify(out_labels[loc], out_labels[loc + E]); } } else if (z > 0 && !in_labels[loc + E]) { out_labels[loc] = out_labels[loc + E]; } else { next_label++; out_labels[loc] = next_label; equivalences.add(out_labels[loc]); } } } } if (next_label <= 1) { N = next_label; return out_labels; } return relabel<OUT>(out_labels, voxels, next_label, equivalences, N, 1); } template <typename OUT = uint64_t> OUT* connected_components( bool* in_labels, const int64_t sx, const int64_t sy, const int64_t sz, const size_t connectivity = 4, size_t &N = _dummy_N ) { const int64_t sxy = sx * sy; const int64_t voxels = sxy * sz; size_t max_labels = voxels; OUT* out_labels = new OUT[voxels](); N = 0; if (connectivity == 4) { max_labels = static_cast<size_t>((sxy + 2) / 2); for (int64_t z = 0; z < sz; z++) { size_t tmp_N = 0; connected_components2d_4<OUT>( (in_labels + sxy * z), sx, sy, 1, max_labels, (out_labels + sxy * z), tmp_N, N + 1 ); N += tmp_N; } } else if (connectivity == 6) { max_labels = static_cast<size_t>(((sx + 1) * (sy + 1) * (sz + 1)) / 2); connected_components3d_6<OUT>( in_labels, sx, sy, sz, max_labels, out_labels, N ); } // removing these lines drops several kB from the WASM // and should be impossible to hit. // else { // throw std::runtime_error("Only 4 and 6 connectivities are supported."); // } return out_labels; } }; #endif <commit_msg>chore: remove spurious semicolon<commit_after>/** * @license * Copyright 2021 William Silvermsith * 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. */ /* * Connected Components for 2D images. * Author: William Silversmith * Affiliation: Seung Lab, Princeton University * Date: August 2018 - June 2019, June 2021 * * ---- * Notes on the license: * * This is a special reduced feature version of cc3d * that includes only the logic needed for CCL 4-connected * and 6-connected. It is also modified to treat black as * foreground and black as background. * * cc3d is ordinarily licensed as GPL v3. * Get the full version of cc3d here: * * https://github.com/seung-lab/connected-components-3d */ #ifndef CC3D_SPECIAL_4_HPP #define CC3D_SPECIAL_4_HPP #include <algorithm> #include <cmath> #include <cstdint> #include <stdexcept> namespace cc3d { static size_t _dummy_N; template <typename T> class DisjointSet { public: T *ids; size_t length; DisjointSet () { length = 65536; // 2^16, some "reasonable" starting size ids = new T[length](); } DisjointSet (size_t len) { length = len; ids = new T[length](); } DisjointSet (const DisjointSet &cpy) { length = cpy.length; ids = new T[length](); for (int i = 0; i < length; i++) { ids[i] = cpy.ids[i]; } } ~DisjointSet () { delete []ids; } T root (T n) { T i = ids[n]; while (i != ids[i]) { ids[i] = ids[ids[i]]; // path compression i = ids[i]; } return i; } bool find (T p, T q) { return root(p) == root(q); } void add(T p) { if (ids[p] == 0) { ids[p] = p; } } void unify (T p, T q) { if (p == q) { return; } T i = root(p); T j = root(q); if (i == 0) { add(p); i = p; } if (j == 0) { add(q); j = q; } ids[i] = j; } // would be easy to write remove. // Will be O(n). }; // This is the second raster pass of the two pass algorithm family. // The input array (output_labels) has been assigned provisional // labels and this resolves them into their final labels. We // modify this pass to also ensure that the output labels are // numbered from 1 sequentially. template <typename OUT = uint32_t> OUT* relabel( OUT* out_labels, const int64_t voxels, const int64_t num_labels, DisjointSet<uint32_t> &equivalences, size_t &N = _dummy_N, OUT start_label = 1 ) { OUT label; OUT* renumber = new OUT[num_labels + 1](); OUT next_label = start_label; for (int64_t i = 1; i <= num_labels; i++) { label = equivalences.root(i); if (renumber[label] == 0) { renumber[label] = next_label; renumber[i] = next_label; next_label++; } else { renumber[i] = renumber[label]; } } // Raster Scan 2: Write final labels based on equivalences N = next_label - start_label; if (N < static_cast<size_t>(num_labels) || start_label != 1) { for (int64_t loc = 0; loc < voxels; loc++) { out_labels[loc] = renumber[out_labels[loc]]; } } delete[] renumber; return out_labels; } template <typename OUT = uint32_t> OUT* connected_components2d_4( bool* in_labels, const int64_t sx, const int64_t sy, const int64_t sz, size_t max_labels, OUT *out_labels = NULL, size_t &N = _dummy_N, OUT start_label = 1 ) { const int64_t sxy = sx * sy; const int64_t voxels = sx * sy * sz; max_labels++; max_labels = std::min(max_labels, static_cast<size_t>(voxels) + 1); // + 1L for an array with no zeros max_labels = std::min(max_labels, static_cast<size_t>(std::numeric_limits<OUT>::max())); DisjointSet<uint32_t> equivalences(max_labels); if (out_labels == NULL) { out_labels = new OUT[voxels](); } /* Layout of forward pass mask. A is the current location. D C B A */ // const int64_t A = 0; const int64_t B = -1; const int64_t C = -sx; const int64_t D = -1-sx; int64_t loc = 0; OUT next_label = 0; // Raster Scan 1: Set temporary labels and // record equivalences in a disjoint set. bool cur = 0; for (int64_t z = 0; z < sz; z++) { for (int64_t y = 0; y < sy; y++) { for (int64_t x = 0; x < sx; x++) { loc = x + sx * y + sxy * z; cur = in_labels[loc]; if (cur) { continue; } if (x > 0 && !in_labels[loc + B]) { out_labels[loc] = out_labels[loc + B]; if (y > 0 && in_labels[loc + D] && !in_labels[loc + C]) { equivalences.unify(out_labels[loc], out_labels[loc + C]); } } else if (y > 0 && !in_labels[loc + C]) { out_labels[loc] = out_labels[loc + C]; } else { next_label++; out_labels[loc] = next_label; equivalences.add(out_labels[loc]); } } } } return relabel<OUT>(out_labels, voxels, next_label, equivalences, N, start_label); } template <typename OUT = uint32_t> OUT* connected_components3d_6( bool* in_labels, const int64_t sx, const int64_t sy, const int64_t sz, size_t max_labels, OUT *out_labels = NULL, size_t &N = _dummy_N ) { const int64_t sxy = sx * sy; const int64_t voxels = sxy * sz; if (out_labels == NULL) { out_labels = new OUT[voxels](); } if (max_labels == 0) { return out_labels; } max_labels++; // corrects Cython estimation max_labels = std::min(max_labels, static_cast<size_t>(voxels) + 1); // + 1L for an array with no zeros max_labels = std::min(max_labels, static_cast<size_t>(std::numeric_limits<OUT>::max())); DisjointSet<OUT> equivalences(max_labels); /* Layout of forward pass mask (which faces backwards). N is the current location. z = -1 z = 0 A B C J K L y = -1 D E F M N y = 0 G H I y = +1 -1 0 +1 -1 0 <-- x axis */ // Z - 1 const int64_t B = -sx - sxy; const int64_t E = -sxy; const int64_t D = -1 - sxy; // Current Z const int64_t K = -sx; const int64_t M = -1; const int64_t J = -1 - sx; // N = 0; int64_t loc = 0; OUT next_label = 0; // Raster Scan 1: Set temporary labels and // record equivalences in a disjoint set. for (int64_t z = 0; z < sz; z++) { for (int64_t y = 0; y < sy; y++) { for (int64_t x = 0; x < sx; x++) { loc = x + sx * (y + sy * z); const bool cur = in_labels[loc]; if (cur) { continue; } if (x > 0 && !in_labels[loc + M]) { out_labels[loc] = out_labels[loc + M]; if (y > 0 && !in_labels[loc + K] && in_labels[loc + J]) { equivalences.unify(out_labels[loc], out_labels[loc + K]); if (z > 0 && !in_labels[loc + E]) { if (in_labels[loc + D] && in_labels[loc + B]) { equivalences.unify(out_labels[loc], out_labels[loc + E]); } } } else if (z > 0 && !in_labels[loc + E] && in_labels[loc + D]) { equivalences.unify(out_labels[loc], out_labels[loc + E]); } } else if (y > 0 && !in_labels[loc + K]) { out_labels[loc] = out_labels[loc + K]; if (z > 0 && !in_labels[loc + E] && in_labels[loc + B]) { equivalences.unify(out_labels[loc], out_labels[loc + E]); } } else if (z > 0 && !in_labels[loc + E]) { out_labels[loc] = out_labels[loc + E]; } else { next_label++; out_labels[loc] = next_label; equivalences.add(out_labels[loc]); } } } } if (next_label <= 1) { N = next_label; return out_labels; } return relabel<OUT>(out_labels, voxels, next_label, equivalences, N, 1); } template <typename OUT = uint64_t> OUT* connected_components( bool* in_labels, const int64_t sx, const int64_t sy, const int64_t sz, const size_t connectivity = 4, size_t &N = _dummy_N ) { const int64_t sxy = sx * sy; const int64_t voxels = sxy * sz; size_t max_labels = voxels; OUT* out_labels = new OUT[voxels](); N = 0; if (connectivity == 4) { max_labels = static_cast<size_t>((sxy + 2) / 2); for (int64_t z = 0; z < sz; z++) { size_t tmp_N = 0; connected_components2d_4<OUT>( (in_labels + sxy * z), sx, sy, 1, max_labels, (out_labels + sxy * z), tmp_N, N + 1 ); N += tmp_N; } } else if (connectivity == 6) { max_labels = static_cast<size_t>(((sx + 1) * (sy + 1) * (sz + 1)) / 2); connected_components3d_6<OUT>( in_labels, sx, sy, sz, max_labels, out_labels, N ); } // removing these lines drops several kB from the WASM // and should be impossible to hit. // else { // throw std::runtime_error("Only 4 and 6 connectivities are supported."); // } return out_labels; } } #endif <|endoftext|>
<commit_before>// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// // #include "contrib/endpoints/src/api_manager/context/request_context.h" #include <uuid/uuid.h> #include <sstream> using ::google::api_manager::utils::Status; namespace google { namespace api_manager { namespace context { namespace { // Cloud Trace Context Header const char kCloudTraceContextHeader[] = "X-Cloud-Trace-Context"; // Log message prefix for a success method. const char kMessage[] = "Method: "; // Log message prefix for an ignored method. const char kIgnoredMessage[] = "Endpoints management skipped for an unrecognized HTTP call: "; // Unknown HTTP verb. const char kUnknownHttpVerb[] = "<Unknown HTTP Verb>"; // Service control does not currently support logging with an empty // operation name so we use this value until fix is available. const char kUnrecognizedOperation[] = "<Unknown Operation Name>"; // Maximum 36 byte string for UUID const int kMaxUUIDBufSize = 40; // Default api key names const char kDefaultApiKeyQueryName1[] = "key"; const char kDefaultApiKeyQueryName2[] = "api_key"; const char kDefaultApiKeyHeaderName[] = "x-api-key"; // Default location const char kDefaultLocation[] = "us-central1"; // Genereates a UUID string std::string GenerateUUID() { char uuid_buf[kMaxUUIDBufSize]; uuid_t uuid; uuid_generate(uuid); uuid_unparse(uuid, uuid_buf); return uuid_buf; } } // namespace using context::ServiceContext; RequestContext::RequestContext(std::shared_ptr<ServiceContext> service_context, std::unique_ptr<Request> request) : service_context_(service_context), request_(std::move(request)), is_first_report_(true) { start_time_ = std::chrono::system_clock::now(); last_report_time_ = std::chrono::steady_clock::now(); operation_id_ = GenerateUUID(); const std::string &method = request_->GetRequestHTTPMethod(); const std::string &path = request_->GetRequestPath(); std::string query_params = request_->GetQueryParameters(); // In addition to matching the method, service_context_->GetMethodCallInfo() // will extract the variable bindings from the url. We need variable bindings // only when we need to do transcoding. If this turns out to be a performance // problem for non-transcoded calls, we have a couple of options: // 1) Do not extract variable bindings here, and do the method matching again // with extracting variable bindings when transcoding is needed. // 2) Store all the pieces needed for extracting variable bindings (such as // http template variables, url path parts) in MethodCallInfo and extract // variables lazily when needed. method_call_ = service_context_->GetMethodCallInfo(method, path, query_params); if (method_call_.method_info) { ExtractApiKey(); } request_->FindHeader("referer", &http_referer_); // Enable trace if tracing is not force disabled and the triggering header is // set. if (service_context_->cloud_trace_aggregator()) { std::string trace_context_header; request_->FindHeader(kCloudTraceContextHeader, &trace_context_header); std::string method_name = kUnrecognizedOperation; if (method_call_.method_info) { method_name = method_call_.method_info->selector(); } // qualify with the service name method_name = service_context_->service_name() + "/" + method_name; cloud_trace_.reset(cloud_trace::CreateCloudTrace( trace_context_header, method_name, &service_context_->cloud_trace_aggregator()->sampler())); } } void RequestContext::ExtractApiKey() { bool api_key_defined = false; auto url_queries = method()->api_key_url_query_parameters(); if (url_queries) { api_key_defined = true; for (const auto &url_query : *url_queries) { if (request_->FindQuery(url_query, &api_key_)) { return; } } } auto headers = method()->api_key_http_headers(); if (headers) { api_key_defined = true; for (const auto &header : *headers) { if (request_->FindHeader(header, &api_key_)) { return; } } } if (!api_key_defined) { // If api_key is not specified for a method, // check "key" first, if not, check "api_key" in query parameter. if (!request_->FindQuery(kDefaultApiKeyQueryName1, &api_key_)) { if (!request_->FindQuery(kDefaultApiKeyQueryName2, &api_key_)) { request_->FindHeader(kDefaultApiKeyHeaderName, &api_key_); } } } } void RequestContext::CompleteCheck(Status status) { // Makes sure set_check_continuation() is called. // Only making sure CompleteCheck() is NOT called twice. GOOGLE_CHECK(check_continuation_); auto temp_continuation = check_continuation_; check_continuation_ = nullptr; temp_continuation(status); } void RequestContext::FillOperationInfo(service_control::OperationInfo *info) { if (method()) { info->operation_name = method()->selector(); } else { info->operation_name = kUnrecognizedOperation; } info->operation_id = operation_id_; if (check_response_info_.is_api_key_valid) { info->api_key = api_key_; } info->producer_project_id = service_context()->project_id(); info->referer = http_referer_; info->request_start_time = start_time_; } void RequestContext::FillLocation(service_control::ReportRequestInfo *info) { if (service_context()->gce_metadata()->has_valid_data() && !service_context()->gce_metadata()->zone().empty()) { info->location = service_context()->gce_metadata()->zone(); } else { info->location = kDefaultLocation; } } void RequestContext::FillComputePlatform( service_control::ReportRequestInfo *info) { compute_platform::ComputePlatform cp; GceMetadata *metadata = service_context()->gce_metadata(); if (metadata == nullptr || !metadata->has_valid_data()) { cp = compute_platform::UNKNOWN; } else { if (!metadata->gae_server_software().empty()) { cp = compute_platform::GAE_FLEX; } else if (!metadata->kube_env().empty()) { cp = compute_platform::GKE; } else { cp = compute_platform::GCE; } } info->compute_platform = cp; } void RequestContext::FillLogMessage(service_control::ReportRequestInfo *info) { if (method()) { info->api_method = method()->selector(); info->api_name = method()->api_name(); info->api_version = method()->api_version(); info->log_message = std::string(kMessage) + method()->selector(); } else { std::string http_verb = info->method; if (http_verb.empty()) { http_verb = kUnknownHttpVerb; } info->log_message = std::string(kIgnoredMessage) + http_verb + " " + request_->GetUnparsedRequestPath(); } } void RequestContext::FillCheckRequestInfo( service_control::CheckRequestInfo *info) { FillOperationInfo(info); info->client_ip = request_->GetClientIP(); info->allow_unregistered_calls = method()->allow_unregistered_calls(); } void RequestContext::FillReportRequestInfo( Response *response, service_control::ReportRequestInfo *info) { FillOperationInfo(info); FillLocation(info); FillComputePlatform(info); info->url = request_->GetUnparsedRequestPath(); info->method = request_->GetRequestHTTPMethod(); info->protocol = request_->GetRequestProtocol(); info->check_response_info = check_response_info_; info->auth_issuer = auth_issuer_; info->auth_audience = auth_audience_; if (!info->is_final_report) { info->request_bytes = request_->GetGrpcRequestBytes(); info->response_bytes = request_->GetGrpcResponseBytes(); } else { info->request_size = response->GetRequestSize(); info->response_size = response->GetResponseSize(); info->request_bytes = info->request_size; info->response_bytes = info->response_size; info->streaming_request_message_counts = request_->GetGrpcRequestMessageCounts(); info->streaming_response_message_counts = request_->GetGrpcResponseMessageCounts(); info->streaming_durations = std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::system_clock::now() - start_time_) .count(); info->status = response->GetResponseStatus(); info->response_code = info->status.HttpCode(); // Must be after response_code and method are assigned. FillLogMessage(info); if(!method()->request_streaming() && !method()->response_streaming()) { response->GetLatencyInfo(&info->latency); } } } void RequestContext::StartBackendSpanAndSetTraceContext() { backend_span_.reset(CreateSpan(cloud_trace_.get(), "Backend")); // Set trace context header to backend. The span id in the header will // be the backend span's id. std::ostringstream trace_context_stream; trace_context_stream << cloud_trace()->trace()->trace_id() << "/" << backend_span_->trace_span()->span_id() << ";" << cloud_trace()->options(); Status status = request()->AddHeaderToBackend(kCloudTraceContextHeader, trace_context_stream.str()); if (!status.ok()) { service_context()->env()->LogError( "Failed to set trace context header to backend."); } } } // namespace context } // namespace api_manager } // namespace google <commit_msg>Fix t test failures in esp. (#21)<commit_after>// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// // #include "contrib/endpoints/src/api_manager/context/request_context.h" #include <uuid/uuid.h> #include <sstream> using ::google::api_manager::utils::Status; namespace google { namespace api_manager { namespace context { namespace { // Cloud Trace Context Header const char kCloudTraceContextHeader[] = "X-Cloud-Trace-Context"; // Log message prefix for a success method. const char kMessage[] = "Method: "; // Log message prefix for an ignored method. const char kIgnoredMessage[] = "Endpoints management skipped for an unrecognized HTTP call: "; // Unknown HTTP verb. const char kUnknownHttpVerb[] = "<Unknown HTTP Verb>"; // Service control does not currently support logging with an empty // operation name so we use this value until fix is available. const char kUnrecognizedOperation[] = "<Unknown Operation Name>"; // Maximum 36 byte string for UUID const int kMaxUUIDBufSize = 40; // Default api key names const char kDefaultApiKeyQueryName1[] = "key"; const char kDefaultApiKeyQueryName2[] = "api_key"; const char kDefaultApiKeyHeaderName[] = "x-api-key"; // Default location const char kDefaultLocation[] = "us-central1"; // Genereates a UUID string std::string GenerateUUID() { char uuid_buf[kMaxUUIDBufSize]; uuid_t uuid; uuid_generate(uuid); uuid_unparse(uuid, uuid_buf); return uuid_buf; } } // namespace using context::ServiceContext; RequestContext::RequestContext(std::shared_ptr<ServiceContext> service_context, std::unique_ptr<Request> request) : service_context_(service_context), request_(std::move(request)), is_first_report_(true) { start_time_ = std::chrono::system_clock::now(); last_report_time_ = std::chrono::steady_clock::now(); operation_id_ = GenerateUUID(); const std::string &method = request_->GetRequestHTTPMethod(); const std::string &path = request_->GetRequestPath(); std::string query_params = request_->GetQueryParameters(); // In addition to matching the method, service_context_->GetMethodCallInfo() // will extract the variable bindings from the url. We need variable bindings // only when we need to do transcoding. If this turns out to be a performance // problem for non-transcoded calls, we have a couple of options: // 1) Do not extract variable bindings here, and do the method matching again // with extracting variable bindings when transcoding is needed. // 2) Store all the pieces needed for extracting variable bindings (such as // http template variables, url path parts) in MethodCallInfo and extract // variables lazily when needed. method_call_ = service_context_->GetMethodCallInfo(method, path, query_params); if (method_call_.method_info) { ExtractApiKey(); } request_->FindHeader("referer", &http_referer_); // Enable trace if tracing is not force disabled and the triggering header is // set. if (service_context_->cloud_trace_aggregator()) { std::string trace_context_header; request_->FindHeader(kCloudTraceContextHeader, &trace_context_header); std::string method_name = kUnrecognizedOperation; if (method_call_.method_info) { method_name = method_call_.method_info->selector(); } // qualify with the service name method_name = service_context_->service_name() + "/" + method_name; cloud_trace_.reset(cloud_trace::CreateCloudTrace( trace_context_header, method_name, &service_context_->cloud_trace_aggregator()->sampler())); } } void RequestContext::ExtractApiKey() { bool api_key_defined = false; auto url_queries = method()->api_key_url_query_parameters(); if (url_queries) { api_key_defined = true; for (const auto &url_query : *url_queries) { if (request_->FindQuery(url_query, &api_key_)) { return; } } } auto headers = method()->api_key_http_headers(); if (headers) { api_key_defined = true; for (const auto &header : *headers) { if (request_->FindHeader(header, &api_key_)) { return; } } } if (!api_key_defined) { // If api_key is not specified for a method, // check "key" first, if not, check "api_key" in query parameter. if (!request_->FindQuery(kDefaultApiKeyQueryName1, &api_key_)) { if (!request_->FindQuery(kDefaultApiKeyQueryName2, &api_key_)) { request_->FindHeader(kDefaultApiKeyHeaderName, &api_key_); } } } } void RequestContext::CompleteCheck(Status status) { // Makes sure set_check_continuation() is called. // Only making sure CompleteCheck() is NOT called twice. GOOGLE_CHECK(check_continuation_); auto temp_continuation = check_continuation_; check_continuation_ = nullptr; temp_continuation(status); } void RequestContext::FillOperationInfo(service_control::OperationInfo *info) { if (method()) { info->operation_name = method()->selector(); } else { info->operation_name = kUnrecognizedOperation; } info->operation_id = operation_id_; if (check_response_info_.is_api_key_valid) { info->api_key = api_key_; } info->producer_project_id = service_context()->project_id(); info->referer = http_referer_; info->request_start_time = start_time_; } void RequestContext::FillLocation(service_control::ReportRequestInfo *info) { if (service_context()->gce_metadata()->has_valid_data() && !service_context()->gce_metadata()->zone().empty()) { info->location = service_context()->gce_metadata()->zone(); } else { info->location = kDefaultLocation; } } void RequestContext::FillComputePlatform( service_control::ReportRequestInfo *info) { compute_platform::ComputePlatform cp; GceMetadata *metadata = service_context()->gce_metadata(); if (metadata == nullptr || !metadata->has_valid_data()) { cp = compute_platform::UNKNOWN; } else { if (!metadata->gae_server_software().empty()) { cp = compute_platform::GAE_FLEX; } else if (!metadata->kube_env().empty()) { cp = compute_platform::GKE; } else { cp = compute_platform::GCE; } } info->compute_platform = cp; } void RequestContext::FillLogMessage(service_control::ReportRequestInfo *info) { if (method()) { info->api_method = method()->selector(); info->api_name = method()->api_name(); info->api_version = method()->api_version(); info->log_message = std::string(kMessage) + method()->selector(); } else { std::string http_verb = info->method; if (http_verb.empty()) { http_verb = kUnknownHttpVerb; } info->log_message = std::string(kIgnoredMessage) + http_verb + " " + request_->GetUnparsedRequestPath(); } } void RequestContext::FillCheckRequestInfo( service_control::CheckRequestInfo *info) { FillOperationInfo(info); info->client_ip = request_->GetClientIP(); info->allow_unregistered_calls = method()->allow_unregistered_calls(); } void RequestContext::FillReportRequestInfo( Response *response, service_control::ReportRequestInfo *info) { FillOperationInfo(info); FillLocation(info); FillComputePlatform(info); info->url = request_->GetUnparsedRequestPath(); info->method = request_->GetRequestHTTPMethod(); info->protocol = request_->GetRequestProtocol(); info->check_response_info = check_response_info_; info->auth_issuer = auth_issuer_; info->auth_audience = auth_audience_; if (!info->is_final_report) { info->request_bytes = request_->GetGrpcRequestBytes(); info->response_bytes = request_->GetGrpcResponseBytes(); } else { info->request_size = response->GetRequestSize(); info->response_size = response->GetResponseSize(); info->request_bytes = info->request_size; info->response_bytes = info->response_size; info->streaming_request_message_counts = request_->GetGrpcRequestMessageCounts(); info->streaming_response_message_counts = request_->GetGrpcResponseMessageCounts(); info->streaming_durations = std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::system_clock::now() - start_time_) .count(); info->status = response->GetResponseStatus(); info->response_code = info->status.HttpCode(); // Must be after response_code and method are assigned. FillLogMessage(info); bool is_streaming = false; if (method() && (method()->request_streaming() || method()->response_streaming())) { is_streaming = true; } if (!is_streaming) { response->GetLatencyInfo(&info->latency); } } } void RequestContext::StartBackendSpanAndSetTraceContext() { backend_span_.reset(CreateSpan(cloud_trace_.get(), "Backend")); // Set trace context header to backend. The span id in the header will // be the backend span's id. std::ostringstream trace_context_stream; trace_context_stream << cloud_trace()->trace()->trace_id() << "/" << backend_span_->trace_span()->span_id() << ";" << cloud_trace()->options(); Status status = request()->AddHeaderToBackend(kCloudTraceContextHeader, trace_context_stream.str()); if (!status.ok()) { service_context()->env()->LogError( "Failed to set trace context header to backend."); } } } // namespace context } // namespace api_manager } // namespace google <|endoftext|>
<commit_before>#include <possumwood_sdk/node_implementation.h> #include <boost/filesystem.hpp> #include "datatypes/vertex_data.inl" #include "datatypes/font.h" #include <possumwood_sdk/datatypes/filename.h> namespace { dependency_graph::InAttr<std::string> a_text; dependency_graph::InAttr<possumwood::Font> a_font; dependency_graph::OutAttr<std::shared_ptr<const possumwood::VertexData>> a_vd; dependency_graph::State compute(dependency_graph::Values& data) { const possumwood::Font& font = data.get(a_font); // and render the text into a new VertexData instance std::unique_ptr<possumwood::VertexData> vd(new possumwood::VertexData(GL_TRIANGLES)); { // construct the array of vertices std::vector<Imath::V2f> vertices; std::vector<Imath::V2f> uvs; float currentPos = 0; for(auto& c : data.get(a_text)) { auto& g = font.glyph(c); Imath::V2f p1(currentPos*font.size() - g.originX, g.originY - g.height); Imath::V2f p2(currentPos*font.size() - g.originX, g.originY); Imath::V2f p3(currentPos*font.size() - g.originX + g.width, g.originY); Imath::V2f p4(currentPos*font.size() - g.originX + g.width, g.originY - g.height); Imath::V2f uv1((float)g.x / font.width(), (float)(g.y + g.height) / font.height()); Imath::V2f uv2((float)g.x / font.width(), (float)g.y / font.height()); Imath::V2f uv3((float)(g.x + g.width) / font.width(), (float)g.y / font.height()); Imath::V2f uv4((float)(g.x + g.width) / font.width(), (float)(g.y + g.height) / font.height()); vertices.push_back(p1 / font.size()); vertices.push_back(p2 / font.size()); vertices.push_back(p3 / font.size()); vertices.push_back(p1 / font.size()); vertices.push_back(p3 / font.size()); vertices.push_back(p4 / font.size()); uvs.push_back(uv1); uvs.push_back(uv2); uvs.push_back(uv3); uvs.push_back(uv1); uvs.push_back(uv3); uvs.push_back(uv4); currentPos += (float)g.advance / font.size(); } // and add them to the vertex data vd->addVBO<Imath::V2f>("position", vertices.size(), possumwood::VertexData::kStatic, [vertices](possumwood::Buffer<float>& buffer, const possumwood::Drawable::ViewportState& viewport) { std::size_t ctr = 0; for(auto& v : vertices) { buffer.element(ctr) = v; ++ctr; } } ); vd->addVBO<Imath::V2f>("uv", uvs.size(), possumwood::VertexData::kStatic, [uvs](possumwood::Buffer<float>& buffer, const possumwood::Drawable::ViewportState& viewport) { std::size_t ctr = 0; for(auto& v : uvs) { buffer.element(ctr) = v; ++ctr; } } ); } data.set(a_vd, std::shared_ptr<const possumwood::VertexData>(vd.release())); return dependency_graph::State(); } void init(possumwood::Metadata& meta) { meta.addAttribute(a_text, "text"); meta.addAttribute(a_font, "font"); meta.addAttribute(a_vd, "vertex_data"); meta.addInfluence(a_font, a_vd); meta.addInfluence(a_text, a_vd); meta.setCompute(compute); } possumwood::NodeImplementation s_impl("render/vertex_data/text", init); } <commit_msg>Added alignment options<commit_after>#include <possumwood_sdk/node_implementation.h> #include <boost/filesystem.hpp> #include "datatypes/vertex_data.inl" #include "datatypes/font.h" #include <possumwood_sdk/datatypes/filename.h> #include <possumwood_sdk/datatypes/enum.h> namespace { dependency_graph::InAttr<std::string> a_text; dependency_graph::InAttr<possumwood::Font> a_font; dependency_graph::InAttr<possumwood::Enum> a_horizAlign, a_vertAlign; dependency_graph::OutAttr<std::shared_ptr<const possumwood::VertexData>> a_vd; dependency_graph::State compute(dependency_graph::Values& data) { const possumwood::Font& font = data.get(a_font); const int horizAlign = data.get(a_horizAlign).intValue(); const int vertAlign = data.get(a_vertAlign).intValue(); // and render the text into a new VertexData instance std::unique_ptr<possumwood::VertexData> vd(new possumwood::VertexData(GL_TRIANGLES)); { // first, figure out the size of the text float totalWidth = 0.0f; for(auto& c : data.get(a_text)) { auto& g = font.glyph(c); totalWidth += (float)g.advance / font.size(); } // construct the array of vertices std::vector<Imath::V2f> vertices; std::vector<Imath::V2f> uvs; float currentPos = 0; float vertPos = 0; if(horizAlign == 1) currentPos = -totalWidth / 2.0f; else if(horizAlign == 2) currentPos = 0; else currentPos = -totalWidth; if(vertAlign == 1) vertPos = -font.size() / 2.0f; else if(vertAlign == 2) vertPos = -font.size(); else vertPos = 0; for(auto& c : data.get(a_text)) { auto& g = font.glyph(c); Imath::V2f p1(currentPos * font.size() - g.originX, g.originY - g.height + vertPos); Imath::V2f p2(currentPos * font.size() - g.originX, g.originY + vertPos); Imath::V2f p3(currentPos * font.size() - g.originX + g.width, g.originY + vertPos); Imath::V2f p4(currentPos * font.size() - g.originX + g.width, g.originY - g.height + vertPos); Imath::V2f uv1((float)g.x / font.width(), (float)(g.y + g.height) / font.height()); Imath::V2f uv2((float)g.x / font.width(), (float)g.y / font.height()); Imath::V2f uv3((float)(g.x + g.width) / font.width(), (float)g.y / font.height()); Imath::V2f uv4((float)(g.x + g.width) / font.width(), (float)(g.y + g.height) / font.height()); vertices.push_back(p1 / font.size()); vertices.push_back(p2 / font.size()); vertices.push_back(p3 / font.size()); vertices.push_back(p1 / font.size()); vertices.push_back(p3 / font.size()); vertices.push_back(p4 / font.size()); uvs.push_back(uv1); uvs.push_back(uv2); uvs.push_back(uv3); uvs.push_back(uv1); uvs.push_back(uv3); uvs.push_back(uv4); currentPos += (float)g.advance / font.size(); } // and add them to the vertex data vd->addVBO<Imath::V2f>("position", vertices.size(), possumwood::VertexData::kStatic, [vertices](possumwood::Buffer<float>& buffer, const possumwood::Drawable::ViewportState & viewport) { std::size_t ctr = 0; for(auto& v : vertices) { buffer.element(ctr) = v; ++ctr; } } ); vd->addVBO<Imath::V2f>("uv", uvs.size(), possumwood::VertexData::kStatic, [uvs](possumwood::Buffer<float>& buffer, const possumwood::Drawable::ViewportState & viewport) { std::size_t ctr = 0; for(auto& v : uvs) { buffer.element(ctr) = v; ++ctr; } } ); } data.set(a_vd, std::shared_ptr<const possumwood::VertexData>(vd.release())); return dependency_graph::State(); } void init(possumwood::Metadata& meta) { meta.addAttribute(a_text, "text"); meta.addAttribute(a_font, "font"); meta.addAttribute(a_vd, "vertex_data"); meta.addAttribute( a_horizAlign, "horiz_align", possumwood::Enum({std::make_pair("Center", 1), std::make_pair("Left", 2), std::make_pair("Right", 3) })); meta.addAttribute( a_vertAlign, "vert_align", possumwood::Enum({std::make_pair("Center", 1), std::make_pair("Top", 2), std::make_pair("Bottom", 3) })); meta.addInfluence(a_font, a_vd); meta.addInfluence(a_text, a_vd); meta.addInfluence(a_horizAlign, a_vd); meta.addInfluence(a_vertAlign, a_vd); meta.setCompute(compute); } possumwood::NodeImplementation s_impl("render/vertex_data/text", init); } <|endoftext|>
<commit_before>// // Bareflank Extended APIs // // Copyright (C) 2015 Assured Information Security, Inc. // Author: Rian Quinn <quinnr@ainfosec.com> // Author: Brendan Kerrigan <kerriganb@ainfosec.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "../../../../../include/hve/arch/intel_x64/exit_handler/exit_handler.h" #include "../../../../../include/hve/arch/intel_x64/exit_handler/vmcall_interface.h" #include <intrinsics.h> namespace intel = intel_x64; namespace vmcs = intel_x64::vmcs; namespace reason = vmcs::exit_reason::basic_exit_reason; exit_handler_intel_x64_eapis::exit_handler_intel_x64_eapis() : m_monitor_trap_callback(&exit_handler_intel_x64_eapis::unhandled_monitor_trap_callback), m_io_access_log_enabled(false), m_vmcs_eapis(nullptr) { init_policy(); register_json_vmcall__verifiers(); register_json_vmcall__io_instruction(); register_json_vmcall__vpid(); register_json_vmcall__msr(); register_json_vmcall__rdmsr(); register_json_vmcall__wrmsr(); } void exit_handler_intel_x64_eapis::resume() { m_vmcs_eapis->resume(); } void exit_handler_intel_x64_eapis::advance_and_resume() { this->advance_rip(); m_vmcs_eapis->resume(); } void exit_handler_intel_x64_eapis::handle_exit(vmcs::value_type reason) { switch (reason) { case reason::monitor_trap_flag: handle_exit__monitor_trap_flag(); break; case reason::io_instruction: handle_exit__io_instruction(); break; case reason::rdmsr: handle_exit__rdmsr(); break; case reason::wrmsr: handle_exit__wrmsr(); break; case reason::control_register_accesses: handle_exit__ctl_reg_access(); break; default: exit_handler_intel_x64::handle_exit(reason); break; } } void exit_handler_intel_x64_eapis::handle_vmcall_registers(vmcall_registers_t &regs) { switch (regs.r02) { case eapis_cat__io_instruction: handle_vmcall__io_instruction(regs); break; case eapis_cat__vpid: handle_vmcall__vpid(regs); break; case eapis_cat__msr: handle_vmcall__msr(regs); break; case eapis_cat__rdmsr: handle_vmcall__rdmsr(regs); break; case eapis_cat__wrmsr: handle_vmcall__wrmsr(regs); break; default: throw std::runtime_error("unknown vmcall category"); } } void exit_handler_intel_x64_eapis::handle_vmcall_data_string_json( const json &ijson, json &ojson) { m_json_commands.at(ijson.at("command"))(ijson, ojson); } void exit_handler_intel_x64_eapis::json_success(json &ojson) { ojson = {"success"}; } <commit_msg>x64/hve: Add fix for cpuid emulation<commit_after>// // Bareflank Extended APIs // // Copyright (C) 2015 Assured Information Security, Inc. // Author: Rian Quinn <quinnr@ainfosec.com> // Author: Brendan Kerrigan <kerriganb@ainfosec.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "../../../../../include/hve/arch/intel_x64/exit_handler/exit_handler.h" #include "../../../../../include/hve/arch/intel_x64/exit_handler/vmcall_interface.h" #include <intrinsics.h> namespace intel = intel_x64; namespace vmcs = intel_x64::vmcs; namespace reason = vmcs::exit_reason::basic_exit_reason; exit_handler_intel_x64_eapis::exit_handler_intel_x64_eapis() : m_monitor_trap_callback(&exit_handler_intel_x64_eapis::unhandled_monitor_trap_callback), m_io_access_log_enabled(false), m_vmcs_eapis(nullptr) { init_policy(); register_json_vmcall__verifiers(); register_json_vmcall__io_instruction(); register_json_vmcall__vpid(); register_json_vmcall__msr(); register_json_vmcall__rdmsr(); register_json_vmcall__wrmsr(); } void exit_handler_intel_x64_eapis::resume() { m_vmcs_eapis->resume(); } void exit_handler_intel_x64_eapis::advance_and_resume() { this->advance_rip(); m_vmcs_eapis->resume(); } void exit_handler_intel_x64_eapis::handle_exit(vmcs::value_type reason) { switch (reason) { case reason::cpuid: handle_exit__cpuid(); break; case reason::monitor_trap_flag: handle_exit__monitor_trap_flag(); break; case reason::io_instruction: handle_exit__io_instruction(); break; case reason::rdmsr: handle_exit__rdmsr(); break; case reason::wrmsr: handle_exit__wrmsr(); break; case reason::control_register_accesses: handle_exit__ctl_reg_access(); break; default: exit_handler_intel_x64::handle_exit(reason); break; } } void exit_handler_intel_x64_eapis::handle_vmcall_registers(vmcall_registers_t &regs) { switch (regs.r02) { case eapis_cat__io_instruction: handle_vmcall__io_instruction(regs); break; case eapis_cat__vpid: handle_vmcall__vpid(regs); break; case eapis_cat__msr: handle_vmcall__msr(regs); break; case eapis_cat__rdmsr: handle_vmcall__rdmsr(regs); break; case eapis_cat__wrmsr: handle_vmcall__wrmsr(regs); break; default: throw std::runtime_error("unknown vmcall category"); } } void exit_handler_intel_x64_eapis::handle_vmcall_data_string_json( const json &ijson, json &ojson) { m_json_commands.at(ijson.at("command"))(ijson, ojson); } void exit_handler_intel_x64_eapis::json_success(json &ojson) { ojson = {"success"}; } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Gregory Haynes <greg@greghaynes.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "documentviewinternal.h" #include "documentview.h" #include "documentcontroller.h" #include "document.h" #include "documentrange.h" #include "documentcaret.h" #include <QPaintEvent> #include <QPainter> #include <QResizeEvent> #include <QWheelEvent> #include <QFontMetrics> #include <QTimer> #include <QCursor> #include <QMouseEvent> #include <QRect> #include <QDebug> #include "documentviewinternal.moc" #define CARET_INTERVAL 500 namespace QSourceEdit { DocumentViewInternal::DocumentViewInternal(DocumentView &parentView) : QWidget(&parentView) , m_view(&parentView) , m_startX(0) , m_startY(0) , m_scrollWheelFactor(1) { setupUi(); setupSignals(); } int DocumentViewInternal::documentOffsetX() const { return m_startX; } int DocumentViewInternal::documentOffsetY() const { return m_startY; } void DocumentViewInternal::setDocumentOffsetX(int x) { if(x < 0) m_startX = 0; else m_startX = x; update(); emit(documentOffsetXChanged(m_startX)); } void DocumentViewInternal::setDocumentOffsetY(int y) { if(y < 0) m_startY = 0; else if(y > (documentOffsetY() - height())) { m_startY = documentOffsetY() - height(); if(m_startY < 0) m_startY = 0; } else m_startY = y; update(); emit(documentOffsetYChanged(m_startY)); } void DocumentViewInternal::paintEvent(QPaintEvent *event) { QRect rect = event->rect(); QPainter paint(this); unsigned int fontHeight = fontMetrics().height(); int lineYStart = (documentOffsetY() % fontHeight); int lineNumStart = lineAt(documentOffsetY()); int numLines = (height() / fontHeight) + 2; int i; Document *doc = &m_view->document(); // Where do we want to stop painting text int textLines = (numLines + lineYStart) <= doc->lineCount() ? numLines : doc->lineCount(); // Paint the text for(i = 0;i < numLines;i++,lineNumStart++) { QRect bound = QRect(0, (i*fontHeight) - lineYStart, rect.width(), fontHeight); paint.fillRect(bound, Qt::white); if(textLines > i) { paint.drawText(bound, doc->text(DocumentRange( DocumentPosition(lineNumStart, 0), DocumentPosition(lineNumStart, -1)))); } } DocumentCaret *pos; foreach(pos, m_view->carets()) paintCaret(paint, pos); } void DocumentViewInternal::resizeEvent(QResizeEvent *event) { emit(sizeChanged(event->size().width(), event->size().height())); } void DocumentViewInternal::keyPressEvent(QKeyEvent *event) { m_view->controller().keyPressEvent(event); } void DocumentViewInternal::keyReleaseEvent(QKeyEvent *event) { m_view->controller().keyReleaseEvent(event); } void DocumentViewInternal::mousePressEvent(QMouseEvent *event) { int pressLine = (event->y() + documentOffsetY()) / fontMetrics().height(); int pressColumn = 0; int lineLength; QString line; if(pressLine >= m_view->document().lineCount()) { pressLine = m_view->document().lineCount()-1; } line = m_view->document().text( DocumentRange( DocumentPosition(pressLine, 0), DocumentPosition(pressLine, -1))); lineLength = line.length(); // Find the column were at int i; for(i = 0;i < lineLength;i++) { pressColumn += fontMetrics().width(line[i]); if(event->x() <= pressColumn) { pressColumn--; break; } } pressColumn = i; update(); } void DocumentViewInternal::wheelEvent(QWheelEvent *event) { event->ignore(); if(event->orientation() == Qt::Vertical) { setDocumentOffsetY(documentOffsetY() - (event->delta() / this->m_scrollWheelFactor)); } } void DocumentViewInternal::setupUi() { setAttribute(Qt::WA_OpaquePaintEvent); setFocusPolicy(Qt::ClickFocus); setCursor(Qt::IBeamCursor); } void DocumentViewInternal::setupSignals() { connect(&m_view->document(), SIGNAL(textChanged()), this, SLOT(documentTextChanged())); } void DocumentViewInternal::paintCaret(QPainter &paint, DocumentCaret *pos) { int fontHeight = fontMetrics().height(); int caretYStart, caretXStart; QString prevText; QRect bound; if(pos->isVisible() && hasFocus()) { prevText = m_view->document().text( DocumentRange( DocumentPosition(pos->line(), 0), DocumentPosition(pos->line(), pos->column()))); caretYStart = (pos->line() * fontHeight) - documentOffsetY(); caretXStart = fontMetrics().width(prevText); bound = QRect(caretXStart, caretYStart, 1, fontMetrics().height()); paint.fillRect(bound, Qt::black); } } void DocumentViewInternal::documentTextChanged() { update(); } int DocumentViewInternal::lineAt(int x) const { return x / fontMetrics().height(); } } <commit_msg>Set keyboard caret on click<commit_after>/* * Copyright (C) 2009 Gregory Haynes <greg@greghaynes.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "documentviewinternal.h" #include "documentview.h" #include "documentcontroller.h" #include "document.h" #include "documentrange.h" #include "documentcaret.h" #include <QPaintEvent> #include <QPainter> #include <QResizeEvent> #include <QWheelEvent> #include <QFontMetrics> #include <QTimer> #include <QCursor> #include <QMouseEvent> #include <QRect> #include <QDebug> #include "documentviewinternal.moc" #define CARET_INTERVAL 500 namespace QSourceEdit { DocumentViewInternal::DocumentViewInternal(DocumentView &parentView) : QWidget(&parentView) , m_view(&parentView) , m_startX(0) , m_startY(0) , m_scrollWheelFactor(1) { setupUi(); setupSignals(); } int DocumentViewInternal::documentOffsetX() const { return m_startX; } int DocumentViewInternal::documentOffsetY() const { return m_startY; } void DocumentViewInternal::setDocumentOffsetX(int x) { if(x < 0) m_startX = 0; else m_startX = x; update(); emit(documentOffsetXChanged(m_startX)); } void DocumentViewInternal::setDocumentOffsetY(int y) { if(y < 0) m_startY = 0; else if(y > (documentOffsetY() - height())) { m_startY = documentOffsetY() - height(); if(m_startY < 0) m_startY = 0; } else m_startY = y; update(); emit(documentOffsetYChanged(m_startY)); } void DocumentViewInternal::paintEvent(QPaintEvent *event) { QRect rect = event->rect(); QPainter paint(this); unsigned int fontHeight = fontMetrics().height(); int lineYStart = (documentOffsetY() % fontHeight); int lineNumStart = lineAt(documentOffsetY()); int numLines = (height() / fontHeight) + 2; int i; Document *doc = &m_view->document(); // Where do we want to stop painting text int textLines = (numLines + lineYStart) <= doc->lineCount() ? numLines : doc->lineCount(); // Paint the text for(i = 0;i < numLines;i++,lineNumStart++) { QRect bound = QRect(0, (i*fontHeight) - lineYStart, rect.width(), fontHeight); paint.fillRect(bound, Qt::white); if(textLines > i) { paint.drawText(bound, doc->text(DocumentRange( DocumentPosition(lineNumStart, 0), DocumentPosition(lineNumStart, -1)))); } } DocumentCaret *pos; foreach(pos, m_view->carets()) paintCaret(paint, pos); } void DocumentViewInternal::resizeEvent(QResizeEvent *event) { emit(sizeChanged(event->size().width(), event->size().height())); } void DocumentViewInternal::keyPressEvent(QKeyEvent *event) { m_view->controller().keyPressEvent(event); } void DocumentViewInternal::keyReleaseEvent(QKeyEvent *event) { m_view->controller().keyReleaseEvent(event); } void DocumentViewInternal::mousePressEvent(QMouseEvent *event) { int pressLine = (event->y() + documentOffsetY()) / fontMetrics().height(); int pressColumn = 0; int lineLength; QString line; if(pressLine >= m_view->document().lineCount()) { pressLine = m_view->document().lineCount()-1; } line = m_view->document().text( DocumentRange( DocumentPosition(pressLine, 0), DocumentPosition(pressLine, -1))); lineLength = line.length(); // Find the column were at int i; for(i = 0;i < lineLength;i++) { pressColumn += fontMetrics().width(line[i]); if(event->x() <= pressColumn) { pressColumn--; break; } } pressColumn = i; // Set keyboard caret m_view->keyboardCaret()->setLine(pressLine); m_view->keyboardCaret()->setColumn(pressColumn); update(); } void DocumentViewInternal::wheelEvent(QWheelEvent *event) { event->ignore(); if(event->orientation() == Qt::Vertical) { setDocumentOffsetY(documentOffsetY() - (event->delta() / this->m_scrollWheelFactor)); } } void DocumentViewInternal::setupUi() { setAttribute(Qt::WA_OpaquePaintEvent); setFocusPolicy(Qt::ClickFocus); setCursor(Qt::IBeamCursor); } void DocumentViewInternal::setupSignals() { connect(&m_view->document(), SIGNAL(textChanged()), this, SLOT(documentTextChanged())); } void DocumentViewInternal::paintCaret(QPainter &paint, DocumentCaret *pos) { int fontHeight = fontMetrics().height(); int caretYStart, caretXStart; QString prevText; QRect bound; if(pos->isVisible() && hasFocus()) { prevText = m_view->document().text( DocumentRange( DocumentPosition(pos->line(), 0), DocumentPosition(pos->line(), pos->column()))); caretYStart = (pos->line() * fontHeight) - documentOffsetY(); caretXStart = fontMetrics().width(prevText); bound = QRect(caretXStart, caretYStart, 1, fontMetrics().height()); paint.fillRect(bound, Qt::black); } } void DocumentViewInternal::documentTextChanged() { update(); } int DocumentViewInternal::lineAt(int x) const { return x / fontMetrics().height(); } } <|endoftext|>
<commit_before>#include "static_controller.hpp" #include "file_system.hpp" #include "content_type_map.hpp" #include "router.hpp" #include "settings.hpp" #include <boost/algorithm/string.hpp> namespace msrv { StaticController::StaticController( Request* request, SettingsStore* store, const ContentTypeMap* ctmap) : ControllerBase(request), store_(store), ctmap_(ctmap) { } StaticController::~StaticController() { } ResponsePtr StaticController::getFile() { auto settings = store_->settings(); const auto& rootDirUtf8 = settings->staticDir; if (rootDirUtf8.empty()) return Response::error(HttpStatus::S_404_NOT_FOUND); std::string pathUtf8 = request()->path; if (!pathUtf8.empty() && pathUtf8.back() == '/') pathUtf8 += "index.html"; auto rootDir = pathFromUtf8(rootDirUtf8); auto fullPath = (rootDir / pathFromUtf8(pathUtf8)).lexically_normal(); if (!isSubpath(rootDir.native(), fullPath.native())) return Response::error(HttpStatus::S_404_NOT_FOUND); return Response::file(fullPath, ctmap_->byFilePath(fullPath)); } void StaticController::defineRoutes( Router* router, WorkQueue* workQueue, SettingsStore* store, const ContentTypeMap* ctmap) { auto routes = router->defineRoutes<StaticController>(); routes.createWith([=](Request* request) { return new StaticController(request, store, ctmap); }); routes.useWorkQueue(workQueue); routes.get("", &StaticController::getFile); routes.get(":path*", &StaticController::getFile); } } <commit_msg>static_controller.cpp: fix path normalization issues on Windows<commit_after>#include "static_controller.hpp" #include "file_system.hpp" #include "content_type_map.hpp" #include "router.hpp" #include "settings.hpp" #include <boost/algorithm/string.hpp> namespace msrv { StaticController::StaticController( Request* request, SettingsStore* store, const ContentTypeMap* ctmap) : ControllerBase(request), store_(store), ctmap_(ctmap) { } StaticController::~StaticController() { } ResponsePtr StaticController::getFile() { auto settings = store_->settings(); const auto& rootDirUtf8 = settings->staticDir; if (rootDirUtf8.empty()) return Response::error(HttpStatus::S_404_NOT_FOUND); std::string pathUtf8 = request()->path; if (!pathUtf8.empty() && pathUtf8.back() == '/') pathUtf8 += "index.html"; auto rootDir = pathFromUtf8(rootDirUtf8).lexically_normal(); auto fullPath = (rootDir / pathFromUtf8(pathUtf8)).lexically_normal(); if (!isSubpath(rootDir.native(), fullPath.native())) return Response::error(HttpStatus::S_404_NOT_FOUND); return Response::file(fullPath, ctmap_->byFilePath(fullPath)); } void StaticController::defineRoutes( Router* router, WorkQueue* workQueue, SettingsStore* store, const ContentTypeMap* ctmap) { auto routes = router->defineRoutes<StaticController>(); routes.createWith([=](Request* request) { return new StaticController(request, store, ctmap); }); routes.useWorkQueue(workQueue); routes.get("", &StaticController::getFile); routes.get(":path*", &StaticController::getFile); } } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/protocol/libjingle_transport_factory.h" #include "base/callback.h" #include "base/single_thread_task_runner.h" #include "base/thread_task_runner_handle.h" #include "base/timer/timer.h" #include "jingle/glue/channel_socket_adapter.h" #include "jingle/glue/utils.h" #include "net/base/net_errors.h" #include "remoting/protocol/network_settings.h" #include "remoting/signaling/jingle_info_request.h" #include "third_party/webrtc/base/network.h" #include "third_party/webrtc/p2p/base/constants.h" #include "third_party/webrtc/p2p/base/p2ptransportchannel.h" #include "third_party/webrtc/p2p/base/port.h" #include "third_party/webrtc/p2p/client/basicportallocator.h" #include "third_party/webrtc/p2p/client/httpportallocator.h" namespace remoting { namespace protocol { namespace { // Try connecting ICE twice with timeout of 15 seconds for each attempt. const int kMaxReconnectAttempts = 2; const int kReconnectDelaySeconds = 15; // Get fresh STUN/Relay configuration every hour. const int kJingleInfoUpdatePeriodSeconds = 3600; class LibjingleTransport : public Transport, public base::SupportsWeakPtr<LibjingleTransport>, public sigslot::has_slots<> { public: LibjingleTransport(cricket::PortAllocator* port_allocator, const NetworkSettings& network_settings); ~LibjingleTransport() override; // Called by JingleTransportFactory when it has fresh Jingle info. void OnCanStart(); // Transport interface. void Connect(const std::string& name, Transport::EventHandler* event_handler, const Transport::ConnectedCallback& callback) override; void AddRemoteCandidate(const cricket::Candidate& candidate) override; const std::string& name() const override; bool is_connected() const override; private: void DoStart(); void NotifyConnected(); // Signal handlers for cricket::TransportChannel. void OnRequestSignaling(cricket::TransportChannelImpl* channel); void OnCandidateReady(cricket::TransportChannelImpl* channel, const cricket::Candidate& candidate); void OnRouteChange(cricket::TransportChannel* channel, const cricket::Candidate& candidate); void OnWritableState(cricket::TransportChannel* channel); // Callback for jingle_glue::TransportChannelSocketAdapter to notify when the // socket is destroyed. void OnChannelDestroyed(); // Tries to connect by restarting ICE. Called by |reconnect_timer_|. void TryReconnect(); cricket::PortAllocator* port_allocator_; NetworkSettings network_settings_; std::string name_; EventHandler* event_handler_; Transport::ConnectedCallback callback_; std::string ice_username_fragment_; std::string ice_password_; bool can_start_; std::list<cricket::Candidate> pending_candidates_; scoped_ptr<cricket::P2PTransportChannel> channel_; bool channel_was_writable_; int connect_attempts_left_; base::RepeatingTimer<LibjingleTransport> reconnect_timer_; base::WeakPtrFactory<LibjingleTransport> weak_factory_; DISALLOW_COPY_AND_ASSIGN(LibjingleTransport); }; LibjingleTransport::LibjingleTransport(cricket::PortAllocator* port_allocator, const NetworkSettings& network_settings) : port_allocator_(port_allocator), network_settings_(network_settings), event_handler_(NULL), ice_username_fragment_( rtc::CreateRandomString(cricket::ICE_UFRAG_LENGTH)), ice_password_(rtc::CreateRandomString(cricket::ICE_PWD_LENGTH)), can_start_(false), channel_was_writable_(false), connect_attempts_left_(kMaxReconnectAttempts), weak_factory_(this) { DCHECK(!ice_username_fragment_.empty()); DCHECK(!ice_password_.empty()); } LibjingleTransport::~LibjingleTransport() { DCHECK(event_handler_); event_handler_->OnTransportDeleted(this); if (channel_.get()) { base::ThreadTaskRunnerHandle::Get()->DeleteSoon( FROM_HERE, channel_.release()); } } void LibjingleTransport::OnCanStart() { DCHECK(CalledOnValidThread()); DCHECK(!can_start_); can_start_ = true; // If Connect() has been called then start connection. if (!callback_.is_null()) DoStart(); while (!pending_candidates_.empty()) { channel_->OnCandidate(pending_candidates_.front()); pending_candidates_.pop_front(); } } void LibjingleTransport::Connect( const std::string& name, Transport::EventHandler* event_handler, const Transport::ConnectedCallback& callback) { DCHECK(CalledOnValidThread()); DCHECK(!name.empty()); DCHECK(event_handler); DCHECK(!callback.is_null()); DCHECK(name_.empty()); name_ = name; event_handler_ = event_handler; callback_ = callback; if (can_start_) DoStart(); } void LibjingleTransport::DoStart() { DCHECK(!channel_.get()); // Create P2PTransportChannel, attach signal handlers and connect it. // TODO(sergeyu): Specify correct component ID for the channel. channel_.reset(new cricket::P2PTransportChannel( std::string(), 0, NULL, port_allocator_)); channel_->SetIceProtocolType(cricket::ICEPROTO_GOOGLE); channel_->SetIceCredentials(ice_username_fragment_, ice_password_); channel_->SignalRequestSignaling.connect( this, &LibjingleTransport::OnRequestSignaling); channel_->SignalCandidateReady.connect( this, &LibjingleTransport::OnCandidateReady); channel_->SignalRouteChange.connect( this, &LibjingleTransport::OnRouteChange); channel_->SignalWritableState.connect( this, &LibjingleTransport::OnWritableState); channel_->set_incoming_only( !(network_settings_.flags & NetworkSettings::NAT_TRAVERSAL_OUTGOING)); channel_->Connect(); --connect_attempts_left_; // Start reconnection timer. reconnect_timer_.Start( FROM_HERE, base::TimeDelta::FromSeconds(kReconnectDelaySeconds), this, &LibjingleTransport::TryReconnect); } void LibjingleTransport::NotifyConnected() { // Create net::Socket adapter for the P2PTransportChannel. scoped_ptr<jingle_glue::TransportChannelSocketAdapter> socket( new jingle_glue::TransportChannelSocketAdapter(channel_.get())); socket->SetOnDestroyedCallback(base::Bind( &LibjingleTransport::OnChannelDestroyed, base::Unretained(this))); Transport::ConnectedCallback callback = callback_; callback_.Reset(); callback.Run(socket.Pass()); } void LibjingleTransport::AddRemoteCandidate( const cricket::Candidate& candidate) { DCHECK(CalledOnValidThread()); // To enforce the no-relay setting, it's not enough to not produce relay // candidates. It's also necessary to discard remote relay candidates. bool relay_allowed = (network_settings_.flags & NetworkSettings::NAT_TRAVERSAL_RELAY) != 0; if (!relay_allowed && candidate.type() == cricket::RELAY_PORT_TYPE) return; if (channel_) { channel_->OnCandidate(candidate); } else { pending_candidates_.push_back(candidate); } } const std::string& LibjingleTransport::name() const { DCHECK(CalledOnValidThread()); return name_; } bool LibjingleTransport::is_connected() const { DCHECK(CalledOnValidThread()); return callback_.is_null(); } void LibjingleTransport::OnRequestSignaling( cricket::TransportChannelImpl* channel) { DCHECK(CalledOnValidThread()); channel_->OnSignalingReady(); } void LibjingleTransport::OnCandidateReady( cricket::TransportChannelImpl* channel, const cricket::Candidate& candidate) { DCHECK(CalledOnValidThread()); event_handler_->OnTransportCandidate(this, candidate); } void LibjingleTransport::OnRouteChange( cricket::TransportChannel* channel, const cricket::Candidate& candidate) { TransportRoute route; if (candidate.type() == "local") { route.type = TransportRoute::DIRECT; } else if (candidate.type() == "stun") { route.type = TransportRoute::STUN; } else if (candidate.type() == "relay") { route.type = TransportRoute::RELAY; } else { LOG(FATAL) << "Unknown candidate type: " << candidate.type(); } if (!jingle_glue::SocketAddressToIPEndPoint( candidate.address(), &route.remote_address)) { LOG(FATAL) << "Failed to convert peer IP address."; } DCHECK(channel_->best_connection()); const cricket::Candidate& local_candidate = channel_->best_connection()->local_candidate(); if (!jingle_glue::SocketAddressToIPEndPoint( local_candidate.address(), &route.local_address)) { LOG(FATAL) << "Failed to convert local IP address."; } event_handler_->OnTransportRouteChange(this, route); } void LibjingleTransport::OnWritableState( cricket::TransportChannel* channel) { DCHECK_EQ(channel, channel_.get()); if (channel->writable()) { if (!channel_was_writable_) { channel_was_writable_ = true; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&LibjingleTransport::NotifyConnected, weak_factory_.GetWeakPtr())); } connect_attempts_left_ = kMaxReconnectAttempts; reconnect_timer_.Stop(); } else if (!channel->writable() && channel_was_writable_) { reconnect_timer_.Reset(); TryReconnect(); } } void LibjingleTransport::OnChannelDestroyed() { if (is_connected()) { // The connection socket is being deleted, so delete the transport too. delete this; } } void LibjingleTransport::TryReconnect() { DCHECK(!channel_->writable()); if (connect_attempts_left_ <= 0) { reconnect_timer_.Stop(); // Notify the caller that ICE connection has failed - normally that will // terminate Jingle connection (i.e. the transport will be destroyed). event_handler_->OnTransportFailed(this); return; } --connect_attempts_left_; // Restart ICE by resetting ICE password. ice_password_ = rtc::CreateRandomString(cricket::ICE_PWD_LENGTH); channel_->SetIceCredentials(ice_username_fragment_, ice_password_); } } // namespace LibjingleTransportFactory::LibjingleTransportFactory( SignalStrategy* signal_strategy, scoped_ptr<cricket::HttpPortAllocatorBase> port_allocator, const NetworkSettings& network_settings) : signal_strategy_(signal_strategy), port_allocator_(port_allocator.Pass()), network_settings_(network_settings) { } LibjingleTransportFactory::~LibjingleTransportFactory() { // This method may be called in response to a libjingle signal, so // libjingle objects must be deleted asynchronously. scoped_refptr<base::SingleThreadTaskRunner> task_runner = base::ThreadTaskRunnerHandle::Get(); task_runner->DeleteSoon(FROM_HERE, port_allocator_.release()); } void LibjingleTransportFactory::PrepareTokens() { EnsureFreshJingleInfo(); } scoped_ptr<Transport> LibjingleTransportFactory::CreateTransport() { scoped_ptr<LibjingleTransport> result( new LibjingleTransport(port_allocator_.get(), network_settings_)); EnsureFreshJingleInfo(); // If there is a pending |jingle_info_request_| delay starting the new // transport until the request is finished. if (jingle_info_request_) { on_jingle_info_callbacks_.push_back( base::Bind(&LibjingleTransport::OnCanStart, result->AsWeakPtr())); } else { result->OnCanStart(); } return result.Pass(); } void LibjingleTransportFactory::EnsureFreshJingleInfo() { uint32 stun_or_relay_flags = NetworkSettings::NAT_TRAVERSAL_STUN | NetworkSettings::NAT_TRAVERSAL_RELAY; if (!(network_settings_.flags & stun_or_relay_flags) || jingle_info_request_) { return; } if (base::TimeTicks::Now() - last_jingle_info_update_time_ > base::TimeDelta::FromSeconds(kJingleInfoUpdatePeriodSeconds)) { jingle_info_request_.reset(new JingleInfoRequest(signal_strategy_)); jingle_info_request_->Send(base::Bind( &LibjingleTransportFactory::OnJingleInfo, base::Unretained(this))); } } void LibjingleTransportFactory::OnJingleInfo( const std::string& relay_token, const std::vector<std::string>& relay_hosts, const std::vector<rtc::SocketAddress>& stun_hosts) { if (!relay_token.empty() && !relay_hosts.empty()) { port_allocator_->SetRelayHosts(relay_hosts); port_allocator_->SetRelayToken(relay_token); } if (!stun_hosts.empty()) { port_allocator_->SetStunHosts(stun_hosts); } jingle_info_request_.reset(); if ((!relay_token.empty() && !relay_hosts.empty()) || !stun_hosts.empty()) last_jingle_info_update_time_ = base::TimeTicks::Now(); while (!on_jingle_info_callbacks_.empty()) { on_jingle_info_callbacks_.begin()->Run(); on_jingle_info_callbacks_.pop_front(); } } } // namespace protocol } // namespace remoting <commit_msg>Fix connection type reporting<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/protocol/libjingle_transport_factory.h" #include <algorithm> #include "base/callback.h" #include "base/single_thread_task_runner.h" #include "base/thread_task_runner_handle.h" #include "base/timer/timer.h" #include "jingle/glue/channel_socket_adapter.h" #include "jingle/glue/utils.h" #include "net/base/net_errors.h" #include "remoting/protocol/network_settings.h" #include "remoting/signaling/jingle_info_request.h" #include "third_party/webrtc/base/network.h" #include "third_party/webrtc/p2p/base/constants.h" #include "third_party/webrtc/p2p/base/p2ptransportchannel.h" #include "third_party/webrtc/p2p/base/port.h" #include "third_party/webrtc/p2p/client/basicportallocator.h" #include "third_party/webrtc/p2p/client/httpportallocator.h" namespace remoting { namespace protocol { namespace { // Try connecting ICE twice with timeout of 15 seconds for each attempt. const int kMaxReconnectAttempts = 2; const int kReconnectDelaySeconds = 15; // Get fresh STUN/Relay configuration every hour. const int kJingleInfoUpdatePeriodSeconds = 3600; // Utility function to map a cricket::Candidate string type to a // TransportRoute::RouteType enum value. TransportRoute::RouteType CandidateTypeToTransportRouteType( const std::string& candidate_type) { if (candidate_type == "local") { return TransportRoute::DIRECT; } else if (candidate_type == "stun") { return TransportRoute::STUN; } else if (candidate_type == "relay") { return TransportRoute::RELAY; } else { LOG(FATAL) << "Unknown candidate type: " << candidate_type; return TransportRoute::DIRECT; } } class LibjingleTransport : public Transport, public base::SupportsWeakPtr<LibjingleTransport>, public sigslot::has_slots<> { public: LibjingleTransport(cricket::PortAllocator* port_allocator, const NetworkSettings& network_settings); ~LibjingleTransport() override; // Called by JingleTransportFactory when it has fresh Jingle info. void OnCanStart(); // Transport interface. void Connect(const std::string& name, Transport::EventHandler* event_handler, const Transport::ConnectedCallback& callback) override; void AddRemoteCandidate(const cricket::Candidate& candidate) override; const std::string& name() const override; bool is_connected() const override; private: void DoStart(); void NotifyConnected(); // Signal handlers for cricket::TransportChannel. void OnRequestSignaling(cricket::TransportChannelImpl* channel); void OnCandidateReady(cricket::TransportChannelImpl* channel, const cricket::Candidate& candidate); void OnRouteChange(cricket::TransportChannel* channel, const cricket::Candidate& candidate); void OnWritableState(cricket::TransportChannel* channel); // Callback for jingle_glue::TransportChannelSocketAdapter to notify when the // socket is destroyed. void OnChannelDestroyed(); // Tries to connect by restarting ICE. Called by |reconnect_timer_|. void TryReconnect(); cricket::PortAllocator* port_allocator_; NetworkSettings network_settings_; std::string name_; EventHandler* event_handler_; Transport::ConnectedCallback callback_; std::string ice_username_fragment_; std::string ice_password_; bool can_start_; std::list<cricket::Candidate> pending_candidates_; scoped_ptr<cricket::P2PTransportChannel> channel_; bool channel_was_writable_; int connect_attempts_left_; base::RepeatingTimer<LibjingleTransport> reconnect_timer_; base::WeakPtrFactory<LibjingleTransport> weak_factory_; DISALLOW_COPY_AND_ASSIGN(LibjingleTransport); }; LibjingleTransport::LibjingleTransport(cricket::PortAllocator* port_allocator, const NetworkSettings& network_settings) : port_allocator_(port_allocator), network_settings_(network_settings), event_handler_(NULL), ice_username_fragment_( rtc::CreateRandomString(cricket::ICE_UFRAG_LENGTH)), ice_password_(rtc::CreateRandomString(cricket::ICE_PWD_LENGTH)), can_start_(false), channel_was_writable_(false), connect_attempts_left_(kMaxReconnectAttempts), weak_factory_(this) { DCHECK(!ice_username_fragment_.empty()); DCHECK(!ice_password_.empty()); } LibjingleTransport::~LibjingleTransport() { DCHECK(event_handler_); event_handler_->OnTransportDeleted(this); if (channel_.get()) { base::ThreadTaskRunnerHandle::Get()->DeleteSoon( FROM_HERE, channel_.release()); } } void LibjingleTransport::OnCanStart() { DCHECK(CalledOnValidThread()); DCHECK(!can_start_); can_start_ = true; // If Connect() has been called then start connection. if (!callback_.is_null()) DoStart(); while (!pending_candidates_.empty()) { channel_->OnCandidate(pending_candidates_.front()); pending_candidates_.pop_front(); } } void LibjingleTransport::Connect( const std::string& name, Transport::EventHandler* event_handler, const Transport::ConnectedCallback& callback) { DCHECK(CalledOnValidThread()); DCHECK(!name.empty()); DCHECK(event_handler); DCHECK(!callback.is_null()); DCHECK(name_.empty()); name_ = name; event_handler_ = event_handler; callback_ = callback; if (can_start_) DoStart(); } void LibjingleTransport::DoStart() { DCHECK(!channel_.get()); // Create P2PTransportChannel, attach signal handlers and connect it. // TODO(sergeyu): Specify correct component ID for the channel. channel_.reset(new cricket::P2PTransportChannel( std::string(), 0, NULL, port_allocator_)); channel_->SetIceProtocolType(cricket::ICEPROTO_GOOGLE); channel_->SetIceCredentials(ice_username_fragment_, ice_password_); channel_->SignalRequestSignaling.connect( this, &LibjingleTransport::OnRequestSignaling); channel_->SignalCandidateReady.connect( this, &LibjingleTransport::OnCandidateReady); channel_->SignalRouteChange.connect( this, &LibjingleTransport::OnRouteChange); channel_->SignalWritableState.connect( this, &LibjingleTransport::OnWritableState); channel_->set_incoming_only( !(network_settings_.flags & NetworkSettings::NAT_TRAVERSAL_OUTGOING)); channel_->Connect(); --connect_attempts_left_; // Start reconnection timer. reconnect_timer_.Start( FROM_HERE, base::TimeDelta::FromSeconds(kReconnectDelaySeconds), this, &LibjingleTransport::TryReconnect); } void LibjingleTransport::NotifyConnected() { // Create net::Socket adapter for the P2PTransportChannel. scoped_ptr<jingle_glue::TransportChannelSocketAdapter> socket( new jingle_glue::TransportChannelSocketAdapter(channel_.get())); socket->SetOnDestroyedCallback(base::Bind( &LibjingleTransport::OnChannelDestroyed, base::Unretained(this))); Transport::ConnectedCallback callback = callback_; callback_.Reset(); callback.Run(socket.Pass()); } void LibjingleTransport::AddRemoteCandidate( const cricket::Candidate& candidate) { DCHECK(CalledOnValidThread()); // To enforce the no-relay setting, it's not enough to not produce relay // candidates. It's also necessary to discard remote relay candidates. bool relay_allowed = (network_settings_.flags & NetworkSettings::NAT_TRAVERSAL_RELAY) != 0; if (!relay_allowed && candidate.type() == cricket::RELAY_PORT_TYPE) return; if (channel_) { channel_->OnCandidate(candidate); } else { pending_candidates_.push_back(candidate); } } const std::string& LibjingleTransport::name() const { DCHECK(CalledOnValidThread()); return name_; } bool LibjingleTransport::is_connected() const { DCHECK(CalledOnValidThread()); return callback_.is_null(); } void LibjingleTransport::OnRequestSignaling( cricket::TransportChannelImpl* channel) { DCHECK(CalledOnValidThread()); channel_->OnSignalingReady(); } void LibjingleTransport::OnCandidateReady( cricket::TransportChannelImpl* channel, const cricket::Candidate& candidate) { DCHECK(CalledOnValidThread()); event_handler_->OnTransportCandidate(this, candidate); } void LibjingleTransport::OnRouteChange( cricket::TransportChannel* channel, const cricket::Candidate& candidate) { TransportRoute route; DCHECK(channel_->best_connection()); const cricket::Connection* connection = channel_->best_connection(); // A connection has both a local and a remote candidate. For our purposes, the // route type is determined by the most indirect candidate type. For example: // it's possible for the local candidate be a "relay" type, while the remote // candidate is "local". In this case, we still want to report a RELAY route // type. static_assert(TransportRoute::DIRECT < TransportRoute::STUN && TransportRoute::STUN < TransportRoute::RELAY, "Route type enum values are ordered by 'indirectness'"); route.type = std::max( CandidateTypeToTransportRouteType(connection->local_candidate().type()), CandidateTypeToTransportRouteType(connection->remote_candidate().type())); if (!jingle_glue::SocketAddressToIPEndPoint( candidate.address(), &route.remote_address)) { LOG(FATAL) << "Failed to convert peer IP address."; } const cricket::Candidate& local_candidate = channel_->best_connection()->local_candidate(); if (!jingle_glue::SocketAddressToIPEndPoint( local_candidate.address(), &route.local_address)) { LOG(FATAL) << "Failed to convert local IP address."; } event_handler_->OnTransportRouteChange(this, route); } void LibjingleTransport::OnWritableState( cricket::TransportChannel* channel) { DCHECK_EQ(channel, channel_.get()); if (channel->writable()) { if (!channel_was_writable_) { channel_was_writable_ = true; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&LibjingleTransport::NotifyConnected, weak_factory_.GetWeakPtr())); } connect_attempts_left_ = kMaxReconnectAttempts; reconnect_timer_.Stop(); } else if (!channel->writable() && channel_was_writable_) { reconnect_timer_.Reset(); TryReconnect(); } } void LibjingleTransport::OnChannelDestroyed() { if (is_connected()) { // The connection socket is being deleted, so delete the transport too. delete this; } } void LibjingleTransport::TryReconnect() { DCHECK(!channel_->writable()); if (connect_attempts_left_ <= 0) { reconnect_timer_.Stop(); // Notify the caller that ICE connection has failed - normally that will // terminate Jingle connection (i.e. the transport will be destroyed). event_handler_->OnTransportFailed(this); return; } --connect_attempts_left_; // Restart ICE by resetting ICE password. ice_password_ = rtc::CreateRandomString(cricket::ICE_PWD_LENGTH); channel_->SetIceCredentials(ice_username_fragment_, ice_password_); } } // namespace LibjingleTransportFactory::LibjingleTransportFactory( SignalStrategy* signal_strategy, scoped_ptr<cricket::HttpPortAllocatorBase> port_allocator, const NetworkSettings& network_settings) : signal_strategy_(signal_strategy), port_allocator_(port_allocator.Pass()), network_settings_(network_settings) { } LibjingleTransportFactory::~LibjingleTransportFactory() { // This method may be called in response to a libjingle signal, so // libjingle objects must be deleted asynchronously. scoped_refptr<base::SingleThreadTaskRunner> task_runner = base::ThreadTaskRunnerHandle::Get(); task_runner->DeleteSoon(FROM_HERE, port_allocator_.release()); } void LibjingleTransportFactory::PrepareTokens() { EnsureFreshJingleInfo(); } scoped_ptr<Transport> LibjingleTransportFactory::CreateTransport() { scoped_ptr<LibjingleTransport> result( new LibjingleTransport(port_allocator_.get(), network_settings_)); EnsureFreshJingleInfo(); // If there is a pending |jingle_info_request_| delay starting the new // transport until the request is finished. if (jingle_info_request_) { on_jingle_info_callbacks_.push_back( base::Bind(&LibjingleTransport::OnCanStart, result->AsWeakPtr())); } else { result->OnCanStart(); } return result.Pass(); } void LibjingleTransportFactory::EnsureFreshJingleInfo() { uint32 stun_or_relay_flags = NetworkSettings::NAT_TRAVERSAL_STUN | NetworkSettings::NAT_TRAVERSAL_RELAY; if (!(network_settings_.flags & stun_or_relay_flags) || jingle_info_request_) { return; } if (base::TimeTicks::Now() - last_jingle_info_update_time_ > base::TimeDelta::FromSeconds(kJingleInfoUpdatePeriodSeconds)) { jingle_info_request_.reset(new JingleInfoRequest(signal_strategy_)); jingle_info_request_->Send(base::Bind( &LibjingleTransportFactory::OnJingleInfo, base::Unretained(this))); } } void LibjingleTransportFactory::OnJingleInfo( const std::string& relay_token, const std::vector<std::string>& relay_hosts, const std::vector<rtc::SocketAddress>& stun_hosts) { if (!relay_token.empty() && !relay_hosts.empty()) { port_allocator_->SetRelayHosts(relay_hosts); port_allocator_->SetRelayToken(relay_token); } if (!stun_hosts.empty()) { port_allocator_->SetStunHosts(stun_hosts); } jingle_info_request_.reset(); if ((!relay_token.empty() && !relay_hosts.empty()) || !stun_hosts.empty()) last_jingle_info_update_time_ = base::TimeTicks::Now(); while (!on_jingle_info_callbacks_.empty()) { on_jingle_info_callbacks_.begin()->Run(); on_jingle_info_callbacks_.pop_front(); } } } // namespace protocol } // namespace remoting <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ #include "NamedNodeMapImpl.hpp" #include "NodeVector.hpp" #include "AttrImpl.hpp" #include "DOM_DOMException.hpp" #include "DocumentImpl.hpp" int NamedNodeMapImpl::gLiveNamedNodeMaps = 0; int NamedNodeMapImpl::gTotalNamedNodeMaps = 0; NamedNodeMapImpl::NamedNodeMapImpl(NodeImpl *ownerNod) { this->ownerNode=ownerNod; this->nodes = null; this->readOnly = false; this->refCount = 1; gLiveNamedNodeMaps++; gTotalNamedNodeMaps++; }; NamedNodeMapImpl::~NamedNodeMapImpl() { if (nodes) { // It is the responsibility of whoever was using the named node // map to do any cleanup on the nodes contained in the map // before deleting it. delete nodes; nodes = 0; } gLiveNamedNodeMaps--; }; void NamedNodeMapImpl::addRef(NamedNodeMapImpl *This) { if (This) ++This->refCount; }; NamedNodeMapImpl *NamedNodeMapImpl::cloneMap(NodeImpl *ownerNod) { NamedNodeMapImpl *newmap = new NamedNodeMapImpl(ownerNod); if (nodes != null) { newmap->nodes = new NodeVector(nodes->size()); for (unsigned int i = 0; i < nodes->size(); ++i) { NodeImpl *n = nodes->elementAt(i)->cloneNode(true); n->isSpecified(nodes->elementAt(i)->isSpecified()); n->ownerNode = ownerNod; n->isOwned(true); newmap->nodes->addElement(n); } } return newmap; }; // // removeAll - This function removes all elements from a named node map. // It is called from the destructors for Elements and DocumentTypes, // to remove the contents when the owning Element or DocType goes // away. The empty NamedNodeMap may persist if the user code // has a reference to it. // // AH Revist - the empty map should be made read-only, since // adding it was logically part of the [Element, DocumentType] // that has been deleted, and adding anything new to it would // be meaningless, and almost certainly an error. // void NamedNodeMapImpl::removeAll() { if (nodes) { for (int i=nodes->size()-1; i>=0; i--) { NodeImpl *n = nodes->elementAt(i); n->ownerNode = ownerNode->getOwnerDocument(); n->isOwned(false); if (n->nodeRefCount == 0) NodeImpl::deleteIf(n); } delete nodes; nodes = null; } } int NamedNodeMapImpl::findNamePoint(const DOMString &name) { // Binary search int i=0; if(nodes!=null) { int first=0,last=nodes->size()-1; while(first<=last) { i=(first+last)/2; int test = name.compareString(nodes->elementAt(i)->getNodeName()); if(test==0) return i; // Name found else if(test<0) last=i-1; else first=i+1; } if(first>i) i=first; } /******************** // Linear search int i = 0; if (nodes != null) for (i = 0; i < nodes.size(); ++i) { int test = name.compareTo(((NodeImpl *) (nodes.elementAt(i))).getNodeName()); if (test == 0) return i; else if (test < 0) { break; // Found insertpoint } } *******************/ return -1 - i; // not-found has to be encoded. }; unsigned int NamedNodeMapImpl::getLength() { return (nodes != null) ? nodes->size() : 0; }; NodeImpl * NamedNodeMapImpl::getNamedItem(const DOMString &name) { int i=findNamePoint(name); return (i<0) ? null : (NodeImpl *)(nodes->elementAt(i)); }; NodeImpl * NamedNodeMapImpl::item(unsigned int index) { return (nodes != null && index < nodes->size()) ? (NodeImpl *) (nodes->elementAt(index)) : null; }; // // removeNamedItem() - Remove the named item, and return it. // The caller must arrange for deletion of the // returned item if its refcount has gone to zero - // we can't do it here because the caller would // never see the returned node. // NodeImpl * NamedNodeMapImpl::removeNamedItem(const DOMString &name) { if (readOnly) throw DOM_DOMException( DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null); int i=findNamePoint(name); NodeImpl *n = null; if(i<0) throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null); n = (NodeImpl *) (nodes->elementAt(i)); nodes->removeElementAt(i); n->ownerNode = ownerNode->getOwnerDocument(); n->isOwned(false); return n; }; void NamedNodeMapImpl::removeRef(NamedNodeMapImpl *This) { if (This && --This->refCount == 0) delete This; }; // // setNamedItem() Put the item into the NamedNodeList by name. // If an item with the same name already was // in the list, replace it. Return the old // item, if there was one. // Caller is responsible for arranging for // deletion of the old item if its ref count is // zero. // NodeImpl * NamedNodeMapImpl::setNamedItem(NodeImpl * arg) { if(arg->getOwnerDocument() != ownerNode->getOwnerDocument()) throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR,null); if (readOnly) throw DOM_DOMException(DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null); if (arg->isOwned()) throw DOM_DOMException(DOM_DOMException::INUSE_ATTRIBUTE_ERR,null); arg->ownerNode = ownerNode; arg->isOwned(true); int i=findNamePoint(arg->getNodeName()); NodeImpl * previous=null; if(i>=0) { previous = nodes->elementAt(i); nodes->setElementAt(arg,i); } else { i=-1-i; // Insert point (may be end of list) if(null==nodes) nodes=new NodeVector(); nodes->insertElementAt(arg,i); } if (previous != null) { previous->ownerNode = ownerNode->getOwnerDocument(); previous->isOwned(false); } return previous; }; void NamedNodeMapImpl::setReadOnly(bool readOnl, bool deep) { this->readOnly=readOnl; if(deep && nodes!=null) { //Enumeration e=nodes->elements(); //while(e->hasMoreElements()) // ((NodeImpl)e->nextElement())->setReadOnly(readOnl,deep); int sz = nodes->size(); for (int i=0; i<sz; ++i) { nodes->elementAt(i)->setReadOnly(readOnl, deep); } } }; //Introduced in DOM Level 2 int NamedNodeMapImpl::findNamePoint(const DOMString &namespaceURI, const DOMString &localName) { if (nodes == null) return -1; // This is a linear search through the same nodes Vector. // The Vector is sorted on the DOM Level 1 nodename. // The DOM Level 2 NS keys are namespaceURI and Localname, // so we must linear search thru it. // In addition, to get this to work with nodes without any namespace // (namespaceURI and localNames are both null) we then use the nodeName // as a secondary key. int i, len = nodes -> size(); for (i = 0; i < len; ++i) { NodeImpl *node = nodes -> elementAt(i); if (! node -> getNamespaceURI().equals(namespaceURI)) //URI not match continue; DOMString nLocalName = node->getLocalName(); if (nLocalName.equals(localName) || (nLocalName == null && localName.equals(node->getNodeName()))) return i; } return -1; //not found } NodeImpl *NamedNodeMapImpl::getNamedItemNS(const DOMString &namespaceURI, const DOMString &localName) { int i = findNamePoint(namespaceURI, localName); return i < 0 ? null : nodes -> elementAt(i); } // // setNamedItemNS() Put the item into the NamedNodeList by name. // If an item with the same name already was // in the list, replace it. Return the old // item, if there was one. // Caller is responsible for arranging for // deletion of the old item if its ref count is // zero. // NodeImpl * NamedNodeMapImpl::setNamedItemNS(NodeImpl *arg) { if (arg->getOwnerDocument() != ownerNode->getOwnerDocument()) throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR,null); if (readOnly) throw DOM_DOMException(DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null); if (arg->isOwned()) throw DOM_DOMException(DOM_DOMException::INUSE_ATTRIBUTE_ERR,null); arg->ownerNode = ownerNode; arg->isOwned(true); int i=findNamePoint(arg->getNamespaceURI(), arg->getLocalName()); NodeImpl *previous=null; if(i>=0) { previous = nodes->elementAt(i); nodes->setElementAt(arg,i); } else { i=-1-i; // Insert point (may be end of list) if(null==nodes) nodes=new NodeVector(); nodes->insertElementAt(arg,i); } if (previous != null) { previous->ownerNode = ownerNode->getOwnerDocument(); previous->isOwned(false); } return previous; }; // removeNamedItemNS() - Remove the named item, and return it. // The caller must arrange for deletion of the // returned item if its refcount has gone to zero - // we can't do it here because the caller would // never see the returned node. NodeImpl *NamedNodeMapImpl::removeNamedItemNS(const DOMString &namespaceURI, const DOMString &localName) { if (readOnly) throw DOM_DOMException( DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null); int i = findNamePoint(namespaceURI, localName); if (i < 0) throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null); NodeImpl * n = nodes -> elementAt(i); nodes -> removeElementAt(i); //remove n from nodes n->ownerNode = ownerNode->getOwnerDocument(); n->isOwned(false); return n; } /** * NON-DOM * set the ownerDocument of this node, its children, and its attributes */ void NamedNodeMapImpl::setOwnerDocument(DocumentImpl *doc) { if (nodes != null) { for (unsigned int i = 0; i < nodes->size(); i++) { item(i)->setOwnerDocument(doc); } } } void NamedNodeMapImpl::cloneContent(NamedNodeMapImpl *srcmap) { if ((srcmap != null) && (srcmap->nodes != null)) { if (nodes != null) delete nodes; nodes = new NodeVector(srcmap->nodes->size()); for (unsigned int i = 0; i < srcmap->nodes->size(); i++) { NodeImpl *n = srcmap->nodes->elementAt(i); NodeImpl *clone = n->cloneNode(true); clone->isSpecified(n->isSpecified()); clone->ownerNode = ownerNode; clone->isOwned(true); nodes->addElement(clone); // n = null; // clone = null; } } } <commit_msg>changed again findNamePoint to only consider the nodeName when namespaceURI is null<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ #include "NamedNodeMapImpl.hpp" #include "NodeVector.hpp" #include "AttrImpl.hpp" #include "DOM_DOMException.hpp" #include "DocumentImpl.hpp" int NamedNodeMapImpl::gLiveNamedNodeMaps = 0; int NamedNodeMapImpl::gTotalNamedNodeMaps = 0; NamedNodeMapImpl::NamedNodeMapImpl(NodeImpl *ownerNod) { this->ownerNode=ownerNod; this->nodes = null; this->readOnly = false; this->refCount = 1; gLiveNamedNodeMaps++; gTotalNamedNodeMaps++; }; NamedNodeMapImpl::~NamedNodeMapImpl() { if (nodes) { // It is the responsibility of whoever was using the named node // map to do any cleanup on the nodes contained in the map // before deleting it. delete nodes; nodes = 0; } gLiveNamedNodeMaps--; }; void NamedNodeMapImpl::addRef(NamedNodeMapImpl *This) { if (This) ++This->refCount; }; NamedNodeMapImpl *NamedNodeMapImpl::cloneMap(NodeImpl *ownerNod) { NamedNodeMapImpl *newmap = new NamedNodeMapImpl(ownerNod); if (nodes != null) { newmap->nodes = new NodeVector(nodes->size()); for (unsigned int i = 0; i < nodes->size(); ++i) { NodeImpl *n = nodes->elementAt(i)->cloneNode(true); n->isSpecified(nodes->elementAt(i)->isSpecified()); n->ownerNode = ownerNod; n->isOwned(true); newmap->nodes->addElement(n); } } return newmap; }; // // removeAll - This function removes all elements from a named node map. // It is called from the destructors for Elements and DocumentTypes, // to remove the contents when the owning Element or DocType goes // away. The empty NamedNodeMap may persist if the user code // has a reference to it. // // AH Revist - the empty map should be made read-only, since // adding it was logically part of the [Element, DocumentType] // that has been deleted, and adding anything new to it would // be meaningless, and almost certainly an error. // void NamedNodeMapImpl::removeAll() { if (nodes) { for (int i=nodes->size()-1; i>=0; i--) { NodeImpl *n = nodes->elementAt(i); n->ownerNode = ownerNode->getOwnerDocument(); n->isOwned(false); if (n->nodeRefCount == 0) NodeImpl::deleteIf(n); } delete nodes; nodes = null; } } int NamedNodeMapImpl::findNamePoint(const DOMString &name) { // Binary search int i=0; if(nodes!=null) { int first=0,last=nodes->size()-1; while(first<=last) { i=(first+last)/2; int test = name.compareString(nodes->elementAt(i)->getNodeName()); if(test==0) return i; // Name found else if(test<0) last=i-1; else first=i+1; } if(first>i) i=first; } /******************** // Linear search int i = 0; if (nodes != null) for (i = 0; i < nodes.size(); ++i) { int test = name.compareTo(((NodeImpl *) (nodes.elementAt(i))).getNodeName()); if (test == 0) return i; else if (test < 0) { break; // Found insertpoint } } *******************/ return -1 - i; // not-found has to be encoded. }; unsigned int NamedNodeMapImpl::getLength() { return (nodes != null) ? nodes->size() : 0; }; NodeImpl * NamedNodeMapImpl::getNamedItem(const DOMString &name) { int i=findNamePoint(name); return (i<0) ? null : (NodeImpl *)(nodes->elementAt(i)); }; NodeImpl * NamedNodeMapImpl::item(unsigned int index) { return (nodes != null && index < nodes->size()) ? (NodeImpl *) (nodes->elementAt(index)) : null; }; // // removeNamedItem() - Remove the named item, and return it. // The caller must arrange for deletion of the // returned item if its refcount has gone to zero - // we can't do it here because the caller would // never see the returned node. // NodeImpl * NamedNodeMapImpl::removeNamedItem(const DOMString &name) { if (readOnly) throw DOM_DOMException( DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null); int i=findNamePoint(name); NodeImpl *n = null; if(i<0) throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null); n = (NodeImpl *) (nodes->elementAt(i)); nodes->removeElementAt(i); n->ownerNode = ownerNode->getOwnerDocument(); n->isOwned(false); return n; }; void NamedNodeMapImpl::removeRef(NamedNodeMapImpl *This) { if (This && --This->refCount == 0) delete This; }; // // setNamedItem() Put the item into the NamedNodeList by name. // If an item with the same name already was // in the list, replace it. Return the old // item, if there was one. // Caller is responsible for arranging for // deletion of the old item if its ref count is // zero. // NodeImpl * NamedNodeMapImpl::setNamedItem(NodeImpl * arg) { if(arg->getOwnerDocument() != ownerNode->getOwnerDocument()) throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR,null); if (readOnly) throw DOM_DOMException(DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null); if (arg->isOwned()) throw DOM_DOMException(DOM_DOMException::INUSE_ATTRIBUTE_ERR,null); arg->ownerNode = ownerNode; arg->isOwned(true); int i=findNamePoint(arg->getNodeName()); NodeImpl * previous=null; if(i>=0) { previous = nodes->elementAt(i); nodes->setElementAt(arg,i); } else { i=-1-i; // Insert point (may be end of list) if(null==nodes) nodes=new NodeVector(); nodes->insertElementAt(arg,i); } if (previous != null) { previous->ownerNode = ownerNode->getOwnerDocument(); previous->isOwned(false); } return previous; }; void NamedNodeMapImpl::setReadOnly(bool readOnl, bool deep) { this->readOnly=readOnl; if(deep && nodes!=null) { //Enumeration e=nodes->elements(); //while(e->hasMoreElements()) // ((NodeImpl)e->nextElement())->setReadOnly(readOnl,deep); int sz = nodes->size(); for (int i=0; i<sz; ++i) { nodes->elementAt(i)->setReadOnly(readOnl, deep); } } }; //Introduced in DOM Level 2 int NamedNodeMapImpl::findNamePoint(const DOMString &namespaceURI, const DOMString &localName) { if (nodes == null) return -1; // This is a linear search through the same nodes Vector. // The Vector is sorted on the DOM Level 1 nodename. // The DOM Level 2 NS keys are namespaceURI and Localname, // so we must linear search thru it. // In addition, to get this to work with nodes without any namespace // (namespaceURI and localNames are both null) we then use the nodeName // as a secondary key. int i, len = nodes -> size(); for (i = 0; i < len; ++i) { NodeImpl *node = nodes -> elementAt(i); if (! node -> getNamespaceURI().equals(namespaceURI)) //URI not match continue; DOMString nNamespaceURI = node->getNamespaceURI(); DOMString nLocalName = node->getLocalName(); if (namespaceURI == null) { if (nNamespaceURI == null && (localName.equals(nLocalName) || (nLocalName == null && localName.equals(node->getNodeName())))) return i; } else { if (namespaceURI.equals(nNamespaceURI) && localName.equals(nLocalName)) return i; } } return -1; //not found } NodeImpl *NamedNodeMapImpl::getNamedItemNS(const DOMString &namespaceURI, const DOMString &localName) { int i = findNamePoint(namespaceURI, localName); return i < 0 ? null : nodes -> elementAt(i); } // // setNamedItemNS() Put the item into the NamedNodeList by name. // If an item with the same name already was // in the list, replace it. Return the old // item, if there was one. // Caller is responsible for arranging for // deletion of the old item if its ref count is // zero. // NodeImpl * NamedNodeMapImpl::setNamedItemNS(NodeImpl *arg) { if (arg->getOwnerDocument() != ownerNode->getOwnerDocument()) throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR,null); if (readOnly) throw DOM_DOMException(DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null); if (arg->isOwned()) throw DOM_DOMException(DOM_DOMException::INUSE_ATTRIBUTE_ERR,null); arg->ownerNode = ownerNode; arg->isOwned(true); int i=findNamePoint(arg->getNamespaceURI(), arg->getLocalName()); NodeImpl *previous=null; if(i>=0) { previous = nodes->elementAt(i); nodes->setElementAt(arg,i); } else { i=-1-i; // Insert point (may be end of list) if(null==nodes) nodes=new NodeVector(); nodes->insertElementAt(arg,i); } if (previous != null) { previous->ownerNode = ownerNode->getOwnerDocument(); previous->isOwned(false); } return previous; }; // removeNamedItemNS() - Remove the named item, and return it. // The caller must arrange for deletion of the // returned item if its refcount has gone to zero - // we can't do it here because the caller would // never see the returned node. NodeImpl *NamedNodeMapImpl::removeNamedItemNS(const DOMString &namespaceURI, const DOMString &localName) { if (readOnly) throw DOM_DOMException( DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null); int i = findNamePoint(namespaceURI, localName); if (i < 0) throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null); NodeImpl * n = nodes -> elementAt(i); nodes -> removeElementAt(i); //remove n from nodes n->ownerNode = ownerNode->getOwnerDocument(); n->isOwned(false); return n; } /** * NON-DOM * set the ownerDocument of this node, its children, and its attributes */ void NamedNodeMapImpl::setOwnerDocument(DocumentImpl *doc) { if (nodes != null) { for (unsigned int i = 0; i < nodes->size(); i++) { item(i)->setOwnerDocument(doc); } } } void NamedNodeMapImpl::cloneContent(NamedNodeMapImpl *srcmap) { if ((srcmap != null) && (srcmap->nodes != null)) { if (nodes != null) delete nodes; nodes = new NodeVector(srcmap->nodes->size()); for (unsigned int i = 0; i < srcmap->nodes->size(); i++) { NodeImpl *n = srcmap->nodes->elementAt(i); NodeImpl *clone = n->cloneNode(true); clone->isSpecified(n->isSpecified()); clone->ownerNode = ownerNode; clone->isOwned(true); nodes->addElement(clone); // n = null; // clone = null; } } } <|endoftext|>
<commit_before>/* * despot1_main.cpp * * Created by Tobias Wood on 23/01/2012. * Copyright 2012 Tobias Wood. All rights reserved. * */ #include <time.h> #include <getopt.h> #include <iostream> #include <atomic> #include <Eigen/Dense> #include "NiftiImage.h" #include "DESPOT.h" #include "DESPOT_Functors.h" #include "RegionContraction.h" #define USE_PROCPAR #ifdef USE_PROCPAR #include "procpar.h" using namespace Recon; #endif using namespace std; using namespace Eigen; //****************************************************************************** // Arguments / Usage //****************************************************************************** const string credit { "despot2 - Written by tobias.wood@kcl.ac.uk, based on work by Sean Deoni. \n\ Acknowledgements greatfully received, grant discussions welcome." }; const string usage { "Usage is: despot2 [options] T1_map ssfp_files\n\ \ Options:\n\ --help, -h : Print this message.\n\ --mask, -m file : Mask input with specified file.\n\ --out, -o path : Add a prefix to the output filenames.\n\ --B0 file : B0 Map file.\n\ --B1 file : B1 Map file.\n\ --M0 file : Proton density file.\n\ --verbose, -v : Print slice processing times.\n\ --start_slice N : Start processing from slice N.\n\ --end_slice N : Finish processing at slice N.\n\ --tesla, -t 3 : Enables DESPOT-FM with boundaries suitable for 3T\n\ 7 : Boundaries suitable for 7T (default)\n\ u : User specified boundaries from stdin.\n" }; // tesla == 0 means NO DESPOT-FM static int tesla = 0, fitB0 = false, verbose = false, start_slice = -1, end_slice = -1; static string outPrefix; static struct option long_options[] = { {"B0", required_argument, 0, '0'}, {"B1", required_argument, 0, '1'}, {"M0", required_argument, 0, 'M'}, {"help", no_argument, 0, 'h'}, {"mask", required_argument, 0, 'm'}, {"tesla", required_argument, 0, 't'}, {"verbose", no_argument, 0, 'v'}, {"start_slice", required_argument, 0, 'S'}, {"end_slice", required_argument, 0, 'E'}, {0, 0, 0, 0} }; //****************************************************************************** // Main //****************************************************************************** int main(int argc, char **argv) { //************************************************************************** // Argument Processing //************************************************************************** cout << credit << endl; if (argc < 4) { cout << usage << endl; return EXIT_FAILURE; } Eigen::initParallel(); NiftiImage inFile, savedHeader; double *maskData = NULL, *B0Data = NULL, *B1Data = NULL, *T1Data = NULL, *M0Data = NULL; string procPath; int indexptr = 0, c; while ((c = getopt_long(argc, argv, "hm:o:vt:", long_options, &indexptr)) != -1) { switch (c) { case 'o': outPrefix = optarg; cout << "Output prefix will be: " << outPrefix << endl; break; case 'm': cout << "Reading mask file " << optarg << endl; inFile.open(optarg, 'r'); maskData = inFile.readVolume<double>(0); inFile.close(); break; case '0': cout << "Reading B0 file: " << optarg << endl; inFile.open(optarg, 'r'); B0Data = inFile.readVolume<double>(0); inFile.close(); break; case '1': cout << "Reading B1 file: " << optarg << endl; inFile.open(optarg, 'r'); B1Data = inFile.readVolume<double>(0); inFile.close(); break; case 'M': cout << "Reading M0 file " << optarg; inFile.open(optarg, 'r'); M0Data = inFile.readVolume<double>(0); inFile.close(); break; case 't': switch (*optarg) { case '3': tesla = 3; break; case '7': tesla = 7; break; case 'u': tesla = -1; break; default: cout << "Unknown boundaries type " << optarg << endl; abort(); break; } cout << "Using " << tesla << "T boundaries." << endl; break; case 'v': verbose = true; break; case 'S': start_slice = atoi(optarg); break; case 'E': end_slice = atoi(optarg); break; case 0: // Just a flag break; case '?': // getopt will print an error message case 'h': cout << usage << endl; return EXIT_FAILURE; } } if ((tesla != 0) && !B0Data) fitB0 = true; cout << "Reading T1 Map from: " << argv[optind] << endl; inFile.open(argv[optind++], 'r'); T1Data = inFile.readVolume<double>(0); inFile.close(); savedHeader = inFile; //************************************************************************** // Gather SSFP Data //************************************************************************** int nFlip, nPhases; nPhases = argc - optind; vector<DESPOTConstants> consts(nPhases); VectorXd ssfpAngles; int voxelsPerSlice, voxelsPerVolume; double **ssfpData = (double **)malloc(nPhases * sizeof(double *)); for (size_t p = 0; p < nPhases; p++) { cout << "Reading SSFP header from " << argv[optind] << endl; inFile.open(argv[optind], 'r'); if (p == 0) { // Read nFlip, TR and flip angles from first file nFlip = inFile.dim(4); voxelsPerSlice = inFile.voxelsPerSlice(); voxelsPerVolume = inFile.voxelsPerVolume(); ssfpAngles.resize(nFlip, 1); #ifdef USE_PROCPAR ParameterList pars; if (ReadProcpar(inFile.basename() + ".procpar", pars)) { consts[0].TR = RealValue(pars, "tr"); for (int i = 0; i < nFlip; i++) ssfpAngles[i] = RealValue(pars, "flip1", i); } else #endif { cout << "Enter SSFP TR (s): " << flush; cin >> consts[0].TR; cout << "Enter " << nFlip << " flip angles (degrees): " << flush; for (int i = 0; i < ssfpAngles.size(); i++) cin >> ssfpAngles[i]; } } else { consts[p].TR = consts[0].TR; } #ifdef USE_PROCPAR ParameterList pars; if (ReadProcpar(inFile.basename() + ".procpar", pars)) { consts[p].phase = RealValue(pars, "rfphase") * M_PI / 180.; } else #endif { cout << "Enter phase-cycling (degrees): " << flush; cin >> consts[p].phase; consts[p].phase *= M_PI / 180.; } cout << "Reading SSFP data..." << endl; ssfpData[p] = inFile.readAllVolumes<double>(); // Don't close the first header because we've saved it to write the // results, and FSLIO gets fussy about cloning closed headers inFile.close(); optind++; } ssfpAngles *= M_PI / 180.; if (optind != argc) { cerr << "Unprocessed arguments supplied.\n" << usage; exit(EXIT_FAILURE); } // Set up boundaries for DESPOT-FM if needed ArrayXd loBounds, hiBounds; const long nP = DESPOT2FM::inputs(); if (tesla != 0) { if (tesla > 0) { loBounds = DESPOT2FM::defaultLo(tesla); hiBounds = DESPOT2FM::defaultHi(tesla); } else if (tesla < 0) { cout << "Enter " << nP << " parameter pairs (low then high): " << flush; for (int i = 0; i < nP; i++) cin >> loBounds[i] >> hiBounds[i]; } // If fitting, give a suitable range and allocate results memory if (fitB0) { loBounds[0] = -0.5 / consts[0].TR; hiBounds[0] = 0.5 / consts[0].TR; B0Data = new double[voxelsPerVolume]; } else { // Otherwise fix and let functors pick up the specified value loBounds[0] = 0.; hiBounds[0] = 0.; } } if (verbose) { cout << "SSFP Angles (deg): " << ssfpAngles.transpose() * 180 / M_PI << endl; if (tesla != 0) cout << "Low bounds: " << loBounds.transpose() << endl << "Hi bounds: " << hiBounds.transpose() << endl; } //************************************************************************** // Set up results data //************************************************************************** vector<double *> paramsData(nP); for (int p = 0; p < nP; p++) paramsData[p] = new double[voxelsPerVolume]; double *residuals = new double[voxelsPerVolume]; //************************************************************************** // Do the fitting //************************************************************************** time_t procStart = time(NULL); if ((start_slice < 0) || (start_slice >= inFile.dim(3))) start_slice = 0; if ((end_slice < 0) || (end_slice > inFile.dim(3))) end_slice = inFile.dim(3); for (int slice = start_slice; slice < end_slice; slice++) { // Read in data if (verbose) cout << "Starting slice " << slice << "..." << flush; atomic<int> voxCount{0}; const int sliceOffset = slice * voxelsPerSlice; clock_t loopStart = clock(); function<void (const int&)> processVox = [&] (const int &vox) { // Set up parameters and constants double residual = 0., T1 = 0.; ArrayXd params(nP); if (!maskData || ((maskData[sliceOffset + vox] > 0.) && (T1Data[sliceOffset + vox] > 0.))) { // Zero T1 causes zero-pivot error. voxCount++; T1 = T1Data[sliceOffset + vox]; // Gather signals. vector<VectorXd> signals; for (int p = 0; p < nPhases; p++) { if (B0Data) consts[p].B0 = B0Data[sliceOffset + vox]; if (B1Data) consts[p].B1 = B1Data[sliceOffset + vox]; VectorXd temp(nFlip); for (int i = 0; i < nFlip; i++) temp(i) = ssfpData[p][i*voxelsPerVolume + sliceOffset + vox]; signals.push_back(temp); } if (tesla == 0) { // Choose phase with accumulated phase closest to 180 and then classic DESPOT2 int index = 0; double bestPhase = DBL_MAX; for (int p = 0; p < nPhases; p++) { double thisPhase = (consts[p].B0 * consts[p].TR * 2 * M_PI) + consts[p].phase; if (fabs(fmod(thisPhase - M_PI, 2 * M_PI)) < bestPhase) { bestPhase = fabs(fmod(thisPhase - M_PI, 2 * M_PI)); index = p; } } residual = classicDESPOT2(ssfpAngles, signals[index], consts[index].TR, T1, consts[index].B1, params[1], params[2]); params[0] = consts[index].B0; } else { // DESPOT2-FM DESPOT2FM tc(ssfpAngles, signals, consts, T1, false, fitB0); ArrayXd params(nP); residual = regionContraction<DESPOT2FM>(params, tc, loBounds, hiBounds); } } for (int p = 0; p < nP; p++) { paramsData[p][sliceOffset + vox] = params[p]; } residuals[sliceOffset + vox] = residual; }; apply_for(voxelsPerSlice, processVox); if (verbose) { clock_t loopEnd = clock(); if (voxCount > 0) cout << voxCount << " unmasked voxels, CPU time per voxel was " << ((loopEnd - loopStart) / ((float)voxCount * CLOCKS_PER_SEC)) << " s, "; cout << "finished." << endl; } } time_t procEnd = time(NULL); struct tm *localEnd = localtime(&procEnd); char theTime[512]; strftime(theTime, 512, "%H:%M:%S", localEnd); cout << "Finished processing at " << theTime << ". Run-time was " << difftime(procEnd, procStart) << " s." << endl; savedHeader.setDim(4, 1); savedHeader.setDatatype(NIFTI_TYPE_FLOAT32); for (int p = 0; p < nP; p++) { savedHeader.open(outPrefix + DESPOT2FM::names()[p] + ".nii.gz", NiftiImage::NIFTI_WRITE); savedHeader.writeVolume(0, paramsData[p]); savedHeader.close(); } savedHeader.open(outPrefix + "D2_Residual.nii.gz", NiftiImage::NIFTI_WRITE); savedHeader.writeVolume(0, residuals); savedHeader.close(); // Clean up memory for (int p = 0; p < nPhases; p++) free(ssfpData[p]); if (B0Data) free(B0Data); if (B1Data) free(B1Data); if (maskData) free(maskData); return EXIT_SUCCESS; } <commit_msg>Fixed other small stupid bugs in despot2.<commit_after>/* * despot1_main.cpp * * Created by Tobias Wood on 23/01/2012. * Copyright 2012 Tobias Wood. All rights reserved. * */ #include <time.h> #include <getopt.h> #include <iostream> #include <atomic> #include <Eigen/Dense> #include "NiftiImage.h" #include "DESPOT.h" #include "DESPOT_Functors.h" #include "RegionContraction.h" #define USE_PROCPAR #ifdef USE_PROCPAR #include "procpar.h" using namespace Recon; #endif using namespace std; using namespace Eigen; //****************************************************************************** // Arguments / Usage //****************************************************************************** const string credit { "despot2 - Written by tobias.wood@kcl.ac.uk, based on work by Sean Deoni. \n\ Acknowledgements greatfully received, grant discussions welcome." }; const string usage { "Usage is: despot2 [options] T1_map ssfp_files\n\ \ Options:\n\ --help, -h : Print this message.\n\ --mask, -m file : Mask input with specified file.\n\ --out, -o path : Add a prefix to the output filenames.\n\ --B0 file : B0 Map file.\n\ --B1 file : B1 Map file.\n\ --M0 file : Proton density file.\n\ --verbose, -v : Print slice processing times.\n\ --start_slice N : Start processing from slice N.\n\ --end_slice N : Finish processing at slice N.\n\ --tesla, -t 3 : Enables DESPOT-FM with boundaries suitable for 3T\n\ 7 : Boundaries suitable for 7T (default)\n\ u : User specified boundaries from stdin.\n" }; // tesla == 0 means NO DESPOT-FM static int tesla = 0, fitB0 = false, verbose = false, start_slice = -1, end_slice = -1; static string outPrefix; static struct option long_options[] = { {"B0", required_argument, 0, '0'}, {"B1", required_argument, 0, '1'}, {"M0", required_argument, 0, 'M'}, {"help", no_argument, 0, 'h'}, {"mask", required_argument, 0, 'm'}, {"tesla", required_argument, 0, 't'}, {"verbose", no_argument, 0, 'v'}, {"start_slice", required_argument, 0, 'S'}, {"end_slice", required_argument, 0, 'E'}, {0, 0, 0, 0} }; //****************************************************************************** // Main //****************************************************************************** int main(int argc, char **argv) { //************************************************************************** // Argument Processing //************************************************************************** cout << credit << endl; if (argc < 4) { cout << usage << endl; return EXIT_FAILURE; } Eigen::initParallel(); NiftiImage inFile, savedHeader; double *maskData = NULL, *B0Data = NULL, *B1Data = NULL, *T1Data = NULL, *M0Data = NULL; string procPath; int indexptr = 0, c; while ((c = getopt_long(argc, argv, "hm:o:vt:", long_options, &indexptr)) != -1) { switch (c) { case 'o': outPrefix = optarg; cout << "Output prefix will be: " << outPrefix << endl; break; case 'm': cout << "Reading mask file " << optarg << endl; inFile.open(optarg, 'r'); maskData = inFile.readVolume<double>(0); inFile.close(); break; case '0': cout << "Reading B0 file: " << optarg << endl; inFile.open(optarg, 'r'); B0Data = inFile.readVolume<double>(0); inFile.close(); break; case '1': cout << "Reading B1 file: " << optarg << endl; inFile.open(optarg, 'r'); B1Data = inFile.readVolume<double>(0); inFile.close(); break; case 'M': cout << "Reading M0 file " << optarg; inFile.open(optarg, 'r'); M0Data = inFile.readVolume<double>(0); inFile.close(); break; case 't': switch (*optarg) { case '3': tesla = 3; break; case '7': tesla = 7; break; case 'u': tesla = -1; break; default: cout << "Unknown boundaries type " << optarg << endl; abort(); break; } cout << "Using " << tesla << "T boundaries." << endl; break; case 'v': verbose = true; break; case 'S': start_slice = atoi(optarg); break; case 'E': end_slice = atoi(optarg); break; case 0: // Just a flag break; case '?': // getopt will print an error message case 'h': cout << usage << endl; return EXIT_FAILURE; } } if ((tesla != 0) && !B0Data) fitB0 = true; cout << "Reading T1 Map from: " << argv[optind] << endl; inFile.open(argv[optind++], 'r'); T1Data = inFile.readVolume<double>(0); inFile.close(); savedHeader = inFile; //************************************************************************** // Gather SSFP Data //************************************************************************** int nFlip, nPhases; nPhases = argc - optind; vector<DESPOTConstants> consts(nPhases); VectorXd ssfpAngles; int voxelsPerSlice, voxelsPerVolume; double **ssfpData = (double **)malloc(nPhases * sizeof(double *)); for (size_t p = 0; p < nPhases; p++) { cout << "Reading SSFP header from " << argv[optind] << endl; inFile.open(argv[optind], 'r'); if (p == 0) { // Read nFlip, TR and flip angles from first file nFlip = inFile.dim(4); voxelsPerSlice = inFile.voxelsPerSlice(); voxelsPerVolume = inFile.voxelsPerVolume(); ssfpAngles.resize(nFlip, 1); #ifdef USE_PROCPAR ParameterList pars; if (ReadProcpar(inFile.basename() + ".procpar", pars)) { consts[0].TR = RealValue(pars, "tr"); for (int i = 0; i < nFlip; i++) ssfpAngles[i] = RealValue(pars, "flip1", i); } else #endif { cout << "Enter SSFP TR (s): " << flush; cin >> consts[0].TR; cout << "Enter " << nFlip << " flip angles (degrees): " << flush; for (int i = 0; i < ssfpAngles.size(); i++) cin >> ssfpAngles[i]; } } else { consts[p].TR = consts[0].TR; } #ifdef USE_PROCPAR ParameterList pars; if (ReadProcpar(inFile.basename() + ".procpar", pars)) { consts[p].phase = RealValue(pars, "rfphase") * M_PI / 180.; } else #endif { cout << "Enter phase-cycling (degrees): " << flush; cin >> consts[p].phase; consts[p].phase *= M_PI / 180.; } cout << "Reading SSFP data..." << endl; ssfpData[p] = inFile.readAllVolumes<double>(); // Don't close the first header because we've saved it to write the // results, and FSLIO gets fussy about cloning closed headers inFile.close(); optind++; } ssfpAngles *= M_PI / 180.; if (optind != argc) { cerr << "Unprocessed arguments supplied.\n" << usage; exit(EXIT_FAILURE); } // Set up boundaries for DESPOT-FM if needed ArrayXd loBounds, hiBounds; const long nP = DESPOT2FM::inputs(); if (tesla != 0) { if (tesla > 0) { loBounds = DESPOT2FM::defaultLo(tesla); hiBounds = DESPOT2FM::defaultHi(tesla); } else if (tesla < 0) { cout << "Enter " << nP << " parameter pairs (low then high): " << flush; for (int i = 0; i < nP; i++) cin >> loBounds[i] >> hiBounds[i]; } // If fitting, give a suitable range and allocate results memory if (fitB0) { loBounds[0] = -0.5 / consts[0].TR; hiBounds[0] = 0.5 / consts[0].TR; B0Data = new double[voxelsPerVolume]; } else { // Otherwise fix and let functors pick up the specified value loBounds[0] = 0.; hiBounds[0] = 0.; } } if (verbose) { cout << "SSFP Angles (deg): " << ssfpAngles.transpose() * 180 / M_PI << endl; if (tesla != 0) cout << "Low bounds: " << loBounds.transpose() << endl << "Hi bounds: " << hiBounds.transpose() << endl; } //************************************************************************** // Set up results data //************************************************************************** vector<double *> paramsData(nP); for (int p = 0; p < nP; p++) paramsData[p] = new double[voxelsPerVolume]; double *residuals = new double[voxelsPerVolume]; //************************************************************************** // Do the fitting //************************************************************************** time_t procStart = time(NULL); if ((start_slice < 0) || (start_slice >= inFile.dim(3))) start_slice = 0; if ((end_slice < 0) || (end_slice > inFile.dim(3))) end_slice = inFile.dim(3); for (int slice = start_slice; slice < end_slice; slice++) { // Read in data if (verbose) cout << "Starting slice " << slice << "..." << flush; atomic<int> voxCount{0}; const int sliceOffset = slice * voxelsPerSlice; clock_t loopStart = clock(); function<void (const int&)> processVox = [&] (const int &vox) { // Set up parameters and constants double residual = 0., T1 = 0.; ArrayXd params(nP); params.setZero(); if (!maskData || ((maskData[sliceOffset + vox] > 0.) && (T1Data[sliceOffset + vox] > 0.))) { // Zero T1 causes zero-pivot error. voxCount++; T1 = T1Data[sliceOffset + vox]; // Gather signals. vector<VectorXd> signals; for (int p = 0; p < nPhases; p++) { if (B0Data) consts[p].B0 = B0Data[sliceOffset + vox]; if (B1Data) consts[p].B1 = B1Data[sliceOffset + vox]; VectorXd temp(nFlip); for (int i = 0; i < nFlip; i++) temp(i) = ssfpData[p][i*voxelsPerVolume + sliceOffset + vox]; signals.push_back(temp); } if (tesla == 0) { // Choose phase with accumulated phase closest to 180 and then classic DESPOT2 int index = 0; double bestPhase = DBL_MAX; for (int p = 0; p < nPhases; p++) { double thisPhase = (consts[p].B0 * consts[p].TR * 2 * M_PI) + consts[p].phase; if (fabs(fmod(thisPhase - M_PI, 2 * M_PI)) < bestPhase) { bestPhase = fabs(fmod(thisPhase - M_PI, 2 * M_PI)); index = p; } } residual = classicDESPOT2(ssfpAngles, signals[index], consts[index].TR, T1, consts[index].B1, params[0], params[1]); } else { // DESPOT2-FM DESPOT2FM tc(ssfpAngles, signals, consts, T1, false, fitB0); ArrayXd params(nP); residual = regionContraction<DESPOT2FM>(params, tc, loBounds, hiBounds); } } for (int p = 0; p < nP; p++) { paramsData[p][sliceOffset + vox] = params[p]; } residuals[sliceOffset + vox] = residual; }; apply_for(voxelsPerSlice, processVox, 1); if (verbose) { clock_t loopEnd = clock(); if (voxCount > 0) cout << voxCount << " unmasked voxels, CPU time per voxel was " << ((loopEnd - loopStart) / ((float)voxCount * CLOCKS_PER_SEC)) << " s, "; cout << "finished." << endl; } } time_t procEnd = time(NULL); struct tm *localEnd = localtime(&procEnd); char theTime[512]; strftime(theTime, 512, "%H:%M:%S", localEnd); cout << "Finished processing at " << theTime << ". Run-time was " << difftime(procEnd, procStart) << " s." << endl; savedHeader.setDim(4, 1); savedHeader.setDatatype(NIFTI_TYPE_FLOAT32); if (tesla == 0) { const vector<const string> classic_names { "D2_PD", "D2_T2" }; for (int p = 0; p < 2; p++) { savedHeader.open(outPrefix + classic_names[p] + ".nii.gz", NiftiImage::NIFTI_WRITE); savedHeader.writeVolume(0, paramsData[p]); savedHeader.close(); } savedHeader.open(outPrefix + "D2_Residual.nii.gz", NiftiImage::NIFTI_WRITE); savedHeader.writeVolume(0, residuals); savedHeader.close(); } else { for (int p = 0; p < nP; p++) { savedHeader.open(outPrefix + DESPOT2FM::names()[p] + ".nii.gz", NiftiImage::NIFTI_WRITE); savedHeader.writeVolume(0, residuals); savedHeader.close(); } savedHeader.open(outPrefix + "FM_Residual.nii.gz", NiftiImage::NIFTI_WRITE); savedHeader.writeVolume(0, residuals); savedHeader.close(); } // Clean up memory for (int p = 0; p < nPhases; p++) free(ssfpData[p]); if (B0Data) free(B0Data); if (B1Data) free(B1Data); if (maskData) free(maskData); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/spdy/core/spdy_header_block.h" #include <memory> #include <utility> #include "net/third_party/quiche/src/spdy/core/spdy_test_utils.h" #include "net/third_party/quiche/src/spdy/platform/api/spdy_test.h" using ::testing::ElementsAre; namespace spdy { namespace test { class ValueProxyPeer { public: static SpdyStringPiece key(SpdyHeaderBlock::ValueProxy* p) { return p->key_; } }; std::pair<SpdyStringPiece, SpdyStringPiece> Pair(SpdyStringPiece k, SpdyStringPiece v) { return std::make_pair(k, v); } // This test verifies that SpdyHeaderBlock behaves correctly when empty. TEST(SpdyHeaderBlockTest, EmptyBlock) { SpdyHeaderBlock block; EXPECT_TRUE(block.empty()); EXPECT_EQ(0u, block.size()); EXPECT_EQ(block.end(), block.find("foo")); EXPECT_TRUE(block.end() == block.begin()); // Should have no effect. block.erase("bar"); } TEST(SpdyHeaderBlockTest, KeyMemoryReclaimedOnLookup) { SpdyHeaderBlock block; SpdyStringPiece copied_key1; { auto proxy1 = block["some key name"]; copied_key1 = ValueProxyPeer::key(&proxy1); } SpdyStringPiece copied_key2; { auto proxy2 = block["some other key name"]; copied_key2 = ValueProxyPeer::key(&proxy2); } // Because proxy1 was never used to modify the block, the memory used for the // key could be reclaimed and used for the second call to operator[]. // Therefore, we expect the pointers of the two SpdyStringPieces to be equal. EXPECT_EQ(copied_key1.data(), copied_key2.data()); { auto proxy1 = block["some key name"]; block["some other key name"] = "some value"; } // Nothing should blow up when proxy1 is destructed, and we should be able to // modify and access the SpdyHeaderBlock. block["key"] = "value"; EXPECT_EQ("value", block["key"]); EXPECT_EQ("some value", block["some other key name"]); EXPECT_TRUE(block.find("some key name") == block.end()); } // This test verifies that headers can be set in a variety of ways. TEST(SpdyHeaderBlockTest, AddHeaders) { SpdyHeaderBlock block; block["foo"] = std::string(300, 'x'); block["bar"] = "baz"; block["qux"] = "qux1"; block["qux"] = "qux2"; block.insert(std::make_pair("key", "value")); EXPECT_EQ(Pair("foo", std::string(300, 'x')), *block.find("foo")); EXPECT_EQ("baz", block["bar"]); std::string qux("qux"); EXPECT_EQ("qux2", block[qux]); ASSERT_NE(block.end(), block.find("key")); EXPECT_EQ(Pair("key", "value"), *block.find("key")); block.erase("key"); EXPECT_EQ(block.end(), block.find("key")); } // This test verifies that SpdyHeaderBlock can be copied using Clone(). TEST(SpdyHeaderBlockTest, CopyBlocks) { SpdyHeaderBlock block1; block1["foo"] = std::string(300, 'x'); block1["bar"] = "baz"; block1.insert(std::make_pair("qux", "qux1")); SpdyHeaderBlock block2 = block1.Clone(); SpdyHeaderBlock block3(block1.Clone()); EXPECT_EQ(block1, block2); EXPECT_EQ(block1, block3); } TEST(SpdyHeaderBlockTest, Equality) { // Test equality and inequality operators. SpdyHeaderBlock block1; block1["foo"] = "bar"; SpdyHeaderBlock block2; block2["foo"] = "bar"; SpdyHeaderBlock block3; block3["baz"] = "qux"; EXPECT_EQ(block1, block2); EXPECT_NE(block1, block3); block2["baz"] = "qux"; EXPECT_NE(block1, block2); } // Test that certain methods do not crash on moved-from instances. TEST(SpdyHeaderBlockTest, MovedFromIsValid) { SpdyHeaderBlock block1; block1["foo"] = "bar"; SpdyHeaderBlock block2(std::move(block1)); EXPECT_THAT(block2, ElementsAre(Pair("foo", "bar"))); block1["baz"] = "qux"; // NOLINT testing post-move behavior SpdyHeaderBlock block3(std::move(block1)); block1["foo"] = "bar"; // NOLINT testing post-move behavior SpdyHeaderBlock block4(std::move(block1)); block1.clear(); // NOLINT testing post-move behavior EXPECT_TRUE(block1.empty()); block1["foo"] = "bar"; EXPECT_THAT(block1, ElementsAre(Pair("foo", "bar"))); } // This test verifies that headers can be appended to no matter how they were // added originally. TEST(SpdyHeaderBlockTest, AppendHeaders) { SpdyHeaderBlock block; block["foo"] = "foo"; block.AppendValueOrAddHeader("foo", "bar"); EXPECT_EQ(Pair("foo", std::string("foo\0bar", 7)), *block.find("foo")); block.insert(std::make_pair("foo", "baz")); EXPECT_EQ("baz", block["foo"]); EXPECT_EQ(Pair("foo", "baz"), *block.find("foo")); // Try all four methods of adding an entry. block["cookie"] = "key1=value1"; block.AppendValueOrAddHeader("h1", "h1v1"); block.insert(std::make_pair("h2", "h2v1")); block.AppendValueOrAddHeader("h3", "h3v2"); block.AppendValueOrAddHeader("h2", "h2v2"); block.AppendValueOrAddHeader("h1", "h1v2"); block.AppendValueOrAddHeader("cookie", "key2=value2"); block.AppendValueOrAddHeader("cookie", "key3=value3"); block.AppendValueOrAddHeader("h1", "h1v3"); block.AppendValueOrAddHeader("h2", "h2v3"); block.AppendValueOrAddHeader("h3", "h3v3"); block.AppendValueOrAddHeader("h4", "singleton"); EXPECT_EQ("key1=value1; key2=value2; key3=value3", block["cookie"]); EXPECT_EQ("baz", block["foo"]); EXPECT_EQ(std::string("h1v1\0h1v2\0h1v3", 14), block["h1"]); EXPECT_EQ(std::string("h2v1\0h2v2\0h2v3", 14), block["h2"]); EXPECT_EQ(std::string("h3v2\0h3v3", 9), block["h3"]); EXPECT_EQ("singleton", block["h4"]); } TEST(JoinTest, JoinEmpty) { std::vector<SpdyStringPiece> empty; SpdyStringPiece separator = ", "; char buf[10] = ""; size_t written = Join(buf, empty, separator); EXPECT_EQ(0u, written); } TEST(JoinTest, JoinOne) { std::vector<SpdyStringPiece> v = {"one"}; SpdyStringPiece separator = ", "; char buf[15]; size_t written = Join(buf, v, separator); EXPECT_EQ(3u, written); EXPECT_EQ("one", SpdyStringPiece(buf, written)); } TEST(JoinTest, JoinMultiple) { std::vector<SpdyStringPiece> v = {"one", "two", "three"}; SpdyStringPiece separator = ", "; char buf[15]; size_t written = Join(buf, v, separator); EXPECT_EQ(15u, written); EXPECT_EQ("one, two, three", SpdyStringPiece(buf, written)); } namespace { size_t SpdyHeaderBlockSize(const SpdyHeaderBlock& block) { size_t size = 0; for (const auto& pair : block) { size += pair.first.size() + pair.second.size(); } return size; } } // namespace // Tests SpdyHeaderBlock SizeEstimate(). TEST(SpdyHeaderBlockTest, TotalBytesUsed) { SpdyHeaderBlock block; const size_t value_size = 300; block["foo"] = std::string(value_size, 'x'); EXPECT_EQ(block.TotalBytesUsed(), SpdyHeaderBlockSize(block)); block.insert(std::make_pair("key", std::string(value_size, 'x'))); EXPECT_EQ(block.TotalBytesUsed(), SpdyHeaderBlockSize(block)); block.AppendValueOrAddHeader("abc", std::string(value_size, 'x')); EXPECT_EQ(block.TotalBytesUsed(), SpdyHeaderBlockSize(block)); // Replace value for existing key. block["foo"] = std::string(value_size, 'x'); EXPECT_EQ(block.TotalBytesUsed(), SpdyHeaderBlockSize(block)); block.insert(std::make_pair("key", std::string(value_size, 'x'))); EXPECT_EQ(block.TotalBytesUsed(), SpdyHeaderBlockSize(block)); // Add value for existing key. block.AppendValueOrAddHeader("abc", std::string(value_size, 'x')); EXPECT_EQ(block.TotalBytesUsed(), SpdyHeaderBlockSize(block)); // Copies/clones SpdyHeaderBlock. size_t block_size = block.TotalBytesUsed(); SpdyHeaderBlock block_copy = std::move(block); EXPECT_EQ(block_size, block_copy.TotalBytesUsed()); // Erases key. block_copy.erase("foo"); EXPECT_EQ(block_copy.TotalBytesUsed(), SpdyHeaderBlockSize(block_copy)); block_copy.erase("key"); EXPECT_EQ(block_copy.TotalBytesUsed(), SpdyHeaderBlockSize(block_copy)); block_copy.erase("abc"); EXPECT_EQ(block_copy.TotalBytesUsed(), SpdyHeaderBlockSize(block_copy)); } } // namespace test } // namespace spdy <commit_msg>Adds a unit test demonstrating that SpdyHeaderBlock can store header names containing uppercase characters.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/spdy/core/spdy_header_block.h" #include <memory> #include <utility> #include "net/third_party/quiche/src/spdy/core/spdy_test_utils.h" #include "net/third_party/quiche/src/spdy/platform/api/spdy_test.h" using ::testing::ElementsAre; namespace spdy { namespace test { class ValueProxyPeer { public: static SpdyStringPiece key(SpdyHeaderBlock::ValueProxy* p) { return p->key_; } }; std::pair<SpdyStringPiece, SpdyStringPiece> Pair(SpdyStringPiece k, SpdyStringPiece v) { return std::make_pair(k, v); } // This test verifies that SpdyHeaderBlock behaves correctly when empty. TEST(SpdyHeaderBlockTest, EmptyBlock) { SpdyHeaderBlock block; EXPECT_TRUE(block.empty()); EXPECT_EQ(0u, block.size()); EXPECT_EQ(block.end(), block.find("foo")); EXPECT_TRUE(block.end() == block.begin()); // Should have no effect. block.erase("bar"); } TEST(SpdyHeaderBlockTest, KeyMemoryReclaimedOnLookup) { SpdyHeaderBlock block; SpdyStringPiece copied_key1; { auto proxy1 = block["some key name"]; copied_key1 = ValueProxyPeer::key(&proxy1); } SpdyStringPiece copied_key2; { auto proxy2 = block["some other key name"]; copied_key2 = ValueProxyPeer::key(&proxy2); } // Because proxy1 was never used to modify the block, the memory used for the // key could be reclaimed and used for the second call to operator[]. // Therefore, we expect the pointers of the two SpdyStringPieces to be equal. EXPECT_EQ(copied_key1.data(), copied_key2.data()); { auto proxy1 = block["some key name"]; block["some other key name"] = "some value"; } // Nothing should blow up when proxy1 is destructed, and we should be able to // modify and access the SpdyHeaderBlock. block["key"] = "value"; EXPECT_EQ("value", block["key"]); EXPECT_EQ("some value", block["some other key name"]); EXPECT_TRUE(block.find("some key name") == block.end()); } // This test verifies that headers can be set in a variety of ways. TEST(SpdyHeaderBlockTest, AddHeaders) { SpdyHeaderBlock block; block["foo"] = std::string(300, 'x'); block["bar"] = "baz"; block["qux"] = "qux1"; block["qux"] = "qux2"; block.insert(std::make_pair("key", "value")); EXPECT_EQ(Pair("foo", std::string(300, 'x')), *block.find("foo")); EXPECT_EQ("baz", block["bar"]); std::string qux("qux"); EXPECT_EQ("qux2", block[qux]); ASSERT_NE(block.end(), block.find("key")); EXPECT_EQ(Pair("key", "value"), *block.find("key")); block.erase("key"); EXPECT_EQ(block.end(), block.find("key")); } // This test verifies that SpdyHeaderBlock can be copied using Clone(). TEST(SpdyHeaderBlockTest, CopyBlocks) { SpdyHeaderBlock block1; block1["foo"] = std::string(300, 'x'); block1["bar"] = "baz"; block1.insert(std::make_pair("qux", "qux1")); SpdyHeaderBlock block2 = block1.Clone(); SpdyHeaderBlock block3(block1.Clone()); EXPECT_EQ(block1, block2); EXPECT_EQ(block1, block3); } TEST(SpdyHeaderBlockTest, Equality) { // Test equality and inequality operators. SpdyHeaderBlock block1; block1["foo"] = "bar"; SpdyHeaderBlock block2; block2["foo"] = "bar"; SpdyHeaderBlock block3; block3["baz"] = "qux"; EXPECT_EQ(block1, block2); EXPECT_NE(block1, block3); block2["baz"] = "qux"; EXPECT_NE(block1, block2); } // Test that certain methods do not crash on moved-from instances. TEST(SpdyHeaderBlockTest, MovedFromIsValid) { SpdyHeaderBlock block1; block1["foo"] = "bar"; SpdyHeaderBlock block2(std::move(block1)); EXPECT_THAT(block2, ElementsAre(Pair("foo", "bar"))); block1["baz"] = "qux"; // NOLINT testing post-move behavior SpdyHeaderBlock block3(std::move(block1)); block1["foo"] = "bar"; // NOLINT testing post-move behavior SpdyHeaderBlock block4(std::move(block1)); block1.clear(); // NOLINT testing post-move behavior EXPECT_TRUE(block1.empty()); block1["foo"] = "bar"; EXPECT_THAT(block1, ElementsAre(Pair("foo", "bar"))); } // This test verifies that headers can be appended to no matter how they were // added originally. TEST(SpdyHeaderBlockTest, AppendHeaders) { SpdyHeaderBlock block; block["foo"] = "foo"; block.AppendValueOrAddHeader("foo", "bar"); EXPECT_EQ(Pair("foo", std::string("foo\0bar", 7)), *block.find("foo")); block.insert(std::make_pair("foo", "baz")); EXPECT_EQ("baz", block["foo"]); EXPECT_EQ(Pair("foo", "baz"), *block.find("foo")); // Try all four methods of adding an entry. block["cookie"] = "key1=value1"; block.AppendValueOrAddHeader("h1", "h1v1"); block.insert(std::make_pair("h2", "h2v1")); block.AppendValueOrAddHeader("h3", "h3v2"); block.AppendValueOrAddHeader("h2", "h2v2"); block.AppendValueOrAddHeader("h1", "h1v2"); block.AppendValueOrAddHeader("cookie", "key2=value2"); block.AppendValueOrAddHeader("cookie", "key3=value3"); block.AppendValueOrAddHeader("h1", "h1v3"); block.AppendValueOrAddHeader("h2", "h2v3"); block.AppendValueOrAddHeader("h3", "h3v3"); block.AppendValueOrAddHeader("h4", "singleton"); EXPECT_EQ("key1=value1; key2=value2; key3=value3", block["cookie"]); EXPECT_EQ("baz", block["foo"]); EXPECT_EQ(std::string("h1v1\0h1v2\0h1v3", 14), block["h1"]); EXPECT_EQ(std::string("h2v1\0h2v2\0h2v3", 14), block["h2"]); EXPECT_EQ(std::string("h3v2\0h3v3", 9), block["h3"]); EXPECT_EQ("singleton", block["h4"]); } // This test demonstrates that the SpdyHeaderBlock data structure does not place // any limitations on the characters present in the header names. TEST(SpdyHeaderBlockTest, UpperCaseNames) { SpdyHeaderBlock block; block["Foo"] = "foo"; block.AppendValueOrAddHeader("Foo", "bar"); EXPECT_EQ(block.end(), block.find("foo")); EXPECT_EQ(Pair("Foo", std::string("foo\0bar", 7)), *block.find("Foo")); // The map is case sensitive, so both "Foo" and "foo" can be present. block.AppendValueOrAddHeader("foo", "baz"); EXPECT_THAT(block, ElementsAre(Pair("Foo", std::string("foo\0bar", 7)), Pair("foo", "baz"))); } TEST(JoinTest, JoinEmpty) { std::vector<SpdyStringPiece> empty; SpdyStringPiece separator = ", "; char buf[10] = ""; size_t written = Join(buf, empty, separator); EXPECT_EQ(0u, written); } TEST(JoinTest, JoinOne) { std::vector<SpdyStringPiece> v = {"one"}; SpdyStringPiece separator = ", "; char buf[15]; size_t written = Join(buf, v, separator); EXPECT_EQ(3u, written); EXPECT_EQ("one", SpdyStringPiece(buf, written)); } TEST(JoinTest, JoinMultiple) { std::vector<SpdyStringPiece> v = {"one", "two", "three"}; SpdyStringPiece separator = ", "; char buf[15]; size_t written = Join(buf, v, separator); EXPECT_EQ(15u, written); EXPECT_EQ("one, two, three", SpdyStringPiece(buf, written)); } namespace { size_t SpdyHeaderBlockSize(const SpdyHeaderBlock& block) { size_t size = 0; for (const auto& pair : block) { size += pair.first.size() + pair.second.size(); } return size; } } // namespace // Tests SpdyHeaderBlock SizeEstimate(). TEST(SpdyHeaderBlockTest, TotalBytesUsed) { SpdyHeaderBlock block; const size_t value_size = 300; block["foo"] = std::string(value_size, 'x'); EXPECT_EQ(block.TotalBytesUsed(), SpdyHeaderBlockSize(block)); block.insert(std::make_pair("key", std::string(value_size, 'x'))); EXPECT_EQ(block.TotalBytesUsed(), SpdyHeaderBlockSize(block)); block.AppendValueOrAddHeader("abc", std::string(value_size, 'x')); EXPECT_EQ(block.TotalBytesUsed(), SpdyHeaderBlockSize(block)); // Replace value for existing key. block["foo"] = std::string(value_size, 'x'); EXPECT_EQ(block.TotalBytesUsed(), SpdyHeaderBlockSize(block)); block.insert(std::make_pair("key", std::string(value_size, 'x'))); EXPECT_EQ(block.TotalBytesUsed(), SpdyHeaderBlockSize(block)); // Add value for existing key. block.AppendValueOrAddHeader("abc", std::string(value_size, 'x')); EXPECT_EQ(block.TotalBytesUsed(), SpdyHeaderBlockSize(block)); // Copies/clones SpdyHeaderBlock. size_t block_size = block.TotalBytesUsed(); SpdyHeaderBlock block_copy = std::move(block); EXPECT_EQ(block_size, block_copy.TotalBytesUsed()); // Erases key. block_copy.erase("foo"); EXPECT_EQ(block_copy.TotalBytesUsed(), SpdyHeaderBlockSize(block_copy)); block_copy.erase("key"); EXPECT_EQ(block_copy.TotalBytesUsed(), SpdyHeaderBlockSize(block_copy)); block_copy.erase("abc"); EXPECT_EQ(block_copy.TotalBytesUsed(), SpdyHeaderBlockSize(block_copy)); } } // namespace test } // namespace spdy <|endoftext|>
<commit_before>#include "Player.h" #include "SDL.h" #include "InputHandler.h" Player::Player(const LoaderParams* pParams) : SDLGameObject(pParams) { } void Player::draw() { SDLGameObject::draw(); //we now use SDLGameObject } void Player::update() { m_velocity.setX(0); m_velocity.setY(0); m_acceleration.setX(0); m_acceleration.setY(0); handleInput(); //adding our function m_currentFrame = int(((SDL_GetTicks() / 100) % 6)); SDLGameObject::update(); } void Player::clean() { //blank clean() function } void Player::handleInput() { if (TheInputHandler::Instance()->joysticksInitialised()) { //for analog sticks of the first joystick if ((TheInputHandler::Instance()->xvalue(0, 1) > 0) || (TheInputHandler::Instance()->xvalue(0, 1) < 0)) { //if we are moving the player with analog stick while pressing Y //it will get an acceleration of 2 in that direction m_velocity.setX((float)1 * TheInputHandler::Instance()->xvalue(0, 1)); if (TheInputHandler::Instance()->getButtonState(0, 3)) //Button 3(Yellow) { //give the player some acceleration m_acceleration.setX((float)2 * TheInputHandler::Instance()->xvalue(0, 1)); } } if ((TheInputHandler::Instance()->yvalue(0, 1) > 0) || (TheInputHandler::Instance()->yvalue(0, 1) < 0)) { m_velocity.setY((float)1 * TheInputHandler::Instance()->yvalue(0, 1)); if (TheInputHandler::Instance()->getButtonState(0, 3)) { m_acceleration.setY((float)2 * TheInputHandler::Instance()->yvalue(0,1)); } } if ((TheInputHandler::Instance()->xvalue(0, 2) > 0) || (TheInputHandler::Instance()->xvalue(0, 2) < 0)) { m_velocity.setX((float)1 * TheInputHandler::Instance()->xvalue(0, 2)); if (TheInputHandler::Instance()->getButtonState(0, 3)) { m_acceleration.setX((float)2 * TheInputHandler::Instance()->xvalue(0, 1)); } } if ((TheInputHandler::Instance()->yvalue(0, 2) > 0) || (TheInputHandler::Instance()->yvalue(0, 2) < 0)) { m_velocity.setY((float)1 * TheInputHandler::Instance()->yvalue(0, 2)); if (TheInputHandler::Instance()->getButtonState(0, 3)) { m_acceleration.setY((float)2 * TheInputHandler::Instance()->yvalue(0, 1)); } } /* Code as in the book //for buttons of the first joystick if (TheInputHandler::Instance()->getButtonState(0, 3)) //Button 3(Yellow) { //give the player some acceleration m_acceleration.setX(1); } */ } //check for mouse button input if (InputHandler::Instance()->getMouseButtonState(LEFT)) { m_acceleration.setX(-3); } if (InputHandler::Instance()->getMouseButtonState(RIGHT)) { m_acceleration.setX(3); } //check for mouse motion input //commenting this feature as I don't want player to follow mouse //uncomment the following code to enable the feature /* Vector2D vec = TheInputHandler::Instance()->getMousePosition(); m_velocity = (vec - m_position) / 100; */ //Adding keyboard controls //UP DOWN RIGHT LEFT for movement //Right Ctrl for Acceleration if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RIGHT)) { m_velocity.setX(2); //check if Right Ctrl is pressed, provide acc. if true if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RCTRL)) { m_acceleration.setX(2.5); } } if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_LEFT)) { m_velocity.setX(-2); //check if Right Ctrl is pressed, provide acc. if true if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RCTRL)) { m_acceleration.setX(-2.5); } } //remember the cartesian plane is inverted along Y Axis if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_UP)) { m_velocity.setY(-2); //check if Right Ctrl is pressed, provide acc. if true if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RCTRL)) { m_acceleration.setY(-2.5); } } if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_DOWN)) { m_velocity.setY(2); //check if Right Ctrl is pressed, provide acc. if true if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RCTRL)) { m_acceleration.setY(2.5); } } }<commit_msg>vec is now Vector2D * in Player<commit_after>#include "Player.h" #include "SDL.h" #include "InputHandler.h" Player::Player(const LoaderParams* pParams) : SDLGameObject(pParams) { } void Player::draw() { SDLGameObject::draw(); //we now use SDLGameObject } void Player::update() { m_velocity.setX(0); m_velocity.setY(0); m_acceleration.setX(0); m_acceleration.setY(0); handleInput(); //adding our function m_currentFrame = int(((SDL_GetTicks() / 100) % 6)); SDLGameObject::update(); } void Player::clean() { //blank clean() function } void Player::handleInput() { if (TheInputHandler::Instance()->joysticksInitialised()) { //for analog sticks of the first joystick if ((TheInputHandler::Instance()->xvalue(0, 1) > 0) || (TheInputHandler::Instance()->xvalue(0, 1) < 0)) { //if we are moving the player with analog stick while pressing Y //it will get an acceleration of 2 in that direction m_velocity.setX((float)1 * TheInputHandler::Instance()->xvalue(0, 1)); if (TheInputHandler::Instance()->getButtonState(0, 3)) //Button 3(Yellow) { //give the player some acceleration m_acceleration.setX((float)2 * TheInputHandler::Instance()->xvalue(0, 1)); } } if ((TheInputHandler::Instance()->yvalue(0, 1) > 0) || (TheInputHandler::Instance()->yvalue(0, 1) < 0)) { m_velocity.setY((float)1 * TheInputHandler::Instance()->yvalue(0, 1)); if (TheInputHandler::Instance()->getButtonState(0, 3)) { m_acceleration.setY((float)2 * TheInputHandler::Instance()->yvalue(0,1)); } } if ((TheInputHandler::Instance()->xvalue(0, 2) > 0) || (TheInputHandler::Instance()->xvalue(0, 2) < 0)) { m_velocity.setX((float)1 * TheInputHandler::Instance()->xvalue(0, 2)); if (TheInputHandler::Instance()->getButtonState(0, 3)) { m_acceleration.setX((float)2 * TheInputHandler::Instance()->xvalue(0, 1)); } } if ((TheInputHandler::Instance()->yvalue(0, 2) > 0) || (TheInputHandler::Instance()->yvalue(0, 2) < 0)) { m_velocity.setY((float)1 * TheInputHandler::Instance()->yvalue(0, 2)); if (TheInputHandler::Instance()->getButtonState(0, 3)) { m_acceleration.setY((float)2 * TheInputHandler::Instance()->yvalue(0, 1)); } } /* Code as in the book //for buttons of the first joystick if (TheInputHandler::Instance()->getButtonState(0, 3)) //Button 3(Yellow) { //give the player some acceleration m_acceleration.setX(1); } */ } //check for mouse button input if (InputHandler::Instance()->getMouseButtonState(LEFT)) { m_acceleration.setX(-3); } if (InputHandler::Instance()->getMouseButtonState(RIGHT)) { m_acceleration.setX(3); } //check for mouse motion input //commenting this feature as I don't want player to follow mouse //uncomment the following code to enable the featurezx /* Vector2D* vec; vec = new Vector2D(0, 0); vec = TheInputHandler::Instance()->getMousePosition(); m_velocity = (*vec - m_position) / 100; */ //Adding keyboard controls //UP DOWN RIGHT LEFT for movement //Right Ctrl for Acceleration if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RIGHT)) { m_velocity.setX(2); //check if Right Ctrl is pressed, provide acc. if true if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RCTRL)) { m_acceleration.setX(2.5); } } if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_LEFT)) { m_velocity.setX(-2); //check if Right Ctrl is pressed, provide acc. if true if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RCTRL)) { m_acceleration.setX(-2.5); } } //remember the cartesian plane is inverted along Y Axis if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_UP)) { m_velocity.setY(-2); //check if Right Ctrl is pressed, provide acc. if true if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RCTRL)) { m_acceleration.setY(-2.5); } } if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_DOWN)) { m_velocity.setY(2); //check if Right Ctrl is pressed, provide acc. if true if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RCTRL)) { m_acceleration.setY(2.5); } } }<|endoftext|>
<commit_before>#include <zombye/rendering/texture.hpp> namespace zombye { texture::texture(const gli::texture2D& texture) noexcept : width_{texture[0].dimensions().x}, height_{texture[0].dimensions().y} { glGenTextures(1, &id_); glBindTexture(GL_TEXTURE_2D, id_); // adapted from http://www.g-truc.net/project-0024.html glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, GLint(texture.levels() - 1)); if (gli::is_compressed(texture.format())) { for (gli::texture2D::size_type level = 0; level < texture.levels(); ++level) { glCompressedTexImage2D(GL_TEXTURE_2D, GLint(level), GLenum{gli::internal_format(texture.format())}, GLsizei(texture[level].dimensions().x), GLsizei(texture[level].dimensions().y), 0, GLsizei(texture[level].size()), texture[level].data()); } } else { for (gli::texture2D::size_type level = 0; level < texture.levels(); ++level) { glTexImage2D(GL_TEXTURE_2D, GLint(level), GLenum(gli::internal_format(texture.format())), GLsizei(texture[level].dimensions().x), GLsizei(texture[level].dimensions().y), 0, GLenum(gli::external_format(texture.format())), GLenum(gli::type_format(texture.format())), texture[level].data()); } } } texture::~texture() { glDeleteTextures(1, &id_); } void texture::bind(uint32_t unit) const noexcept { glActiveTexture(GL_TEXTURE0 + unit); glBindTexture(GL_TEXTURE_2D, id_); } }<commit_msg>add trilinear mip map interpolation<commit_after>#include <zombye/rendering/texture.hpp> namespace zombye { texture::texture(const gli::texture2D& texture) noexcept : width_{texture.dimensions().x}, height_{texture.dimensions().y} { glGenTextures(1, &id_); glBindTexture(GL_TEXTURE_2D, id_); // adapted from http://www.g-truc.net/project-0024.html glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, GLint(texture.levels() - 1)); if (gli::is_compressed(texture.format())) { for (gli::texture2D::size_type level = 0; level < texture.levels(); ++level) { glCompressedTexImage2D(GL_TEXTURE_2D, GLint(level), GLenum{gli::internal_format(texture.format())}, GLsizei(texture[level].dimensions().x), GLsizei(texture[level].dimensions().y), 0, GLsizei(texture[level].size()), texture[level].data()); } } else { for (gli::texture2D::size_type level = 0; level < texture.levels(); ++level) { glTexImage2D(GL_TEXTURE_2D, GLint(level), GLenum(gli::internal_format(texture.format())), GLsizei(texture[level].dimensions().x), GLsizei(texture[level].dimensions().y), 0, GLenum(gli::external_format(texture.format())), GLenum(gli::type_format(texture.format())), texture[level].data()); } } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } texture::~texture() { glDeleteTextures(1, &id_); } void texture::bind(uint32_t unit) const noexcept { glActiveTexture(GL_TEXTURE0 + unit); glBindTexture(GL_TEXTURE_2D, id_); } }<|endoftext|>
<commit_before>// $Id: mesh_data_unv_support.C,v 1.3 2003-05-22 09:39:58 spetersen Exp $ // The Next Great Finite Element Library. // Copyright (C) 2002 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <fstream> #include <stdio.h> // Local includes #include "mesh_data.h" #include "mesh_base.h" //------------------------------------------------------ // MeshData UNV support functions void MeshData::read_unv(const std::string& name) { /* * When reading data, make sure the id maps are ok */ assert (_node_id_map_closed); assert (_elem_id_map_closed); /** * clear the data, but keep the id maps */ this->clear(); std::ifstream in_file (name.c_str()); if ( !in_file.good() ) { std::cerr << "ERROR: Input file not good." << std::endl; error(); } const std::string _label_dataset_mesh_data = "2414"; /** * locate the beginning of data set * and read it. */ { std::string olds, news; while (true) { in_file >> olds >> news; /* * a "-1" followed by a number means the beginning of a dataset * stop combing at the end of the file */ while( ((olds != "-1") || (news == "-1") ) && !in_file.eof() ) { olds = news; in_file >> news; } if(in_file.eof()) break; /* * if beginning of dataset, buffer it in * temp_buffer, if desired */ if (news == _label_dataset_mesh_data) { /** * Now read the data of interest. */ /** * Ignore the first lines that stand for * analysis dataset label and name. */ for(unsigned int i=0; i<3; i++) in_file.ignore(256,'\n'); unsigned int Dataset_location; unsigned int Model_type, Analysis_type, Data_characteristic, Result_type, Data_type, NVALDC; Real dummy_Real; /** * Read the dataset location, where * 1: Data at nodes * 2: Data on elements * other sets are currently not supported. */ in_file >> Dataset_location; if (Dataset_location != 1) { std::cerr << "ERROR: Currently only Data at nodes is supported." << std::endl; error(); } /** * Ignore five ID lines. */ for(unsigned int i=0; i<6; i++) in_file.ignore(256,'\n'); /** * Read record 9. */ in_file >> Model_type // not supported yet >> Analysis_type // not supported yet >> Data_characteristic // not supported yet >> Result_type // not supported yet >> Data_type >> NVALDC; /** * Ignore record 10 and 11 * (Integer analysis type specific data). */ for (unsigned int i=0; i<3; i++) in_file.ignore(256,'\n'); /** * Ignore record 12 and record 13. */ for (unsigned int i=0; i<12; i++) in_file >> dummy_Real; /** * Now get the foreign node id number and the respective nodal data. */ int f_n_id; std::vector<Number> values; while(true) { in_file >> f_n_id; /** * if node_nr = -1 then we have reached the end of the dataset. */ if (f_n_id==-1) break; /** * Resize the values vector (usually data in three * principal directions, i.e. NVALDC = 3). */ values.resize(NVALDC); /** * Read the meshdata for the respective node. */ for (unsigned int data_cnt=0; data_cnt<NVALDC; data_cnt++) { /** * Check what data type we are reading. * 2,4: Real * 5,6: Complex * other data types are not supported yet. */ if (Data_type == 2 || Data_type == 4) in_file >> values[data_cnt]; else if(Data_type == 5 || Data_type == 6) { Real re_val, im_val; in_file >> re_val >> im_val; values[data_cnt] = Complex(re_val,im_val); } else { std::cerr << "ERROR: Data type not supported." << std::endl; error(); } } // end loop data_cnt /** * Add the values vector to the MechData data structure. */ const Node* node = foreign_id_to_node(f_n_id); _node_data.insert (std::make_pair(node, values)); } // while(true) } else { /** * all other datasets are ignored */ } } } /* * finished reading. Ready for use */ this->_node_data_closed = true; this->_elem_data_closed = true; } void MeshData::write_unv (const std::string& name) { /* * make sure the id maps are ready * and that we have data to write */ assert (_node_id_map_closed); assert (_elem_id_map_closed); assert (_node_data_closed); assert (_elem_data_closed); std::ofstream out_file (name.c_str()); const std::string _label_dataset_mesh_data = "2414"; /** * Currently this function handles only nodal data. */ assert (!_node_data.empty()); /** * Write the beginning of the dataset. */ out_file << " -1\n" << " " << _label_dataset_mesh_data << "\n"; /** * Record 1 (analysis dataset label, currently just a dummy). */ char buf[78]; sprintf(buf, "%10i\n",1); out_file << buf; /** * Record 2 (analysis dataset name, currently just a dummy). */ std::string _dummy_string = "libMesh\n"; out_file << _dummy_string; /** * Record 3 (dataset location). */ sprintf(buf, "%10i\n",1); out_file << buf; /** * Record 4 trough 8 (ID lines). */ for (unsigned int i=0; i<5;i++) out_file << _dummy_string; /** * Record 9 trough 11. */ sprintf(buf, "%10i%10i%10i%10i%10i%10i\n", 0, 0, 0, 0, 0, 0); out_file << buf; sprintf(buf, "%10i%10i%10i%10i%10i%10i%10i%10i\n", 0, 0, 0, 0, 0, 0, 0, 0); out_file << buf; sprintf(buf, "%10i%10i\n", 0, 0); out_file << buf; /** * Record 12 and 13. */ sprintf(buf, "%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n", 0., 0., 0., 0., 0., 0.); out_file << buf; sprintf(buf, "%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n", 0., 0., 0., 0., 0., 0.); out_file << buf; /** * Write the foreign node number and the respective data. */ std::map<const Node*, std::vector<Number> >::const_iterator nit = _node_data.begin(); for (; nit != _node_data.end(); ++nit) { const Node* node = (*nit).first; unsigned int f_n_id = node_to_foreign_id (node); sprintf(buf, "%10i\n", f_n_id); out_file << buf; std::vector<Number> values; this->operator()(node, values); for (unsigned int v_cnt=0; v_cnt<values.size(); v_cnt++) { #ifdef USE_COMPLEX_NUMBERS sprintf(buf, "%13.5E%13.5E", values[v_cnt].real(), values[v_cnt].imag()); out_file << buf; #else sprintf(buf, "%13.5E%13.5E", values[v_cnt]); out_file << buf; #endif } out_file << "\n"; } /** * Write end of the dataset. */ out_file << " -1\n"; } <commit_msg>fixed for Real data<commit_after>// $Id: mesh_data_unv_support.C,v 1.4 2003-05-22 16:20:52 benkirk Exp $ // The Next Great Finite Element Library. // Copyright (C) 2002 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <fstream> #include <stdio.h> // Local includes #include "mesh_data.h" #include "mesh_base.h" //------------------------------------------------------ // MeshData UNV support functions void MeshData::read_unv(const std::string& name) { /* * When reading data, make sure the id maps are ok */ assert (_node_id_map_closed); assert (_elem_id_map_closed); /** * clear the data, but keep the id maps */ this->clear(); std::ifstream in_file (name.c_str()); if ( !in_file.good() ) { std::cerr << "ERROR: Input file not good." << std::endl; error(); } const std::string _label_dataset_mesh_data = "2414"; /** * locate the beginning of data set * and read it. */ { std::string olds, news; while (true) { in_file >> olds >> news; /* * a "-1" followed by a number means the beginning of a dataset * stop combing at the end of the file */ while( ((olds != "-1") || (news == "-1") ) && !in_file.eof() ) { olds = news; in_file >> news; } if(in_file.eof()) break; /* * if beginning of dataset, buffer it in * temp_buffer, if desired */ if (news == _label_dataset_mesh_data) { /** * Now read the data of interest. */ /** * Ignore the first lines that stand for * analysis dataset label and name. */ for(unsigned int i=0; i<3; i++) in_file.ignore(256,'\n'); unsigned int Dataset_location; unsigned int Model_type, Analysis_type, Data_characteristic, Result_type, Data_type, NVALDC; Real dummy_Real; /** * Read the dataset location, where * 1: Data at nodes * 2: Data on elements * other sets are currently not supported. */ in_file >> Dataset_location; if (Dataset_location != 1) { std::cerr << "ERROR: Currently only Data at nodes is supported." << std::endl; error(); } /** * Ignore five ID lines. */ for(unsigned int i=0; i<6; i++) in_file.ignore(256,'\n'); /** * Read record 9. */ in_file >> Model_type // not supported yet >> Analysis_type // not supported yet >> Data_characteristic // not supported yet >> Result_type // not supported yet >> Data_type >> NVALDC; /** * Ignore record 10 and 11 * (Integer analysis type specific data). */ for (unsigned int i=0; i<3; i++) in_file.ignore(256,'\n'); /** * Ignore record 12 and record 13. */ for (unsigned int i=0; i<12; i++) in_file >> dummy_Real; /** * Now get the foreign node id number and the respective nodal data. */ int f_n_id; std::vector<Number> values; while(true) { in_file >> f_n_id; /** * if node_nr = -1 then we have reached the end of the dataset. */ if (f_n_id==-1) break; /** * Resize the values vector (usually data in three * principal directions, i.e. NVALDC = 3). */ values.resize(NVALDC); /** * Read the meshdata for the respective node. */ for (unsigned int data_cnt=0; data_cnt<NVALDC; data_cnt++) { /** * Check what data type we are reading. * 2,4: Real * 5,6: Complex * other data types are not supported yet. */ if (Data_type == 2 || Data_type == 4) in_file >> values[data_cnt]; else if(Data_type == 5 || Data_type == 6) { #ifdef USE_COMPLEX_NUMBERS Real re_val, im_val; in_file >> re_val >> im_val; values[data_cnt] = Complex(re_val,im_val); #else std::cerr << "ERROR: Complex data only supported" << std::endl << "when libMesh is configured with --enable-complex!" << std::endl; error(); #endif } else { std::cerr << "ERROR: Data type not supported." << std::endl; error(); } } // end loop data_cnt /** * Add the values vector to the MechData data structure. */ const Node* node = foreign_id_to_node(f_n_id); _node_data.insert (std::make_pair(node, values)); } // while(true) } else { /** * all other datasets are ignored */ } } } /* * finished reading. Ready for use */ this->_node_data_closed = true; this->_elem_data_closed = true; } void MeshData::write_unv (const std::string& name) { /* * make sure the id maps are ready * and that we have data to write */ assert (_node_id_map_closed); assert (_elem_id_map_closed); assert (_node_data_closed); assert (_elem_data_closed); std::ofstream out_file (name.c_str()); const std::string _label_dataset_mesh_data = "2414"; /** * Currently this function handles only nodal data. */ assert (!_node_data.empty()); /** * Write the beginning of the dataset. */ out_file << " -1\n" << " " << _label_dataset_mesh_data << "\n"; /** * Record 1 (analysis dataset label, currently just a dummy). */ char buf[78]; sprintf(buf, "%10i\n",1); out_file << buf; /** * Record 2 (analysis dataset name, currently just a dummy). */ std::string _dummy_string = "libMesh\n"; out_file << _dummy_string; /** * Record 3 (dataset location). */ sprintf(buf, "%10i\n",1); out_file << buf; /** * Record 4 trough 8 (ID lines). */ for (unsigned int i=0; i<5;i++) out_file << _dummy_string; /** * Record 9 trough 11. */ sprintf(buf, "%10i%10i%10i%10i%10i%10i\n", 0, 0, 0, 0, 0, 0); out_file << buf; sprintf(buf, "%10i%10i%10i%10i%10i%10i%10i%10i\n", 0, 0, 0, 0, 0, 0, 0, 0); out_file << buf; sprintf(buf, "%10i%10i\n", 0, 0); out_file << buf; /** * Record 12 and 13. */ sprintf(buf, "%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n", 0., 0., 0., 0., 0., 0.); out_file << buf; sprintf(buf, "%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n", 0., 0., 0., 0., 0., 0.); out_file << buf; /** * Write the foreign node number and the respective data. */ std::map<const Node*, std::vector<Number> >::const_iterator nit = _node_data.begin(); for (; nit != _node_data.end(); ++nit) { const Node* node = (*nit).first; unsigned int f_n_id = node_to_foreign_id (node); sprintf(buf, "%10i\n", f_n_id); out_file << buf; std::vector<Number> values; this->operator()(node, values); for (unsigned int v_cnt=0; v_cnt<values.size(); v_cnt++) { #ifdef USE_COMPLEX_NUMBERS sprintf(buf, "%13.5E%13.5E", values[v_cnt].real(), values[v_cnt].imag()); out_file << buf; #else sprintf(buf, "%13.5E", values[v_cnt]); out_file << buf; #endif } out_file << "\n"; } /** * Write end of the dataset. */ out_file << " -1\n"; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (ivan.frade@nokia.com) ** ** This file is part of the QtSparql module (not yet part of the Qt Toolkit). ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at ivan.frade@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsparqlconnection.h" #include "qsparqlconnection_p.h" #include "qsparqlquery.h" #ifdef QT_SPARQL_VIRTUOSO #include "../drivers/virtuoso/qsparql_virtuoso.h" #endif #ifdef QT_SPARQL_TRACKER #include "../drivers/tracker/qsparql_tracker.h" #endif #ifdef QT_SPARQL_TRACKER_DIRECT #include "../drivers/tracker_direct/qsparql_tracker_direct.h" #endif #ifdef QT_SPARQL_ENDPOINT #include "../drivers/endpoint/qsparql_endpoint.h" #endif #include "qdebug.h" #include "qcoreapplication.h" #include "qsparqlresult.h" #include "qsparqlconnectionoptions.h" #include "qsparqldriver_p.h" #include "qsparqldriverplugin_p.h" #if WE_ARE_QT // QFactoryLoader is an internal part of Qt; we'll use it when where part of Qt // (or when Qt publishes it.) # include "qfactoryloader_p.h" #else # include "qdir.h" # include "qpluginloader.h" #endif #include "qsparqlnulldriver_p.h" #include "qhash.h" QT_BEGIN_NAMESPACE #if WE_ARE_QT #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, (QSparqlDriverFactoryInterface_iid, QLatin1String("/sparqldrivers"))) #endif #endif typedef QHash<QString, QSparqlDriverCreatorBase*> DriverDict; class QSparqlConnectionPrivate { public: QSparqlConnectionPrivate(QSparqlDriver *dr, const QString& name, const QSparqlConnectionOptions& opts): driver(dr), drvName(name), options(opts) { } ~QSparqlConnectionPrivate(); static DriverDict &driverDict(); static QSparqlDriver* findDriver(const QString& type); static QSparqlDriver* findDriverWithFactoryLoader(const QString& type); static QSparqlDriver* findDriverWithPluginLoader(const QString& type); static void registerConnectionCreator(const QString &type, QSparqlDriverCreatorBase* creator); static QSparqlConnectionPrivate* shared_null(); QSparqlDriver* driver; QString drvName; QSparqlConnectionOptions options; }; QSparqlConnectionPrivate *QSparqlConnectionPrivate::shared_null() { static QSparqlNullDriver dr; static QSparqlConnectionPrivate n(&dr, QString(), QSparqlConnectionOptions()); return &n; } QSparqlConnectionPrivate::~QSparqlConnectionPrivate() { if (driver != shared_null()->driver) { delete driver; driver = shared_null()->driver; } } static bool qDriverDictInit = false; static void cleanDriverDict() { qDeleteAll(QSparqlConnectionPrivate::driverDict()); QSparqlConnectionPrivate::driverDict().clear(); qDriverDictInit = false; } DriverDict &QSparqlConnectionPrivate::driverDict() { static DriverDict dict; if (!qDriverDictInit) { qDriverDictInit = true; qAddPostRoutine(cleanDriverDict); } return dict; } /*! \internal Create the actual driver instance \a type. */ QSparqlDriver* QSparqlConnectionPrivate::findDriver(const QString &type) { // separately defined drivers (e.g., for tests) QSparqlDriver * driver = 0; DriverDict dict = QSparqlConnectionPrivate::driverDict(); for (DriverDict::const_iterator it = dict.constBegin(); it != dict.constEnd() && !driver; ++it) { if (type == it.key()) { driver = ((QSparqlDriverCreatorBase*)(*it))->createObject(); } } if (driver) return driver; // drivers built into the .so #ifdef QT_SPARQL_TRACKER if (type == QLatin1String("QTRACKER")) driver = new QTrackerDriver(); #endif #ifdef QT_SPARQL_TRACKER_DIRECT if (type == QLatin1String("QTRACKER_DIRECT")) driver = new QTrackerDirectDriver(); #endif #ifdef QT_SPARQL_ENDPOINT if (type == QLatin1String("QSPARQL_ENDPOINT")) driver = new EndpointDriver(); #endif #ifdef QT_SPARQL_VIRTUOSO if (type == QLatin1String("QVIRTUOSO")) driver = new QVirtuosoDriver(); #endif if (driver) return driver; // drivers built as plugins #if WE_ARE_QT return findDriverWithFactoryLoader(type); #else return findDriverWithPluginLoader(type); #endif } QSparqlDriver* QSparqlConnectionPrivate::findDriverWithFactoryLoader(const QString &type) { #if WE_ARE_QT #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) if (!driver && loader()) { if (QSparqlDriverFactoryInterface *factory = qobject_cast<QSparqlDriverFactoryInterface*>(loader()->instance(type))) driver = factory->create(type); } #endif // QT_NO_LIBRARY if (!driver) { qWarning("QSparqlConnection: %s driver not loaded", type.toLatin1().data()); qWarning("QSparqlConnection: available drivers: %s", QSparqlConnection::drivers().join(QLatin1String(" ")).toLatin1().data()); if (QCoreApplication::instance() == 0) qWarning("QSparqlConnectionPrivate: an instance of QCoreApplication is required for loading driver plugins"); driver = QSparqlConnectionPrivate::shared_null()->driver; } return driver; #else return 0; #endif } QSparqlDriver* QSparqlConnectionPrivate::findDriverWithPluginLoader(const QString &type) { #if WE_ARE_QT return 0; #else static bool keysRead = false; static QHash<QString, QSparqlDriverPlugin*> plugins; if (!keysRead) { keysRead = true; QStringList paths = QCoreApplication::libraryPaths(); foreach(const QString& path, paths) { QString realPath = path + QLatin1String("/sparqldrivers"); QStringList pluginNames = QDir(realPath).entryList(QDir::Files); for (int j = 0; j < pluginNames.count(); ++j) { QString fileName = QDir::cleanPath(realPath + QLatin1Char('/') + pluginNames.at(j)); QPluginLoader loader(fileName); QObject* instance = loader.instance(); QFactoryInterface *factory = qobject_cast<QFactoryInterface*>(instance); QSparqlDriverPlugin* driPlu = dynamic_cast<QSparqlDriverPlugin*>(factory); if (instance && factory && driPlu) { QStringList keys = factory->keys(); for (int k = 0; k < keys.size(); ++k) { plugins[keys[k]] = driPlu; } } } } } if (plugins.contains(type)) return plugins[type]->create(type); return QSparqlConnectionPrivate::shared_null()->driver; #endif } void qSparqlRegisterConnectionCreator(const QString& type, QSparqlDriverCreatorBase* creator) { QSparqlConnectionPrivate::registerConnectionCreator(type, creator); } void QSparqlConnectionPrivate::registerConnectionCreator(const QString& name, QSparqlDriverCreatorBase* creator) { delete QSparqlConnectionPrivate::driverDict().take(name); if (creator) QSparqlConnectionPrivate::driverDict().insert(name, creator); } /*! \class QSparqlConnection \brief The QSparqlConnection class provides an interface for accessing an RDF store. \inmodule QtSparql */ /*! Destroys the object and frees any allocated resources. \sa close() */ QSparqlConnection::QSparqlConnection(QObject* parent) : QObject(parent) { QSparqlDriver* driver = QSparqlConnectionPrivate::shared_null()->driver; d = new QSparqlConnectionPrivate(driver, QString(), QSparqlConnectionOptions()); } QSparqlConnection::QSparqlConnection(const QString& type, const QSparqlConnectionOptions& options, QObject* parent) : QObject(parent) { QSparqlDriver* driver = QSparqlConnectionPrivate::findDriver(type); d = new QSparqlConnectionPrivate(driver, type, options); d->driver->open(d->options); } QSparqlConnection::~QSparqlConnection() { d->driver->close(); delete d; } /*! Executes a SPARQL query on the database and returns a pointer to a QSparqlResult object. The user is responsible for freeing it. If \a query is empty or if the this QSparqlConnection is not valid, exec() returns a QSparqlResult which is in the error state. It won't emit the finished() signal. \sa QSparqlQuery, QSparqlResult, QSparqlResult::hasError */ // TODO: isn't it quite bad that the user must check the error // state of the result? Or should the "error result" emit the // finished() signal when the main loop is entered the next time, // so that the user has a change to connect to it? QSparqlResult* QSparqlConnection::exec(const QSparqlQuery& query) const { if (d->driver->isOpenError()) { qWarning("QSparqlConnection::exec: connection not open"); QSparqlResult* result = new QSparqlNullResult(); result->setLastError(d->driver->lastError()); return result; } if (!d->driver->isOpen()) { qWarning("QSparqlConnection::exec: connection not open"); QSparqlResult* result = new QSparqlNullResult(); result->setLastError(QSparqlError(QLatin1String("Connection not open"), QSparqlError::ConnectionError)); return result; } QString queryText = query.preparedQueryText(); if (queryText.isEmpty()) { qWarning("QSparqlConnection::exec: empty query"); QSparqlResult* result = new QSparqlNullResult(); result->setLastError(QSparqlError(QLatin1String("Query is empty"), QSparqlError::ConnectionError)); return result; } return d->driver->exec(queryText, query.type()); } /*! Returns the connection's driver name. */ QString QSparqlConnection::driverName() const { return d->drvName; } /*! \enum QSparqlConnection::Feature This enum contains a list of features a driver might support. Use hasFeature() to query whether a feature is supported or not. \value QuerySize Whether the database is capable of reporting the size of a query. Note that some databases do not support returning the size (i.e. number of rows returned) of a query, in which case QSparqlQuery::size() will return -1. \value DefaultGraph The store has a default graph which doesn't have to be specified. Some stores, like Virtuoso, don't have a default graph. \value AskQueries The driver supports ASK queries \value ConstructQueries The driver supports CONSTRUCT queries \value UpdateQueries The driver supports INSERT and UPDATE queries \sa hasFeature() */ /*! Returns true if the QSparqlConnection supports feature \a feature; otherwise returns false. */ bool QSparqlConnection::hasFeature(Feature feature) const { return d->driver->hasFeature(feature); } /*! Returns true if the QSparqlConnection has a valid driver, i.e., the name of the driver given in the constructor was valid. Example: \snippet doc/src/snippets/code/src_sparql_kernel_qsparqlconnection.cpp 8 */ bool QSparqlConnection::isValid() const { return d->driver && d->driver != d->shared_null()->driver; } /*! Adds a prefix/uri pair to the connection. Each SPARQL query made with the connection will have the prefixes prepended to it. */ void QSparqlConnection::addPrefix(const QString& prefix, const QUrl& uri) { d->driver->addPrefix(prefix, uri); } QStringList QSparqlConnection::drivers() { QStringList list; return list; // a hack #if WE_ARE_QT #ifdef QT_SPARQL_ODBC list << QLatin1String("QODBC3"); list << QLatin1String("QODBC"); #endif #ifdef QT_SPARQL_TRACKER list << QLatin1String("QTRACKER"); #endif #ifdef QT_SPARQL_TRACKER_DIRECT list << QLatin1String("QTRACKER_DIRECT"); #endif #ifdef QT_SPARQL_ENDPOINT list << QLatin1String("QSPARQL_ENDPOINT"); #endif #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) if (QFactoryLoader *fl = loader()) { QStringList keys = fl->keys(); for (QStringList::const_iterator i = keys.constBegin(); i != keys.constEnd(); ++i) { if (!list.contains(*i)) list << *i; } } #endif DriverDict dict = QSparqlConnectionPrivate::driverDict(); for (DriverDict::const_iterator i = dict.constBegin(); i != dict.constEnd(); ++i) { if (!list.contains(i.key())) list << i.key(); } return list; #endif } #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug dbg, const QSparqlConnection &d) { if (!d.isValid()) { dbg.nospace() << "QSparqlConnection(invalid)"; return dbg.space(); } dbg.nospace() << "QSparqlConnection(driver=\"" << d.driverName() << ")"; return dbg.space(); } #endif QT_END_NAMESPACE <commit_msg>* Fix the QSparqlConnection::drivers() method by adding a QSparqlConnectionPrivate::initKeys() that sets up a global list of the keys<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (ivan.frade@nokia.com) ** ** This file is part of the QtSparql module (not yet part of the Qt Toolkit). ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at ivan.frade@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsparqlconnection.h" #include "qsparqlconnection_p.h" #include "qsparqlquery.h" #ifdef QT_SPARQL_VIRTUOSO #include "../drivers/virtuoso/qsparql_virtuoso.h" #endif #ifdef QT_SPARQL_TRACKER #include "../drivers/tracker/qsparql_tracker.h" #endif #ifdef QT_SPARQL_TRACKER_DIRECT #include "../drivers/tracker_direct/qsparql_tracker_direct.h" #endif #ifdef QT_SPARQL_ENDPOINT #include "../drivers/endpoint/qsparql_endpoint.h" #endif #include "qdebug.h" #include "qcoreapplication.h" #include "qsparqlresult.h" #include "qsparqlconnectionoptions.h" #include "qsparqldriver_p.h" #include "qsparqldriverplugin_p.h" #if WE_ARE_QT // QFactoryLoader is an internal part of Qt; we'll use it when where part of Qt // (or when Qt publishes it.) # include "qfactoryloader_p.h" #else # include "qdir.h" # include "qpluginloader.h" #endif #include "qsparqlnulldriver_p.h" #include "qhash.h" QT_BEGIN_NAMESPACE #if WE_ARE_QT #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, (QSparqlDriverFactoryInterface_iid, QLatin1String("/sparqldrivers"))) #endif #endif typedef QHash<QString, QSparqlDriverCreatorBase*> DriverDict; class QSparqlConnectionPrivate { public: QSparqlConnectionPrivate(QSparqlDriver *dr, const QString& name, const QSparqlConnectionOptions& opts): driver(dr), drvName(name), options(opts) { } ~QSparqlConnectionPrivate(); static DriverDict &driverDict(); static QSparqlDriver* findDriver(const QString& type); static QSparqlDriver* findDriverWithFactoryLoader(const QString& type); static void initKeys(); static QStringList allKeys; static QHash<QString, QSparqlDriverPlugin*> plugins; static QSparqlDriver* findDriverWithPluginLoader(const QString& type); static void registerConnectionCreator(const QString &type, QSparqlDriverCreatorBase* creator); static QSparqlConnectionPrivate* shared_null(); QSparqlDriver* driver; QString drvName; QSparqlConnectionOptions options; }; QSparqlConnectionPrivate *QSparqlConnectionPrivate::shared_null() { static QSparqlNullDriver dr; static QSparqlConnectionPrivate n(&dr, QString(), QSparqlConnectionOptions()); return &n; } QSparqlConnectionPrivate::~QSparqlConnectionPrivate() { if (driver != shared_null()->driver) { delete driver; driver = shared_null()->driver; } } static bool qDriverDictInit = false; static void cleanDriverDict() { qDeleteAll(QSparqlConnectionPrivate::driverDict()); QSparqlConnectionPrivate::driverDict().clear(); qDriverDictInit = false; } DriverDict &QSparqlConnectionPrivate::driverDict() { static DriverDict dict; if (!qDriverDictInit) { qDriverDictInit = true; qAddPostRoutine(cleanDriverDict); } return dict; } /*! \internal Create the actual driver instance \a type. */ QSparqlDriver* QSparqlConnectionPrivate::findDriver(const QString &type) { // separately defined drivers (e.g., for tests) QSparqlDriver * driver = 0; DriverDict dict = QSparqlConnectionPrivate::driverDict(); for (DriverDict::const_iterator it = dict.constBegin(); it != dict.constEnd() && !driver; ++it) { if (type == it.key()) { driver = ((QSparqlDriverCreatorBase*)(*it))->createObject(); } } if (driver) return driver; // drivers built into the .so #ifdef QT_SPARQL_TRACKER if (type == QLatin1String("QTRACKER")) driver = new QTrackerDriver(); #endif #ifdef QT_SPARQL_TRACKER_DIRECT if (type == QLatin1String("QTRACKER_DIRECT")) driver = new QTrackerDirectDriver(); #endif #ifdef QT_SPARQL_ENDPOINT if (type == QLatin1String("QSPARQL_ENDPOINT")) driver = new EndpointDriver(); #endif #ifdef QT_SPARQL_VIRTUOSO if (type == QLatin1String("QVIRTUOSO")) driver = new QVirtuosoDriver(); #endif if (driver) return driver; // drivers built as plugins #if WE_ARE_QT return findDriverWithFactoryLoader(type); #else return findDriverWithPluginLoader(type); #endif } QSparqlDriver* QSparqlConnectionPrivate::findDriverWithFactoryLoader(const QString &type) { #if WE_ARE_QT #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) if (!driver && loader()) { if (QSparqlDriverFactoryInterface *factory = qobject_cast<QSparqlDriverFactoryInterface*>(loader()->instance(type))) driver = factory->create(type); } #endif // QT_NO_LIBRARY if (!driver) { qWarning("QSparqlConnection: %s driver not loaded", type.toLatin1().data()); qWarning("QSparqlConnection: available drivers: %s", QSparqlConnection::drivers().join(QLatin1String(" ")).toLatin1().data()); if (QCoreApplication::instance() == 0) qWarning("QSparqlConnectionPrivate: an instance of QCoreApplication is required for loading driver plugins"); driver = QSparqlConnectionPrivate::shared_null()->driver; } return driver; #else return 0; #endif } QStringList QSparqlConnectionPrivate::allKeys; QHash<QString, QSparqlDriverPlugin*> QSparqlConnectionPrivate::plugins; void QSparqlConnectionPrivate::initKeys() { static bool keysRead = false; if (keysRead) return; QStringList paths = QCoreApplication::libraryPaths(); foreach(const QString& path, paths) { QString realPath = path + QLatin1String("/sparqldrivers"); QStringList pluginNames = QDir(realPath).entryList(QDir::Files); for (int j = 0; j < pluginNames.count(); ++j) { QString fileName = QDir::cleanPath(realPath + QLatin1Char('/') + pluginNames.at(j)); QPluginLoader loader(fileName); QObject* instance = loader.instance(); QFactoryInterface *factory = qobject_cast<QFactoryInterface*>(instance); QSparqlDriverPlugin* driPlu = dynamic_cast<QSparqlDriverPlugin*>(factory); if (instance && factory && driPlu) { QStringList keys = factory->keys(); for (int k = 0; k < keys.size(); ++k) { plugins[keys[k]] = driPlu; } allKeys.append(keys); } } } keysRead = true; return; } QSparqlDriver* QSparqlConnectionPrivate::findDriverWithPluginLoader(const QString &type) { #if WE_ARE_QT return 0; #else initKeys(); if (plugins.contains(type)) return plugins[type]->create(type); return QSparqlConnectionPrivate::shared_null()->driver; #endif } void qSparqlRegisterConnectionCreator(const QString& type, QSparqlDriverCreatorBase* creator) { QSparqlConnectionPrivate::registerConnectionCreator(type, creator); } void QSparqlConnectionPrivate::registerConnectionCreator(const QString& name, QSparqlDriverCreatorBase* creator) { delete QSparqlConnectionPrivate::driverDict().take(name); if (creator) QSparqlConnectionPrivate::driverDict().insert(name, creator); } /*! \class QSparqlConnection \brief The QSparqlConnection class provides an interface for accessing an RDF store. \inmodule QtSparql */ /*! Destroys the object and frees any allocated resources. \sa close() */ QSparqlConnection::QSparqlConnection(QObject* parent) : QObject(parent) { QSparqlDriver* driver = QSparqlConnectionPrivate::shared_null()->driver; d = new QSparqlConnectionPrivate(driver, QString(), QSparqlConnectionOptions()); } QSparqlConnection::QSparqlConnection(const QString& type, const QSparqlConnectionOptions& options, QObject* parent) : QObject(parent) { QSparqlDriver* driver = QSparqlConnectionPrivate::findDriver(type); d = new QSparqlConnectionPrivate(driver, type, options); d->driver->open(d->options); } QSparqlConnection::~QSparqlConnection() { d->driver->close(); delete d; } /*! Executes a SPARQL query on the database and returns a pointer to a QSparqlResult object. The user is responsible for freeing it. If \a query is empty or if the this QSparqlConnection is not valid, exec() returns a QSparqlResult which is in the error state. It won't emit the finished() signal. \sa QSparqlQuery, QSparqlResult, QSparqlResult::hasError */ // TODO: isn't it quite bad that the user must check the error // state of the result? Or should the "error result" emit the // finished() signal when the main loop is entered the next time, // so that the user has a change to connect to it? QSparqlResult* QSparqlConnection::exec(const QSparqlQuery& query) const { if (d->driver->isOpenError()) { qWarning("QSparqlConnection::exec: connection not open"); QSparqlResult* result = new QSparqlNullResult(); result->setLastError(d->driver->lastError()); return result; } if (!d->driver->isOpen()) { qWarning("QSparqlConnection::exec: connection not open"); QSparqlResult* result = new QSparqlNullResult(); result->setLastError(QSparqlError(QLatin1String("Connection not open"), QSparqlError::ConnectionError)); return result; } QString queryText = query.preparedQueryText(); if (queryText.isEmpty()) { qWarning("QSparqlConnection::exec: empty query"); QSparqlResult* result = new QSparqlNullResult(); result->setLastError(QSparqlError(QLatin1String("Query is empty"), QSparqlError::ConnectionError)); return result; } return d->driver->exec(queryText, query.type()); } /*! Returns the connection's driver name. */ QString QSparqlConnection::driverName() const { return d->drvName; } /*! \enum QSparqlConnection::Feature This enum contains a list of features a driver might support. Use hasFeature() to query whether a feature is supported or not. \value QuerySize Whether the database is capable of reporting the size of a query. Note that some databases do not support returning the size (i.e. number of rows returned) of a query, in which case QSparqlQuery::size() will return -1. \value DefaultGraph The store has a default graph which doesn't have to be specified. Some stores, like Virtuoso, don't have a default graph. \value AskQueries The driver supports ASK queries \value ConstructQueries The driver supports CONSTRUCT queries \value UpdateQueries The driver supports INSERT and UPDATE queries \sa hasFeature() */ /*! Returns true if the QSparqlConnection supports feature \a feature; otherwise returns false. */ bool QSparqlConnection::hasFeature(Feature feature) const { return d->driver->hasFeature(feature); } /*! Returns true if the QSparqlConnection has a valid driver, i.e., the name of the driver given in the constructor was valid. Example: \snippet doc/src/snippets/code/src_sparql_kernel_qsparqlconnection.cpp 8 */ bool QSparqlConnection::isValid() const { return d->driver && d->driver != d->shared_null()->driver; } /*! Adds a prefix/uri pair to the connection. Each SPARQL query made with the connection will have the prefixes prepended to it. */ void QSparqlConnection::addPrefix(const QString& prefix, const QUrl& uri) { d->driver->addPrefix(prefix, uri); } QStringList QSparqlConnection::drivers() { QStringList list; #ifdef QT_SPARQL_VIRTUOSO list << QLatin1String("QVIRTUOSO"); #endif #ifdef QT_SPARQL_TRACKER list << QLatin1String("QTRACKER"); #endif #ifdef QT_SPARQL_TRACKER_DIRECT list << QLatin1String("QTRACKER_DIRECT"); #endif #ifdef QT_SPARQL_ENDPOINT list << QLatin1String("QSPARQL_ENDPOINT"); #endif #if WE_ARE_QT #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) if (QFactoryLoader *fl = loader()) { QStringList keys = fl->keys(); for (QStringList::const_iterator i = keys.constBegin(); i != keys.constEnd(); ++i) { if (!list.contains(*i)) list << *i; } } #endif #else QSparqlConnectionPrivate::initKeys(); QStringList keys = QSparqlConnectionPrivate::allKeys; for (QStringList::const_iterator i = keys.constBegin(); i != keys.constEnd(); ++i) { if (!list.contains(*i)) list << *i; } #endif DriverDict dict = QSparqlConnectionPrivate::driverDict(); for (DriverDict::const_iterator i = dict.constBegin(); i != dict.constEnd(); ++i) { if (!list.contains(i.key())) list << i.key(); } return list; } #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug dbg, const QSparqlConnection &d) { if (!d.isValid()) { dbg.nospace() << "QSparqlConnection(invalid)"; return dbg.space(); } dbg.nospace() << "QSparqlConnection(driver=\"" << d.driverName() << ")"; return dbg.space(); } #endif QT_END_NAMESPACE <|endoftext|>
<commit_before>/* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_serving/servables/tensorflow/classifier.h" #include <stddef.h> #include <algorithm> #include <functional> #include <memory> #include <string> #include <vector> #include "tensorflow/cc/saved_model/signature_constants.h" #include "tensorflow/contrib/session_bundle/signature.h" #include "tensorflow/core/example/example.pb.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/notification.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/platform/tracing.h" #include "tensorflow/core/platform/types.h" #include "tensorflow_serving/apis/classification.pb.h" #include "tensorflow_serving/apis/classifier.h" #include "tensorflow_serving/apis/input.pb.h" #include "tensorflow_serving/apis/model.pb.h" #include "tensorflow_serving/servables/tensorflow/util.h" namespace tensorflow { namespace serving { namespace { // Implementation of the ClassificationService using the legacy SessionBundle // ClassificationSignature signature format. class TensorFlowClassifier : public ClassifierInterface { public: explicit TensorFlowClassifier(Session* session, const ClassificationSignature* signature) : session_(session), signature_(signature) {} Status Classify(const ClassificationRequest& request, ClassificationResult* result) override { TRACELITERAL("TensorFlowClassifier::Classify"); TRACELITERAL("ConvertInputTFEXamplesToTensor"); // Setup the input Tensor to be a vector of string containing the serialized // tensorflow.Example. Tensor input_tensor; TF_RETURN_IF_ERROR( InputToSerializedExampleTensor(request.input(), &input_tensor)); const int num_examples = input_tensor.dim_size(0); if (num_examples == 0) { return errors::InvalidArgument("ClassificationRequest::input is empty."); } TRACELITERAL("RunClassification"); // Support serving models that return classes, scores or both. std::unique_ptr<Tensor> classes; if (!signature_->classes().tensor_name().empty()) { classes.reset(new Tensor); } std::unique_ptr<Tensor> scores; if (!signature_->scores().tensor_name().empty()) { scores.reset(new Tensor); } TF_RETURN_IF_ERROR(RunClassification(*signature_, input_tensor, session_, classes.get(), scores.get())); // Validate classes output Tensor. if (classes) { if (classes->dtype() != DT_STRING) { return errors::Internal("Expected classes Tensor of DT_STRING. Got: ", DataType_Name(classes->dtype())); } if (classes->dim_size(0) != num_examples) { return errors::Internal("Expected output batch size of ", num_examples, ". Got: ", classes->dim_size(0)); } } // Validate scores output Tensor. if (scores) { if (scores->dtype() != DT_FLOAT) { return errors::Internal("Expected scores Tensor of DT_FLOAT. Got: ", DataType_Name(scores->dtype())); } if (scores->dim_size(0) != num_examples) { return errors::Internal("Expected output batch size of ", num_examples, ". Got: ", scores->dim_size(0)); } } // Extract the number of classes from either the class or score output // Tensor. int num_classes = 0; if (classes && scores) { // If we have both Tensors they should agree in the second dimmension. if (classes->dim_size(1) != scores->dim_size(1)) { return errors::Internal( "Tensors class and score should match in dim_size(1). Got ", classes->dim_size(1), " vs. ", scores->dim_size(1)); } num_classes = classes->dim_size(1); } else if (classes) { num_classes = classes->dim_size(1); } else if (scores) { num_classes = scores->dim_size(1); } TRACELITERAL("ConvertToClassificationResult"); // Convert the output to ClassificationResult format. for (int i = 0; i < num_examples; ++i) { serving::Classifications* classifications = result->add_classifications(); for (int c = 0; c < num_classes; ++c) { serving::Class* cl = classifications->add_classes(); if (classes) { cl->set_label((classes->matrix<string>())(i, c)); } if (scores) { cl->set_score((scores->matrix<float>())(i, c)); } } } return Status::OK(); } private: Session* const session_; const ClassificationSignature* const signature_; TF_DISALLOW_COPY_AND_ASSIGN(TensorFlowClassifier); }; // Implementation of the ClassifierInterface using SavedModel. class SavedModelTensorFlowClassifier : public ClassifierInterface { public: explicit SavedModelTensorFlowClassifier(Session* session, const SignatureDef* const signature) : session_(session), signature_(signature) {} ~SavedModelTensorFlowClassifier() override = default; Status Classify(const ClassificationRequest& request, ClassificationResult* result) override { TRACELITERAL("TensorFlowClassifier::Classify"); const int num_examples = NumInputExamples(request.input()); if (num_examples == 0) { return errors::InvalidArgument("ClassificationRequest::input is empty."); } string input_tensor_name; std::vector<string> output_tensor_names; TF_RETURN_IF_ERROR(PreProcessClassification(*signature_, &input_tensor_name, &output_tensor_names)); std::vector<Tensor> outputs; TF_RETURN_IF_ERROR(PerformOneShotTensorComputation( request.input(), input_tensor_name, output_tensor_names, session_, &outputs)); TRACELITERAL("ConvertToClassificationResult"); return PostProcessClassificationResult( *signature_, num_examples, output_tensor_names, outputs, result); } private: Session* const session_; const SignatureDef* const signature_; TF_DISALLOW_COPY_AND_ASSIGN(SavedModelTensorFlowClassifier); }; // Implementation of the ClassificationService. class SessionBundleClassifier : public ClassifierInterface { public: explicit SessionBundleClassifier(std::unique_ptr<SessionBundle> bundle) : bundle_(std::move(bundle)) {} ~SessionBundleClassifier() override = default; Status Classify(const ClassificationRequest& request, ClassificationResult* result) override { // Get the default signature of the graph. Expected to be a // classification signature. // TODO(b/26220896): Move TensorFlowClassifier creation to construction // time. ClassificationSignature signature; TF_RETURN_IF_ERROR( GetClassificationSignature(bundle_->meta_graph_def, &signature)); TensorFlowClassifier classifier(bundle_->session.get(), &signature); return classifier.Classify(request, result); } private: std::unique_ptr<SessionBundle> bundle_; TF_DISALLOW_COPY_AND_ASSIGN(SessionBundleClassifier); }; class SavedModelClassifier : public ClassifierInterface { public: explicit SavedModelClassifier(std::unique_ptr<SavedModelBundle> bundle) : bundle_(std::move(bundle)) {} ~SavedModelClassifier() override = default; Status Classify(const ClassificationRequest& request, ClassificationResult* result) override { // Get the default signature of the graph. Expected to be a // classification signature. // TODO(b/26220896): Move TensorFlowClassifier creation to construction // time. SignatureDef signature; TF_RETURN_IF_ERROR(GetClassificationSignatureDef( request.model_spec(), bundle_->meta_graph_def, &signature)); SavedModelTensorFlowClassifier classifier(bundle_->session.get(), &signature); return classifier.Classify(request, result); } private: std::unique_ptr<SavedModelBundle> bundle_; TF_DISALLOW_COPY_AND_ASSIGN(SavedModelClassifier); }; } // namespace Status CreateClassifierFromBundle( std::unique_ptr<SessionBundle> bundle, std::unique_ptr<ClassifierInterface>* service) { service->reset(new SessionBundleClassifier(std::move(bundle))); return Status::OK(); } Status CreateClassifierFromSavedModelBundle( std::unique_ptr<SavedModelBundle> bundle, std::unique_ptr<ClassifierInterface>* service) { service->reset(new SavedModelClassifier(std::move(bundle))); return Status::OK(); } Status CreateFlyweightTensorFlowClassifier( Session* session, const ClassificationSignature* const signature, std::unique_ptr<ClassifierInterface>* service) { service->reset(new TensorFlowClassifier(session, signature)); return Status::OK(); } Status CreateFlyweightTensorFlowClassifier( Session* session, const SignatureDef* signature, std::unique_ptr<ClassifierInterface>* service) { service->reset(new SavedModelTensorFlowClassifier(session, signature)); return Status::OK(); } Status GetClassificationSignatureDef(const ModelSpec& model_spec, const MetaGraphDef& meta_graph_def, SignatureDef* signature) { const string signature_name = model_spec.signature_name().empty() ? kDefaultServingSignatureDefKey : model_spec.signature_name(); auto iter = meta_graph_def.signature_def().find(signature_name); if (iter == meta_graph_def.signature_def().end()) { return errors::InvalidArgument(strings::StrCat( "No signature was found with the name: ", signature_name)); } if (iter->second.method_name() != kClassifyMethodName) { return errors::InvalidArgument(strings::StrCat( "Expected classification signature method_name to be ", kClassifyMethodName, ". Was: ", iter->second.method_name())); } *signature = iter->second; return Status::OK(); } Status PreProcessClassification(const SignatureDef& signature, string* input_tensor_name, std::vector<string>* output_tensor_names) { if (signature.method_name() != kClassifyMethodName) { return errors::InvalidArgument(strings::StrCat( "Expected classification signature method_name to be ", kClassifyMethodName, ". Was: ", signature.method_name())); } if (signature.inputs().size() != 1) { return errors::InvalidArgument( strings::StrCat("Expected one input Tensor.")); } if (signature.outputs().size() != 1 && signature.outputs().size() != 2) { return errors::InvalidArgument( strings::StrCat("Expected one or two output Tensors, found ", signature.outputs().size())); } auto input_iter = signature.inputs().find(kClassifyInputs); if (input_iter == signature.inputs().end()) { return errors::FailedPrecondition( "No classification inputs found in SignatureDef: ", signature.DebugString()); } *input_tensor_name = input_iter->second.name(); auto classes_iter = signature.outputs().find(kClassifyOutputClasses); auto scores_iter = signature.outputs().find(kClassifyOutputScores); if (classes_iter == signature.outputs().end() && scores_iter == signature.outputs().end()) { return errors::FailedPrecondition(strings::StrCat( "Expected classification signature outputs to contain at least one of ", "\"", kClassifyOutputClasses, "\" or \"", kClassifyOutputScores, "\". Signature was: ", signature.DebugString())); } if (classes_iter != signature.outputs().end()) { output_tensor_names->push_back(classes_iter->second.name()); } if (scores_iter != signature.outputs().end()) { output_tensor_names->push_back(scores_iter->second.name()); } return Status::OK(); } Status PostProcessClassificationResult( const SignatureDef& signature, int num_examples, const std::vector<string>& output_tensor_names, const std::vector<Tensor>& output_tensors, ClassificationResult* result) { if (output_tensors.size() != output_tensor_names.size()) { return errors::InvalidArgument( strings::StrCat("Expected ", output_tensor_names.size(), " output tensor(s). Got: ", output_tensors.size())); } auto classes_iter = signature.outputs().find(kClassifyOutputClasses); string classes_tensor_name; if (classes_iter != signature.outputs().end()) { classes_tensor_name = classes_iter->second.name(); } auto scores_iter = signature.outputs().find(kClassifyOutputScores); string scores_tensor_name; if (scores_iter != signature.outputs().end()) { scores_tensor_name = scores_iter->second.name(); } const Tensor* classes = nullptr; const Tensor* scores = nullptr; for (int i = 0; i < output_tensors.size(); ++i) { if (output_tensor_names[i] == classes_tensor_name) { classes = &output_tensors[i]; } else if (output_tensor_names[i] == scores_tensor_name) { scores = &output_tensors[i]; } } // Validate classes output Tensor. if (classes) { if (classes->dtype() != DT_STRING) { return errors::InvalidArgument( "Expected classes Tensor of DT_STRING. Got: ", DataType_Name(classes->dtype())); } if (classes->dim_size(0) != num_examples) { return errors::InvalidArgument("Expected classes output batch size of ", num_examples, ". Got: ", classes->dim_size(0)); } } // Validate scores output Tensor. if (scores) { if (scores->dtype() != DT_FLOAT) { return errors::InvalidArgument( "Expected scores Tensor of DT_FLOAT. Got: ", DataType_Name(scores->dtype())); } if (scores->dim_size(0) != num_examples) { return errors::InvalidArgument("Expected scores output batch size of ", num_examples, ". Got: ", scores->dim_size(0)); } } // Extract the number of classes from either the class or score output // Tensor. int num_classes = 0; if (classes && scores) { // If we have both Tensors they should agree in the second dimmension. if (classes->dim_size(1) != scores->dim_size(1)) { return errors::InvalidArgument( "Tensors class and score should match in dim_size(1). Got ", classes->dim_size(1), " vs. ", scores->dim_size(1)); } num_classes = classes->dim_size(1); } else if (classes) { num_classes = classes->dim_size(1); } else if (scores) { num_classes = scores->dim_size(1); } // Convert the output to ClassificationResult format. for (int i = 0; i < num_examples; ++i) { serving::Classifications* classifications = result->add_classifications(); for (int c = 0; c < num_classes; ++c) { serving::Class* cl = classifications->add_classes(); if (classes) { cl->set_label((classes->matrix<string>())(i, c)); } if (scores) { cl->set_score((scores->matrix<float>())(i, c)); } } } return Status::OK(); } } // namespace serving } // namespace tensorflow <commit_msg>Return error if shape is wrong for classifier call. Change: 150025160<commit_after>/* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_serving/servables/tensorflow/classifier.h" #include <stddef.h> #include <algorithm> #include <functional> #include <memory> #include <string> #include <vector> #include "tensorflow/cc/saved_model/signature_constants.h" #include "tensorflow/contrib/session_bundle/signature.h" #include "tensorflow/core/example/example.pb.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/notification.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/platform/tracing.h" #include "tensorflow/core/platform/types.h" #include "tensorflow_serving/apis/classification.pb.h" #include "tensorflow_serving/apis/classifier.h" #include "tensorflow_serving/apis/input.pb.h" #include "tensorflow_serving/apis/model.pb.h" #include "tensorflow_serving/servables/tensorflow/util.h" namespace tensorflow { namespace serving { namespace { // Implementation of the ClassificationService using the legacy SessionBundle // ClassificationSignature signature format. class TensorFlowClassifier : public ClassifierInterface { public: explicit TensorFlowClassifier(Session* session, const ClassificationSignature* signature) : session_(session), signature_(signature) {} Status Classify(const ClassificationRequest& request, ClassificationResult* result) override { TRACELITERAL("TensorFlowClassifier::Classify"); TRACELITERAL("ConvertInputTFEXamplesToTensor"); // Setup the input Tensor to be a vector of string containing the serialized // tensorflow.Example. Tensor input_tensor; TF_RETURN_IF_ERROR( InputToSerializedExampleTensor(request.input(), &input_tensor)); const int num_examples = input_tensor.dim_size(0); if (num_examples == 0) { return errors::InvalidArgument("ClassificationRequest::input is empty."); } TRACELITERAL("RunClassification"); // Support serving models that return classes, scores or both. std::unique_ptr<Tensor> classes; if (!signature_->classes().tensor_name().empty()) { classes.reset(new Tensor); } std::unique_ptr<Tensor> scores; if (!signature_->scores().tensor_name().empty()) { scores.reset(new Tensor); } TF_RETURN_IF_ERROR(RunClassification(*signature_, input_tensor, session_, classes.get(), scores.get())); // Validate classes output Tensor. if (classes) { if (classes->dims() != 2) { return errors::InvalidArgument( "Expected Tensor shape: [batch_size num_classes] but got ", classes->shape().DebugString()); } if (classes->dtype() != DT_STRING) { return errors::Internal("Expected classes Tensor of DT_STRING. Got: ", DataType_Name(classes->dtype())); } if (classes->dim_size(0) != num_examples) { return errors::Internal("Expected output batch size of ", num_examples, ". Got: ", classes->dim_size(0)); } } // Validate scores output Tensor. if (scores) { if (scores->dtype() != DT_FLOAT) { return errors::Internal("Expected scores Tensor of DT_FLOAT. Got: ", DataType_Name(scores->dtype())); } if (scores->dim_size(0) != num_examples) { return errors::Internal("Expected output batch size of ", num_examples, ". Got: ", scores->dim_size(0)); } } // Extract the number of classes from either the class or score output // Tensor. int num_classes = 0; if (classes && scores) { // If we have both Tensors they should agree in the second dimmension. if (classes->dim_size(1) != scores->dim_size(1)) { return errors::Internal( "Tensors class and score should match in dim_size(1). Got ", classes->dim_size(1), " vs. ", scores->dim_size(1)); } num_classes = classes->dim_size(1); } else if (classes) { num_classes = classes->dim_size(1); } else if (scores) { num_classes = scores->dim_size(1); } TRACELITERAL("ConvertToClassificationResult"); // Convert the output to ClassificationResult format. for (int i = 0; i < num_examples; ++i) { serving::Classifications* classifications = result->add_classifications(); for (int c = 0; c < num_classes; ++c) { serving::Class* cl = classifications->add_classes(); if (classes) { cl->set_label((classes->matrix<string>())(i, c)); } if (scores) { cl->set_score((scores->matrix<float>())(i, c)); } } } return Status::OK(); } private: Session* const session_; const ClassificationSignature* const signature_; TF_DISALLOW_COPY_AND_ASSIGN(TensorFlowClassifier); }; // Implementation of the ClassifierInterface using SavedModel. class SavedModelTensorFlowClassifier : public ClassifierInterface { public: explicit SavedModelTensorFlowClassifier(Session* session, const SignatureDef* const signature) : session_(session), signature_(signature) {} ~SavedModelTensorFlowClassifier() override = default; Status Classify(const ClassificationRequest& request, ClassificationResult* result) override { TRACELITERAL("TensorFlowClassifier::Classify"); const int num_examples = NumInputExamples(request.input()); if (num_examples == 0) { return errors::InvalidArgument("ClassificationRequest::input is empty."); } string input_tensor_name; std::vector<string> output_tensor_names; TF_RETURN_IF_ERROR(PreProcessClassification(*signature_, &input_tensor_name, &output_tensor_names)); std::vector<Tensor> outputs; TF_RETURN_IF_ERROR(PerformOneShotTensorComputation( request.input(), input_tensor_name, output_tensor_names, session_, &outputs)); TRACELITERAL("ConvertToClassificationResult"); return PostProcessClassificationResult( *signature_, num_examples, output_tensor_names, outputs, result); } private: Session* const session_; const SignatureDef* const signature_; TF_DISALLOW_COPY_AND_ASSIGN(SavedModelTensorFlowClassifier); }; // Implementation of the ClassificationService. class SessionBundleClassifier : public ClassifierInterface { public: explicit SessionBundleClassifier(std::unique_ptr<SessionBundle> bundle) : bundle_(std::move(bundle)) {} ~SessionBundleClassifier() override = default; Status Classify(const ClassificationRequest& request, ClassificationResult* result) override { // Get the default signature of the graph. Expected to be a // classification signature. // TODO(b/26220896): Move TensorFlowClassifier creation to construction // time. ClassificationSignature signature; TF_RETURN_IF_ERROR( GetClassificationSignature(bundle_->meta_graph_def, &signature)); TensorFlowClassifier classifier(bundle_->session.get(), &signature); return classifier.Classify(request, result); } private: std::unique_ptr<SessionBundle> bundle_; TF_DISALLOW_COPY_AND_ASSIGN(SessionBundleClassifier); }; class SavedModelClassifier : public ClassifierInterface { public: explicit SavedModelClassifier(std::unique_ptr<SavedModelBundle> bundle) : bundle_(std::move(bundle)) {} ~SavedModelClassifier() override = default; Status Classify(const ClassificationRequest& request, ClassificationResult* result) override { // Get the default signature of the graph. Expected to be a // classification signature. // TODO(b/26220896): Move TensorFlowClassifier creation to construction // time. SignatureDef signature; TF_RETURN_IF_ERROR(GetClassificationSignatureDef( request.model_spec(), bundle_->meta_graph_def, &signature)); SavedModelTensorFlowClassifier classifier(bundle_->session.get(), &signature); return classifier.Classify(request, result); } private: std::unique_ptr<SavedModelBundle> bundle_; TF_DISALLOW_COPY_AND_ASSIGN(SavedModelClassifier); }; } // namespace Status CreateClassifierFromBundle( std::unique_ptr<SessionBundle> bundle, std::unique_ptr<ClassifierInterface>* service) { service->reset(new SessionBundleClassifier(std::move(bundle))); return Status::OK(); } Status CreateClassifierFromSavedModelBundle( std::unique_ptr<SavedModelBundle> bundle, std::unique_ptr<ClassifierInterface>* service) { service->reset(new SavedModelClassifier(std::move(bundle))); return Status::OK(); } Status CreateFlyweightTensorFlowClassifier( Session* session, const ClassificationSignature* const signature, std::unique_ptr<ClassifierInterface>* service) { service->reset(new TensorFlowClassifier(session, signature)); return Status::OK(); } Status CreateFlyweightTensorFlowClassifier( Session* session, const SignatureDef* signature, std::unique_ptr<ClassifierInterface>* service) { service->reset(new SavedModelTensorFlowClassifier(session, signature)); return Status::OK(); } Status GetClassificationSignatureDef(const ModelSpec& model_spec, const MetaGraphDef& meta_graph_def, SignatureDef* signature) { const string signature_name = model_spec.signature_name().empty() ? kDefaultServingSignatureDefKey : model_spec.signature_name(); auto iter = meta_graph_def.signature_def().find(signature_name); if (iter == meta_graph_def.signature_def().end()) { return errors::InvalidArgument(strings::StrCat( "No signature was found with the name: ", signature_name)); } if (iter->second.method_name() != kClassifyMethodName) { return errors::InvalidArgument(strings::StrCat( "Expected classification signature method_name to be ", kClassifyMethodName, ". Was: ", iter->second.method_name())); } *signature = iter->second; return Status::OK(); } Status PreProcessClassification(const SignatureDef& signature, string* input_tensor_name, std::vector<string>* output_tensor_names) { if (signature.method_name() != kClassifyMethodName) { return errors::InvalidArgument(strings::StrCat( "Expected classification signature method_name to be ", kClassifyMethodName, ". Was: ", signature.method_name())); } if (signature.inputs().size() != 1) { return errors::InvalidArgument( strings::StrCat("Expected one input Tensor.")); } if (signature.outputs().size() != 1 && signature.outputs().size() != 2) { return errors::InvalidArgument( strings::StrCat("Expected one or two output Tensors, found ", signature.outputs().size())); } auto input_iter = signature.inputs().find(kClassifyInputs); if (input_iter == signature.inputs().end()) { return errors::FailedPrecondition( "No classification inputs found in SignatureDef: ", signature.DebugString()); } *input_tensor_name = input_iter->second.name(); auto classes_iter = signature.outputs().find(kClassifyOutputClasses); auto scores_iter = signature.outputs().find(kClassifyOutputScores); if (classes_iter == signature.outputs().end() && scores_iter == signature.outputs().end()) { return errors::FailedPrecondition(strings::StrCat( "Expected classification signature outputs to contain at least one of ", "\"", kClassifyOutputClasses, "\" or \"", kClassifyOutputScores, "\". Signature was: ", signature.DebugString())); } if (classes_iter != signature.outputs().end()) { output_tensor_names->push_back(classes_iter->second.name()); } if (scores_iter != signature.outputs().end()) { output_tensor_names->push_back(scores_iter->second.name()); } return Status::OK(); } Status PostProcessClassificationResult( const SignatureDef& signature, int num_examples, const std::vector<string>& output_tensor_names, const std::vector<Tensor>& output_tensors, ClassificationResult* result) { if (output_tensors.size() != output_tensor_names.size()) { return errors::InvalidArgument( strings::StrCat("Expected ", output_tensor_names.size(), " output tensor(s). Got: ", output_tensors.size())); } auto classes_iter = signature.outputs().find(kClassifyOutputClasses); string classes_tensor_name; if (classes_iter != signature.outputs().end()) { classes_tensor_name = classes_iter->second.name(); } auto scores_iter = signature.outputs().find(kClassifyOutputScores); string scores_tensor_name; if (scores_iter != signature.outputs().end()) { scores_tensor_name = scores_iter->second.name(); } const Tensor* classes = nullptr; const Tensor* scores = nullptr; for (int i = 0; i < output_tensors.size(); ++i) { if (output_tensor_names[i] == classes_tensor_name) { classes = &output_tensors[i]; } else if (output_tensor_names[i] == scores_tensor_name) { scores = &output_tensors[i]; } } // Validate classes output Tensor. if (classes) { if (classes->dims() != 2) { return errors::InvalidArgument( "Expected Tensor shape: [batch_size num_classes] but got ", classes->shape().DebugString()); } if (classes->dtype() != DT_STRING) { return errors::InvalidArgument( "Expected classes Tensor of DT_STRING. Got: ", DataType_Name(classes->dtype())); } if (classes->dim_size(0) != num_examples) { return errors::InvalidArgument("Expected classes output batch size of ", num_examples, ". Got: ", classes->dim_size(0)); } } // Validate scores output Tensor. if (scores) { if (scores->dtype() != DT_FLOAT) { return errors::InvalidArgument( "Expected scores Tensor of DT_FLOAT. Got: ", DataType_Name(scores->dtype())); } if (scores->dim_size(0) != num_examples) { return errors::InvalidArgument("Expected scores output batch size of ", num_examples, ". Got: ", scores->dim_size(0)); } } // Extract the number of classes from either the class or score output // Tensor. int num_classes = 0; if (classes && scores) { // If we have both Tensors they should agree in the second dimmension. if (classes->dim_size(1) != scores->dim_size(1)) { return errors::InvalidArgument( "Tensors class and score should match in dim_size(1). Got ", classes->dim_size(1), " vs. ", scores->dim_size(1)); } num_classes = classes->dim_size(1); } else if (classes) { num_classes = classes->dim_size(1); } else if (scores) { num_classes = scores->dim_size(1); } // Convert the output to ClassificationResult format. for (int i = 0; i < num_examples; ++i) { serving::Classifications* classifications = result->add_classifications(); for (int c = 0; c < num_classes; ++c) { serving::Class* cl = classifications->add_classes(); if (classes) { cl->set_label((classes->matrix<string>())(i, c)); } if (scores) { cl->set_score((scores->matrix<float>())(i, c)); } } } return Status::OK(); } } // namespace serving } // namespace tensorflow <|endoftext|>
<commit_before>/** \brief A tool for installing IxTheo and KrimDok from scratch on Ubuntu and Centos systems. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2016 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <unistd.h> #include "Compiler.h" #include "ExecUtil.h" #include "FileUtil.h" #include "StringUtil.h" #include "util.h" void Usage() { std::cerr << "Usage: " << ::progname << " vufind_system_type\n"; std::cerr << " where \"vufind_system_type\" must be either \"krimdok\" or \"ixtheo\".\n\n"; std::exit(EXIT_FAILURE); } // Print a log message to the terminal with a bright green background. void Echo(const std::string &log_message) { std::cout << "\x1B" << "[42m--- " << log_message << "\x1B" << "[0m\n"; } enum VuFindSystemType { KRIMDOK, IXTHEO }; enum OSSystemType { UBUNTU, CENTOS }; static std::string master_password; OSSystemType DetermineOSSystemType() { std::string file_contents; if (FileUtil::ReadString("/etc/issue", &file_contents) and StringUtil::FindCaseInsensitive(file_contents, "ubuntu") != std::string::npos) return UBUNTU; if (FileUtil::ReadString("/etc/redhat-release", &file_contents) and StringUtil::FindCaseInsensitive(file_contents, "centos") != std::string::npos) return CENTOS; Error("you're probably not on an Ubuntu nor on a CentOS system!"); } void ExecOrDie(const std::string &command, const std::vector<std::string> &arguments) { int exit_code; if ((exit_code = ExecUtil::Exec(command, arguments)) != 0) Error("Failed to execute \"" + command + "\"! (exit code was " + std::to_string(exit_code) + ")"); } void MountLUKSContainerOrDie() { FileUtil::AutoTempFile key_file_temp_file; if (not FileUtil::WriteString(key_file_temp_file.getFilePath(), master_password)) Error("failed to write the master password into the temporary LUKS key file!"); const std::string LUKS_IMAGE_FILE("/usr/local/ub_tools/configs.ext4.luks"); const std::string LUKS_MOUNT_POINT("/usr/local/ub_tools/configs"); ExecOrDie(ExecUtil::Which("cryptsetup"), { "luksOpen", "--batch-mode", "--key-file", key_file_temp_file.getFilePath(), LUKS_IMAGE_FILE, "configs" }); ExecOrDie("/bin/mount", { "/dev/mapper/configs", LUKS_MOUNT_POINT }); } void ExecuteCommandSequence( const std::vector<std::pair<std::string, std::vector<std::string>>> &commands_and_arguments) { for (const auto &command_and_arguments : commands_and_arguments) ExecOrDie(command_and_arguments.first, command_and_arguments.second); } inline std::pair<std::string, std::vector<std::string>> CmdAndArgs(const std::string &command, const std::vector<std::string> &arguments) { return std::pair<std::string, std::vector<std::string>>(command, arguments); } void InstallUbuntuSoftwarePackages(const VuFindSystemType vufind_system_type) { const std::vector<std::pair<std::string, std::vector<std::string>>> &commands_and_arguments { CmdAndArgs("/usr/bin/add-apt-repository", { "--yes", "ppa:ubuntu-lxc/lxd-stable" }), CmdAndArgs("/usr/bin/apt", { "update" }), CmdAndArgs( "/usr/bin/apt", { "install", "--yes", "clang", "golang", "wget", "curl", "git", "apache2", "libapache2-mod-gnutls", "mysql-server", "php7.0", "php7.0-dev", "php-pear", "php7.0-json", "php7.0-ldap", "php7.0-mcrypt", "php7.0-mysql", "php7.0-xsl", "php7.0-intl", "php7.0-gd", "libapache2-mod-php7.0", "composer", "openjdk-8-jdk", "libmagic-dev", "libpcre3-dev", "libssl-dev", "libkyotocabinet-dev", "mutt", "libxml2-dev", "libmysqlclient-dev", "libcurl4-openssl-dev", "ant", "libtokyocabinet-dev", "liblz4-tool", "libarchive-dev", "libboost-all-dev", "clang-3.8", "clang++-3.8", "clang", "golang" }), CmdAndArgs("/usr/sbin/a2enmod", { "rewrite" }), CmdAndArgs("/usr/sbin/phpenmod", { "mcrypt" }), CmdAndArgs("/etc/init.d/apache2", { "restart" }), // CmdAndArgs("mysql_secure_installation", { }), }; ExecuteCommandSequence(commands_and_arguments); // If installing a KrimDok system we need tesseract: if (vufind_system_type == KRIMDOK) ExecOrDie("/usr/bin/apt", { "install", "--yes", "tesseract-ocr-all" }); } void InstallCentOSSoftwarePackages(const VuFindSystemType vufind_system_type) { const std::vector<std::pair<std::string, std::vector<std::string>>> &commands_and_arguments { CmdAndArgs("/bin/yum", { "update" }), CmdAndArgs("/bin/yum", { "-y", "install", "epel-release" }), CmdAndArgs( "/bin/yum", { "-y", "install", "mawk", "git", "mariadb", "mariadb-server", "httpd", "php", "php-devel", "php-mcrypt", "php-intl", "php-ldap", "php-mysql", "php-xsl", "php-gd", "php-mbstring", "php-mcrypt", "java-*-openjdk-devel", "mawk", "mod_ssl", "epel-release", "wget", "policycoreutils-python" }), CmdAndArgs("systemctl", { "start", "mariadb.service" }), CmdAndArgs("mysql_secure_installation", { }), CmdAndArgs( "/bin/wget", { "http://download.opensuse.org/repositories/security:shibboleth/CentOS_7/security:shibboleth.repo", "--directory-prefix=/etc/yum.repos.d/" }), CmdAndArgs( "/bin/yum", { "-y", "install", "curl-openssl", "mutt", "golang", "lsof", "clang", "gcc-c++.x86_64", "file-devel", "pcre-devel", "openssl-devel", "kyotocabinet-devel", "tokyocabinet-devel", "poppler-utils", "libwebp", "mariadb-devel.x86_64", "libxml2-devel.x86_64", "libcurl-openssl-devel.x86_64", "ant", "lz4", "unzip", "libarchive-devel", "boost-devel" }), CmdAndArgs( "/bin/ln", { "-s", "/usr/share/tessdata/deu.traineddata", "/usr/share/tesseract/tessdata/deu.traineddata" }), }; ExecuteCommandSequence(commands_and_arguments); if (vufind_system_type == KRIMDOK) { std::vector<std::string> rpm_package_install_args; FileUtil::GetFileNameList("*.\\\\.rpm", &rpm_package_install_args, "/mnt/ZE020150/IT-Abteilung/02_Projekte/11_KrimDok_neu/05_Pakete/"); rpm_package_install_args.insert(rpm_package_install_args.begin(), "-y"); rpm_package_install_args.insert(rpm_package_install_args.begin(), "install"); ExecOrDie("/bin/yum", rpm_package_install_args); } } void InstallSoftwarePackages(const OSSystemType os_system_type, const VuFindSystemType vufind_system_type) { if (os_system_type == UBUNTU) InstallUbuntuSoftwarePackages(vufind_system_type); else InstallCentOSSoftwarePackages(vufind_system_type); Echo("installed software packages"); } void GetMasterPassword() { errno = 0; master_password = ::getpass("Master password >"); if (errno != 0) Error("failed to read the password from the terminal!"); } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 2) Usage(); if (::geteuid() != 0) Error("you must execute this program as root!"); GetMasterPassword(); VuFindSystemType vufind_system_type; if (::strcasecmp(argv[1], "krimdok") == 0) vufind_system_type = KRIMDOK; else if (::strcasecmp(argv[1], "ixtheo") == 0) vufind_system_type = IXTHEO; else Error("system type must be either \"krimdok\" or \"ixtheo\"!"); const OSSystemType os_system_type(DetermineOSSystemType()); try { MountLUKSContainerOrDie(); InstallSoftwarePackages(os_system_type, vufind_system_type); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <commit_msg>Work in progress.<commit_after>/** \brief A tool for installing IxTheo and KrimDok from scratch on Ubuntu and Centos systems. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2016 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <unistd.h> #include "Compiler.h" #include "ExecUtil.h" #include "FileUtil.h" #include "StringUtil.h" #include "util.h" void Usage() { std::cerr << "Usage: " << ::progname << " vufind_system_type\n"; std::cerr << " where \"vufind_system_type\" must be either \"krimdok\" or \"ixtheo\".\n\n"; std::exit(EXIT_FAILURE); } // Print a log message to the terminal with a bright green background. void Echo(const std::string &log_message) { std::cout << "\x1B" << "[42m--- " << log_message << "\x1B" << "[0m\n"; } enum VuFindSystemType { KRIMDOK, IXTHEO }; enum OSSystemType { UBUNTU, CENTOS }; static std::string master_password; OSSystemType DetermineOSSystemType() { std::string file_contents; if (FileUtil::ReadString("/etc/issue", &file_contents) and StringUtil::FindCaseInsensitive(file_contents, "ubuntu") != std::string::npos) return UBUNTU; if (FileUtil::ReadString("/etc/redhat-release", &file_contents) and StringUtil::FindCaseInsensitive(file_contents, "centos") != std::string::npos) return CENTOS; Error("you're probably not on an Ubuntu nor on a CentOS system!"); } void ExecOrDie(const std::string &command, const std::vector<std::string> &arguments) { int exit_code; if ((exit_code = ExecUtil::Exec(command, arguments)) != 0) Error("Failed to execute \"" + command + "\"! (exit code was " + std::to_string(exit_code) + ")"); } void MountLUKSContainerOrDie() { FileUtil::AutoTempFile key_file_temp_file; if (not FileUtil::WriteString(key_file_temp_file.getFilePath(), master_password)) Error("failed to write the master password into the temporary LUKS key file!"); const std::string LUKS_IMAGE_FILE("/usr/local/ub_tools/configs.ext4.luks"); const std::string LUKS_MOUNT_POINT("/usr/local/ub_tools/configs"); ExecOrDie(ExecUtil::Which("cryptsetup"), { "luksOpen", "--batch-mode", "--key-file", key_file_temp_file.getFilePath(), LUKS_IMAGE_FILE, "configs" }); ExecOrDie("/bin/mount", { "/dev/mapper/configs", LUKS_MOUNT_POINT }); } void ExecuteCommandSequence( const std::vector<std::pair<std::string, std::vector<std::string>>> &commands_and_arguments) { for (const auto &command_and_arguments : commands_and_arguments) ExecOrDie(command_and_arguments.first, command_and_arguments.second); } inline std::pair<std::string, std::vector<std::string>> CmdAndArgs(const std::string &command, const std::vector<std::string> &arguments) { return std::pair<std::string, std::vector<std::string>>(command, arguments); } void InstallUbuntuSoftwarePackages(const VuFindSystemType vufind_system_type) { const std::vector<std::pair<std::string, std::vector<std::string>>> &commands_and_arguments { CmdAndArgs("/usr/bin/add-apt-repository", { "--yes", "ppa:ubuntu-lxc/lxd-stable" }), CmdAndArgs("/usr/bin/apt", { "update" }), CmdAndArgs( "/usr/bin/apt", { "install", "--yes", "clang", "golang", "wget", "curl", "git", "apache2", "libapache2-mod-gnutls", "mysql-server", "php7.0", "php7.0-dev", "php-pear", "php7.0-json", "php7.0-ldap", "php7.0-mcrypt", "php7.0-mysql", "php7.0-xsl", "php7.0-intl", "php7.0-gd", "libapache2-mod-php7.0", "composer", "openjdk-8-jdk", "libmagic-dev", "libpcre3-dev", "libssl-dev", "libkyotocabinet-dev", "mutt", "libxml2-dev", "libmysqlclient-dev", "libcurl4-openssl-dev", "ant", "libtokyocabinet-dev", "liblz4-tool", "libarchive-dev", "libboost-all-dev", "clang-3.8", "clang++-3.8", "clang", "golang" }), CmdAndArgs("/usr/sbin/a2enmod", { "rewrite" }), CmdAndArgs("/usr/sbin/phpenmod", { "mcrypt" }), CmdAndArgs("/etc/init.d/apache2", { "restart" }), // CmdAndArgs("mysql_secure_installation", { }), }; ExecuteCommandSequence(commands_and_arguments); // If installing a KrimDok system we need tesseract: if (vufind_system_type == KRIMDOK) ExecOrDie("/usr/bin/apt", { "install", "--yes", "tesseract-ocr-all" }); } void InstallCentOSSoftwarePackages(const VuFindSystemType vufind_system_type) { const std::vector<std::pair<std::string, std::vector<std::string>>> &commands_and_arguments { CmdAndArgs("/bin/yum", { "update" }), CmdAndArgs("/bin/yum", { "-y", "install", "epel-release" }), CmdAndArgs( "/bin/yum", { "-y", "install", "mawk", "git", "mariadb", "mariadb-server", "httpd", "php", "php-devel", "php-mcrypt", "php-intl", "php-ldap", "php-mysql", "php-xsl", "php-gd", "php-mbstring", "php-mcrypt", "java-*-openjdk-devel", "mawk", "mod_ssl", "epel-release", "wget", "policycoreutils-python" }), CmdAndArgs("systemctl", { "start", "mariadb.service" }), CmdAndArgs("mysql_secure_installation", { }), CmdAndArgs( "/bin/wget", { "http://download.opensuse.org/repositories/security:shibboleth/CentOS_7/security:shibboleth.repo", "--directory-prefix=/etc/yum.repos.d/" }), CmdAndArgs( "/bin/yum", { "-y", "install", "curl-openssl", "mutt", "golang", "lsof", "clang", "gcc-c++.x86_64", "file-devel", "pcre-devel", "openssl-devel", "kyotocabinet-devel", "tokyocabinet-devel", "poppler-utils", "libwebp", "mariadb-devel.x86_64", "libxml2-devel.x86_64", "libcurl-openssl-devel.x86_64", "ant", "lz4", "unzip", "libarchive-devel", "boost-devel" }), CmdAndArgs( "/bin/ln", { "-s", "/usr/share/tessdata/deu.traineddata", "/usr/share/tesseract/tessdata/deu.traineddata" }), }; ExecuteCommandSequence(commands_and_arguments); if (vufind_system_type == KRIMDOK) { std::vector<std::string> rpm_package_install_args; FileUtil::GetFileNameList("*.\\\\.rpm", &rpm_package_install_args, "/mnt/ZE020150/IT-Abteilung/02_Projekte/11_KrimDok_neu/05_Pakete/"); rpm_package_install_args.insert(rpm_package_install_args.begin(), "-y"); rpm_package_install_args.insert(rpm_package_install_args.begin(), "install"); ExecOrDie("/bin/yum", rpm_package_install_args); } } void InstallSoftwarePackages(const OSSystemType os_system_type, const VuFindSystemType vufind_system_type) { if (os_system_type == UBUNTU) InstallUbuntuSoftwarePackages(vufind_system_type); else InstallCentOSSoftwarePackages(vufind_system_type); Echo("installed software packages"); } void ChangeDirectoryOrDie(const std::string &new_working_directory) { if (::chdir(new_working_directory.c_str()) != 0) Error("failed to set the new working directory to \"" + new_working_directory + "\"! (" + std::string(::strerror(errno)) + ")"); } void InstallUBTools() { const std::string UB_TOOLS_DIRECTORY("/usr/local/ub_tools"); ExecOrDie(ExecUtil::Which("git"), { "clone", "https://github.com/ubtue/ub_tools.git", UB_TOOLS_DIRECTORY }); ChangeDirectoryOrDie(UB_TOOLS_DIRECTORY); ExecOrDie(ExecUtil::Which("make"), { "install" }); } void GetMasterPassword() { errno = 0; master_password = ::getpass("Master password >"); if (errno != 0) Error("failed to read the password from the terminal!"); } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 2) Usage(); if (::geteuid() != 0) Error("you must execute this program as root!"); GetMasterPassword(); VuFindSystemType vufind_system_type; if (::strcasecmp(argv[1], "krimdok") == 0) vufind_system_type = KRIMDOK; else if (::strcasecmp(argv[1], "ixtheo") == 0) vufind_system_type = IXTHEO; else Error("system type must be either \"krimdok\" or \"ixtheo\"!"); const OSSystemType os_system_type(DetermineOSSystemType()); try { MountLUKSContainerOrDie(); InstallSoftwarePackages(os_system_type, vufind_system_type); InstallUBTools(); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>/** \brief Utility for two collections of MARC records. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <map> #include <stdexcept> #include <unordered_map> #include <vector> #include <cstdio> #include <cstdlib> #include "FileUtil.h" #include "MARC.h" #include "util.h" namespace { static void Usage() __attribute__((noreturn)); static void Usage() { std::cerr << "Usage: " << ::progname << " [--verbose] marc_collection1 marc_collection2\n"; std::exit(EXIT_FAILURE); } unsigned LoadMap(MARC::Reader * const marc_reader, std::unordered_map<std::string, off_t> * const control_number_to_offset_map) { unsigned record_count(0); while (const MARC::Record record = marc_reader->read()) { ++record_count; (*control_number_to_offset_map)[record.getControlNumber()] = marc_reader->tell(); } return record_count; } void EmitDetailedReport(const std::string &/*collection1_name*/, const std::string &/*collection2_name*/, const std::unordered_map<std::string, off_t> &/*control_number_to_offset_map1*/, const std::unordered_map<std::string, off_t> &/*control_number_to_offset_map2*/, MARC::Reader * const /*reader1*/, MARC::Reader * const /*reader2*/) { } inline void InitSortedControlNumbersList(const std::unordered_map<std::string, off_t> &control_number_to_offset_map, std::vector<std::string> * const sorted_control_numbers) { sorted_control_numbers->clear(); sorted_control_numbers->reserve(control_number_to_offset_map.size()); for (const auto &control_number_and_offset : control_number_to_offset_map) sorted_control_numbers->emplace_back(control_number_and_offset.first); std::sort(sorted_control_numbers->begin(), sorted_control_numbers->end()); } void EmitStandardReport(const std::string &collection1_name, const std::string &collection2_name, const unsigned collection1_size, const unsigned collection2_size, const std::unordered_map<std::string, off_t> &control_number_to_offset_map1, const std::unordered_map<std::string, off_t> &control_number_to_offset_map2) { std::vector<std::string> sorted_control_numbers1; InitSortedControlNumbersList(control_number_to_offset_map1, &sorted_control_numbers1); std::vector<std::string> sorted_control_numbers2; InitSortedControlNumbersList(control_number_to_offset_map2, &sorted_control_numbers2); unsigned in_map1_only_count(0), in_map2_only_count(0); auto control_number1(sorted_control_numbers1.cbegin()); auto control_number2(sorted_control_numbers2.cbegin()); while (control_number1 != sorted_control_numbers1.cend() and control_number2 != sorted_control_numbers2.cend()) { if (*control_number1 == *control_number2) { ++control_number1; ++control_number2; } else if (*control_number1 < *control_number2) { ++in_map1_only_count; ++control_number1; } else { // *control_number2 < *control_number1 ++in_map2_only_count; ++control_number2; } } in_map1_only_count += sorted_control_numbers1.cend() - control_number1; in_map2_only_count += sorted_control_numbers2.cend() - control_number2; std::cout << '"' << collection1_name << "\" contains " << collection1_size << " record(s).\n"; std::cout << '"' << collection2_name << "\" contains " << collection2_size << " record(s).\n"; std::cout << in_map1_only_count << " control number(s) are only in \"" << collection1_name << "\" but not in \"" << collection2_name << "\".\n"; std::cout << in_map2_only_count << " control number(s) are only in \"" << collection2_name << "\" but not in \"" << collection1_name << "\".\n"; std::cout << (collection1_size - in_map1_only_count) << " are in both collections.\n"; } } // unnamed namespace int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc < 3) Usage(); const bool verbose(std::strcmp(argv[1], "--verbose") == 0); if (verbose) --argc, ++argv; if (argc != 3) Usage(); try { const std::string collection1_name(argv[1]); const std::string collection2_name(argv[2]); std::unique_ptr<MARC::Reader> marc_reader1(MARC::Reader::Factory(collection1_name)); std::unique_ptr<MARC::Reader> marc_reader2(MARC::Reader::Factory(collection2_name)); std::unordered_map<std::string, off_t> control_number_to_offset_map1; const unsigned collection1_size(LoadMap(marc_reader1.get(), &control_number_to_offset_map1)); std::unordered_map<std::string, off_t> control_number_to_offset_map2; const unsigned collection2_size(LoadMap(marc_reader2.get(), &control_number_to_offset_map2)); if (verbose) EmitDetailedReport(collection1_name, collection2_name, control_number_to_offset_map1, control_number_to_offset_map2, marc_reader1.get(), marc_reader2.get()); EmitStandardReport(collection1_name, collection2_name, collection1_size, collection2_size, control_number_to_offset_map1, control_number_to_offset_map2); } catch (const std::exception &e) { ERROR("Caught exception: " + std::string(e.what())); } } <commit_msg>Only reformatting.<commit_after>/** \brief Utility for two collections of MARC records. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <map> #include <stdexcept> #include <unordered_map> #include <vector> #include <cstdio> #include <cstdlib> #include "FileUtil.h" #include "MARC.h" #include "util.h" namespace { static void Usage() __attribute__((noreturn)); static void Usage() { std::cerr << "Usage: " << ::progname << " [--verbose] marc_collection1 marc_collection2\n"; std::exit(EXIT_FAILURE); } unsigned LoadMap(MARC::Reader * const marc_reader, std::unordered_map<std::string, off_t> * const control_number_to_offset_map) { unsigned record_count(0); while (const MARC::Record record = marc_reader->read()) { ++record_count; (*control_number_to_offset_map)[record.getControlNumber()] = marc_reader->tell(); } return record_count; } void EmitDetailedReport(const std::string &/*collection1_name*/, const std::string &/*collection2_name*/, const std::unordered_map<std::string, off_t> &/*control_number_to_offset_map1*/, const std::unordered_map<std::string, off_t> &/*control_number_to_offset_map2*/, MARC::Reader * const /*reader1*/, MARC::Reader * const /*reader2*/) { } inline void InitSortedControlNumbersList(const std::unordered_map<std::string, off_t> &control_number_to_offset_map, std::vector<std::string> * const sorted_control_numbers) { sorted_control_numbers->clear(); sorted_control_numbers->reserve(control_number_to_offset_map.size()); for (const auto &control_number_and_offset : control_number_to_offset_map) sorted_control_numbers->emplace_back(control_number_and_offset.first); std::sort(sorted_control_numbers->begin(), sorted_control_numbers->end()); } void EmitStandardReport(const std::string &collection1_name, const std::string &collection2_name, const unsigned collection1_size, const unsigned collection2_size, const std::unordered_map<std::string, off_t> &control_number_to_offset_map1, const std::unordered_map<std::string, off_t> &control_number_to_offset_map2) { std::vector<std::string> sorted_control_numbers1; InitSortedControlNumbersList(control_number_to_offset_map1, &sorted_control_numbers1); std::vector<std::string> sorted_control_numbers2; InitSortedControlNumbersList(control_number_to_offset_map2, &sorted_control_numbers2); unsigned in_map1_only_count(0), in_map2_only_count(0); auto control_number1(sorted_control_numbers1.cbegin()); auto control_number2(sorted_control_numbers2.cbegin()); while (control_number1 != sorted_control_numbers1.cend() and control_number2 != sorted_control_numbers2.cend()) { if (*control_number1 == *control_number2) { ++control_number1; ++control_number2; } else if (*control_number1 < *control_number2) { ++in_map1_only_count; ++control_number1; } else { // *control_number2 < *control_number1 ++in_map2_only_count; ++control_number2; } } in_map1_only_count += sorted_control_numbers1.cend() - control_number1; in_map2_only_count += sorted_control_numbers2.cend() - control_number2; std::cout << '"' << collection1_name << "\" contains " << collection1_size << " record(s).\n"; std::cout << '"' << collection2_name << "\" contains " << collection2_size << " record(s).\n"; std::cout << in_map1_only_count << " control number(s) are only in \"" << collection1_name << "\" but not in \"" << collection2_name << "\".\n"; std::cout << in_map2_only_count << " control number(s) are only in \"" << collection2_name << "\" but not in \"" << collection1_name << "\".\n"; std::cout << (collection1_size - in_map1_only_count) << " are in both collections.\n"; } } // unnamed namespace int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc < 3) Usage(); const bool verbose(std::strcmp(argv[1], "--verbose") == 0); if (verbose) --argc, ++argv; if (argc != 3) Usage(); try { const std::string collection1_name(argv[1]); const std::string collection2_name(argv[2]); std::unique_ptr<MARC::Reader> marc_reader1(MARC::Reader::Factory(collection1_name)); std::unique_ptr<MARC::Reader> marc_reader2(MARC::Reader::Factory(collection2_name)); std::unordered_map<std::string, off_t> control_number_to_offset_map1; const unsigned collection1_size(LoadMap(marc_reader1.get(), &control_number_to_offset_map1)); std::unordered_map<std::string, off_t> control_number_to_offset_map2; const unsigned collection2_size(LoadMap(marc_reader2.get(), &control_number_to_offset_map2)); if (verbose) EmitDetailedReport(collection1_name, collection2_name, control_number_to_offset_map1, control_number_to_offset_map2, marc_reader1.get(), marc_reader2.get()); EmitStandardReport(collection1_name, collection2_name, collection1_size, collection2_size, control_number_to_offset_map1, control_number_to_offset_map2); } catch (const std::exception &e) { ERROR("Caught exception: " + std::string(e.what())); } } <|endoftext|>
<commit_before>#include "AppDelegate.h" #include "cocos2d.h" #include "SimpleAudioEngine.h" #include "ScriptingCore.h" #include "jsb_cocos2dx_auto.hpp" #include "jsb_cocos2dx_extension_auto.hpp" #include "jsb_cocos2dx_builder_auto.hpp" #include "jsb_cocos2dx_spine_auto.hpp" #include "jsb_cocos2dx_3d_auto.hpp" #include "3d/jsb_cocos2dx_3d_manual.h" #include "extension/jsb_cocos2dx_extension_manual.h" #include "cocostudio/jsb_cocos2dx_studio_manual.h" #include "jsb_cocos2dx_studio_auto.hpp" #include "jsb_cocos2dx_ui_auto.hpp" #include "ui/jsb_cocos2dx_ui_manual.h" #include "spine/jsb_cocos2dx_spine_manual.h" #include "cocos2d_specifics.hpp" #include "cocosbuilder/cocosbuilder_specifics.hpp" #include "chipmunk/js_bindings_chipmunk_registration.h" #include "localstorage/js_bindings_system_registration.h" #include "jsb_opengl_registration.h" #include "network/XMLHTTPRequest.h" #include "network/jsb_websocket.h" #include "network/jsb_socketio.h" #include "cocosbuilder/js_bindings_ccbreader.h" #include "js_DrawNode3D_bindings.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include "jsb_cocos2dx_pluginx_auto.hpp" #include "jsb_pluginx_extension_registration.h" #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include "platform/android/CCJavascriptJavaBridge.h" #elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) #include "platform/ios/JavaScriptObjCBridge.h" #endif #if(CC_TARGET_PLATFORM != CC_PLATFORM_WP8) #include "js_Effect3D_bindings.h" #endif USING_NS_CC; USING_NS_CC_EXT; using namespace CocosDenshion; AppDelegate::AppDelegate() { } AppDelegate::~AppDelegate() { ScriptEngineManager::destroyInstance(); } void AppDelegate::initGLContextAttrs() { GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; GLView::setGLContextAttrs(glContextAttrs); } bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); auto glview = director->getOpenGLView(); if(!glview) { #if(CC_TARGET_PLATFORM == CC_PLATFORM_WP8) glview = cocos2d::GLViewImpl::create("js-tests"); #else glview = cocos2d::GLViewImpl::createWithRect("js-tests", Rect(0,0,900,640)); #endif director->setOpenGLView(glview); } // set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0 / 60); ScriptingCore* sc = ScriptingCore::getInstance(); sc->addRegisterCallback(register_all_cocos2dx); sc->addRegisterCallback(register_cocos2dx_js_core); sc->addRegisterCallback(register_cocos2dx_js_extensions); sc->addRegisterCallback(jsb_register_system); sc->addRegisterCallback(register_all_cocos2dx_extension); sc->addRegisterCallback(register_all_cocos2dx_extension_manual); sc->addRegisterCallback(jsb_register_chipmunk); sc->addRegisterCallback(JSB_register_opengl); sc->addRegisterCallback(MinXmlHttpRequest::_js_register); sc->addRegisterCallback(register_jsb_websocket); sc->addRegisterCallback(register_jsb_socketio); sc->addRegisterCallback(register_all_cocos2dx_builder); sc->addRegisterCallback(register_CCBuilderReader); sc->addRegisterCallback(register_all_cocos2dx_ui); sc->addRegisterCallback(register_all_cocos2dx_ui_manual); sc->addRegisterCallback(register_all_cocos2dx_studio); sc->addRegisterCallback(register_all_cocos2dx_studio_manual); sc->addRegisterCallback(register_all_cocos2dx_spine); sc->addRegisterCallback(register_all_cocos2dx_spine_manual); sc->addRegisterCallback(register_all_cocos2dx_3d); sc->addRegisterCallback(register_all_cocos2dx_3d_manual); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) sc->addRegisterCallback(register_all_pluginx_protocols); sc->addRegisterCallback(register_pluginx_js_extensions); #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) sc->addRegisterCallback(JavascriptJavaBridge::_js_register); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) sc->addRegisterCallback(JavaScriptObjCBridge::_js_register); #endif sc->addRegisterCallback(register_DrawNode3D_bindings); #if(CC_TARGET_PLATFORM != CC_PLATFORM_WP8) sc->addRegisterCallback(register_Effect3D_bindings); #endif sc->start(); sc->runScript("script/jsb_boot.js"); #if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) sc->enableDebugger(); #endif auto pEngine = ScriptingCore::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(pEngine); ScriptingCore::getInstance()->runScript("main.js"); return true; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { auto director = Director::getInstance(); director->stopAnimation(); director->getEventDispatcher()->dispatchCustomEvent("game_on_hide"); SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); SimpleAudioEngine::getInstance()->pauseAllEffects(); } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { auto director = Director::getInstance(); director->startAnimation(); director->getEventDispatcher()->dispatchCustomEvent("game_on_show"); SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); SimpleAudioEngine::getInstance()->resumeAllEffects(); } <commit_msg>added CC_PLATFORM_WINRT<commit_after>#include "AppDelegate.h" #include "cocos2d.h" #include "SimpleAudioEngine.h" #include "ScriptingCore.h" #include "jsb_cocos2dx_auto.hpp" #include "jsb_cocos2dx_extension_auto.hpp" #include "jsb_cocos2dx_builder_auto.hpp" #include "jsb_cocos2dx_spine_auto.hpp" #include "jsb_cocos2dx_3d_auto.hpp" #include "3d/jsb_cocos2dx_3d_manual.h" #include "extension/jsb_cocos2dx_extension_manual.h" #include "cocostudio/jsb_cocos2dx_studio_manual.h" #include "jsb_cocos2dx_studio_auto.hpp" #include "jsb_cocos2dx_ui_auto.hpp" #include "ui/jsb_cocos2dx_ui_manual.h" #include "spine/jsb_cocos2dx_spine_manual.h" #include "cocos2d_specifics.hpp" #include "cocosbuilder/cocosbuilder_specifics.hpp" #include "chipmunk/js_bindings_chipmunk_registration.h" #include "localstorage/js_bindings_system_registration.h" #include "jsb_opengl_registration.h" #include "network/XMLHTTPRequest.h" #include "network/jsb_websocket.h" #include "network/jsb_socketio.h" #include "cocosbuilder/js_bindings_ccbreader.h" #include "js_DrawNode3D_bindings.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include "jsb_cocos2dx_pluginx_auto.hpp" #include "jsb_pluginx_extension_registration.h" #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include "platform/android/CCJavascriptJavaBridge.h" #elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) #include "platform/ios/JavaScriptObjCBridge.h" #endif #if(CC_TARGET_PLATFORM != CC_PLATFORM_WP8) #include "js_Effect3D_bindings.h" #endif USING_NS_CC; USING_NS_CC_EXT; using namespace CocosDenshion; AppDelegate::AppDelegate() { } AppDelegate::~AppDelegate() { ScriptEngineManager::destroyInstance(); } void AppDelegate::initGLContextAttrs() { GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; GLView::setGLContextAttrs(glContextAttrs); } bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); auto glview = director->getOpenGLView(); if(!glview) { #if(CC_TARGET_PLATFORM == CC_PLATFORM_WP8 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) glview = cocos2d::GLViewImpl::create("js-tests"); #else glview = cocos2d::GLViewImpl::createWithRect("js-tests", Rect(0,0,900,640)); #endif director->setOpenGLView(glview); } // set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0 / 60); ScriptingCore* sc = ScriptingCore::getInstance(); sc->addRegisterCallback(register_all_cocos2dx); sc->addRegisterCallback(register_cocos2dx_js_core); sc->addRegisterCallback(register_cocos2dx_js_extensions); sc->addRegisterCallback(jsb_register_system); sc->addRegisterCallback(register_all_cocos2dx_extension); sc->addRegisterCallback(register_all_cocos2dx_extension_manual); sc->addRegisterCallback(jsb_register_chipmunk); sc->addRegisterCallback(JSB_register_opengl); sc->addRegisterCallback(MinXmlHttpRequest::_js_register); sc->addRegisterCallback(register_jsb_websocket); sc->addRegisterCallback(register_jsb_socketio); sc->addRegisterCallback(register_all_cocos2dx_builder); sc->addRegisterCallback(register_CCBuilderReader); sc->addRegisterCallback(register_all_cocos2dx_ui); sc->addRegisterCallback(register_all_cocos2dx_ui_manual); sc->addRegisterCallback(register_all_cocos2dx_studio); sc->addRegisterCallback(register_all_cocos2dx_studio_manual); sc->addRegisterCallback(register_all_cocos2dx_spine); sc->addRegisterCallback(register_all_cocos2dx_spine_manual); sc->addRegisterCallback(register_all_cocos2dx_3d); sc->addRegisterCallback(register_all_cocos2dx_3d_manual); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) sc->addRegisterCallback(register_all_pluginx_protocols); sc->addRegisterCallback(register_pluginx_js_extensions); #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) sc->addRegisterCallback(JavascriptJavaBridge::_js_register); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) sc->addRegisterCallback(JavaScriptObjCBridge::_js_register); #endif sc->addRegisterCallback(register_DrawNode3D_bindings); #if(CC_TARGET_PLATFORM != CC_PLATFORM_WP8) sc->addRegisterCallback(register_Effect3D_bindings); #endif sc->start(); sc->runScript("script/jsb_boot.js"); #if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) sc->enableDebugger(); #endif auto pEngine = ScriptingCore::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(pEngine); ScriptingCore::getInstance()->runScript("main.js"); return true; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { auto director = Director::getInstance(); director->stopAnimation(); director->getEventDispatcher()->dispatchCustomEvent("game_on_hide"); SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); SimpleAudioEngine::getInstance()->pauseAllEffects(); } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { auto director = Director::getInstance(); director->startAnimation(); director->getEventDispatcher()->dispatchCustomEvent("game_on_show"); SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); SimpleAudioEngine::getInstance()->resumeAllEffects(); } <|endoftext|>
<commit_before>/* * Copyright (C) 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. * * 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 <tntdb/stmtparser.h> #include <cxxtools/log.h> log_define("tntdb.stmtparser") namespace tntdb { void StmtParser::parse(const std::string& sqlIn, StmtEvent& event) { { enum state_type { STATE_0, STATE_NAME0, STATE_NAME, STATE_STRING, STATE_STRING_ESC, STATE_ESC } state = STATE_0; std::string name; sql.clear(); char end_token; log_debug("parse sql \"" << sqlIn << "\""); for (std::string::const_iterator it = sqlIn.begin(); it != sqlIn.end(); ++it) { char ch = *it; switch(state) { case STATE_0: if (ch == ':') state = STATE_NAME0; else if (ch == '\\') state = STATE_ESC; else { sql += ch; if (ch == '\'' || ch == '"' || ch == '`') { state = STATE_STRING; end_token = ch; } } break; case STATE_NAME0: if (std::isalpha(ch)) { name = ch; state = STATE_NAME; } else if (ch == ':') sql += ':'; else if (ch == '\\') { sql += ':'; state = STATE_ESC; } break; case STATE_NAME: if (std::isalnum(ch) || ch == '_') name += ch; else { log_debug("hostvar :" << name); sql += event.onHostVar(name); if (ch == '\\') state = STATE_ESC; else { sql += ch; state = STATE_0; } } break; case STATE_STRING: sql += ch; if (ch == end_token) state = STATE_0; else if (ch == '\\') state = STATE_STRING_ESC; break; case STATE_STRING_ESC: sql += ch; state = STATE_STRING; break; case STATE_ESC: sql += ch; state = STATE_0; break; } } switch(state) { case STATE_NAME0: sql += ':'; break; case STATE_NAME: log_debug("hostvar :" << name); sql += event.onHostVar(name); break; default: ; } } } } <commit_msg>add missing include<commit_after>/* * Copyright (C) 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. * * 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 <tntdb/stmtparser.h> #include <cxxtools/log.h> #include <cctype> log_define("tntdb.stmtparser") namespace tntdb { void StmtParser::parse(const std::string& sqlIn, StmtEvent& event) { { enum state_type { STATE_0, STATE_NAME0, STATE_NAME, STATE_STRING, STATE_STRING_ESC, STATE_ESC } state = STATE_0; std::string name; sql.clear(); char end_token; log_debug("parse sql \"" << sqlIn << "\""); for (std::string::const_iterator it = sqlIn.begin(); it != sqlIn.end(); ++it) { char ch = *it; switch(state) { case STATE_0: if (ch == ':') state = STATE_NAME0; else if (ch == '\\') state = STATE_ESC; else { sql += ch; if (ch == '\'' || ch == '"' || ch == '`') { state = STATE_STRING; end_token = ch; } } break; case STATE_NAME0: if (std::isalpha(ch)) { name = ch; state = STATE_NAME; } else if (ch == ':') sql += ':'; else if (ch == '\\') { sql += ':'; state = STATE_ESC; } break; case STATE_NAME: if (std::isalnum(ch) || ch == '_') name += ch; else { log_debug("hostvar :" << name); sql += event.onHostVar(name); if (ch == '\\') state = STATE_ESC; else { sql += ch; state = STATE_0; } } break; case STATE_STRING: sql += ch; if (ch == end_token) state = STATE_0; else if (ch == '\\') state = STATE_STRING_ESC; break; case STATE_STRING_ESC: sql += ch; state = STATE_STRING; break; case STATE_ESC: sql += ch; state = STATE_0; break; } } switch(state) { case STATE_NAME0: sql += ':'; break; case STATE_NAME: log_debug("hostvar :" << name); sql += event.onHostVar(name); break; default: ; } } } } <|endoftext|>
<commit_before>#include "pqrs/xml_compiler.hpp" namespace pqrs { xml_compiler::symbol_map::symbol_map(void) { clear(); } void xml_compiler::symbol_map::clear(void) { symbol_map_.clear(); symbol_map_["ConfigIndex::VK__AUTOINDEX__BEGIN__"] = 0; map_for_get_name_.clear(); } void xml_compiler::symbol_map::dump(void) const { for (const auto& it : symbol_map_) { std::cout << it.first << " " << it.second << std::endl; } } uint32_t xml_compiler::symbol_map::get(const std::string& name) const { auto v = get_optional(name); if (!v) { throw xml_compiler_runtime_error("Unknown symbol:\n\n" + name); } return *v; } uint32_t xml_compiler::symbol_map::get(const std::string& type, const std::string& name) const { return get(type + "::" + name); } boost::optional<uint32_t> xml_compiler::symbol_map::get_optional(const std::string& name) const { auto it = symbol_map_.find(name); if (it == symbol_map_.end()) { // XXX::RawValue::YYY does not appear frequently. // Therefore, we don't check "XXX::RawValue::" prefix at first in order to improve performance. // Treat XXX::RawValue::XXX at here. auto found = name.find("::RawValue::"); if (found != std::string::npos) { return pqrs::string::to_uint32_t(name.c_str() + found + strlen("::RawValue::")); } return boost::none; } return it->second; } boost::optional<uint32_t> xml_compiler::symbol_map::get_optional(const std::string& type, const std::string& name) const { return get_optional(type + "::" + name); } uint32_t xml_compiler::symbol_map::add(const std::string& type, const std::string& name, uint32_t value) { assert(!type.empty()); assert(!name.empty()); // register value if the definition does not exists. auto n = type + "::" + name; symbol_map_.emplace(n, value); map_for_get_name_.emplace(type + "::" + boost::lexical_cast<std::string>(value), n); return value; } uint32_t xml_compiler::symbol_map::add(const std::string& type, const std::string& name) { auto n = type + "::VK__AUTOINDEX__BEGIN__"; auto v = get_optional(n); assert(v); assert(*v != std::numeric_limits<uint32_t>::max()); symbol_map_[n] = *v + 1; return add(type, name, *v); } boost::optional<const std::string&> xml_compiler::symbol_map::get_name(const std::string& type, uint32_t value) const { auto it = map_for_get_name_.find(type + "::" + boost::lexical_cast<std::string>(value)); if (it == map_for_get_name_.end()) { return boost::none; } return it->second; } // ============================================================ void xml_compiler::symbol_map_loader::traverse(const extracted_ptree& pt) const { for (const auto& it : pt) { if (it.get_tag_name() != "symbol_map") { if (!it.children_empty()) { traverse(it.children_extracted_ptree()); } } else { std::vector<boost::optional<std::string>> vector; const char* attrs[] = { "<xmlattr>.type", "<xmlattr>.name", "<xmlattr>.value", }; for (const auto& attr : attrs) { const char* attrname = attr + strlen("<xmlattr>."); auto v = it.get_optional(attr); if (!v) { xml_compiler_.error_information_.set(std::string("No '") + attrname + "' Attribute within <symbol_map>."); break; } std::string value = pqrs::string::remove_whitespaces_copy(*v); if (value.empty()) { xml_compiler_.error_information_.set(std::string("Empty '") + attrname + "' Attribute within <symbol_map>."); continue; } vector.push_back(value); } // An error has occured when vector.size != attrs.size. if (vector.size() != sizeof(attrs) / sizeof(attrs[0])) { continue; } auto value = pqrs::string::to_uint32_t(vector[2]); if (!value) { xml_compiler_.error_information_.set(boost::format("Invalid 'value' Attribute within <symbol_map>:\n" "\n" "<symbol_map type=\"%1%\" name=\"%2%\" value=\"%3%\" />") % *(vector[0]) % *(vector[1]) % *(vector[2])); continue; } symbol_map_.add(*(vector[0]), *(vector[1]), *value); } } } } <commit_msg>update #include<commit_after>#include <iostream> #include "pqrs/xml_compiler.hpp" namespace pqrs { xml_compiler::symbol_map::symbol_map(void) { clear(); } void xml_compiler::symbol_map::clear(void) { symbol_map_.clear(); symbol_map_["ConfigIndex::VK__AUTOINDEX__BEGIN__"] = 0; map_for_get_name_.clear(); } void xml_compiler::symbol_map::dump(void) const { for (const auto& it : symbol_map_) { std::cout << it.first << " " << it.second << std::endl; } } uint32_t xml_compiler::symbol_map::get(const std::string& name) const { auto v = get_optional(name); if (!v) { throw xml_compiler_runtime_error("Unknown symbol:\n\n" + name); } return *v; } uint32_t xml_compiler::symbol_map::get(const std::string& type, const std::string& name) const { return get(type + "::" + name); } boost::optional<uint32_t> xml_compiler::symbol_map::get_optional(const std::string& name) const { auto it = symbol_map_.find(name); if (it == symbol_map_.end()) { // XXX::RawValue::YYY does not appear frequently. // Therefore, we don't check "XXX::RawValue::" prefix at first in order to improve performance. // Treat XXX::RawValue::XXX at here. auto found = name.find("::RawValue::"); if (found != std::string::npos) { return pqrs::string::to_uint32_t(name.c_str() + found + strlen("::RawValue::")); } return boost::none; } return it->second; } boost::optional<uint32_t> xml_compiler::symbol_map::get_optional(const std::string& type, const std::string& name) const { return get_optional(type + "::" + name); } uint32_t xml_compiler::symbol_map::add(const std::string& type, const std::string& name, uint32_t value) { assert(!type.empty()); assert(!name.empty()); // register value if the definition does not exists. auto n = type + "::" + name; symbol_map_.emplace(n, value); map_for_get_name_.emplace(type + "::" + boost::lexical_cast<std::string>(value), n); return value; } uint32_t xml_compiler::symbol_map::add(const std::string& type, const std::string& name) { auto n = type + "::VK__AUTOINDEX__BEGIN__"; auto v = get_optional(n); assert(v); assert(*v != std::numeric_limits<uint32_t>::max()); symbol_map_[n] = *v + 1; return add(type, name, *v); } boost::optional<const std::string&> xml_compiler::symbol_map::get_name(const std::string& type, uint32_t value) const { auto it = map_for_get_name_.find(type + "::" + boost::lexical_cast<std::string>(value)); if (it == map_for_get_name_.end()) { return boost::none; } return it->second; } // ============================================================ void xml_compiler::symbol_map_loader::traverse(const extracted_ptree& pt) const { for (const auto& it : pt) { if (it.get_tag_name() != "symbol_map") { if (!it.children_empty()) { traverse(it.children_extracted_ptree()); } } else { std::vector<boost::optional<std::string>> vector; const char* attrs[] = { "<xmlattr>.type", "<xmlattr>.name", "<xmlattr>.value", }; for (const auto& attr : attrs) { const char* attrname = attr + strlen("<xmlattr>."); auto v = it.get_optional(attr); if (!v) { xml_compiler_.error_information_.set(std::string("No '") + attrname + "' Attribute within <symbol_map>."); break; } std::string value = pqrs::string::remove_whitespaces_copy(*v); if (value.empty()) { xml_compiler_.error_information_.set(std::string("Empty '") + attrname + "' Attribute within <symbol_map>."); continue; } vector.push_back(value); } // An error has occured when vector.size != attrs.size. if (vector.size() != sizeof(attrs) / sizeof(attrs[0])) { continue; } auto value = pqrs::string::to_uint32_t(vector[2]); if (!value) { xml_compiler_.error_information_.set(boost::format("Invalid 'value' Attribute within <symbol_map>:\n" "\n" "<symbol_map type=\"%1%\" name=\"%2%\" value=\"%3%\" />") % *(vector[0]) % *(vector[1]) % *(vector[2])); continue; } symbol_map_.add(*(vector[0]), *(vector[1]), *value); } } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLConsolidationContext.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: sab $ $Date: 2001-02-28 08:19:33 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SC_XMLCONSOLIDATIONCONTEXT_HXX #define _SC_XMLCONSOLIDATIONCONTEXT_HXX #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif class ScXMLImport; //___________________________________________________________________ class ScXMLConsolidationContext : public SvXMLImportContext { private: ::rtl::OUString sSourceList; ::rtl::OUString sUseLabel; ScAddress aTargetAddr; ScSubTotalFunc eFunction; sal_Bool bLinkToSource : 1; sal_Bool bTargetAddr : 1; protected: const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); } ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); } public: ScXMLConsolidationContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual ~ScXMLConsolidationContext(); virtual SvXMLImportContext* CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual void EndElement(); }; #endif <commit_msg>INTEGRATION: CWS rowlimit (1.3.338); FILE MERGED 2003/11/28 19:47:55 er 1.3.338.1: #i1967# move ScAddress, ScRange from global.hxx to address.hxx<commit_after>/************************************************************************* * * $RCSfile: XMLConsolidationContext.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:08:32 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SC_XMLCONSOLIDATIONCONTEXT_HXX #define _SC_XMLCONSOLIDATIONCONTEXT_HXX #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif class ScXMLImport; //___________________________________________________________________ class ScXMLConsolidationContext : public SvXMLImportContext { private: ::rtl::OUString sSourceList; ::rtl::OUString sUseLabel; ScAddress aTargetAddr; ScSubTotalFunc eFunction; sal_Bool bLinkToSource : 1; sal_Bool bTargetAddr : 1; protected: const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); } ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); } public: ScXMLConsolidationContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual ~ScXMLConsolidationContext(); virtual SvXMLImportContext* CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual void EndElement(); }; #endif <|endoftext|>
<commit_before>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com> #include <memory> #include <string> #include <vector> #include <iostream> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/program_options.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <hadesmem/error.hpp> #include <hadesmem/module.hpp> #include <hadesmem/region.hpp> #include <hadesmem/process.hpp> #include <hadesmem/module_list.hpp> #include <hadesmem/region_list.hpp> #include <hadesmem/process_list.hpp> #include <hadesmem/process_entry.hpp> #include "../common/initialize.hpp" namespace { std::wstring PtrToString(void const* const ptr) { std::wostringstream str; str.imbue(std::locale::classic()); str << std::hex << reinterpret_cast<DWORD_PTR>(ptr); return str.str(); } void DumpRegions(hadesmem::Process const& process) { std::wcout << "\nRegions:\n"; hadesmem::RegionList const regions(&process); for (auto const& region : regions) { std::wcout << "\n"; std::wcout << "\tBase: " << PtrToString(region.GetBase()) << "\n"; std::wcout << "\tAllocation Base: " << PtrToString(region.GetAllocBase()) << "\n"; std::wcout << "\tAllocation Protect: " << std::hex << region.GetAllocProtect() << std::dec << "\n"; std::wcout << "\tSize: " << std::hex << region.GetSize() << std::dec << "\n"; std::wcout << "\tState: " << std::hex << region.GetState() << std::dec << "\n"; std::wcout << "\tProtect: " << std::hex << region.GetProtect() << std::dec << "\n"; std::wcout << "\tType: " << std::hex << region.GetType() << std::dec << "\n"; } } void DumpModules(hadesmem::Process const& process) { std::wcout << "\nModules:\n"; hadesmem::ModuleList const modules(&process); for (auto const& module : modules) { std::wcout << "\n"; std::wcout << "\tHandle: " << PtrToString(module.GetHandle()) << "\n"; std::wcout << "\tSize: " << std::hex << module.GetSize() << std::dec << "\n"; std::wcout << "\tName: " << module.GetName() << "\n"; std::wcout << "\tPath: " << module.GetPath() << "\n"; } } void DumpProcessEntry(hadesmem::ProcessEntry const& process_entry) { std::wcout << "\n"; std::wcout << "ID: " << process_entry.GetId() << "\n"; std::wcout << "Threads: " << process_entry.GetThreads() << "\n"; std::wcout << "Parent: " << process_entry.GetParentId() << "\n"; std::wcout << "Priority: " << process_entry.GetPriority() << "\n"; std::wcout << "Name: " << process_entry.GetName() << "\n"; std::unique_ptr<hadesmem::Process> process; try { process.reset(new hadesmem::Process(process_entry.GetId())); } catch (std::exception const& /*e*/) { std::wcout << "\nCould not open process for further inspection.\n\n"; return; } std::wcout << "Path: " << hadesmem::GetPath(*process) << "\n"; std::wcout << "WoW64: " << (hadesmem::IsWoW64(*process) ? "Yes" : "No") << "\n"; DumpModules(*process); DumpRegions(*process); } } int main() { try { DisableUserModeCallbackExceptionFilter(); EnableCrtDebugFlags(); EnableTerminationOnHeapCorruption(); EnableBottomUpRand(); ImbueAllDefault(); std::cout << "HadesMem Dumper\n"; boost::program_options::options_description opts_desc( "General options"); opts_desc.add_options() ("help", "produce help message") ("pid", boost::program_options::value<DWORD>(), "process id") ; std::vector<std::wstring> const args = boost::program_options:: split_winmain(GetCommandLine()); boost::program_options::variables_map var_map; boost::program_options::store(boost::program_options::wcommand_line_parser( args).options(opts_desc).run(), var_map); boost::program_options::notify(var_map); if (var_map.count("help")) { std::cout << opts_desc << '\n'; return 1; } DWORD pid = 0; if (var_map.count("pid")) { pid = var_map["pid"].as<DWORD>(); } try { hadesmem::GetSeDebugPrivilege(); std::wcout << "\nAcquired SeDebugPrivilege.\n"; } catch (std::exception const& /*e*/) { std::wcout << "\nFailed to acquire SeDebugPrivilege.\n"; } if (pid) { hadesmem::ProcessList const processes; auto iter = std::find_if(std::begin(processes), std::end(processes), [pid] (hadesmem::ProcessEntry const& process_entry) { return process_entry.GetId() == pid; }); DumpProcessEntry(*iter); } else { std::wcout << "\nProcesses:\n"; hadesmem::ProcessList const processes; for (auto const& process_entry : processes) { DumpProcessEntry(process_entry); } } } catch (std::exception const& e) { std::cerr << "Error!\n"; std::cerr << boost::diagnostic_information(e) << "\n"; return 1; } } <commit_msg>* Output fix.<commit_after>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com> #include <memory> #include <string> #include <vector> #include <iostream> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/program_options.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <hadesmem/error.hpp> #include <hadesmem/module.hpp> #include <hadesmem/region.hpp> #include <hadesmem/process.hpp> #include <hadesmem/module_list.hpp> #include <hadesmem/region_list.hpp> #include <hadesmem/process_list.hpp> #include <hadesmem/process_entry.hpp> #include "../common/initialize.hpp" namespace { std::wstring PtrToString(void const* const ptr) { std::wostringstream str; str.imbue(std::locale::classic()); str << std::hex << reinterpret_cast<DWORD_PTR>(ptr); return str.str(); } void DumpRegions(hadesmem::Process const& process) { std::wcout << "\nRegions:\n"; hadesmem::RegionList const regions(&process); for (auto const& region : regions) { std::wcout << "\n"; std::wcout << "\tBase: " << PtrToString(region.GetBase()) << "\n"; std::wcout << "\tAllocation Base: " << PtrToString(region.GetAllocBase()) << "\n"; std::wcout << "\tAllocation Protect: " << std::hex << region.GetAllocProtect() << std::dec << "\n"; std::wcout << "\tSize: " << std::hex << region.GetSize() << std::dec << "\n"; std::wcout << "\tState: " << std::hex << region.GetState() << std::dec << "\n"; std::wcout << "\tProtect: " << std::hex << region.GetProtect() << std::dec << "\n"; std::wcout << "\tType: " << std::hex << region.GetType() << std::dec << "\n"; } } void DumpModules(hadesmem::Process const& process) { std::wcout << "\nModules:\n"; hadesmem::ModuleList const modules(&process); for (auto const& module : modules) { std::wcout << "\n"; std::wcout << "\tHandle: " << PtrToString(module.GetHandle()) << "\n"; std::wcout << "\tSize: " << std::hex << module.GetSize() << std::dec << "\n"; std::wcout << "\tName: " << module.GetName() << "\n"; std::wcout << "\tPath: " << module.GetPath() << "\n"; } } void DumpProcessEntry(hadesmem::ProcessEntry const& process_entry) { std::wcout << "\n"; std::wcout << "ID: " << process_entry.GetId() << "\n"; std::wcout << "Threads: " << process_entry.GetThreads() << "\n"; std::wcout << "Parent: " << process_entry.GetParentId() << "\n"; std::wcout << "Priority: " << process_entry.GetPriority() << "\n"; std::wcout << "Name: " << process_entry.GetName() << "\n"; std::unique_ptr<hadesmem::Process> process; try { process.reset(new hadesmem::Process(process_entry.GetId())); } catch (std::exception const& /*e*/) { std::wcout << "\nCould not open process for further inspection.\n\n"; return; } std::wcout << "Path: " << hadesmem::GetPath(*process) << "\n"; std::wcout << "WoW64: " << (hadesmem::IsWoW64(*process) ? "Yes" : "No") << "\n"; DumpModules(*process); DumpRegions(*process); } } int main() { try { DisableUserModeCallbackExceptionFilter(); EnableCrtDebugFlags(); EnableTerminationOnHeapCorruption(); EnableBottomUpRand(); ImbueAllDefault(); std::cout << "HadesMem Dumper\n"; boost::program_options::options_description opts_desc( "General options"); opts_desc.add_options() ("help", "produce help message") ("pid", boost::program_options::value<DWORD>(), "process id") ; std::vector<std::wstring> const args = boost::program_options:: split_winmain(GetCommandLine()); boost::program_options::variables_map var_map; boost::program_options::store(boost::program_options::wcommand_line_parser( args).options(opts_desc).run(), var_map); boost::program_options::notify(var_map); if (var_map.count("help")) { std::cout << '\n' << opts_desc << '\n'; return 1; } DWORD pid = 0; if (var_map.count("pid")) { pid = var_map["pid"].as<DWORD>(); } try { hadesmem::GetSeDebugPrivilege(); std::wcout << "\nAcquired SeDebugPrivilege.\n"; } catch (std::exception const& /*e*/) { std::wcout << "\nFailed to acquire SeDebugPrivilege.\n"; } if (pid) { hadesmem::ProcessList const processes; auto iter = std::find_if(std::begin(processes), std::end(processes), [pid] (hadesmem::ProcessEntry const& process_entry) { return process_entry.GetId() == pid; }); DumpProcessEntry(*iter); } else { std::wcout << "\nProcesses:\n"; hadesmem::ProcessList const processes; for (auto const& process_entry : processes) { DumpProcessEntry(process_entry); } } } catch (std::exception const& e) { std::cerr << "Error!\n"; std::cerr << boost::diagnostic_information(e) << "\n"; return 1; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: apinodeaccess.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2003-10-06 16:10:18 $ * * 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 CONFIGMGR_API_NODEACCESS_HXX_ #define CONFIGMGR_API_NODEACCESS_HXX_ #ifndef CONFIGMGR_UTILITY_HXX_ #include "utility.hxx" #endif #if defined(_MSC_VER) && (_MSC_VER >=1310) #ifndef CONFIGMGR_CONFIGNODE_HXX_ #include "noderef.hxx" #endif #endif namespace osl { class Mutex; } namespace configmgr { namespace memory { class Accessor; class Segment; } namespace configuration { class Name; class AnyNodeRef; class NodeRef; class TreeRef; class Tree; class SetElementInfo; class TemplateInfo; class ElementRef; class ElementTree; } namespace configapi { class Factory; class Notifier; class SetElement; class ApiTreeImpl; namespace uno = com::sun::star::uno; typedef uno::XInterface UnoInterface; typedef uno::Any UnoAny; // API object implementation wrappers // these objects just provide the pieces needed to navigate and manipulate trees and nodes // The common part of all nodes, provides all you need to read and listen class NodeAccess : Noncopyable { public: virtual ~NodeAccess(); // model access configuration::NodeRef getNodeRef() const; configuration::TreeRef getTreeRef() const; configuration::Tree getTree(memory::Accessor const& _aAccessor) const; // self-locked methods for dispose handling void checkAlive() const; void disposeNode(); // api object handling UnoInterface* getUnoInstance() const { return doGetUnoInstance(); } Factory& getFactory() const; Notifier getNotifier() const; // locking support osl::Mutex& getDataLock() const; memory::Segment const* getSourceData() const; osl::Mutex& getApiLock(); protected: virtual configuration::NodeRef doGetNode() const = 0; virtual UnoInterface* doGetUnoInstance() const = 0; virtual ApiTreeImpl& getApiTree() const = 0; }; /** builds a Uno <type scope='com::sun::star::uno'>Any</type> representing node <var>aNode</var>. <p> Uses the <type scope='configmgr::configapi'>Factory</type> provided to create service implementations wrapping inner nodes</p> <p> returns VOID if <var>aNode</var> is empty.</p> */ UnoAny makeElement(configapi::Factory& rFactory, configuration::Tree const& aTree, configuration::AnyNodeRef const& aNode); /** builds a Uno <type scope='com::sun::star::uno'>Any</type> representing inner node <var>aNode</var>. <p> Uses the <type scope='configmgr::configapi'>Factory</type> provided to create service implementations wrapping inner nodes</p> <p> returns VOID if <var>aNode</var> is empty.</p> */ UnoAny makeInnerElement(configapi::Factory& rFactory, configuration::Tree const& aTree, configuration::NodeRef const& aNode); /** builds a Uno <type scope='com::sun::star::uno'>Any</type> representing set element <var>aElement</var>. <p> Uses the <type scope='configmgr::configapi'>Factory</type> provided to create service implementations wrapping inner nodes</p> <p> returns VOID if <var>aNode</var> is empty.</p> */ UnoAny makeElement(configapi::Factory& rFactory, configuration::ElementTree const& aTree); // Info interfaces for Group Nodes class NodeGroupInfoAccess : public NodeAccess { public: // currently only used for tagging group nodes }; // Info interfaces for Set Nodes class NodeSetInfoAccess : public NodeAccess { friend class SetElement; public: configuration::SetElementInfo getElementInfo(memory::Accessor const& _aAccessor) const; }; /** extracts a <type scope='configmgr::configuration'>ElementTree</type> from a <type scope='com::sun::star::uno'>Any</type> which must contain an object which wraps an instance of the template available in <var>aElementInfo</var>. <p> Uses the <type scope='configmgr::configapi'>Factory</type> provided to resolve inner nodes (which may suppose that the object was created using the same factory)</p> <p> returns an empty <type scope='configmgr::configuration'>Tree</type> if <var>aElement</var> is empty.</p> <p> May throw exceptions if the type doesn't match the template.</p> */ configuration::ElementRef extractElementRef (Factory& rFactory, UnoAny const& aElement, configuration::TemplateInfo const& aElementInfo ); configuration::ElementTree extractElementTree(Factory& rFactory, UnoAny const& aElement, configuration::SetElementInfo const& aElementInfo ); /// finds a existing <type>SetElement</type> for a given <type scope='configmgr::configuration'>ElementTree</type> SetElement* findSetElement(Factory& rFactory, configuration::ElementRef const& aElementTree); // Guarding and locking implementations /// guards a NodeAccess; provides an object (read) lock, ensures object was not disposed class NodeReadGuardImpl : Noncopyable { osl::MutexGuard m_aLock; NodeAccess& m_rNode; public: NodeReadGuardImpl(NodeAccess& rNode) throw(); ~NodeReadGuardImpl() throw (); public: NodeAccess& get() const { return m_rNode; } configuration::Tree getTree(memory::Accessor const& _aAccessor) const; configuration::NodeRef getNode() const; }; // Thin Wrappers around NodeAccesses: Provide guarding and convenient access /// wraps a NodeAccess; provides an object (read) lock, ensures object was not disposed template <class Access> class GuardedNode { NodeReadGuardImpl m_aViewLock; public: GuardedNode(Access& rNode) : m_aViewLock(rNode) {} public: Access& get() const { return static_cast<Access&>(m_aViewLock.get()); } }; typedef GuardedNode<NodeAccess> GuardedNodeAccess; /// wraps a NodeAccess; provides both object and provider (read) locks, ensures object was not disposed template <class Access> class GuardedNodeData { memory::Accessor m_aDataAccess; NodeReadGuardImpl m_aViewLock; public: GuardedNodeData(Access& rNode); public: Access& get() const { return static_cast<Access&>(m_aViewLock.get()); } configuration::Tree getTree() const; configuration::NodeRef getNode() const; memory::Accessor const & getDataAccessor() const { return m_aDataAccess; } }; typedef GuardedNodeData<NodeAccess> GuardedNodeDataAccess; template <class Access> GuardedNodeData<Access>::GuardedNodeData(Access& rNode) : m_aDataAccess(rNode.getSourceData()) , m_aViewLock(rNode) { } template <class Access> configuration::Tree GuardedNodeData<Access>::getTree() const { return (configuration::Tree) m_aViewLock.getTree(m_aDataAccess); } template <class Access> configuration::NodeRef GuardedNodeData<Access>::getNode() const { return m_aViewLock.getNode(); } } } #endif // CONFIGMGR_API_NODEACCESS_HXX_ <commit_msg>INTEGRATION: CWS gcc340fixes01 (1.6.34); FILE MERGED 2004/07/13 20:22:05 fa 1.6.34.1: #i31261# Specify namespaces/explicitly scope variables for gcc 3.4<commit_after>/************************************************************************* * * $RCSfile: apinodeaccess.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: kz $ $Date: 2004-07-30 15:07:20 $ * * 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 CONFIGMGR_API_NODEACCESS_HXX_ #define CONFIGMGR_API_NODEACCESS_HXX_ #ifndef CONFIGMGR_UTILITY_HXX_ #include "utility.hxx" #endif #if defined(_MSC_VER) && (_MSC_VER >=1310) #ifndef CONFIGMGR_CONFIGNODE_HXX_ #include "noderef.hxx" #endif #endif #ifndef CONFIGMGR_ACCESSOR_HXX #include <accessor.hxx> #endif namespace osl { class Mutex; } namespace configmgr { namespace memory { class Accessor; class Segment; } namespace configuration { class Name; class AnyNodeRef; class NodeRef; class TreeRef; class Tree; class SetElementInfo; class TemplateInfo; class ElementRef; class ElementTree; } namespace configapi { class Factory; class Notifier; class SetElement; class ApiTreeImpl; namespace uno = com::sun::star::uno; typedef uno::XInterface UnoInterface; typedef uno::Any UnoAny; // API object implementation wrappers // these objects just provide the pieces needed to navigate and manipulate trees and nodes // The common part of all nodes, provides all you need to read and listen class NodeAccess : Noncopyable { public: virtual ~NodeAccess(); // model access configuration::NodeRef getNodeRef() const; configuration::TreeRef getTreeRef() const; configuration::Tree getTree(memory::Accessor const& _aAccessor) const; // self-locked methods for dispose handling void checkAlive() const; void disposeNode(); // api object handling UnoInterface* getUnoInstance() const { return doGetUnoInstance(); } Factory& getFactory() const; Notifier getNotifier() const; // locking support osl::Mutex& getDataLock() const; memory::Segment const* getSourceData() const; osl::Mutex& getApiLock(); protected: virtual configuration::NodeRef doGetNode() const = 0; virtual UnoInterface* doGetUnoInstance() const = 0; virtual ApiTreeImpl& getApiTree() const = 0; }; /** builds a Uno <type scope='com::sun::star::uno'>Any</type> representing node <var>aNode</var>. <p> Uses the <type scope='configmgr::configapi'>Factory</type> provided to create service implementations wrapping inner nodes</p> <p> returns VOID if <var>aNode</var> is empty.</p> */ UnoAny makeElement(configapi::Factory& rFactory, configuration::Tree const& aTree, configuration::AnyNodeRef const& aNode); /** builds a Uno <type scope='com::sun::star::uno'>Any</type> representing inner node <var>aNode</var>. <p> Uses the <type scope='configmgr::configapi'>Factory</type> provided to create service implementations wrapping inner nodes</p> <p> returns VOID if <var>aNode</var> is empty.</p> */ UnoAny makeInnerElement(configapi::Factory& rFactory, configuration::Tree const& aTree, configuration::NodeRef const& aNode); /** builds a Uno <type scope='com::sun::star::uno'>Any</type> representing set element <var>aElement</var>. <p> Uses the <type scope='configmgr::configapi'>Factory</type> provided to create service implementations wrapping inner nodes</p> <p> returns VOID if <var>aNode</var> is empty.</p> */ UnoAny makeElement(configapi::Factory& rFactory, configuration::ElementTree const& aTree); // Info interfaces for Group Nodes class NodeGroupInfoAccess : public NodeAccess { public: // currently only used for tagging group nodes }; // Info interfaces for Set Nodes class NodeSetInfoAccess : public NodeAccess { friend class SetElement; public: configuration::SetElementInfo getElementInfo(memory::Accessor const& _aAccessor) const; }; /** extracts a <type scope='configmgr::configuration'>ElementTree</type> from a <type scope='com::sun::star::uno'>Any</type> which must contain an object which wraps an instance of the template available in <var>aElementInfo</var>. <p> Uses the <type scope='configmgr::configapi'>Factory</type> provided to resolve inner nodes (which may suppose that the object was created using the same factory)</p> <p> returns an empty <type scope='configmgr::configuration'>Tree</type> if <var>aElement</var> is empty.</p> <p> May throw exceptions if the type doesn't match the template.</p> */ configuration::ElementRef extractElementRef (Factory& rFactory, UnoAny const& aElement, configuration::TemplateInfo const& aElementInfo ); configuration::ElementTree extractElementTree(Factory& rFactory, UnoAny const& aElement, configuration::SetElementInfo const& aElementInfo ); /// finds a existing <type>SetElement</type> for a given <type scope='configmgr::configuration'>ElementTree</type> SetElement* findSetElement(Factory& rFactory, configuration::ElementRef const& aElementTree); // Guarding and locking implementations /// guards a NodeAccess; provides an object (read) lock, ensures object was not disposed class NodeReadGuardImpl : Noncopyable { osl::MutexGuard m_aLock; NodeAccess& m_rNode; public: NodeReadGuardImpl(NodeAccess& rNode) throw(); ~NodeReadGuardImpl() throw (); public: NodeAccess& get() const { return m_rNode; } configuration::Tree getTree(memory::Accessor const& _aAccessor) const; configuration::NodeRef getNode() const; }; // Thin Wrappers around NodeAccesses: Provide guarding and convenient access /// wraps a NodeAccess; provides an object (read) lock, ensures object was not disposed template <class Access> class GuardedNode { NodeReadGuardImpl m_aViewLock; public: GuardedNode(Access& rNode) : m_aViewLock(rNode) {} public: Access& get() const { return static_cast<Access&>(m_aViewLock.get()); } }; typedef GuardedNode<NodeAccess> GuardedNodeAccess; /// wraps a NodeAccess; provides both object and provider (read) locks, ensures object was not disposed template <class Access> class GuardedNodeData { memory::Accessor m_aDataAccess; NodeReadGuardImpl m_aViewLock; public: GuardedNodeData(Access& rNode); public: Access& get() const { return static_cast<Access&>(m_aViewLock.get()); } configuration::Tree getTree() const; configuration::NodeRef getNode() const; memory::Accessor const & getDataAccessor() const { return m_aDataAccess; } }; typedef GuardedNodeData<NodeAccess> GuardedNodeDataAccess; template <class Access> GuardedNodeData<Access>::GuardedNodeData(Access& rNode) : m_aDataAccess(rNode.getSourceData()) , m_aViewLock(rNode) { } template <class Access> configuration::Tree GuardedNodeData<Access>::getTree() const { return (configuration::Tree) m_aViewLock.getTree(m_aDataAccess); } template <class Access> configuration::NodeRef GuardedNodeData<Access>::getNode() const { return m_aViewLock.getNode(); } } } #endif // CONFIGMGR_API_NODEACCESS_HXX_ <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <stan/math/prim/mat.hpp> #include <limits> #include <string> #include <vector> template <typename T_x, typename T_sigma> std::string pull_msg(std::vector<T_x> x, T_sigma sigma) { std::string message; try { stan::math::gp_dot_prod_cov(x, sigma); } catch (std::domain_error &e) { message = e.what(); } catch (...) { message = "Threw the wrong exection"; } return message; } template <typename T_x1, typename T_x2, typename T_sigma> std::string pull_msg(std::vector<T_x1> x1, std::vector<T_x2> x2, T_sigma sigma) { std::string message; try { stan::math::gp_dot_prod_cov(x1, x2, sigma); } catch (std::domain_error &e) { message = e.what(); } catch (...) { message = "Threw the wrong exection"; } return message; } TEST(MathPrimMat, vec_double_gp_dot_prod_cov0) { double sigma = 0.5; double sigma_sq = pow(sigma, 2); std::vector<double> x(3); x[0] = -2; x[1] = -1; x[2] = -0.5; Eigen::MatrixXd cov; cov = stan::math::gp_dot_prod_cov(x, sigma); EXPECT_NO_THROW(cov = stan::math::gp_dot_prod_cov(x, sigma)); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) EXPECT_FLOAT_EQ(sigma_sq + x[i] * x[j], cov(i, j)) << "index: (" << i << ", " << j << ")"; } TEST(MathPrimMat, vec_x_gp_dot_prod_cov0) { double sigma = 0.5; std::vector<Eigen::Matrix<double, -1, 1>> x(3); for (size_t i = 0; i < x.size(); ++i) { x[i].resize(3, 1); x[i] << 2 * i, 3 * i, 4 * i; } Eigen::MatrixXd cov; EXPECT_NO_THROW(cov = stan::math::gp_dot_prod_cov(x, sigma)); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { EXPECT_FLOAT_EQ(sigma * sigma + stan::math::dot_product(x[i], x[j]), cov(i, j)) << "index: (" << i << ", " << j << ")"; } } } TEST(MathPrimMat, vec_NaN_x_gp_dot_prod_cov_cov0) { double sigma = 1; std::vector<double> x(2); x[0] = 1; x[1] = std::numeric_limits<double>::quiet_NaN(); EXPECT_THROW(stan::math::gp_dot_prod_cov(x, sigma), std::domain_error); std::string msg; msg = pull_msg(x, sigma); EXPECT_TRUE(std::string::npos != msg.find(" x")) << msg; } TEST(MathPrimMat, vec_NaN_sigma_gp_dot_prod_cov_cov0) { double sigma = std::numeric_limits<double>::quiet_NaN(); std::vector<double> x(2); x[0] = 1; x[1] = 2; EXPECT_THROW(stan::math::gp_dot_prod_cov(x, sigma), std::domain_error); std::string msg; msg = pull_msg(x, sigma); EXPECT_TRUE(std::string::npos != msg.find(" sigma")) << msg; } TEST(MathPrimMat, vec_NaN_x1_gp_dot_prod_cov_cov0) { double sigma = 2; std::vector<double> x1(2); x1[0] = std::numeric_limits<double>::quiet_NaN(); x1[1] = 2; std::vector<double> x2(2); x2[0] = 1; x2[1] = 2; EXPECT_THROW(stan::math::gp_dot_prod_cov(x1, x2, sigma), std::domain_error); std::string msg; msg = pull_msg(x1, x2, sigma); EXPECT_TRUE(std::string::npos != msg.find(" x1")) << msg; } TEST(MathPrimMat, vec_NaN_x2_gp_dot_prod_cov_cov0) { double sigma = 2; std::vector<double> x1(2); x1[0] = 1; x1[1] = 2; std::vector<double> x2(2); x2[0] = 1; x2[1] = std::numeric_limits<double>::quiet_NaN(); EXPECT_THROW(stan::math::gp_dot_prod_cov(x1, x2, sigma), std::domain_error); std::string msg; msg = pull_msg(x1, x2, sigma); EXPECT_TRUE(std::string::npos != msg.find(" x2")) << msg; } TEST(MathPrimMat, vec_NaN_x1_x2_sigma_gp_dot_prod_cov_cov0) { double sigma = std::numeric_limits<double>::quiet_NaN(); std::vector<double> x1(2); x1[0] = 1; x1[1] = 2; std::vector<double> x2(2); x2[0] = 1; x2[1] = 3; EXPECT_THROW(stan::math::gp_dot_prod_cov(x1, x2, sigma), std::domain_error); std::string msg; msg = pull_msg(x1, x2, sigma); EXPECT_TRUE(std::string::npos != msg.find(" sigma")) << msg; } TEST(MathPrimMat, vec_inf_x_gp_dot_prod_cov_cov0) { double sigma = 1; std::vector<double> x(2); x[0] = 1; x[1] = std::numeric_limits<double>::infinity(); EXPECT_THROW(stan::math::gp_dot_prod_cov(x, sigma), std::domain_error); std::string msg; msg = pull_msg(x, sigma); EXPECT_TRUE(std::string::npos != msg.find(" x")) << msg; } TEST(MathPrimMat, vec_inf_sigma_gp_dot_prod_cov_cov0) { double sigma = std::numeric_limits<double>::infinity(); std::vector<double> x(2); x[0] = 1; x[1] = 2; EXPECT_THROW(stan::math::gp_dot_prod_cov(x, sigma), std::domain_error); std::string msg; msg = pull_msg(x, sigma); EXPECT_TRUE(std::string::npos != msg.find(" sigma")) << msg; } TEST(MathPrimMat, vec_inf_x1_gp_dot_prod_cov_cov0) { double sigma = 2; std::vector<double> x1(2); x1[0] = std::numeric_limits<double>::infinity(); x1[1] = 2; std::vector<double> x2(2); x2[0] = 1; x2[1] = 2; EXPECT_THROW(stan::math::gp_dot_prod_cov(x1, x2, sigma), std::domain_error); std::string msg; msg = pull_msg(x1, x2, sigma); EXPECT_TRUE(std::string::npos != msg.find(" x1")) << msg; } TEST(MathPrimMat, vec_inf_x2_gp_dot_prod_cov_cov0) { double sigma = 2; std::vector<double> x1(2); x1[0] = 1; x1[1] = 2; std::vector<double> x2(2); x2[0] = 1; x2[1] = std::numeric_limits<double>::infinity(); EXPECT_THROW(stan::math::gp_dot_prod_cov(x1, x2, sigma), std::domain_error); std::string msg; msg = pull_msg(x1, x2, sigma); EXPECT_TRUE(std::string::npos != msg.find(" x2")) << msg; } TEST(MathPrimMat, vec_inf_x1_x2_sigma_gp_dot_prod_cov_cov0) { double sigma = std::numeric_limits<double>::infinity(); std::vector<double> x1(2); x1[0] = 1; x1[1] = 2; std::vector<double> x2(2); x2[0] = 1; x2[1] = 3; EXPECT_THROW(stan::math::gp_dot_prod_cov(x1, x2, sigma), std::domain_error); std::string msg; msg = pull_msg(x1, x2, sigma); EXPECT_TRUE(std::string::npos != msg.find(" sigma")) << msg; } TEST(MathPrimMat, rvec_x_gp_dot_prod_cov0) { double sigma = 0.5; std::vector<Eigen::Matrix<double, 1, -1>> x(3); for (size_t i = 0; i < x.size(); ++i) { x[i].resize(1, 3); x[i] << 1 * i, 2 * i, 3 * i; } Eigen::MatrixXd cov; EXPECT_NO_THROW(cov = stan::math::gp_dot_prod_cov(x, sigma)); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { EXPECT_FLOAT_EQ(sigma * sigma + stan::math::dot_product(x[i], x[j]), cov(i, j)) << "index: (" << i << ", " << j << ")"; } } } TEST(MathPrimMat, vec_vec_x1_x2_gp_dot_prod_cov0) { double sigma = 0.5; std::vector<Eigen::Matrix<double, -1, 1>> x1(3); for (size_t i = 0; i < x1.size(); ++i) { x1[i].resize(3, 1); x1[i] << 2 * i, 3 * i, 4 * i; } std::vector<Eigen::Matrix<double, -1, 1>> x2(4); for (size_t i = 0; i < x2.size(); ++i) { x2[i].resize(3, 1); x2[i] << 1 * i, 2 * i, 3 * i; } Eigen::MatrixXd cov; EXPECT_NO_THROW(cov = stan::math::gp_dot_prod_cov(x1, x2, sigma)); EXPECT_EQ(3, cov.rows()); EXPECT_EQ(4, cov.cols()); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) { EXPECT_FLOAT_EQ(sigma * sigma + stan::math::dot_product(x1[i], x2[j]), cov(i, j)) << "index: (" << i << ", " << j << ")"; } } } TEST(MathPrimMat, rvec_vec_x1_x2_gp_dot_prod_cov0) { double sigma = 0.5; std::vector<Eigen::Matrix<double, 1, -1>> x1(3); std::vector<Eigen::Matrix<double, 1, -1>> x2(4); for (size_t i = 0; i < x1.size(); ++i) { x1[i].resize(1, 3); x1[i] << 1 * i, 2 * i, 3 * i; } for (size_t i = 0; i < x2.size(); ++i) { x2[i].resize(1, 3); x2[i] << 2 * i, 3 * i, 4 * i; } Eigen::MatrixXd cov; EXPECT_NO_THROW(cov = stan::math::gp_dot_prod_cov(x1, x2, sigma)); EXPECT_EQ(3, cov.rows()); EXPECT_EQ(4, cov.cols()); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) { EXPECT_FLOAT_EQ(sigma * sigma + stan::math::dot_product(x1[i], x2[j]), cov(i, j)) << "index: (" << i << ", " << j << ")"; } } Eigen::MatrixXd cov2; EXPECT_NO_THROW(cov2 = stan::math::gp_dot_prod_cov(x1, x2, sigma)); EXPECT_EQ(3, cov2.rows()); EXPECT_EQ(4, cov2.cols()); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) { EXPECT_FLOAT_EQ(sigma * sigma + stan::math::dot_product(x1[i], x2[j]), cov2(i, j)) << "index: (" << i << ", " << j << ")"; } } } TEST(MathPrimMat, vec_rvec_x1_x2_gp_dot_prod_cov0) { double sigma = 0.7; std::vector<Eigen::Matrix<double, 1, -1>> x1_rvec(3); for (size_t i = 0; i < x1_rvec.size(); ++i) { x1_rvec[i].resize(1, 3); x1_rvec[i] << 1 * i, 2 * i, 3 * i; } std::vector<Eigen::Matrix<double, -1, 1>> x1_vec(3); for (size_t i = 0; i < x1_vec.size(); ++i) { x1_vec[i].resize(3, 1); x1_vec[i] << 1 * i, 2 * i, 3 * i; } Eigen::MatrixXd cov; EXPECT_NO_THROW(cov = stan::math::gp_dot_prod_cov(x1_vec, x1_rvec, sigma)); EXPECT_EQ(3, cov.rows()); EXPECT_EQ(3, cov.cols()); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { EXPECT_FLOAT_EQ( sigma * sigma + stan::math::dot_product(x1_vec[i], x1_rvec[j]), cov(i, j)) << "index: (" << i << ", " << j << ")"; } } } TEST(MathPrimMat, rvec_rvec_x1_x2_gp_dot_prod_cov0) { double sigma = 0.8; std::vector<Eigen::Matrix<double, 1, -1>> x1_rvec(3); std::vector<Eigen::Matrix<double, 1, -1>> x2_rvec(4); for (size_t i = 0; i < x1_rvec.size(); ++i) { x1_rvec[i].resize(1, 3); x1_rvec[i] << 1 * i, 2 * i, 3 * i; } for (size_t i = 0; i < x2_rvec.size(); ++i) { x2_rvec[i].resize(1, 3); x2_rvec[i] << 2 * i, 3 * i, 4 * i; } Eigen::MatrixXd cov; EXPECT_NO_THROW(cov = stan::math::gp_dot_prod_cov(x1_rvec, x2_rvec, sigma)); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { EXPECT_FLOAT_EQ( sigma * sigma + stan::math::dot_product(x1_rvec[i], x2_rvec[j]), cov(i, j)) << "index: (" << i << ", " << j << ")"; } } } <commit_msg>Delete gp_dot_prod_cov_test.cpp<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2011 - 2018, GS Group, https://github.com/GSGroup // 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 <stingraykit/thread/ThreadlessTaskExecutor.h> #include <stingraykit/diagnostics/AsyncProfiler.h> #include <stingraykit/diagnostics/ExecutorsProfiler.h> #include <stingraykit/function/bind.h> #include <stingraykit/ScopeExit.h> namespace stingray { STINGRAYKIT_DEFINE_NAMED_LOGGER(ThreadlessTaskExecutor); const TimeDuration ThreadlessTaskExecutor::DefaultProfileTimeout = TimeDuration::FromSeconds(10); ThreadlessTaskExecutor::ThreadlessTaskExecutor(const std::string& name, const optional<TimeDuration>& profileTimeout, const ExceptionHandlerType& exceptionHandler) : _name(name), _profileTimeout(profileTimeout), _exceptionHandler(exceptionHandler) { } void ThreadlessTaskExecutor::AddTask(const TaskType& task, const FutureExecutionTester& tester) { MutexLock l(_syncRoot); _queue.push_back(std::make_pair(task, tester)); } void ThreadlessTaskExecutor::ExecuteTasks(const ICancellationToken& token) { MutexLock l(_syncRoot); if (_activeExecutor) { s_logger.Warning() << "[" << _name << "] Already running tasks in thread " << _activeExecutor; return; } const ScopeExitInvoker sei(bind(&optional<std::string>::reset, ref(_activeExecutor))); _activeExecutor = Thread::GetCurrentThreadName(); while (!_queue.empty() && token) { optional<TaskPair> top = _queue.front(); _queue.pop_front(); MutexUnlock ul(l); ExecuteTask(*top); top.reset(); // destroy object with unlocked mutex to keep lock order correct Thread::InterruptionPoint(); } } void ThreadlessTaskExecutor::ClearTasks() { MutexLock l(_syncRoot); _queue.clear(); } void ThreadlessTaskExecutor::DefaultExceptionHandler(const std::exception& ex) { s_logger.Error() << "Executor func exception: " << ex; } std::string ThreadlessTaskExecutor::GetProfilerMessage(const function<void()>& func) const { return StringBuilder() % get_function_name(func) % " in ThreadlessTaskExecutor '" % _name % "'"; } void ThreadlessTaskExecutor::ExecuteTask(const TaskPair& task) const { try { LocalExecutionGuard guard(task.second); if (!guard) return; if (_profileTimeout) { AsyncProfiler::Session profiler_session(ExecutorsProfiler::Instance().GetProfiler(), bind(&ThreadlessTaskExecutor::GetProfilerMessage, this, ref(task.first)), *_profileTimeout, AsyncProfiler::NameGetterTag()); task.first(); } else task.first(); } catch(const std::exception& ex) { _exceptionHandler(ex); } } } <commit_msg>ThreadlessTaskExecutor: some warning<commit_after>// Copyright (c) 2011 - 2018, GS Group, https://github.com/GSGroup // 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 <stingraykit/thread/ThreadlessTaskExecutor.h> #include <stingraykit/diagnostics/AsyncProfiler.h> #include <stingraykit/diagnostics/ExecutorsProfiler.h> #include <stingraykit/function/bind.h> #include <stingraykit/ScopeExit.h> namespace stingray { STINGRAYKIT_DEFINE_NAMED_LOGGER(ThreadlessTaskExecutor); const TimeDuration ThreadlessTaskExecutor::DefaultProfileTimeout = TimeDuration::FromSeconds(10); ThreadlessTaskExecutor::ThreadlessTaskExecutor(const std::string& name, const optional<TimeDuration>& profileTimeout, const ExceptionHandlerType& exceptionHandler) : _name(name), _profileTimeout(profileTimeout), _exceptionHandler(exceptionHandler) { } void ThreadlessTaskExecutor::AddTask(const TaskType& task, const FutureExecutionTester& tester) { MutexLock l(_syncRoot); _queue.push_back(std::make_pair(task, tester)); } void ThreadlessTaskExecutor::ExecuteTasks(const ICancellationToken& token) { MutexLock l(_syncRoot); if (_activeExecutor) { s_logger.Warning() << "[" << _name << "] Already running tasks in thread " << _activeExecutor; return; } const ScopeExitInvoker sei(bind(&optional<std::string>::reset, ref(_activeExecutor))); _activeExecutor = Thread::GetCurrentThreadName(); while (!_queue.empty() && token) { optional<TaskPair> top = _queue.front(); _queue.pop_front(); MutexUnlock ul(l); ExecuteTask(*top); top.reset(); // destroy object with unlocked mutex to keep lock order correct Thread::InterruptionPoint(); } } void ThreadlessTaskExecutor::ClearTasks() { MutexLock l(_syncRoot); if (!_queue.empty()) s_logger.Warning() << "[" << _name << "] Clear " << _queue.size() << " tasks"; _queue.clear(); } void ThreadlessTaskExecutor::DefaultExceptionHandler(const std::exception& ex) { s_logger.Error() << "Executor func exception: " << ex; } std::string ThreadlessTaskExecutor::GetProfilerMessage(const function<void()>& func) const { return StringBuilder() % get_function_name(func) % " in ThreadlessTaskExecutor '" % _name % "'"; } void ThreadlessTaskExecutor::ExecuteTask(const TaskPair& task) const { try { LocalExecutionGuard guard(task.second); if (!guard) return; if (_profileTimeout) { AsyncProfiler::Session profiler_session(ExecutorsProfiler::Instance().GetProfiler(), bind(&ThreadlessTaskExecutor::GetProfilerMessage, this, ref(task.first)), *_profileTimeout, AsyncProfiler::NameGetterTag()); task.first(); } else task.first(); } catch(const std::exception& ex) { _exceptionHandler(ex); } } } <|endoftext|>
<commit_before>/** * Intrusive linked lists. * * An intrusive linked list uses link fields embedded directly in * objects as fields, much like how linked lists are often implemented * in C. As a result, adding an object to an intrusive linked list * requires no copying or allocation and is exception-safe. The * downside is that a given object can only be on one list per link * field in that object; however, this property is often true in * practice. * * Example use: * struct thing { * ilink<thing> link; * }; * ilist<thing, &thing::link> list; * * Because the usual access checks apply to the member data pointer * template argument, if the list is declared outside of the class, * then either the link field must be public (as above), or the list's * type must be declared inside the class (e.g., as a typedef): * class thing { * ilink<thing> link; * public: * typedef ilist<thing, &thing::link> list_t; * }; * thing::list_t list; * This is not necessary if the list is declared inside the class * (e.g., as a static field), though if this list is publicly * accessible, outside users will not be able to refer to its type * except through an in-class typedef or auto. */ #pragma once #include <utility> /** * @internal Given a pointer to a member and a member data pointer, * return a pointer to the object containing that member. */ template<class Container, class Member> Container * container_from_member(const Member *member, const Member Container::* mem_ptr) { // List of compilers where this trick works from Boost.Intrusive. #if defined(__GNUC__) || defined(__HP_aCC) || defined(__IBMCPP__) || \ defined(__DECCXX) Container *c = nullptr; const char *c_mem = reinterpret_cast<const char*>(&(c->*mem_ptr)); auto offset = c_mem - reinterpret_cast<const char*>(c); #else #error Unsupported compiler #endif return (Container*)((char*)member - offset); } /** * An embedded link used for singly-linked lists. */ template<typename T> struct islink { T* next; }; /** * Forward-iterator over singly linked lists. */ template<typename T, islink<T> T::* L> struct isiterator { T* elem; constexpr isiterator() : elem(nullptr) { } constexpr isiterator(T* e) : elem(e) { } T& operator*() const noexcept { return *elem; } T* operator->() const noexcept { return elem; } bool operator==(const isiterator &o) const noexcept { return o.elem == elem; } bool operator!=(const isiterator &o) const noexcept { return o.elem != elem; } isiterator &operator++() noexcept { elem = (elem->*L).next; return *this; } isiterator operator++(int) noexcept { isiterator cur = *this; ++(*this); return cur; } }; /** * An intrusive singly-linked list. This provides an API similar to * C++'s std::forward_list, but it is pointer-based instead of * value-based: adding an object to the list shares ownership of that * instance with the list, rather than copying it. As a result, this * class never performs allocation and never throws exceptions. * * Being a singly-linked list, this supports only forward iteration * starting at the first element of the list. Furthermore, having an * iterator to an element generally isn't enough to modify the list * around that element; most methods require an iterator to the * element *before* the position being modified (in contrast with the * standard requirement of an iterator to after the position being * modified). */ template<typename T, islink<T> T::* L> struct islist { typedef isiterator<T, L> iterator; islink<T> head; constexpr islist() : head{nullptr} { } islist(const islist &o) = delete; islist &operator=(const islist &o) = delete; islist(islist &&o) { *this = std::move(o); } islist &operator=(islist &&o) noexcept { head = o.head; o.head.next = nullptr; return *this; } iterator before_begin() noexcept { return iterator(container_from_member(&head, L)); } iterator begin() noexcept { return iterator(head.next); } iterator end() noexcept { return iterator(nullptr); } bool empty() const noexcept { return head.next == nullptr; } T& front() noexcept { return *head.next; } const T& front() const noexcept { return *head.next; } void push_front(T *x) noexcept { (x->*L).next = head.next; head.next = x; } void pop_front() noexcept { head.next = (head.next->*L).next; } iterator insert_after(iterator pos, T* x) noexcept { (x->*L).next = (pos.elem->*L).next; (pos.elem->*L).next = x; return ++pos; } iterator erase_after(iterator pos) noexcept { (pos.elem->*L).next = ((pos.elem->*L).next->*L).next; return ++pos; } iterator erase_after(iterator pos, iterator last) noexcept { (pos.elem->*L).next = last.elem; return last; } void clear() noexcept { head.next = nullptr; } /** * Insert the contents of x after pos and clear x. In general, this * is linear in the length of x, but if pos points to the last * element of this list, this is constant-time. */ void splice_after(iterator pos, islist &&x) { if ((pos.elem->*L).next) { // Find the last link in x and patch it. As a special case, if // pos's next is null, we can skip this entirely, making // splice_after O(1) when splicing at the end of the list. for (auto xit = x.begin(), end = x.end(); xit != end; ++xit) { if ((*xit.*L).next == nullptr) { (*xit.*L).next = (pos.elem->*L).next; break; } } } (pos.elem->*L).next = x.head.next; x.head.next = nullptr; } /** * Cut this list after the element pointed to by @c pos and return a * new list consisting of all elements starting at <code>pos + * 1</code>. */ islist cut_after(iterator pos) noexcept { auto nfirst = (pos.elem->*L).next; (pos.elem->*L).next = nullptr; islist nl; nl.head.next = nfirst; return nl; } /** * Return an iterator pointing to elem, which must be in this list. */ iterator iterator_to(T *elem) { return iterator(elem); } }; /** * An embedded link used for doubly-linked lists. */ template<typename T> struct ilink { T *prev, *next; }; /** * Iterator over double-linked lists. */ template<typename T, ilink<T> T::* L> struct iiterator { T* elem; constexpr iiterator(T* e) : elem(e) { } constexpr iiterator() : elem(nullptr) { } T& operator*() const noexcept { return *elem; } T* operator->() const noexcept { return elem; } bool operator==(const iiterator &o) const noexcept { return o.elem == elem; } bool operator!=(const iiterator &o) const noexcept { return o.elem != elem; } iiterator &operator++() noexcept { elem = (elem->*L).next; return *this; } iiterator operator++(int) noexcept { iiterator cur = *this; ++(*this); return cur; } iiterator &operator--() noexcept { elem = (elem->*L).prev; return *this; } iiterator operator--(int) noexcept { iiterator cur = *this; --(*this); return cur; } }; /** * An intrusive doubly-linked list. This provides an API similar to * C++'s std::list, but it is pointer-based instead of value-based: * adding an object to the list shares ownership of that instance with * the list, rather than copying it. As a result, this class never * performs allocation and never throws exceptions. * * Being a doubly-linked list, this supports bi-directional * iteration. This list tracks both the head and the tail of the * list, so it's possible to start from either end. */ template<typename T, ilink<T> T::* L> struct ilist { typedef iiterator<T, L> iterator; ilink<T> head; ilist() { clear(); } ilist(const ilist &o) = delete; ilist &operator=(const ilist &o) = delete; ilist(ilist &&o) { *this = std::move(o); } ilist &operator=(ilist &&o) noexcept { // Fix up first and last elements to point to this list. It's // important to do this on o.head *before* we copy it to head: if // the other list is empty, o.head will point to itself so our // update will update o.head. (o.head.next->*L).prev = (o.head.prev->*L).next = container_from_member(&head, L); head = o.head; // Reset other list o.clear(); return *this; } iterator begin() const noexcept { return iterator(head.next); } iterator end() const noexcept { return iterator(container_from_member(&head, L)); } bool empty() const noexcept { return head.next == container_from_member(&head, L); } T& front() noexcept { return *head.next; } const T& front() const noexcept { return *head.next; } T& back() noexcept { return *head.prev; } const T& back() const noexcept { return *head.prev; } void push_front(T *x) noexcept { insert(begin(), x); } void pop_front() noexcept { erase(begin()); } void push_back(T *x) noexcept { insert(end(), x); } void pop_back() noexcept { erase(iterator(head.prev)); } iterator insert(iterator pos, T* x) noexcept { (x->*L).next = pos.elem; (x->*L).prev = (pos.elem->*L).prev; ((pos.elem->*L).prev->*L).next = x; (pos.elem->*L).prev = x; return ++pos; } iterator erase(iterator pos) noexcept { ((pos.elem->*L).next->*L).prev = (pos.elem->*L).prev; ((pos.elem->*L).prev->*L).next = (pos.elem->*L).next; return ++pos; } iterator erase(iterator pos, iterator last) noexcept { ((pos.elem->*L).prev->*L).next = last.elem; (last.elem->*L).prev = (pos.elem->*L).prev; return last; } void clear() noexcept { head.prev = head.next = container_from_member(&head, L); } /** * Return an iterator pointing to elem, which must be in this list. */ static iterator iterator_to(T *elem) { return iterator(elem); } }; <commit_msg>ilist: Add a singly-linked queue class<commit_after>/** * Intrusive linked lists. * * An intrusive linked list uses link fields embedded directly in * objects as fields, much like how linked lists are often implemented * in C. As a result, adding an object to an intrusive linked list * requires no copying or allocation and is exception-safe. The * downside is that a given object can only be on one list per link * field in that object; however, this property is often true in * practice. * * Example use: * struct thing { * ilink<thing> link; * }; * ilist<thing, &thing::link> list; * * Because the usual access checks apply to the member data pointer * template argument, if the list is declared outside of the class, * then either the link field must be public (as above), or the list's * type must be declared inside the class (e.g., as a typedef): * class thing { * ilink<thing> link; * public: * typedef ilist<thing, &thing::link> list_t; * }; * thing::list_t list; * This is not necessary if the list is declared inside the class * (e.g., as a static field), though if this list is publicly * accessible, outside users will not be able to refer to its type * except through an in-class typedef or auto. */ #pragma once #include <utility> /** * @internal Given a pointer to a member and a member data pointer, * return a pointer to the object containing that member. */ template<class Container, class Member> Container * container_from_member(const Member *member, const Member Container::* mem_ptr) { // List of compilers where this trick works from Boost.Intrusive. #if defined(__GNUC__) || defined(__HP_aCC) || defined(__IBMCPP__) || \ defined(__DECCXX) Container *c = nullptr; const char *c_mem = reinterpret_cast<const char*>(&(c->*mem_ptr)); auto offset = c_mem - reinterpret_cast<const char*>(c); #else #error Unsupported compiler #endif return (Container*)((char*)member - offset); } /** * An embedded link used for singly-linked lists. */ template<typename T> struct islink { T* next; }; /** * Forward-iterator over singly linked lists. */ template<typename T, islink<T> T::* L> struct isiterator { T* elem; constexpr isiterator() : elem(nullptr) { } constexpr isiterator(T* e) : elem(e) { } T& operator*() const noexcept { return *elem; } T* operator->() const noexcept { return elem; } bool operator==(const isiterator &o) const noexcept { return o.elem == elem; } bool operator!=(const isiterator &o) const noexcept { return o.elem != elem; } isiterator &operator++() noexcept { elem = (elem->*L).next; return *this; } isiterator operator++(int) noexcept { isiterator cur = *this; ++(*this); return cur; } }; /** * An intrusive singly-linked list. This provides an API similar to * C++'s std::forward_list, but it is pointer-based instead of * value-based: adding an object to the list shares ownership of that * instance with the list, rather than copying it. As a result, this * class never performs allocation and never throws exceptions. * * Being a singly-linked list, this supports only forward iteration * starting at the first element of the list. Furthermore, having an * iterator to an element generally isn't enough to modify the list * around that element; most methods require an iterator to the * element *before* the position being modified (in contrast with the * standard requirement of an iterator to after the position being * modified). */ template<typename T, islink<T> T::* L> struct islist { typedef isiterator<T, L> iterator; islink<T> head; constexpr islist() : head{nullptr} { } islist(const islist &o) = delete; islist &operator=(const islist &o) = delete; islist(islist &&o) { *this = std::move(o); } islist &operator=(islist &&o) noexcept { head = o.head; o.head.next = nullptr; return *this; } iterator before_begin() noexcept { return iterator(container_from_member(&head, L)); } iterator begin() noexcept { return iterator(head.next); } iterator end() noexcept { return iterator(nullptr); } bool empty() const noexcept { return head.next == nullptr; } T& front() noexcept { return *head.next; } const T& front() const noexcept { return *head.next; } void push_front(T *x) noexcept { (x->*L).next = head.next; head.next = x; } void pop_front() noexcept { head.next = (head.next->*L).next; } iterator insert_after(iterator pos, T* x) noexcept { (x->*L).next = (pos.elem->*L).next; (pos.elem->*L).next = x; return ++pos; } iterator erase_after(iterator pos) noexcept { (pos.elem->*L).next = ((pos.elem->*L).next->*L).next; return ++pos; } iterator erase_after(iterator pos, iterator last) noexcept { (pos.elem->*L).next = last.elem; return last; } void clear() noexcept { head.next = nullptr; } /** * Insert the contents of x after pos and clear x. In general, this * is linear in the length of x, but if pos points to the last * element of this list, this is constant-time. */ void splice_after(iterator pos, islist &&x) { if ((pos.elem->*L).next) { // Find the last link in x and patch it. As a special case, if // pos's next is null, we can skip this entirely, making // splice_after O(1) when splicing at the end of the list. for (auto xit = x.begin(), end = x.end(); xit != end; ++xit) { if ((*xit.*L).next == nullptr) { (*xit.*L).next = (pos.elem->*L).next; break; } } } (pos.elem->*L).next = x.head.next; x.head.next = nullptr; } /** * Cut this list after the element pointed to by @c pos and return a * new list consisting of all elements starting at <code>pos + * 1</code>. */ islist cut_after(iterator pos) noexcept { auto nfirst = (pos.elem->*L).next; (pos.elem->*L).next = nullptr; islist nl; nl.head.next = nfirst; return nl; } /** * Return an iterator pointing to elem, which must be in this list. */ iterator iterator_to(T *elem) { return iterator(elem); } }; /** * An intrusive single-linked list with both head and tail pointers. * This is similar to islist (and uses the same link and iterator * type), but can provides O(1) access to the last element in the * list. */ template<typename T, islink<T> T::* L> struct isqueue : private islist<T, L> { typedef typename islist<T,L>::iterator iterator; using islist<T,L>::head; private: T* last; public: constexpr isqueue() : islist<T,L>(), last(nullptr) { } isqueue(const isqueue &o) = delete; isqueue &operator=(const isqueue &o) = delete; isqueue(isqueue &&o) { *this = std::move(o); } isqueue &operator=(isqueue &&o) noexcept { head = o.head; last = o.last; o.head.next = nullptr; o.last = nullptr; return *this; } using islist<T,L>::before_begin; iterator before_end() noexcept { if (empty()) return before_begin(); return iterator_to(last); } using islist<T,L>::begin; using islist<T,L>::end; using islist<T,L>::empty; using islist<T,L>::front; T& back() noexcept { return *last; } void push_front(T *x) noexcept { if (empty()) last = x; islist<T, L>::push_front(x); } void push_back(T *x) noexcept { insert_after(before_end(), x); } void pop_front() noexcept { islist<T, L>::pop_front(); if (empty()) last = nullptr; } iterator insert_after(iterator pos, T* x) noexcept { if (!(pos.elem->*L).next) last = x; return islist<T, L>::insert_after(pos, x); } iterator erase_after(iterator pos) noexcept { auto it = islist<T, L>::erase_after(pos); if (empty()) last = nullptr; else if (!(pos.elem->*L).next) last = pos.elem; return it; } iterator erase_after(iterator pos, iterator last) noexcept { auto it = islist<T, L>::erase_after(pos, last); if (empty()) last = nullptr; else if (!(pos.elem->*L).next) last = pos.elem; return it; } void clear() noexcept { islist<T, L>::clear(); last = nullptr; } isqueue cut_after(iterator pos) noexcept { isqueue nq; nq.last = last; auto nl = islist<T, L>::cut_after(pos); nq.head = nl.head; if (empty()) last = nullptr; else last = pos.elem; return nq; } using islist<T, L>::iterator_to; }; /** * An embedded link used for doubly-linked lists. */ template<typename T> struct ilink { T *prev, *next; }; /** * Iterator over double-linked lists. */ template<typename T, ilink<T> T::* L> struct iiterator { T* elem; constexpr iiterator(T* e) : elem(e) { } constexpr iiterator() : elem(nullptr) { } T& operator*() const noexcept { return *elem; } T* operator->() const noexcept { return elem; } bool operator==(const iiterator &o) const noexcept { return o.elem == elem; } bool operator!=(const iiterator &o) const noexcept { return o.elem != elem; } iiterator &operator++() noexcept { elem = (elem->*L).next; return *this; } iiterator operator++(int) noexcept { iiterator cur = *this; ++(*this); return cur; } iiterator &operator--() noexcept { elem = (elem->*L).prev; return *this; } iiterator operator--(int) noexcept { iiterator cur = *this; --(*this); return cur; } }; /** * An intrusive doubly-linked list. This provides an API similar to * C++'s std::list, but it is pointer-based instead of value-based: * adding an object to the list shares ownership of that instance with * the list, rather than copying it. As a result, this class never * performs allocation and never throws exceptions. * * Being a doubly-linked list, this supports bi-directional * iteration. This list tracks both the head and the tail of the * list, so it's possible to start from either end. */ template<typename T, ilink<T> T::* L> struct ilist { typedef iiterator<T, L> iterator; ilink<T> head; ilist() { clear(); } ilist(const ilist &o) = delete; ilist &operator=(const ilist &o) = delete; ilist(ilist &&o) { *this = std::move(o); } ilist &operator=(ilist &&o) noexcept { // Fix up first and last elements to point to this list. It's // important to do this on o.head *before* we copy it to head: if // the other list is empty, o.head will point to itself so our // update will update o.head. (o.head.next->*L).prev = (o.head.prev->*L).next = container_from_member(&head, L); head = o.head; // Reset other list o.clear(); return *this; } iterator begin() const noexcept { return iterator(head.next); } iterator end() const noexcept { return iterator(container_from_member(&head, L)); } bool empty() const noexcept { return head.next == container_from_member(&head, L); } T& front() noexcept { return *head.next; } const T& front() const noexcept { return *head.next; } T& back() noexcept { return *head.prev; } const T& back() const noexcept { return *head.prev; } void push_front(T *x) noexcept { insert(begin(), x); } void pop_front() noexcept { erase(begin()); } void push_back(T *x) noexcept { insert(end(), x); } void pop_back() noexcept { erase(iterator(head.prev)); } iterator insert(iterator pos, T* x) noexcept { (x->*L).next = pos.elem; (x->*L).prev = (pos.elem->*L).prev; ((pos.elem->*L).prev->*L).next = x; (pos.elem->*L).prev = x; return ++pos; } iterator erase(iterator pos) noexcept { ((pos.elem->*L).next->*L).prev = (pos.elem->*L).prev; ((pos.elem->*L).prev->*L).next = (pos.elem->*L).next; return ++pos; } iterator erase(iterator pos, iterator last) noexcept { ((pos.elem->*L).prev->*L).next = last.elem; (last.elem->*L).prev = (pos.elem->*L).prev; return last; } void clear() noexcept { head.prev = head.next = container_from_member(&head, L); } /** * Return an iterator pointing to elem, which must be in this list. */ static iterator iterator_to(T *elem) { return iterator(elem); } }; <|endoftext|>
<commit_before>#include "../metaSMT/impl/_var_id.hpp" #include <boost/atomic.hpp> namespace metaSMT { namespace impl { unsigned new_var_id( ) { static boost::atomic_uint _id ( 0u ); ++_id; return _id; } } /* impl */ } /* metaSMT */ <commit_msg>workaround for the boost::atomic issue<commit_after>#include "../metaSMT/impl/_var_id.hpp" #include <boost/version.hpp> #if BOOST_VERSION >= 105500 #include <boost/atomic.hpp> unsigned metaSMT::impl::new_var_id() { static boost::atomic_uint _id ( 0u ); ++_id; return _id; } #else unsigned metaSMT::impl::new_var_id() { static unsigned _id ( 0u ); ++_id; return _id; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test/test_timeouts.h" #include "base/command_line.h" #include "base/logging.h" #include "base/string_number_conversions.h" #include "base/test/test_switches.h" namespace { // Sets value to the greatest of: // 1) value's current value. // 2) min_value. // 3) the numerical value given by switch_name on the command line. void InitializeTimeout(const char* switch_name, int min_value, int* value) { DCHECK(value); if (CommandLine::ForCurrentProcess()->HasSwitch(switch_name)) { std::string string_value( CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switch_name)); int timeout; base::StringToInt(string_value, &timeout); *value = std::max(*value, timeout); } *value = std::max(*value, min_value); } // Sets value to the greatest of: // 1) value's current value. // 2) 0 // 3) the numerical value given by switch_name on the command line. void InitializeTimeout(const char* switch_name, int* value) { InitializeTimeout(switch_name, 0, value); } } // namespace // static bool TestTimeouts::initialized_ = false; // The timeout values should increase in the order they appear in this block. // static int TestTimeouts::tiny_timeout_ms_ = 100; int TestTimeouts::action_timeout_ms_ = 2000; int TestTimeouts::action_max_timeout_ms_ = 31000; int TestTimeouts::large_test_timeout_ms_ = 3 * 60 * 1000; int TestTimeouts::huge_test_timeout_ms_ = 10 * 60 * 1000; // static int TestTimeouts::live_operation_timeout_ms_ = 45000; // static void TestTimeouts::Initialize() { if (initialized_) { NOTREACHED(); return; } initialized_ = true; // Note that these timeouts MUST be initialized in the correct order as // per the CHECKS below. InitializeTimeout(switches::kTestTinyTimeout, &tiny_timeout_ms_); InitializeTimeout(switches::kUiTestActionTimeout, tiny_timeout_ms_, &action_timeout_ms_); InitializeTimeout(switches::kUiTestActionMaxTimeout, action_timeout_ms_, &action_max_timeout_ms_); // TODO(phajdan.jr): Fix callers and remove kTestTerminateTimeout. InitializeTimeout(switches::kTestTerminateTimeout, &action_max_timeout_ms_); InitializeTimeout(switches::kTestLargeTimeout, action_max_timeout_ms_, &large_test_timeout_ms_); InitializeTimeout(switches::kUiTestTimeout, large_test_timeout_ms_, &huge_test_timeout_ms_); // The timeout values should be increasing in the right order. CHECK(tiny_timeout_ms_ <= action_timeout_ms_); CHECK(action_timeout_ms_ <= action_max_timeout_ms_); CHECK(action_max_timeout_ms_ <= large_test_timeout_ms_); CHECK(large_test_timeout_ms_ <= huge_test_timeout_ms_); InitializeTimeout(switches::kLiveOperationTimeout, &live_operation_timeout_ms_); } <commit_msg>Increase test timeout to 45s.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test/test_timeouts.h" #include "base/command_line.h" #include "base/logging.h" #include "base/string_number_conversions.h" #include "base/test/test_switches.h" namespace { // Sets value to the greatest of: // 1) value's current value. // 2) min_value. // 3) the numerical value given by switch_name on the command line. void InitializeTimeout(const char* switch_name, int min_value, int* value) { DCHECK(value); if (CommandLine::ForCurrentProcess()->HasSwitch(switch_name)) { std::string string_value( CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switch_name)); int timeout; base::StringToInt(string_value, &timeout); *value = std::max(*value, timeout); } *value = std::max(*value, min_value); } // Sets value to the greatest of: // 1) value's current value. // 2) 0 // 3) the numerical value given by switch_name on the command line. void InitializeTimeout(const char* switch_name, int* value) { InitializeTimeout(switch_name, 0, value); } } // namespace // static bool TestTimeouts::initialized_ = false; // The timeout values should increase in the order they appear in this block. // static int TestTimeouts::tiny_timeout_ms_ = 100; int TestTimeouts::action_timeout_ms_ = 2000; int TestTimeouts::action_max_timeout_ms_ = 45000; int TestTimeouts::large_test_timeout_ms_ = 3 * 60 * 1000; int TestTimeouts::huge_test_timeout_ms_ = 10 * 60 * 1000; // static int TestTimeouts::live_operation_timeout_ms_ = 45000; // static void TestTimeouts::Initialize() { if (initialized_) { NOTREACHED(); return; } initialized_ = true; // Note that these timeouts MUST be initialized in the correct order as // per the CHECKS below. InitializeTimeout(switches::kTestTinyTimeout, &tiny_timeout_ms_); InitializeTimeout(switches::kUiTestActionTimeout, tiny_timeout_ms_, &action_timeout_ms_); InitializeTimeout(switches::kUiTestActionMaxTimeout, action_timeout_ms_, &action_max_timeout_ms_); // TODO(phajdan.jr): Fix callers and remove kTestTerminateTimeout. InitializeTimeout(switches::kTestTerminateTimeout, &action_max_timeout_ms_); InitializeTimeout(switches::kTestLargeTimeout, action_max_timeout_ms_, &large_test_timeout_ms_); InitializeTimeout(switches::kUiTestTimeout, large_test_timeout_ms_, &huge_test_timeout_ms_); // The timeout values should be increasing in the right order. CHECK(tiny_timeout_ms_ <= action_timeout_ms_); CHECK(action_timeout_ms_ <= action_max_timeout_ms_); CHECK(action_max_timeout_ms_ <= large_test_timeout_ms_); CHECK(large_test_timeout_ms_ <= huge_test_timeout_ms_); InitializeTimeout(switches::kLiveOperationTimeout, &live_operation_timeout_ms_); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: emptyproperties.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:14:05 $ * * 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 _SDR_PROPERTIES_EMPTYPROPERTIES_HXX #include <svx/sdr/properties/emptyproperties.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #ifndef _SVDDEF_HXX #include <svddef.hxx> #endif #ifndef _SVDOBJ_HXX #include <svdobj.hxx> #endif #ifndef _SVDPOOL_HXX #include <svdpool.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace properties { // create a new itemset SfxItemSet& EmptyProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool) { // Basic implementation; Basic object has NO attributes DBG_ASSERT(sal_False, "EmptyProperties::CreateObjectSpecificItemSet() should never be called"); return *(new SfxItemSet(rPool)); } EmptyProperties::EmptyProperties(SdrObject& rObj) : BaseProperties(rObj), mpEmptyItemSet(0L) { } EmptyProperties::EmptyProperties(const EmptyProperties& rProps, SdrObject& rObj) : BaseProperties(rProps, rObj), mpEmptyItemSet(0L) { // #115593# // do not gererate an assert, else derivations like PageProperties will generate an assert // using the Clone() operator path. } EmptyProperties::~EmptyProperties() { if(mpEmptyItemSet) { delete mpEmptyItemSet; mpEmptyItemSet = 0L; } } BaseProperties& EmptyProperties::Clone(SdrObject& rObj) const { return *(new EmptyProperties(*this, rObj)); } const SfxItemSet& EmptyProperties::GetObjectItemSet() const { if(!mpEmptyItemSet) { ((EmptyProperties*)this)->mpEmptyItemSet = &(((EmptyProperties*)this)->CreateObjectSpecificItemSet(*GetSdrObject().GetObjectItemPool())); } DBG_ASSERT(mpEmptyItemSet, "Could not create an SfxItemSet(!)"); DBG_ASSERT(sal_False, "EmptyProperties::GetObjectItemSet() should never be called (!)"); return *mpEmptyItemSet; } void EmptyProperties::SetObjectItem(const SfxPoolItem& rItem) { DBG_ASSERT(sal_False, "EmptyProperties::SetObjectItem() should never be called (!)"); } void EmptyProperties::SetObjectItemDirect(const SfxPoolItem& rItem) { DBG_ASSERT(sal_False, "EmptyProperties::SetObjectItemDirect() should never be called (!)"); } void EmptyProperties::ClearObjectItem(const sal_uInt16 nWhich) { DBG_ASSERT(sal_False, "EmptyProperties::ClearObjectItem() should never be called (!)"); } void EmptyProperties::ClearObjectItemDirect(const sal_uInt16 nWhich) { DBG_ASSERT(sal_False, "EmptyProperties::ClearObjectItemDirect() should never be called (!)"); } void EmptyProperties::SetObjectItemSet(const SfxItemSet& rSet) { DBG_ASSERT(sal_False, "EmptyProperties::SetObjectItemSet() should never be called (!)"); } void EmptyProperties::ItemSetChanged(const SfxItemSet& rSet) { DBG_ASSERT(sal_False, "EmptyProperties::ItemSetChanged() should never be called (!)"); } sal_Bool EmptyProperties::AllowItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem) const { DBG_ASSERT(sal_False, "EmptyProperties::AllowItemChange() should never be called (!)"); return sal_True; } void EmptyProperties::ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem) { DBG_ASSERT(sal_False, "EmptyProperties::ItemChange() should never be called (!)"); } void EmptyProperties::PostItemChange(const sal_uInt16 nWhich) { DBG_ASSERT(sal_False, "EmptyProperties::PostItemChange() should never be called (!)"); } void EmptyProperties::SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr) { DBG_ASSERT(sal_False, "EmptyProperties::SetStyleSheet() should never be called (!)"); } SfxStyleSheet* EmptyProperties::GetStyleSheet() const { DBG_ASSERT(sal_False, "EmptyProperties::GetStyleSheet() should never be called (!)"); return 0L; } //BFS01 void EmptyProperties::PreProcessSave() //BFS01 { //BFS01 } //BFS01 void EmptyProperties::PostProcessSave() //BFS01 { //BFS01 } } // end of namespace properties } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <commit_msg>INTEGRATION: CWS warnings01 (1.5.220); FILE MERGED 2006/02/21 16:59:33 aw 1.5.220.1: #i55991# Adaptions to warning free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: emptyproperties.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2006-06-19 16:30:28 $ * * 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 _SDR_PROPERTIES_EMPTYPROPERTIES_HXX #include <svx/sdr/properties/emptyproperties.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #ifndef _SVDDEF_HXX #include <svddef.hxx> #endif #ifndef _SVDOBJ_HXX #include <svdobj.hxx> #endif #ifndef _SVDPOOL_HXX #include <svdpool.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace properties { // create a new itemset SfxItemSet& EmptyProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool) { // Basic implementation; Basic object has NO attributes DBG_ASSERT(sal_False, "EmptyProperties::CreateObjectSpecificItemSet() should never be called"); return *(new SfxItemSet(rPool)); } EmptyProperties::EmptyProperties(SdrObject& rObj) : BaseProperties(rObj), mpEmptyItemSet(0L) { } EmptyProperties::EmptyProperties(const EmptyProperties& rProps, SdrObject& rObj) : BaseProperties(rProps, rObj), mpEmptyItemSet(0L) { // #115593# // do not gererate an assert, else derivations like PageProperties will generate an assert // using the Clone() operator path. } EmptyProperties::~EmptyProperties() { if(mpEmptyItemSet) { delete mpEmptyItemSet; mpEmptyItemSet = 0L; } } BaseProperties& EmptyProperties::Clone(SdrObject& rObj) const { return *(new EmptyProperties(*this, rObj)); } const SfxItemSet& EmptyProperties::GetObjectItemSet() const { if(!mpEmptyItemSet) { ((EmptyProperties*)this)->mpEmptyItemSet = &(((EmptyProperties*)this)->CreateObjectSpecificItemSet(*GetSdrObject().GetObjectItemPool())); } DBG_ASSERT(mpEmptyItemSet, "Could not create an SfxItemSet(!)"); DBG_ASSERT(sal_False, "EmptyProperties::GetObjectItemSet() should never be called (!)"); return *mpEmptyItemSet; } void EmptyProperties::SetObjectItem(const SfxPoolItem& /*rItem*/) { DBG_ASSERT(sal_False, "EmptyProperties::SetObjectItem() should never be called (!)"); } void EmptyProperties::SetObjectItemDirect(const SfxPoolItem& /*rItem*/) { DBG_ASSERT(sal_False, "EmptyProperties::SetObjectItemDirect() should never be called (!)"); } void EmptyProperties::ClearObjectItem(const sal_uInt16 /*nWhich*/) { DBG_ASSERT(sal_False, "EmptyProperties::ClearObjectItem() should never be called (!)"); } void EmptyProperties::ClearObjectItemDirect(const sal_uInt16 /*nWhich*/) { DBG_ASSERT(sal_False, "EmptyProperties::ClearObjectItemDirect() should never be called (!)"); } void EmptyProperties::SetObjectItemSet(const SfxItemSet& /*rSet*/) { DBG_ASSERT(sal_False, "EmptyProperties::SetObjectItemSet() should never be called (!)"); } void EmptyProperties::ItemSetChanged(const SfxItemSet& /*rSet*/) { DBG_ASSERT(sal_False, "EmptyProperties::ItemSetChanged() should never be called (!)"); } sal_Bool EmptyProperties::AllowItemChange(const sal_uInt16 /*nWhich*/, const SfxPoolItem* /*pNewItem*/) const { DBG_ASSERT(sal_False, "EmptyProperties::AllowItemChange() should never be called (!)"); return sal_True; } void EmptyProperties::ItemChange(const sal_uInt16 /*nWhich*/, const SfxPoolItem* /*pNewItem*/) { DBG_ASSERT(sal_False, "EmptyProperties::ItemChange() should never be called (!)"); } void EmptyProperties::PostItemChange(const sal_uInt16 /*nWhich*/) { DBG_ASSERT(sal_False, "EmptyProperties::PostItemChange() should never be called (!)"); } void EmptyProperties::SetStyleSheet(SfxStyleSheet* /*pNewStyleSheet*/, sal_Bool /*bDontRemoveHardAttr*/) { DBG_ASSERT(sal_False, "EmptyProperties::SetStyleSheet() should never be called (!)"); } SfxStyleSheet* EmptyProperties::GetStyleSheet() const { DBG_ASSERT(sal_False, "EmptyProperties::GetStyleSheet() should never be called (!)"); return 0L; } //BFS01 void EmptyProperties::PreProcessSave() //BFS01 { //BFS01 } //BFS01 void EmptyProperties::PostProcessSave() //BFS01 { //BFS01 } } // end of namespace properties } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <|endoftext|>
<commit_before>/* * boost_input_utils.cc * * Created on: 12/12/14 * Author: Steven Wu * Modified DJW Aug-15 */ #include "utils/bamtools_fasta.h" #include "parsers.h" #include "boost_input_utils.h" void validate(boost::any& v, const vector<string>& values, nfreqs* target_type, int){ nfreqs result; vector<double> pi; for(vector<string>::const_iterator it = values.begin(); it != values.end(); ++it){ stringstream ss(*it); copy(istream_iterator<double>(ss), istream_iterator<double>(), back_inserter(pi)); } if(pi.size() != 4){ throw boost::program_options::invalid_option_value("Must specify 4 (and only 4) nucleotide frequencies"); } result.freqs = pi; v= result; } namespace BoostUtils { using namespace std; namespace po = boost::program_options; static bool file_exists(const std::string &name) { struct stat buffer; return (stat(name.c_str(), &buffer) == 0); } SampleMap ParseSamples(boost::program_options::variables_map &vm, BamTools::SamHeader &header){ //OK. We want to store data form each sample in a unique position in //a ReadDataVector. The caller also assumes that the ancestral sequence //is in the 0th poistion of the ReadDataVector. //The sample info in the BAM file is all in the ReadGroup headers, and //we want to be able to exclude some samples.So, we ask users to provide //a list of included samples. //To acheive all this we start parsing through every read group in the //BAM. If it's one to include, we add it the index map and remove it //from the list of samples to include. If it's not in our include list //we warn the user we are skipping some of the data. SampleMap name_map; vector<string> keepers = vm["sample-name"].as< vector<string> >(); string anc_tag = vm["ancestor"].as<string>(); uint16_t sindex = 1; bool ancestor_in_BAM = false; for(auto it = header.ReadGroups.Begin(); it!= header.ReadGroups.End(); it++){ if(it->HasSample()){ if (find(keepers.begin(), keepers.end(), it->Sample) == keepers.end()){ if(it->Sample == anc_tag ){ name_map[it->Sample] = 0; ancestor_in_BAM = true; } else { name_map[it->Sample] = numeric_limits<uint32_t>::max() ; cerr << "Warning: excluding data from '" << it->Sample << "' which is included in the BAM file but not the list of included samples" << endl; } } else { auto s = name_map.find(it->Sample); if( s == name_map.end()){//samples can have multiple readgroups... name_map[it->Sample] = sindex; sindex += 1; keepers.erase(find(keepers.begin(),keepers.end(),it->Sample)); } } } } //Once we've built the index map we can check if we now about every //sample in the BAM file and if we have set the ancesoe if(!ancestor_in_BAM){ cerr << "Error: No data for ancestral sample '" << anc_tag << "' in the specifified BAM file. Check the sample tags match" << endl; exit(1); } if(!keepers.size()==0){ cerr << "Sample(s) note persent in BAM file: "; for(auto s: keepers){ cerr << s; } cerr << endl; exit(1); } // And now.. go back over the read groups to map RG->sample index SampleMap samples; for(auto it = header.ReadGroups.Begin(); it!= header.ReadGroups.End(); it++){ if(it->HasSample()){ samples[it->ID] = name_map[it->Sample]; } } return samples; } void check_args(boost::program_options::variables_map &vm){ // Is the experimental design one of the ones we can handle? if (vm["ploidy-ancestor"].as<int>() > 2 or vm["ploidy-ancestor"].as<int>() < 1){ throw po::invalid_option_value("accuMUlate can't only deal with haploid or diploid ancestral samples"); } if (vm["ploidy-descendant"].as<int>() > 2 or vm["ploidy-descendant"].as<int>() < 1){ throw po::invalid_option_value("accuMUlate can't only deal with haploid or descendant samples"); } if (vm["ploidy-ancestor"].as<int>() == 1 and vm["ploidy-descendant"].as<int>() == 2){ throw po::invalid_option_value("accuMUlate has no model for a haploid->diploid MA experiemt"); } //Do we have the right over-dispersion params set if (vm["ploidy-ancestor"].as<int>() == 1 or vm["ploidy-descendant"].as<int>() == 1){ if(not vm.count("phi-haploid")){ throw po::invalid_option_value("Must specify phi-haploid (overdispersion for haploid sequencing)"); } } if (vm["ploidy-ancestor"].as<int>() == 2 or vm["ploidy-descendant"].as<int>() == 2){ if(not vm.count("phi-diploid")){ throw po::invalid_option_value("Must specify phi-diploid (overdispersion for diploid sequencing)"); } } } void ParseCommandLineInput(int argc, char **argv, boost::program_options::variables_map &vm) { po::options_description cmd("Command line options"); cmd.add_options() ("help,h", "Print a help message") ("bam,b", po::value<string>()->required(), "Path to BAM file") ("bam-index,x", po::value<string>()->default_value(""), "Path to BAM index, (defalult is <bam_path>.bai") ("reference,r", po::value<string>()->required(), "Path to reference genome") ("ancestor,a", po::value<string>()->required(), "Ancestor RG sample ID") ("sample-name,s", po::value<vector <string> >()->required(), "Sample tags to include") ("qual,q", po::value<int>()->default_value(13), "Base quality cuttoff") ("mapping-qual,m", po::value<int>()->default_value(13), "Mapping quality cuttoff") ("prob,p", po::value<double>()->default_value(0.1), "Mutaton probability cut-off") ("out,o", po::value<string>()->default_value("acuMUlate_result.tsv"), "Out file name") ("intervals,i", po::value<string>(), "Path to bed file") ("config,c", po::value<string>(), "Path to config file") ("theta", po::value<double>()->required(), "theta") ("nfreqs", po::value< nfreqs >()->multitoken(), "Nucleotide frequencies") ("mu", po::value<double>()->required(), "Experiment-long mutation rate") ("seq-error", po::value<double>()->required(), "Probability of sequencing error") ("ploidy-ancestor", po::value<int>()->default_value(2), "Polidy of ancestor (1 or 2)") ("ploidy-descendant", po::value<int>()->default_value(2), "Ploidy of descendant (1 or 2)") ("phi-haploid", po::value<double>(), "Over-dispersion for haploid sequencing") ("phi-diploid", po::value<double>(), "Over-dispersion for diploid sequencing"); po::store(po::parse_command_line(argc, argv, cmd), vm); if (vm.count("help")) { cout << cmd << endl; exit(-1); } if (vm.count("config")) { ifstream config_stream(vm["config"].as<string>()); po::store(po::parse_config_file(config_stream, cmd, false), vm); } vm.notify(); check_args(vm); } // Set up everything that has to be refered to by reference void ExtractInputVariables(boost::program_options::variables_map &vm, BamTools::BamReader &experiment, BamTools::RefVector &references, BamTools::SamHeader &header, BamTools::Fasta &reference_genome ) { string ref_file = vm["reference"].as<string>(); string bam_path = vm["bam"].as<string>(); string index_path = vm["bam-index"].as<string>(); if (index_path == "") { index_path = bam_path + ".bai"; } experiment.Open(bam_path); experiment.OpenIndex(index_path); references = experiment.GetReferenceData(); header = experiment.GetHeader(); experiment.OpenIndex(index_path); if (!file_exists(ref_file + ".fai")) { reference_genome.Open(ref_file); reference_genome.CreateIndex(ref_file + ".fai"); } else { reference_genome.Open(ref_file, ref_file + ".fai"); } } ModelParams CreateModelParams(boost::program_options::variables_map vm) { ModelParams params = { vm["theta"].as<double>(), vm["nfreqs"].as< nfreqs >().freqs, vm["mu"].as<double>(), vm["seq-error"].as<double>(), vm["phi-haploid"].as<double>(), vm["phi-diploid"].as<double>(), vm["ploidy-ancestor"].as<int>(), vm["ploidy-descendant"].as<int>() }; return params; } } <commit_msg>Test nfreqs sum to 1.0, closes #16<commit_after>/* * boost_input_utils.cc * * Created on: 12/12/14 * Author: Steven Wu * Modified DJW Aug-15 */ #include "utils/bamtools_fasta.h" #include "parsers.h" #include "boost_input_utils.h" void validate(boost::any& v, const vector<string>& values, nfreqs* target_type, int){ nfreqs result; vector<double> pi; for(vector<string>::const_iterator it = values.begin(); it != values.end(); ++it){ stringstream ss(*it); copy(istream_iterator<double>(ss), istream_iterator<double>(), back_inserter(pi)); } if(pi.size() != 4){ throw boost::program_options::invalid_option_value("Must specify 4 (and only 4) nucleotide frequencies"); } if( accumulate(pi.begin(), pi.end(), 0.0) != 1.0){ throw boost::program_options::invalid_option_value("Nucleotide frequencies don't sum to 1.0"); } result.freqs = pi; v= result; } namespace BoostUtils { using namespace std; namespace po = boost::program_options; static bool file_exists(const std::string &name) { struct stat buffer; return (stat(name.c_str(), &buffer) == 0); } SampleMap ParseSamples(boost::program_options::variables_map &vm, BamTools::SamHeader &header){ //OK. We want to store data form each sample in a unique position in //a ReadDataVector. The caller also assumes that the ancestral sequence //is in the 0th poistion of the ReadDataVector. //The sample info in the BAM file is all in the ReadGroup headers, and //we want to be able to exclude some samples.So, we ask users to provide //a list of included samples. //To acheive all this we start parsing through every read group in the //BAM. If it's one to include, we add it the index map and remove it //from the list of samples to include. If it's not in our include list //we warn the user we are skipping some of the data. SampleMap name_map; vector<string> keepers = vm["sample-name"].as< vector<string> >(); string anc_tag = vm["ancestor"].as<string>(); uint16_t sindex = 1; bool ancestor_in_BAM = false; for(auto it = header.ReadGroups.Begin(); it!= header.ReadGroups.End(); it++){ if(it->HasSample()){ if (find(keepers.begin(), keepers.end(), it->Sample) == keepers.end()){ if(it->Sample == anc_tag ){ name_map[it->Sample] = 0; ancestor_in_BAM = true; } else { name_map[it->Sample] = numeric_limits<uint32_t>::max() ; cerr << "Warning: excluding data from '" << it->Sample << "' which is included in the BAM file but not the list of included samples" << endl; } } else { auto s = name_map.find(it->Sample); if( s == name_map.end()){//samples can have multiple readgroups... name_map[it->Sample] = sindex; sindex += 1; keepers.erase(find(keepers.begin(),keepers.end(),it->Sample)); } } } } //Once we've built the index map we can check if we now about every //sample in the BAM file and if we have set the ancesoe if(!ancestor_in_BAM){ cerr << "Error: No data for ancestral sample '" << anc_tag << "' in the specifified BAM file. Check the sample tags match" << endl; exit(1); } if(!keepers.size()==0){ cerr << "Sample(s) note persent in BAM file: "; for(auto s: keepers){ cerr << s; } cerr << endl; exit(1); } // And now.. go back over the read groups to map RG->sample index SampleMap samples; for(auto it = header.ReadGroups.Begin(); it!= header.ReadGroups.End(); it++){ if(it->HasSample()){ samples[it->ID] = name_map[it->Sample]; } } return samples; } void check_args(boost::program_options::variables_map &vm){ // Is the experimental design one of the ones we can handle? if (vm["ploidy-ancestor"].as<int>() > 2 or vm["ploidy-ancestor"].as<int>() < 1){ throw po::invalid_option_value("accuMUlate can't only deal with haploid or diploid ancestral samples"); } if (vm["ploidy-descendant"].as<int>() > 2 or vm["ploidy-descendant"].as<int>() < 1){ throw po::invalid_option_value("accuMUlate can't only deal with haploid or descendant samples"); } if (vm["ploidy-ancestor"].as<int>() == 1 and vm["ploidy-descendant"].as<int>() == 2){ throw po::invalid_option_value("accuMUlate has no model for a haploid->diploid MA experiemt"); } //Do we have the right over-dispersion params set if (vm["ploidy-ancestor"].as<int>() == 1 or vm["ploidy-descendant"].as<int>() == 1){ if(not vm.count("phi-haploid")){ throw po::invalid_option_value("Must specify phi-haploid (overdispersion for haploid sequencing)"); } } if (vm["ploidy-ancestor"].as<int>() == 2 or vm["ploidy-descendant"].as<int>() == 2){ if(not vm.count("phi-diploid")){ throw po::invalid_option_value("Must specify phi-diploid (overdispersion for diploid sequencing)"); } } } void ParseCommandLineInput(int argc, char **argv, boost::program_options::variables_map &vm) { po::options_description cmd("Command line options"); cmd.add_options() ("help,h", "Print a help message") ("bam,b", po::value<string>()->required(), "Path to BAM file") ("bam-index,x", po::value<string>()->default_value(""), "Path to BAM index, (defalult is <bam_path>.bai") ("reference,r", po::value<string>()->required(), "Path to reference genome") ("ancestor,a", po::value<string>()->required(), "Ancestor RG sample ID") ("sample-name,s", po::value<vector <string> >()->required(), "Sample tags to include") ("qual,q", po::value<int>()->default_value(13), "Base quality cuttoff") ("mapping-qual,m", po::value<int>()->default_value(13), "Mapping quality cuttoff") ("prob,p", po::value<double>()->default_value(0.1), "Mutaton probability cut-off") ("out,o", po::value<string>()->default_value("acuMUlate_result.tsv"), "Out file name") ("intervals,i", po::value<string>(), "Path to bed file") ("config,c", po::value<string>(), "Path to config file") ("theta", po::value<double>()->required(), "theta") ("nfreqs", po::value< nfreqs >()->multitoken(), "Nucleotide frequencies") ("mu", po::value<double>()->required(), "Experiment-long mutation rate") ("seq-error", po::value<double>()->required(), "Probability of sequencing error") ("ploidy-ancestor", po::value<int>()->default_value(2), "Polidy of ancestor (1 or 2)") ("ploidy-descendant", po::value<int>()->default_value(2), "Ploidy of descendant (1 or 2)") ("phi-haploid", po::value<double>(), "Over-dispersion for haploid sequencing") ("phi-diploid", po::value<double>(), "Over-dispersion for diploid sequencing"); po::store(po::parse_command_line(argc, argv, cmd), vm); if (vm.count("help")) { cout << cmd << endl; exit(-1); } if (vm.count("config")) { ifstream config_stream(vm["config"].as<string>()); po::store(po::parse_config_file(config_stream, cmd, false), vm); } vm.notify(); check_args(vm); } // Set up everything that has to be refered to by reference void ExtractInputVariables(boost::program_options::variables_map &vm, BamTools::BamReader &experiment, BamTools::RefVector &references, BamTools::SamHeader &header, BamTools::Fasta &reference_genome ) { string ref_file = vm["reference"].as<string>(); string bam_path = vm["bam"].as<string>(); string index_path = vm["bam-index"].as<string>(); if (index_path == "") { index_path = bam_path + ".bai"; } experiment.Open(bam_path); experiment.OpenIndex(index_path); references = experiment.GetReferenceData(); header = experiment.GetHeader(); experiment.OpenIndex(index_path); if (!file_exists(ref_file + ".fai")) { reference_genome.Open(ref_file); reference_genome.CreateIndex(ref_file + ".fai"); } else { reference_genome.Open(ref_file, ref_file + ".fai"); } } ModelParams CreateModelParams(boost::program_options::variables_map vm) { ModelParams params = { vm["theta"].as<double>(), vm["nfreqs"].as< nfreqs >().freqs, vm["mu"].as<double>(), vm["seq-error"].as<double>(), vm["phi-haploid"].as<double>(), vm["phi-diploid"].as<double>(), vm["ploidy-ancestor"].as<int>(), vm["ploidy-descendant"].as<int>() }; return params; } } <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "ContactMaster.h" #include "SystemBase.h" // libmesh includes #include "sparse_matrix.h" template<> InputParameters validParams<ContactMaster>() { InputParameters params = validParams<DiracKernel>(); params.addRequiredParam<unsigned int>("boundary", "The master boundary"); params.addRequiredParam<unsigned int>("slave", "The slave boundary"); params.addRequiredParam<Real>("component", "An integer corresponding to the direction the variable this kernel acts in. (0 for x, 1 for y, 2 for z)"); params.addCoupledVar("disp_x", "The x displacement"); params.addCoupledVar("disp_y", "The y displacement"); params.addCoupledVar("disp_z", "The z displacement"); params.set<bool>("use_displaced_mesh") = true; return params; } ContactMaster::ContactMaster(const std::string & name, InputParameters parameters) : DiracKernel(name, parameters), _component(getParam<Real>("component")), _penetration_locator(getPenetrationLocator(getParam<unsigned int>("boundary"), getParam<unsigned int>("slave"))), _residual_copy(_sys.residualCopy()), _x_var(isCoupled("disp_x") ? coupled("disp_x") : 99999), _y_var(isCoupled("disp_y") ? coupled("disp_y") : 99999), _z_var(isCoupled("disp_z") ? coupled("disp_z") : 99999), _vars(_x_var, _y_var, _z_var) {} void ContactMaster::addPoints() { point_to_info.clear(); std::map<unsigned int, PenetrationLocator::PenetrationInfo *>::iterator it = _penetration_locator._penetration_info.begin(); std::map<unsigned int, PenetrationLocator::PenetrationInfo *>::iterator end = _penetration_locator._penetration_info.end(); for(; it!=end; ++it) { unsigned int slave_node_num = it->first; PenetrationLocator::PenetrationInfo * pinfo = it->second; if(!pinfo) continue; Node * node = pinfo->_node; if(_sys.currentlyComputingJacobian()) {/* RealVectorValue res_vec; // Build up residual vector for(unsigned int i=0; i<_dim; i++) { long int dof_number = node->dof_number(0, _vars(i), 0); res_vec(i) = _residual_copy(dof_number); } Real res_mag = pinfo->_normal * res_vec; */ if(pinfo->_distance > 0) _penetration_locator._has_penetrated[slave_node_num] = true; } if(_penetration_locator._has_penetrated[slave_node_num]) { addPoint(pinfo->_elem, pinfo->_closest_point); point_to_info[pinfo->_closest_point] = pinfo; } } } Real ContactMaster::computeQpResidual() { PenetrationLocator::PenetrationInfo * pinfo = point_to_info[_current_point]; Node * node = pinfo->_node; // std::cout<<node->id()<<std::endl; // long int dof_number = node->dof_number(0, _var_num, 0); // std::cout<<dof_number<<std::endl; // std::cout<<_residual_copy(dof_number)<<std::endl; // std::cout<<node->id()<<": "<<_residual_copy(dof_number)<<std::endl; RealVectorValue res_vec; // Build up residual vector for(unsigned int i=0; i<_dim; i++) { long int dof_number = node->dof_number(0, _vars(i), 0); res_vec(i) = _residual_copy(dof_number); } Real res_mag = pinfo->_normal * res_vec; // std::cout<<node->id()<<":: "<<res_mag<<std::endl; return _phi[_i][_qp]*pinfo->_normal(_component)*res_mag; } Real ContactMaster::computeQpJacobian() { return 0; /* if(_i != _j) return 0; PenetrationLocator::PenetrationInfo * pinfo = point_to_info[_current_point]; Node * node = pinfo->_node; RealVectorValue jac_vec; // Build up jac vector for(unsigned int i=0; i<_dim; i++) { long int dof_number = node->dof_number(0, _vars(i), 0); jac_vec(i) = _jacobian_copy(dof_number, dof_number); } Real jac_mag = pinfo->_normal * jac_vec; return _phi[_i][_qp]*pinfo->_normal(_component)*jac_mag; */ } <commit_msg>Whitespace<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "ContactMaster.h" #include "SystemBase.h" // libmesh includes #include "sparse_matrix.h" template<> InputParameters validParams<ContactMaster>() { InputParameters params = validParams<DiracKernel>(); params.addRequiredParam<unsigned int>("boundary", "The master boundary"); params.addRequiredParam<unsigned int>("slave", "The slave boundary"); params.addRequiredParam<Real>("component", "An integer corresponding to the direction the variable this kernel acts in. (0 for x, 1 for y, 2 for z)"); params.addCoupledVar("disp_x", "The x displacement"); params.addCoupledVar("disp_y", "The y displacement"); params.addCoupledVar("disp_z", "The z displacement"); params.set<bool>("use_displaced_mesh") = true; return params; } ContactMaster::ContactMaster(const std::string & name, InputParameters parameters) : DiracKernel(name, parameters), _component(getParam<Real>("component")), _penetration_locator(getPenetrationLocator(getParam<unsigned int>("boundary"), getParam<unsigned int>("slave"))), _residual_copy(_sys.residualCopy()), _x_var(isCoupled("disp_x") ? coupled("disp_x") : 99999), _y_var(isCoupled("disp_y") ? coupled("disp_y") : 99999), _z_var(isCoupled("disp_z") ? coupled("disp_z") : 99999), _vars(_x_var, _y_var, _z_var) {} void ContactMaster::addPoints() { point_to_info.clear(); std::map<unsigned int, PenetrationLocator::PenetrationInfo *>::iterator it = _penetration_locator._penetration_info.begin(); std::map<unsigned int, PenetrationLocator::PenetrationInfo *>::iterator end = _penetration_locator._penetration_info.end(); for(; it!=end; ++it) { unsigned int slave_node_num = it->first; PenetrationLocator::PenetrationInfo * pinfo = it->second; if(!pinfo) continue; Node * node = pinfo->_node; if(_sys.currentlyComputingJacobian()) {/* RealVectorValue res_vec; // Build up residual vector for(unsigned int i=0; i<_dim; i++) { long int dof_number = node->dof_number(0, _vars(i), 0); res_vec(i) = _residual_copy(dof_number); } Real res_mag = pinfo->_normal * res_vec; */ if(pinfo->_distance > 0) _penetration_locator._has_penetrated[slave_node_num] = true; } if(_penetration_locator._has_penetrated[slave_node_num]) { addPoint(pinfo->_elem, pinfo->_closest_point); point_to_info[pinfo->_closest_point] = pinfo; } } } Real ContactMaster::computeQpResidual() { PenetrationLocator::PenetrationInfo * pinfo = point_to_info[_current_point]; Node * node = pinfo->_node; // std::cout<<node->id()<<std::endl; // long int dof_number = node->dof_number(0, _var_num, 0); // std::cout<<dof_number<<std::endl; // std::cout<<_residual_copy(dof_number)<<std::endl; // std::cout<<node->id()<<": "<<_residual_copy(dof_number)<<std::endl; RealVectorValue res_vec; // Build up residual vector for(unsigned int i=0; i<_dim; i++) { long int dof_number = node->dof_number(0, _vars(i), 0); res_vec(i) = _residual_copy(dof_number); } Real res_mag = pinfo->_normal * res_vec; // std::cout<<node->id()<<":: "<<res_mag<<std::endl; return _phi[_i][_qp]*pinfo->_normal(_component)*res_mag; } Real ContactMaster::computeQpJacobian() { return 0; /* if(_i != _j) return 0; PenetrationLocator::PenetrationInfo * pinfo = point_to_info[_current_point]; Node * node = pinfo->_node; RealVectorValue jac_vec; // Build up jac vector for(unsigned int i=0; i<_dim; i++) { long int dof_number = node->dof_number(0, _vars(i), 0); jac_vec(i) = _jacobian_copy(dof_number, dof_number); } Real jac_mag = pinfo->_normal * jac_vec; return _phi[_i][_qp]*pinfo->_normal(_component)*jac_mag; */ } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "precomp.hpp" using namespace cv; using namespace cv::cuda; #if !defined (HAVE_CUDA) || defined (CUDA_DISABLER) Ptr<FastFeatureDetector> cv::cuda::FastFeatureDetector::create(int, bool, int, int) { throw_no_cuda(); return Ptr<FastFeatureDetector>(); } #else /* !defined (HAVE_CUDA) */ namespace cv { namespace cuda { namespace device { namespace fast { int calcKeypoints_gpu(PtrStepSzb img, PtrStepSzb mask, short2* kpLoc, int maxKeypoints, PtrStepSzi score, int threshold, cudaStream_t stream); int nonmaxSuppression_gpu(const short2* kpLoc, int count, PtrStepSzi score, short2* loc, float* response, cudaStream_t stream); } }}} namespace { class FAST_Impl : public cv::cuda::FastFeatureDetector { public: FAST_Impl(int threshold, bool nonmaxSuppression, int max_npoints); virtual void detect(InputArray _image, std::vector<KeyPoint>& keypoints, InputArray _mask); virtual void detectAsync(InputArray _image, OutputArray _keypoints, InputArray _mask, Stream& stream); virtual void convert(InputArray _gpu_keypoints, std::vector<KeyPoint>& keypoints); virtual void setThreshold(int threshold) { threshold_ = threshold; } virtual int getThreshold() const { return threshold_; } virtual void setNonmaxSuppression(bool f) { nonmaxSuppression_ = f; } virtual bool getNonmaxSuppression() const { return nonmaxSuppression_; } virtual void setMaxNumPoints(int max_npoints) { max_npoints_ = max_npoints; } virtual int getMaxNumPoints() const { return max_npoints_; } virtual void setType(int type) { CV_Assert( type == TYPE_9_16 ); } virtual int getType() const { return TYPE_9_16; } private: int threshold_; bool nonmaxSuppression_; int max_npoints_; }; FAST_Impl::FAST_Impl(int threshold, bool nonmaxSuppression, int max_npoints) : threshold_(threshold), nonmaxSuppression_(nonmaxSuppression), max_npoints_(max_npoints) { } void FAST_Impl::detect(InputArray _image, std::vector<KeyPoint>& keypoints, InputArray _mask) { if (_image.empty()) { keypoints.clear(); return; } BufferPool pool(Stream::Null()); GpuMat d_keypoints = pool.getBuffer(ROWS_COUNT, max_npoints_, CV_16SC2); detectAsync(_image, d_keypoints, _mask, Stream::Null()); convert(d_keypoints, keypoints); } void FAST_Impl::detectAsync(InputArray _image, OutputArray _keypoints, InputArray _mask, Stream& stream) { using namespace cv::cuda::device::fast; const GpuMat img = _image.getGpuMat(); const GpuMat mask = _mask.getGpuMat(); CV_Assert( img.type() == CV_8UC1 ); CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.size() == img.size()) ); BufferPool pool(stream); GpuMat kpLoc = pool.getBuffer(1, max_npoints_, CV_16SC2); GpuMat score; if (nonmaxSuppression_) { score = pool.getBuffer(img.size(), CV_32SC1); score.setTo(Scalar::all(0), stream); } int count = calcKeypoints_gpu(img, mask, kpLoc.ptr<short2>(), max_npoints_, score, threshold_, StreamAccessor::getStream(stream)); count = std::min(count, max_npoints_); if (count == 0) { _keypoints.release(); return; } ensureSizeIsEnough(ROWS_COUNT, count, CV_32FC1, _keypoints); GpuMat& keypoints = _keypoints.getGpuMatRef(); if (nonmaxSuppression_) { count = nonmaxSuppression_gpu(kpLoc.ptr<short2>(), count, score, keypoints.ptr<short2>(LOCATION_ROW), keypoints.ptr<float>(RESPONSE_ROW), StreamAccessor::getStream(stream)); if (count == 0) { keypoints.release(); } else { keypoints.cols = count; } } else { GpuMat locRow(1, count, kpLoc.type(), keypoints.ptr(0)); kpLoc.colRange(0, count).copyTo(locRow, stream); keypoints.row(1).setTo(Scalar::all(0), stream); } } void FAST_Impl::convert(InputArray _gpu_keypoints, std::vector<KeyPoint>& keypoints) { if (_gpu_keypoints.empty()) { keypoints.clear(); return; } Mat h_keypoints; if (_gpu_keypoints.kind() == _InputArray::CUDA_GPU_MAT) { _gpu_keypoints.getGpuMat().download(h_keypoints); } else { h_keypoints = _gpu_keypoints.getMat(); } CV_Assert( h_keypoints.rows == ROWS_COUNT ); CV_Assert( h_keypoints.elemSize() == 4 ); const int npoints = h_keypoints.cols; keypoints.resize(npoints); const short2* loc_row = h_keypoints.ptr<short2>(LOCATION_ROW); const float* response_row = h_keypoints.ptr<float>(RESPONSE_ROW); for (int i = 0; i < npoints; ++i) { KeyPoint kp(loc_row[i].x, loc_row[i].y, static_cast<float>(FEATURE_SIZE), -1, response_row[i]); keypoints[i] = kp; } } } Ptr<cv::cuda::FastFeatureDetector> cv::cuda::FastFeatureDetector::create(int threshold, bool nonmaxSuppression, int type, int max_npoints) { CV_Assert( type == TYPE_9_16 ); return makePtr<FAST_Impl>(threshold, nonmaxSuppression, max_npoints); } #endif /* !defined (HAVE_CUDA) */ <commit_msg>fix compilation without CUDA<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "precomp.hpp" using namespace cv; using namespace cv::cuda; #if !defined (HAVE_CUDA) || defined (CUDA_DISABLER) Ptr<cv::cuda::FastFeatureDetector> cv::cuda::FastFeatureDetector::create(int, bool, int, int) { throw_no_cuda(); return Ptr<cv::cuda::FastFeatureDetector>(); } #else /* !defined (HAVE_CUDA) */ namespace cv { namespace cuda { namespace device { namespace fast { int calcKeypoints_gpu(PtrStepSzb img, PtrStepSzb mask, short2* kpLoc, int maxKeypoints, PtrStepSzi score, int threshold, cudaStream_t stream); int nonmaxSuppression_gpu(const short2* kpLoc, int count, PtrStepSzi score, short2* loc, float* response, cudaStream_t stream); } }}} namespace { class FAST_Impl : public cv::cuda::FastFeatureDetector { public: FAST_Impl(int threshold, bool nonmaxSuppression, int max_npoints); virtual void detect(InputArray _image, std::vector<KeyPoint>& keypoints, InputArray _mask); virtual void detectAsync(InputArray _image, OutputArray _keypoints, InputArray _mask, Stream& stream); virtual void convert(InputArray _gpu_keypoints, std::vector<KeyPoint>& keypoints); virtual void setThreshold(int threshold) { threshold_ = threshold; } virtual int getThreshold() const { return threshold_; } virtual void setNonmaxSuppression(bool f) { nonmaxSuppression_ = f; } virtual bool getNonmaxSuppression() const { return nonmaxSuppression_; } virtual void setMaxNumPoints(int max_npoints) { max_npoints_ = max_npoints; } virtual int getMaxNumPoints() const { return max_npoints_; } virtual void setType(int type) { CV_Assert( type == TYPE_9_16 ); } virtual int getType() const { return TYPE_9_16; } private: int threshold_; bool nonmaxSuppression_; int max_npoints_; }; FAST_Impl::FAST_Impl(int threshold, bool nonmaxSuppression, int max_npoints) : threshold_(threshold), nonmaxSuppression_(nonmaxSuppression), max_npoints_(max_npoints) { } void FAST_Impl::detect(InputArray _image, std::vector<KeyPoint>& keypoints, InputArray _mask) { if (_image.empty()) { keypoints.clear(); return; } BufferPool pool(Stream::Null()); GpuMat d_keypoints = pool.getBuffer(ROWS_COUNT, max_npoints_, CV_16SC2); detectAsync(_image, d_keypoints, _mask, Stream::Null()); convert(d_keypoints, keypoints); } void FAST_Impl::detectAsync(InputArray _image, OutputArray _keypoints, InputArray _mask, Stream& stream) { using namespace cv::cuda::device::fast; const GpuMat img = _image.getGpuMat(); const GpuMat mask = _mask.getGpuMat(); CV_Assert( img.type() == CV_8UC1 ); CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.size() == img.size()) ); BufferPool pool(stream); GpuMat kpLoc = pool.getBuffer(1, max_npoints_, CV_16SC2); GpuMat score; if (nonmaxSuppression_) { score = pool.getBuffer(img.size(), CV_32SC1); score.setTo(Scalar::all(0), stream); } int count = calcKeypoints_gpu(img, mask, kpLoc.ptr<short2>(), max_npoints_, score, threshold_, StreamAccessor::getStream(stream)); count = std::min(count, max_npoints_); if (count == 0) { _keypoints.release(); return; } ensureSizeIsEnough(ROWS_COUNT, count, CV_32FC1, _keypoints); GpuMat& keypoints = _keypoints.getGpuMatRef(); if (nonmaxSuppression_) { count = nonmaxSuppression_gpu(kpLoc.ptr<short2>(), count, score, keypoints.ptr<short2>(LOCATION_ROW), keypoints.ptr<float>(RESPONSE_ROW), StreamAccessor::getStream(stream)); if (count == 0) { keypoints.release(); } else { keypoints.cols = count; } } else { GpuMat locRow(1, count, kpLoc.type(), keypoints.ptr(0)); kpLoc.colRange(0, count).copyTo(locRow, stream); keypoints.row(1).setTo(Scalar::all(0), stream); } } void FAST_Impl::convert(InputArray _gpu_keypoints, std::vector<KeyPoint>& keypoints) { if (_gpu_keypoints.empty()) { keypoints.clear(); return; } Mat h_keypoints; if (_gpu_keypoints.kind() == _InputArray::CUDA_GPU_MAT) { _gpu_keypoints.getGpuMat().download(h_keypoints); } else { h_keypoints = _gpu_keypoints.getMat(); } CV_Assert( h_keypoints.rows == ROWS_COUNT ); CV_Assert( h_keypoints.elemSize() == 4 ); const int npoints = h_keypoints.cols; keypoints.resize(npoints); const short2* loc_row = h_keypoints.ptr<short2>(LOCATION_ROW); const float* response_row = h_keypoints.ptr<float>(RESPONSE_ROW); for (int i = 0; i < npoints; ++i) { KeyPoint kp(loc_row[i].x, loc_row[i].y, static_cast<float>(FEATURE_SIZE), -1, response_row[i]); keypoints[i] = kp; } } } Ptr<cv::cuda::FastFeatureDetector> cv::cuda::FastFeatureDetector::create(int threshold, bool nonmaxSuppression, int type, int max_npoints) { CV_Assert( type == TYPE_9_16 ); return makePtr<FAST_Impl>(threshold, nonmaxSuppression, max_npoints); } #endif /* !defined (HAVE_CUDA) */ <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include <boost/python.hpp> #include "IECore/ScopedMessageHandler.h" using namespace boost::python; namespace IECore { void bindScopedMessageHandler() { class_<ScopedMessageHandler, boost::noncopyable>( "ScopedMessageHandler", init<MessageHandlerPtr>() ) ; } } <commit_msg>Added a todo.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include <boost/python.hpp> #include "IECore/ScopedMessageHandler.h" using namespace boost::python; namespace IECore { /// \todo This would be better bound as a MessageHandlerContext context handler for use in "with" blocks. void bindScopedMessageHandler() { class_<ScopedMessageHandler, boost::noncopyable>( "ScopedMessageHandler", init<MessageHandlerPtr>() ) ; } } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <iostream> #include <fstream> #include <istream> #include <sstream> #include <exception> #include <stdexcept> #include <test/unit/gm/utility.hpp> TEST(gm_parser,eight_schools) { EXPECT_TRUE(is_parsable("src/models/misc/eight_schools/eight_schools.stan")); } TEST(gm_parser,bugs_1_kidney) { EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/kidney/kidney.stan")); } TEST(gm_parser,bugs_1_mice) { EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/mice/mice.stan")); } TEST(gm_parser,bugs_1_oxford) { EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/oxford/oxford.stan")); } TEST(gm_parser,bugs_1_rats) { EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/rats/rats.stan")); } TEST(gm_parser,bugs_1_salm) { EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/salm/salm.stan")); } TEST(gm_parser,bugs_1_seeds) { EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/seeds/seeds.stan")); } TEST(gm_parser,bugs_1_surgical) { EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/surgical/surgical.stan")); } TEST(gm_parser,bugs_2_beetles_cloglog) { EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_cloglog.stan")); } TEST(gm_parser,bugs_2_beetles_logit) { EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_logit.stan")); } TEST(gm_parser,bugs_2_beetles_probit) { EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_probit.stan")); } TEST(gm_parser,bugs_2_birats) { EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/birats/birats.stan")); } TEST(gm_parser,bugs_2_dugongs) { EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/dugongs/dugongs.stan")); } TEST(gm_parser,bugs_2_eyes) { EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/eyes/eyes.stan")); } TEST(gm_parser,bugs_2_ice) { EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/ice/ice.stan")); } // why commented out? //TEST(gm_parser,bugs_2_stagnant) { // EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/stagnant/stagnant.stan")); // } TEST(gm_parser,triangle_lp) { EXPECT_TRUE(is_parsable("src/models/basic_distributions/triangle.stan")); } <commit_msg>removing test that parsers some of the bugs and misc models. Should be added in a more structured format in the future<commit_after><|endoftext|>
<commit_before>/* * Adplug - Replayer for many OPL2/OPL3 audio file formats. * Copyright (C) 1999 - 2006 Simon Peter, <dn.tlp@gmx.net>, et al. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * amd.cpp - AMD Loader by Simon Peter <dn.tlp@gmx.net> */ #include <string.h> #include "amd.h" #include "debug.h" CPlayer *CamdLoader::factory(Copl *newopl) { return new CamdLoader(newopl); } bool CamdLoader::load(const std::string &filename, const CFileProvider &fp) { binistream *f = fp.open(filename); if(!f) return false; struct { char id[9]; unsigned char version; } header; int i, j, k, t, numtrax, maxi = 0; unsigned char buf, buf2, buf3; const unsigned char convfx[10] = {0,1,2,9,17,11,13,18,3,14}; // file validation section if(fp.filesize(f) < 1072) { fp.close(f); return false; } f->seek(1062); f->readString(header.id, 9); header.version = f->readInt(1); if(strncmp(header.id, "<o\xefQU\xeeRoR", 9) && strncmp(header.id, "MaDoKaN96", 9)) { fp.close(f); return false; } // load section memset(inst, 0, sizeof(inst)); f->seek(0); f->readString(songname, sizeof(songname)); f->readString(author, sizeof(author)); for(i = 0; i < 26; i++) { f->readString(instname[i], 23); for(j = 0; j < 11; j++) inst[i].data[j] = f->readInt(1); } length = f->readInt(1); nop = f->readInt(1) + 1; for(i=0;i<128;i++) order[i] = f->readInt(1); f->seek(10, binio::Add); if(header.version == 0x10) { // unpacked module maxi = nop * 9; for(i=0;i<64*9;i++) trackord[i/9][i%9] = i+1; t = 0; while(!f->ateof()) { for(j=0;j<64;j++) for(i=t;i<t+9;i++) { buf = f->readInt(1); tracks[i][j].param2 = (buf&127) % 10; tracks[i][j].param1 = (buf&127) / 10; buf = f->readInt(1); tracks[i][j].inst = buf >> 4; tracks[i][j].command = buf & 0x0f; buf = f->readInt(1); if(buf >> 4) // fix bug in AMD save routine tracks[i][j].note = ((buf & 14) >> 1) * 12 + (buf >> 4); else tracks[i][j].note = 0; tracks[i][j].inst += (buf & 1) << 4; } t += 9; } } else { // packed module for(i=0;i<nop;i++) for(j=0;j<9;j++) trackord[i][j] = f->readInt(2) + 1; numtrax = f->readInt(2); for(k=0;k<numtrax;k++) { i = f->readInt(2); if(i > 575) i = 575; // fix corrupted modules maxi = (i + 1 > maxi ? i + 1 : maxi); j = 0; do { buf = f->readInt(1); if(buf & 128) { for(t = j; t < j + (buf & 127) && t < 64; t++) { tracks[i][t].command = 0; tracks[i][t].inst = 0; tracks[i][t].note = 0; tracks[i][t].param1 = 0; tracks[i][t].param2 = 0; } j += buf & 127; continue; } tracks[i][j].param2 = buf % 10; tracks[i][j].param1 = buf / 10; buf = f->readInt(1); tracks[i][j].inst = buf >> 4; tracks[i][j].command = buf & 0x0f; buf = f->readInt(1); if(buf >> 4) // fix bug in AMD save routine tracks[i][j].note = ((buf & 14) >> 1) * 12 + (buf >> 4); else tracks[i][j].note = 0; tracks[i][j].inst += (buf & 1) << 4; j++; } while(j<64); } } fp.close(f); // convert to protracker replay data bpm = 50; restartpos = 0; activechan = 0xffff; flags = Decimal; for(i=0;i<26;i++) { // convert instruments buf = inst[i].data[0]; buf2 = inst[i].data[1]; inst[i].data[0] = inst[i].data[10]; inst[i].data[1] = buf; buf = inst[i].data[2]; inst[i].data[2] = inst[i].data[5]; buf3 = inst[i].data[3]; inst[i].data[3] = buf; buf = inst[i].data[4]; inst[i].data[4] = inst[i].data[7]; inst[i].data[5] = buf3; buf3 = inst[i].data[6]; inst[i].data[6] = inst[i].data[8]; inst[i].data[7] = buf; inst[i].data[8] = inst[i].data[9]; inst[i].data[9] = buf2; inst[i].data[10] = buf3; for(j=0;j<23;j++) // convert names if(instname[i][j] == '\xff') instname[i][j] = '\x20'; } for(i=0;i<maxi;i++) // convert patterns for(j=0;j<64;j++) { tracks[i][j].command = convfx[tracks[i][j].command]; // extended command if(tracks[i][j].command == 14) { if(tracks[i][j].param1 == 2) { tracks[i][j].command = 10; tracks[i][j].param1 = tracks[i][j].param2; tracks[i][j].param2 = 0; } if(tracks[i][j].param1 == 3) { tracks[i][j].command = 10; tracks[i][j].param1 = 0; } } } rewind(0); return true; } float CamdLoader::getrefresh() { if(tempo) return (float) (tempo); else return 18.2f; } <commit_msg>Fixed volume handling, by adding conversion table.<commit_after>/* * Adplug - Replayer for many OPL2/OPL3 audio file formats. * Copyright (C) 1999 - 2006 Simon Peter, <dn.tlp@gmx.net>, et al. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * amd.cpp - AMD Loader by Simon Peter <dn.tlp@gmx.net> */ #include <string.h> #include "amd.h" #include "debug.h" CPlayer *CamdLoader::factory(Copl *newopl) { return new CamdLoader(newopl); } bool CamdLoader::load(const std::string &filename, const CFileProvider &fp) { binistream *f = fp.open(filename); if(!f) return false; struct { char id[9]; unsigned char version; } header; int i, j, k, t, numtrax, maxi = 0; unsigned char buf, buf2, buf3; const unsigned char convfx[10] = {0,1,2,9,17,11,13,18,3,14}; const unsigned char convvol[64] = { 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 9, 9, 0xa, 0xa, 0xb, 0xc, 0xc, 0xd, 0xe, 0xe, 0xf, 0x10, 0x10, 0x11, 0x12, 0x13, 0x14, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x21, 0x22, 0x23, 0x25, 0x26, 0x28, 0x29, 0x2b, 0x2d, 0x2e, 0x30, 0x32, 0x35, 0x37, 0x3a, 0x3c, 0x3f }; // file validation section if(fp.filesize(f) < 1072) { fp.close(f); return false; } f->seek(1062); f->readString(header.id, 9); header.version = f->readInt(1); if(strncmp(header.id, "<o\xefQU\xeeRoR", 9) && strncmp(header.id, "MaDoKaN96", 9)) { fp.close(f); return false; } // load section memset(inst, 0, sizeof(inst)); f->seek(0); f->readString(songname, sizeof(songname)); f->readString(author, sizeof(author)); for(i = 0; i < 26; i++) { f->readString(instname[i], 23); for(j = 0; j < 11; j++) inst[i].data[j] = f->readInt(1); } length = f->readInt(1); nop = f->readInt(1) + 1; for(i=0;i<128;i++) order[i] = f->readInt(1); f->seek(10, binio::Add); if(header.version == 0x10) { // unpacked module maxi = nop * 9; for(i=0;i<64*9;i++) trackord[i/9][i%9] = i+1; t = 0; while(!f->ateof()) { for(j=0;j<64;j++) for(i=t;i<t+9;i++) { buf = f->readInt(1); tracks[i][j].param2 = (buf&127) % 10; tracks[i][j].param1 = (buf&127) / 10; buf = f->readInt(1); tracks[i][j].inst = buf >> 4; tracks[i][j].command = buf & 0x0f; buf = f->readInt(1); if(buf >> 4) // fix bug in AMD save routine tracks[i][j].note = ((buf & 14) >> 1) * 12 + (buf >> 4); else tracks[i][j].note = 0; tracks[i][j].inst += (buf & 1) << 4; } t += 9; } } else { // packed module for(i=0;i<nop;i++) for(j=0;j<9;j++) trackord[i][j] = f->readInt(2) + 1; numtrax = f->readInt(2); for(k=0;k<numtrax;k++) { i = f->readInt(2); if(i > 575) i = 575; // fix corrupted modules maxi = (i + 1 > maxi ? i + 1 : maxi); j = 0; do { buf = f->readInt(1); if(buf & 128) { for(t = j; t < j + (buf & 127) && t < 64; t++) { tracks[i][t].command = 0; tracks[i][t].inst = 0; tracks[i][t].note = 0; tracks[i][t].param1 = 0; tracks[i][t].param2 = 0; } j += buf & 127; continue; } tracks[i][j].param2 = buf % 10; tracks[i][j].param1 = buf / 10; buf = f->readInt(1); tracks[i][j].inst = buf >> 4; tracks[i][j].command = buf & 0x0f; buf = f->readInt(1); if(buf >> 4) // fix bug in AMD save routine tracks[i][j].note = ((buf & 14) >> 1) * 12 + (buf >> 4); else tracks[i][j].note = 0; tracks[i][j].inst += (buf & 1) << 4; j++; } while(j<64); } } fp.close(f); // convert to protracker replay data bpm = 50; restartpos = 0; activechan = 0xffff; flags = Decimal; for(i=0;i<26;i++) { // convert instruments buf = inst[i].data[0]; buf2 = inst[i].data[1]; inst[i].data[0] = inst[i].data[10]; inst[i].data[1] = buf; buf = inst[i].data[2]; inst[i].data[2] = inst[i].data[5]; buf3 = inst[i].data[3]; inst[i].data[3] = buf; buf = inst[i].data[4]; inst[i].data[4] = inst[i].data[7]; inst[i].data[5] = buf3; buf3 = inst[i].data[6]; inst[i].data[6] = inst[i].data[8]; inst[i].data[7] = buf; inst[i].data[8] = inst[i].data[9]; inst[i].data[9] = buf2; inst[i].data[10] = buf3; for(j=0;j<23;j++) // convert names if(instname[i][j] == '\xff') instname[i][j] = '\x20'; } for(i=0;i<maxi;i++) // convert patterns for(j=0;j<64;j++) { tracks[i][j].command = convfx[tracks[i][j].command]; // extended command if(tracks[i][j].command == 14) { if(tracks[i][j].param1 == 2) { tracks[i][j].command = 10; tracks[i][j].param1 = tracks[i][j].param2; tracks[i][j].param2 = 0; } if(tracks[i][j].param1 == 3) { tracks[i][j].command = 10; tracks[i][j].param1 = 0; } } // fix volume if(tracks[i][j].command == 17) { int vol = convvol[tracks[i][j].param1 * 10 + tracks[i][j].param2]; if(vol > 63) vol = 63; tracks[i][j].param1 = vol / 10; tracks[i][j].param2 = vol % 10; } } rewind(0); return true; } float CamdLoader::getrefresh() { if(tempo) return (float) (tempo); else return 18.2f; } <|endoftext|>
<commit_before>/* * File: AizuJudger.cpp * Author: 51isoft * * Created on 2014年8月13日, 下午2:53 */ #include "AizuJudger.h" AizuJudger::AizuJudger(JudgerInfo * _info) : VirtualJudger(_info) { socket->sendMessage(CONFIG->GetJudge_connect_string() + "\nAizu"); language_table["1"] = "C++"; language_table["2"] = "C"; language_table["3"] = "JAVA"; language_table["6"] = "C#"; language_table["5"] = "Python"; language_table["9"] = "Ruby"; } AizuJudger::~AizuJudger() { } /** * Login to Aizu */ void AizuJudger::login() { prepareCurl(); curl_easy_setopt(curl, CURLOPT_URL, "http://judge.u-aizu.ac.jp/onlinejudge/index.jsp"); string post = (string)"loginUserID=" + info->GetUsername() + "&loginPassword=" + escapeURL(info->GetPassword()) + "&submit=Sign+in"; curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post.c_str()); performCurl(); string html = loadAllFromFile(tmpfilename); //cout<<ts; if (html.find("<span class=\"line\">Login</span>") != string::npos) { throw Exception("Login failed!"); } } /** * Submit a run * @param bott Bott file for Run info * @return Submit status */ int AizuJudger::submit(Bott * bott) { prepareCurl(); curl_easy_setopt(curl, CURLOPT_URL, "http://judge.u-aizu.ac.jp/onlinejudge/servlet/Submit"); string post = (string) "userID=" + escapeURL(info->GetUsername()) + "&password=" + escapeURL(info->GetPassword()) + "&problemNO=" + bott->Getvid() + "&language=" + escapeURL(bott->Getlanguage()) + "&sourceCode=" + escapeURL(bott->Getsrc()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post.c_str()); try { performCurl(); } catch (Exception & e) { return SUBMIT_OTHER_ERROR; } string html = loadAllFromFile(tmpfilename); if (html.find("UserID or Password is Wrong.") != string::npos || html.find("<span class=\"line\">Login</span>") != string::npos) return SUBMIT_OTHER_ERROR; return SUBMIT_NORMAL; } /** * Get result and related info * @param bott Original Bott info * @return Result Bott file */ Bott * AizuJudger::getStatus(Bott * bott) { time_t begin_time = time(NULL); Bott * result_bott; while (true) { // check wait time if (time(NULL) - begin_time > info->GetMax_wait_time()) { throw Exception("Failed to get current result, judge time out."); } prepareCurl(); curl_easy_setopt(curl, CURLOPT_URL, ((string)"http://judge.u-aizu.ac.jp/onlinejudge/status.jsp").c_str()); performCurl(); string html = loadAllFromFile(tmpfilename); string status; string runid, result, time_used, memory_used; // get first row if (!RE2::PartialMatch(html, "(?s)(<tr class=\"dat\".*?</tr>)", &status)) { throw Exception("Failed to get status row."); } // get result if (!RE2::PartialMatch(status, "(?s)rid=([0-9]*).*_link.*?<a.*?>(.*?)</a>", &runid, &result)) { throw Exception("Failed to get current result."); } result = convertResult(trim(result)); if (isFinalResult(result)) { // result is the final one, get details if (result != "Runtime Error" && result != "Compile Error") { if (!RE2::PartialMatch(status, "(?s)<td class=\"text-center\">([0-9\\.]*) s.*?<td.*?>([0-9]*) KB", &time_used, &memory_used)) { throw Exception("Failed to parse details from status row."); } } else { memory_used = time_used = "0"; } result_bott = new Bott; result_bott->Settype(RESULT_REPORT); result_bott->Setresult(convertResult(result)); result_bott->Settime_used(intToString(stringToDouble(time_used) * 100 + 0.1)); result_bott->Setmemory_used(trim(memory_used)); result_bott->Setremote_runid(trim(runid)); break; } } return result_bott; } /** * Convert result text to local ones, keep consistency * @param result Original result * @return Converted local result */ string AizuJudger::convertResult(string result) { if (result.find("Time Limit Exceeded") != string::npos) return "Time Limit Exceed"; if (result.find("Memory Limit Exceeded") != string::npos) return "Memory Limit Exceed"; if (result.find("Output Limit Exceeded") != string::npos) return "Output Limit Exceed"; return trim(result); } /** * Get compile error info * @param bott Result bott file * @return Compile error info */ string AizuJudger::getCEinfo(Bott * bott) { prepareCurl(); curl_easy_setopt(curl, CURLOPT_URL, ("http://judge.u-aizu.ac.jp/onlinejudge/compile_log.jsp?runID=" + bott->Getremote_runid()).c_str()); performCurl(); string info = loadAllFromFile(tmpfilename); string result; char * ce_info = new char[info.length() + 1]; strcpy(ce_info, info.c_str()); char * buffer = new char[info.length() * 2]; // SCU is in GBK charset charset_convert("SHIFT_JIS", "UTF-8//TRANSLIT", ce_info, info.length() + 1, buffer, info.length() * 2); if (!RE2::PartialMatch(buffer, "(?s)<p style=\"font-size:11pt;\">(.*)</p>", &result)) { return ""; } strcpy(buffer, result.c_str()); decode_html_entities_utf8(buffer, NULL); result = buffer; delete [] ce_info; delete [] buffer; return trim(result); } <commit_msg>Aizu VJ failed to get status<commit_after>/* * File: AizuJudger.cpp * Author: 51isoft * * Created on 2014年8月13日, 下午2:53 */ #include "AizuJudger.h" AizuJudger::AizuJudger(JudgerInfo * _info) : VirtualJudger(_info) { socket->sendMessage(CONFIG->GetJudge_connect_string() + "\nAizu"); language_table["1"] = "C++"; language_table["2"] = "C"; language_table["3"] = "JAVA"; language_table["6"] = "C#"; language_table["5"] = "Python"; language_table["9"] = "Ruby"; } AizuJudger::~AizuJudger() { } /** * Login to Aizu */ void AizuJudger::login() { prepareCurl(); curl_easy_setopt(curl, CURLOPT_URL, "http://judge.u-aizu.ac.jp/onlinejudge/index.jsp"); string post = (string)"loginUserID=" + info->GetUsername() + "&loginPassword=" + escapeURL(info->GetPassword()) + "&submit=Sign+in"; curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post.c_str()); performCurl(); string html = loadAllFromFile(tmpfilename); //cout<<ts; if (html.find("<span class=\"line\">Login</span>") != string::npos) { throw Exception("Login failed!"); } } /** * Submit a run * @param bott Bott file for Run info * @return Submit status */ int AizuJudger::submit(Bott * bott) { prepareCurl(); curl_easy_setopt(curl, CURLOPT_URL, "http://judge.u-aizu.ac.jp/onlinejudge/servlet/Submit"); string post = (string) "userID=" + escapeURL(info->GetUsername()) + "&password=" + escapeURL(info->GetPassword()) + "&problemNO=" + bott->Getvid() + "&language=" + escapeURL(bott->Getlanguage()) + "&sourceCode=" + escapeURL(bott->Getsrc()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post.c_str()); try { performCurl(); } catch (Exception & e) { return SUBMIT_OTHER_ERROR; } string html = loadAllFromFile(tmpfilename); if (html.find("UserID or Password is Wrong.") != string::npos || html.find("<span class=\"line\">Login</span>") != string::npos) return SUBMIT_OTHER_ERROR; return SUBMIT_NORMAL; } /** * Get result and related info * @param bott Original Bott info * @return Result Bott file */ Bott * AizuJudger::getStatus(Bott * bott) { time_t begin_time = time(NULL); Bott * result_bott; while (true) { // check wait time if (time(NULL) - begin_time > info->GetMax_wait_time()) { throw Exception("Failed to get current result, judge time out."); } prepareCurl(); curl_easy_setopt(curl, CURLOPT_URL, ((string)"http://judge.u-aizu.ac.jp/onlinejudge/status.jsp").c_str()); performCurl(); string html = loadAllFromFile(tmpfilename); string status; string runid, result, time_used, memory_used; // get first row of current user if (!RE2::PartialMatch(html, "(?s)(<tr class=\"dat\".*?id="+info->GetUsername()+".*?</tr>)", &status)) { throw Exception("Failed to get status row."); } // get result if (!RE2::PartialMatch(status, "(?s)rid=([0-9]*).*status.*?<a href=\"review.*?>(.*?)</a>", &runid, &result)) { throw Exception("Failed to get current result."); } result = convertResult(trim(result)); if (isFinalResult(result)) { // result is the final one, get details if (result != "Runtime Error" && result != "Compile Error") { if (!RE2::PartialMatch(status, "(?s)<td class=\"text-center\">([0-9\\.]*) s.*?<td.*?>([0-9]*) KB", &time_used, &memory_used)) { throw Exception("Failed to parse details from status row."); } } else { memory_used = time_used = "0"; } result_bott = new Bott; result_bott->Settype(RESULT_REPORT); result_bott->Setresult(convertResult(result)); result_bott->Settime_used(intToString(stringToDouble(time_used) * 100 + 0.1)); result_bott->Setmemory_used(trim(memory_used)); result_bott->Setremote_runid(trim(runid)); break; } } return result_bott; } /** * Convert result text to local ones, keep consistency * @param result Original result * @return Converted local result */ string AizuJudger::convertResult(string result) { if (result.find("Time Limit Exceeded") != string::npos) return "Time Limit Exceed"; if (result.find("Memory Limit Exceeded") != string::npos) return "Memory Limit Exceed"; if (result.find("Output Limit Exceeded") != string::npos) return "Output Limit Exceed"; return trim(result); } /** * Get compile error info * @param bott Result bott file * @return Compile error info */ string AizuJudger::getCEinfo(Bott * bott) { prepareCurl(); curl_easy_setopt(curl, CURLOPT_URL, ("http://judge.u-aizu.ac.jp/onlinejudge/compile_log.jsp?runID=" + bott->Getremote_runid()).c_str()); performCurl(); string info = loadAllFromFile(tmpfilename); string result; char * ce_info = new char[info.length() + 1]; strcpy(ce_info, info.c_str()); char * buffer = new char[info.length() * 2]; // SCU is in GBK charset charset_convert("SHIFT_JIS", "UTF-8//TRANSLIT", ce_info, info.length() + 1, buffer, info.length() * 2); if (!RE2::PartialMatch(buffer, "(?s)<p style=\"font-size:11pt;\">(.*)</p>", &result)) { return ""; } strcpy(buffer, result.c_str()); decode_html_entities_utf8(buffer, NULL); result = buffer; delete [] ce_info; delete [] buffer; return trim(result); } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperElevationParametersHandler.h" #include "otbDEMHandler.h" namespace otb { namespace Wrapper { void ElevationParametersHandler::AddElevationParameters(Application::Pointer app, const std::string & key) { app->AddParameter(ParameterType_Group, key, "Elevation management"); app->SetParameterDescription(key, "This group of parameters allows to manage elevation values. Supported formats are SRTM, DTED or any geotiff processed by the DEM import application"); // DEM directory std::ostringstream oss; oss << key<<".dem"; app->AddParameter(ParameterType_Directory, oss.str(), "DEM directory"); app->SetParameterDescription(oss.str(), "This parameter allows to select a directory containing Digital Elevation Model tiles"); app->MandatoryOff(oss.str()); std::string demDirFromConfig = otb::ConfigurationFile::GetInstance()->GetDEMDirectory(); if(demDirFromConfig!="") { app->SetParameterString(oss.str(), otb::ConfigurationFile::GetInstance()->GetDEMDirectory()); app->EnableParameter(oss.str()); } else { app->DisableParameter(oss.str()); } // Geoid file oss.str(""); oss << key<<".geoid"; app->AddParameter(ParameterType_InputFilename, oss.str(), "Geoid File"); app->SetParameterDescription(oss.str(),"Use a geoid grid to get the height above the ellipsoid used"); app->MandatoryOff(oss.str()); std::string geoidFromConfig = otb::ConfigurationFile::GetInstance()->GetGeoidFile(); if(geoidFromConfig!="") { app->SetParameterString(oss.str(),geoidFromConfig ); app->EnableParameter(oss.str()); } else { app->DisableParameter(oss.str()); } // Average elevation oss.str(""); oss << key <<".default"; app->AddParameter(ParameterType_Float, oss.str(), "Default elevation"); app->SetParameterDescription(oss.str(),"This parameter allows to set the default height above ellipsoid when there is no elevation coverage from DEM (or if DEM directory is not set)."); app->SetDefaultParameterFloat(oss.str(), 0.); // TODO : not implemented yet // // Tiff image // oss << ".tiff"; // app->AddChoice(oss.str(), "Tiff file"); // app->AddParameter(ParameterType_InputImage, oss.str(), "Tiff file"); // app->SetParameterDescription(oss.str(),"Tiff file used to get elevation for each location in the image"); } void ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(const Application::Pointer app, const std::string& key) { // Set default elevation otb::DEMHandler::Instance()->SetDefaultHeightAboveEllipsoid(GetDefaultElevation(app,key)); std::ostringstream oss; oss<<"Elevation management: setting default height above ellipsoid to " << GetDefaultElevation(app,key) << " meters"; app->GetLogger()->Info(oss.str()); // Set geoid if available if(IsGeoidUsed(app,key)) { oss.str(""); oss<<"Elevation management: using geoid file ("<<GetGeoidFile(app,key)<<")"; otb::DEMHandler::Instance()->OpenGeoidFile(GetGeoidFile(app,key)); app->GetLogger()->Info(oss.str()); } // Set DEM directory if available if(IsDEMUsed(app,key)) { oss.str(""); oss<<"Elevation management: using DEM directory ("<<GetDEMDirectory(app,key)<<")"; otb::DEMHandler::Instance()->OpenDEMDirectory(GetDEMDirectory(app,key)); app->GetLogger()->Info(oss.str()); } } /** * * Get the Average elevation value */ float ElevationParametersHandler::GetDefaultElevation(const Application::Pointer app, const std::string& key) { std::ostringstream oss; oss << key <<".default"; return app->GetParameterFloat(oss.str()); } /** * Get the Geoid file */ const std::string ElevationParametersHandler::GetGeoidFile(const Application::Pointer app, const std::string& key) { std::ostringstream oss; oss << key <<".geoid"; if (IsGeoidUsed(app, key)) { return app->GetParameterString(oss.str()); } return ""; } /** * Is Geoid used */ bool ElevationParametersHandler::IsGeoidUsed(const Application::Pointer app, const std::string& key) { std::ostringstream geoidKey; geoidKey<< key<<".geoid"; return app->IsParameterEnabled(geoidKey.str()) && app->HasValue(geoidKey.str()); } /** * * Is Geoid used */ bool ElevationParametersHandler::IsDEMUsed(const Application::Pointer app, const std::string& key) { std::ostringstream geoidKey; geoidKey<< key<<".dem"; return app->IsParameterEnabled(geoidKey.str()) && app->HasValue(geoidKey.str()); } const std::string ElevationParametersHandler::GetDEMDirectory(const Application::Pointer app, const std::string& key) { std::ostringstream oss; oss << key <<".dem"; if (IsDEMUsed(app, key)) { return app->GetParameterString(oss.str()); } return ""; } }// End namespace Wrapper }// End namespace otb <commit_msg>STY: Missing newline at end of log messages<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperElevationParametersHandler.h" #include "otbDEMHandler.h" namespace otb { namespace Wrapper { void ElevationParametersHandler::AddElevationParameters(Application::Pointer app, const std::string & key) { app->AddParameter(ParameterType_Group, key, "Elevation management"); app->SetParameterDescription(key, "This group of parameters allows to manage elevation values. Supported formats are SRTM, DTED or any geotiff processed by the DEM import application"); // DEM directory std::ostringstream oss; oss << key<<".dem"; app->AddParameter(ParameterType_Directory, oss.str(), "DEM directory"); app->SetParameterDescription(oss.str(), "This parameter allows to select a directory containing Digital Elevation Model tiles"); app->MandatoryOff(oss.str()); std::string demDirFromConfig = otb::ConfigurationFile::GetInstance()->GetDEMDirectory(); if(demDirFromConfig!="") { app->SetParameterString(oss.str(), otb::ConfigurationFile::GetInstance()->GetDEMDirectory()); app->EnableParameter(oss.str()); } else { app->DisableParameter(oss.str()); } // Geoid file oss.str(""); oss << key<<".geoid"; app->AddParameter(ParameterType_InputFilename, oss.str(), "Geoid File"); app->SetParameterDescription(oss.str(),"Use a geoid grid to get the height above the ellipsoid used"); app->MandatoryOff(oss.str()); std::string geoidFromConfig = otb::ConfigurationFile::GetInstance()->GetGeoidFile(); if(geoidFromConfig!="") { app->SetParameterString(oss.str(),geoidFromConfig ); app->EnableParameter(oss.str()); } else { app->DisableParameter(oss.str()); } // Average elevation oss.str(""); oss << key <<".default"; app->AddParameter(ParameterType_Float, oss.str(), "Default elevation"); app->SetParameterDescription(oss.str(),"This parameter allows to set the default height above ellipsoid when there is no elevation coverage from DEM (or if DEM directory is not set)."); app->SetDefaultParameterFloat(oss.str(), 0.); // TODO : not implemented yet // // Tiff image // oss << ".tiff"; // app->AddChoice(oss.str(), "Tiff file"); // app->AddParameter(ParameterType_InputImage, oss.str(), "Tiff file"); // app->SetParameterDescription(oss.str(),"Tiff file used to get elevation for each location in the image"); } void ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(const Application::Pointer app, const std::string& key) { // Set default elevation otb::DEMHandler::Instance()->SetDefaultHeightAboveEllipsoid(GetDefaultElevation(app,key)); std::ostringstream oss; oss<<"Elevation management: setting default height above ellipsoid to " << GetDefaultElevation(app,key) << " meters"<<std::endl; app->GetLogger()->Info(oss.str()); // Set geoid if available if(IsGeoidUsed(app,key)) { oss.str(""); oss<<"Elevation management: using geoid file ("<<GetGeoidFile(app,key)<<")"<<std::endl; otb::DEMHandler::Instance()->OpenGeoidFile(GetGeoidFile(app,key)); app->GetLogger()->Info(oss.str()); } // Set DEM directory if available if(IsDEMUsed(app,key)) { oss.str(""); oss<<"Elevation management: using DEM directory ("<<GetDEMDirectory(app,key)<<")"<<std::endl; otb::DEMHandler::Instance()->OpenDEMDirectory(GetDEMDirectory(app,key)); app->GetLogger()->Info(oss.str()); } } /** * * Get the Average elevation value */ float ElevationParametersHandler::GetDefaultElevation(const Application::Pointer app, const std::string& key) { std::ostringstream oss; oss << key <<".default"; return app->GetParameterFloat(oss.str()); } /** * Get the Geoid file */ const std::string ElevationParametersHandler::GetGeoidFile(const Application::Pointer app, const std::string& key) { std::ostringstream oss; oss << key <<".geoid"; if (IsGeoidUsed(app, key)) { return app->GetParameterString(oss.str()); } return ""; } /** * Is Geoid used */ bool ElevationParametersHandler::IsGeoidUsed(const Application::Pointer app, const std::string& key) { std::ostringstream geoidKey; geoidKey<< key<<".geoid"; return app->IsParameterEnabled(geoidKey.str()) && app->HasValue(geoidKey.str()); } /** * * Is Geoid used */ bool ElevationParametersHandler::IsDEMUsed(const Application::Pointer app, const std::string& key) { std::ostringstream geoidKey; geoidKey<< key<<".dem"; return app->IsParameterEnabled(geoidKey.str()) && app->HasValue(geoidKey.str()); } const std::string ElevationParametersHandler::GetDEMDirectory(const Application::Pointer app, const std::string& key) { std::ostringstream oss; oss << key <<".dem"; if (IsDEMUsed(app, key)) { return app->GetParameterString(oss.str()); } return ""; } }// End namespace Wrapper }// End namespace otb <|endoftext|>
<commit_before>/* * Copyright © 2012 Intel Corporation * * 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 (including the next * paragraph) 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. */ /** @file brw_fs_register_coalesce.cpp * * Implements register coalescing: Checks if the two registers involved in a * raw move don't interfere, in which case they can both be stored in the same * place and the MOV removed. * * To do this, all uses of the source of the MOV in the shader are replaced * with the destination of the MOV. For example: * * add vgrf3:F, vgrf1:F, vgrf2:F * mov vgrf4:F, vgrf3:F * mul vgrf5:F, vgrf5:F, vgrf4:F * * becomes * * add vgrf4:F, vgrf1:F, vgrf2:F * mul vgrf5:F, vgrf5:F, vgrf4:F */ #include "brw_fs.h" #include "brw_cfg.h" #include "brw_fs_live_variables.h" static bool is_nop_mov(const fs_inst *inst) { if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD) { fs_reg dst = inst->dst; for (int i = 0; i < inst->sources; i++) { dst.offset = i * REG_SIZE + dst.offset % REG_SIZE; if (!dst.equals(inst->src[i])) { return false; } } return true; } else if (inst->opcode == BRW_OPCODE_MOV) { return inst->dst.equals(inst->src[0]); } return false; } static bool is_coalesce_candidate(const fs_visitor *v, const fs_inst *inst) { if ((inst->opcode != BRW_OPCODE_MOV && inst->opcode != SHADER_OPCODE_LOAD_PAYLOAD) || inst->is_partial_write() || inst->saturate || inst->src[0].file != VGRF || inst->src[0].negate || inst->src[0].abs || !inst->src[0].is_contiguous() || inst->dst.file != VGRF || inst->dst.type != inst->src[0].type) { return false; } if (v->alloc.sizes[inst->src[0].nr] > v->alloc.sizes[inst->dst.nr]) return false; if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD) { if (!inst->is_copy_payload(v->alloc)) { return false; } } return true; } static bool can_coalesce_vars(brw::fs_live_variables *live_intervals, const cfg_t *cfg, const fs_inst *inst, int dst_var, int src_var) { if (!live_intervals->vars_interfere(src_var, dst_var)) return true; int dst_start = live_intervals->start[dst_var]; int dst_end = live_intervals->end[dst_var]; int src_start = live_intervals->start[src_var]; int src_end = live_intervals->end[src_var]; /* Variables interfere and one line range isn't a subset of the other. */ if ((dst_end > src_end && src_start < dst_start) || (src_end > dst_end && dst_start < src_start)) return false; /* Check for a write to either register in the intersection of their live * ranges. */ int start_ip = MAX2(dst_start, src_start); int end_ip = MIN2(dst_end, src_end); foreach_block(block, cfg) { if (block->end_ip < start_ip) continue; int scan_ip = block->start_ip - 1; foreach_inst_in_block(fs_inst, scan_inst, block) { scan_ip++; /* Ignore anything before the intersection of the live ranges */ if (scan_ip < start_ip) continue; /* Ignore the copying instruction itself */ if (scan_inst == inst) continue; if (scan_ip > end_ip) return true; /* registers do not interfere */ if (scan_inst->overwrites_reg(inst->dst) || scan_inst->overwrites_reg(inst->src[0])) return false; /* registers interfere */ } } return true; } bool fs_visitor::register_coalesce() { bool progress = false; calculate_live_intervals(); int src_size = 0; int channels_remaining = 0; int src_reg = -1, dst_reg = -1; int dst_reg_offset[MAX_VGRF_SIZE]; fs_inst *mov[MAX_VGRF_SIZE]; int dst_var[MAX_VGRF_SIZE]; int src_var[MAX_VGRF_SIZE]; foreach_block_and_inst(block, fs_inst, inst, cfg) { if (!is_coalesce_candidate(this, inst)) continue; if (is_nop_mov(inst)) { inst->opcode = BRW_OPCODE_NOP; progress = true; continue; } if (src_reg != inst->src[0].nr) { src_reg = inst->src[0].nr; src_size = alloc.sizes[inst->src[0].nr]; assert(src_size <= MAX_VGRF_SIZE); channels_remaining = src_size; memset(mov, 0, sizeof(mov)); dst_reg = inst->dst.nr; } if (dst_reg != inst->dst.nr) continue; if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD) { for (int i = 0; i < src_size; i++) { dst_reg_offset[i] = i; } mov[0] = inst; channels_remaining -= regs_written(inst); } else { const int offset = inst->src[0].offset / REG_SIZE; if (mov[offset]) { /* This is the second time that this offset in the register has * been set. This means, in particular, that inst->dst was * live before this instruction and that the live ranges of * inst->dst and inst->src[0] overlap and we can't coalesce the * two variables. Let's ensure that doesn't happen. */ channels_remaining = -1; continue; } dst_reg_offset[offset] = inst->dst.offset / REG_SIZE; if (inst->size_written > REG_SIZE) dst_reg_offset[offset + 1] = inst->dst.offset / REG_SIZE + 1; mov[offset] = inst; channels_remaining -= regs_written(inst); } if (channels_remaining) continue; bool can_coalesce = true; for (int i = 0; i < src_size; i++) { if (dst_reg_offset[i] != dst_reg_offset[0] + i) { /* Registers are out-of-order. */ can_coalesce = false; src_reg = -1; break; } dst_var[i] = live_intervals->var_from_vgrf[dst_reg] + dst_reg_offset[i]; src_var[i] = live_intervals->var_from_vgrf[src_reg] + i; if (!can_coalesce_vars(live_intervals, cfg, inst, dst_var[i], src_var[i])) { can_coalesce = false; src_reg = -1; break; } } if (!can_coalesce) continue; progress = true; for (int i = 0; i < src_size; i++) { if (mov[i]) { mov[i]->opcode = BRW_OPCODE_NOP; mov[i]->conditional_mod = BRW_CONDITIONAL_NONE; mov[i]->dst = reg_undef; for (int j = 0; j < mov[i]->sources; j++) { mov[i]->src[j] = reg_undef; } } } foreach_block_and_inst(block, fs_inst, scan_inst, cfg) { if (scan_inst->dst.file == VGRF && scan_inst->dst.nr == src_reg) { scan_inst->dst.nr = dst_reg; scan_inst->dst.offset = scan_inst->dst.offset % REG_SIZE + dst_reg_offset[scan_inst->dst.offset / REG_SIZE] * REG_SIZE; } for (int j = 0; j < scan_inst->sources; j++) { if (scan_inst->src[j].file == VGRF && scan_inst->src[j].nr == src_reg) { scan_inst->src[j].nr = dst_reg; scan_inst->src[j].offset = scan_inst->src[j].offset % REG_SIZE + dst_reg_offset[scan_inst->src[j].offset / REG_SIZE] * REG_SIZE; } } } for (int i = 0; i < src_size; i++) { live_intervals->start[dst_var[i]] = MIN2(live_intervals->start[dst_var[i]], live_intervals->start[src_var[i]]); live_intervals->end[dst_var[i]] = MAX2(live_intervals->end[dst_var[i]], live_intervals->end[src_var[i]]); } src_reg = -1; } if (progress) { foreach_block_and_inst_safe (block, backend_instruction, inst, cfg) { if (inst->opcode == BRW_OPCODE_NOP) { inst->remove(block); } } invalidate_live_intervals(); } return progress; } <commit_msg>i965/fs: Fix LOAD_PAYLOAD handling in register coalesce is_nop_mov().<commit_after>/* * Copyright © 2012 Intel Corporation * * 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 (including the next * paragraph) 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. */ /** @file brw_fs_register_coalesce.cpp * * Implements register coalescing: Checks if the two registers involved in a * raw move don't interfere, in which case they can both be stored in the same * place and the MOV removed. * * To do this, all uses of the source of the MOV in the shader are replaced * with the destination of the MOV. For example: * * add vgrf3:F, vgrf1:F, vgrf2:F * mov vgrf4:F, vgrf3:F * mul vgrf5:F, vgrf5:F, vgrf4:F * * becomes * * add vgrf4:F, vgrf1:F, vgrf2:F * mul vgrf5:F, vgrf5:F, vgrf4:F */ #include "brw_fs.h" #include "brw_cfg.h" #include "brw_fs_live_variables.h" static bool is_nop_mov(const fs_inst *inst) { if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD) { fs_reg dst = inst->dst; for (int i = 0; i < inst->sources; i++) { if (!dst.equals(inst->src[i])) { return false; } dst.offset += (i < inst->header_size ? REG_SIZE : inst->exec_size * dst.stride * type_sz(inst->src[i].type)); } return true; } else if (inst->opcode == BRW_OPCODE_MOV) { return inst->dst.equals(inst->src[0]); } return false; } static bool is_coalesce_candidate(const fs_visitor *v, const fs_inst *inst) { if ((inst->opcode != BRW_OPCODE_MOV && inst->opcode != SHADER_OPCODE_LOAD_PAYLOAD) || inst->is_partial_write() || inst->saturate || inst->src[0].file != VGRF || inst->src[0].negate || inst->src[0].abs || !inst->src[0].is_contiguous() || inst->dst.file != VGRF || inst->dst.type != inst->src[0].type) { return false; } if (v->alloc.sizes[inst->src[0].nr] > v->alloc.sizes[inst->dst.nr]) return false; if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD) { if (!inst->is_copy_payload(v->alloc)) { return false; } } return true; } static bool can_coalesce_vars(brw::fs_live_variables *live_intervals, const cfg_t *cfg, const fs_inst *inst, int dst_var, int src_var) { if (!live_intervals->vars_interfere(src_var, dst_var)) return true; int dst_start = live_intervals->start[dst_var]; int dst_end = live_intervals->end[dst_var]; int src_start = live_intervals->start[src_var]; int src_end = live_intervals->end[src_var]; /* Variables interfere and one line range isn't a subset of the other. */ if ((dst_end > src_end && src_start < dst_start) || (src_end > dst_end && dst_start < src_start)) return false; /* Check for a write to either register in the intersection of their live * ranges. */ int start_ip = MAX2(dst_start, src_start); int end_ip = MIN2(dst_end, src_end); foreach_block(block, cfg) { if (block->end_ip < start_ip) continue; int scan_ip = block->start_ip - 1; foreach_inst_in_block(fs_inst, scan_inst, block) { scan_ip++; /* Ignore anything before the intersection of the live ranges */ if (scan_ip < start_ip) continue; /* Ignore the copying instruction itself */ if (scan_inst == inst) continue; if (scan_ip > end_ip) return true; /* registers do not interfere */ if (scan_inst->overwrites_reg(inst->dst) || scan_inst->overwrites_reg(inst->src[0])) return false; /* registers interfere */ } } return true; } bool fs_visitor::register_coalesce() { bool progress = false; calculate_live_intervals(); int src_size = 0; int channels_remaining = 0; int src_reg = -1, dst_reg = -1; int dst_reg_offset[MAX_VGRF_SIZE]; fs_inst *mov[MAX_VGRF_SIZE]; int dst_var[MAX_VGRF_SIZE]; int src_var[MAX_VGRF_SIZE]; foreach_block_and_inst(block, fs_inst, inst, cfg) { if (!is_coalesce_candidate(this, inst)) continue; if (is_nop_mov(inst)) { inst->opcode = BRW_OPCODE_NOP; progress = true; continue; } if (src_reg != inst->src[0].nr) { src_reg = inst->src[0].nr; src_size = alloc.sizes[inst->src[0].nr]; assert(src_size <= MAX_VGRF_SIZE); channels_remaining = src_size; memset(mov, 0, sizeof(mov)); dst_reg = inst->dst.nr; } if (dst_reg != inst->dst.nr) continue; if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD) { for (int i = 0; i < src_size; i++) { dst_reg_offset[i] = i; } mov[0] = inst; channels_remaining -= regs_written(inst); } else { const int offset = inst->src[0].offset / REG_SIZE; if (mov[offset]) { /* This is the second time that this offset in the register has * been set. This means, in particular, that inst->dst was * live before this instruction and that the live ranges of * inst->dst and inst->src[0] overlap and we can't coalesce the * two variables. Let's ensure that doesn't happen. */ channels_remaining = -1; continue; } dst_reg_offset[offset] = inst->dst.offset / REG_SIZE; if (inst->size_written > REG_SIZE) dst_reg_offset[offset + 1] = inst->dst.offset / REG_SIZE + 1; mov[offset] = inst; channels_remaining -= regs_written(inst); } if (channels_remaining) continue; bool can_coalesce = true; for (int i = 0; i < src_size; i++) { if (dst_reg_offset[i] != dst_reg_offset[0] + i) { /* Registers are out-of-order. */ can_coalesce = false; src_reg = -1; break; } dst_var[i] = live_intervals->var_from_vgrf[dst_reg] + dst_reg_offset[i]; src_var[i] = live_intervals->var_from_vgrf[src_reg] + i; if (!can_coalesce_vars(live_intervals, cfg, inst, dst_var[i], src_var[i])) { can_coalesce = false; src_reg = -1; break; } } if (!can_coalesce) continue; progress = true; for (int i = 0; i < src_size; i++) { if (mov[i]) { mov[i]->opcode = BRW_OPCODE_NOP; mov[i]->conditional_mod = BRW_CONDITIONAL_NONE; mov[i]->dst = reg_undef; for (int j = 0; j < mov[i]->sources; j++) { mov[i]->src[j] = reg_undef; } } } foreach_block_and_inst(block, fs_inst, scan_inst, cfg) { if (scan_inst->dst.file == VGRF && scan_inst->dst.nr == src_reg) { scan_inst->dst.nr = dst_reg; scan_inst->dst.offset = scan_inst->dst.offset % REG_SIZE + dst_reg_offset[scan_inst->dst.offset / REG_SIZE] * REG_SIZE; } for (int j = 0; j < scan_inst->sources; j++) { if (scan_inst->src[j].file == VGRF && scan_inst->src[j].nr == src_reg) { scan_inst->src[j].nr = dst_reg; scan_inst->src[j].offset = scan_inst->src[j].offset % REG_SIZE + dst_reg_offset[scan_inst->src[j].offset / REG_SIZE] * REG_SIZE; } } } for (int i = 0; i < src_size; i++) { live_intervals->start[dst_var[i]] = MIN2(live_intervals->start[dst_var[i]], live_intervals->start[src_var[i]]); live_intervals->end[dst_var[i]] = MAX2(live_intervals->end[dst_var[i]], live_intervals->end[src_var[i]]); } src_reg = -1; } if (progress) { foreach_block_and_inst_safe (block, backend_instruction, inst, cfg) { if (inst->opcode == BRW_OPCODE_NOP) { inst->remove(block); } } invalidate_live_intervals(); } return progress; } <|endoftext|>