text
stringlengths
54
60.6k
<commit_before>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <sstream> #include <stdexcept> #include <boost/algorithm/string/replace.hpp> #include <jitk/compiler.hpp> using namespace std; namespace { // Returns the command where {OUT} and {IN} are expanded. string expand_cmd(const string &cmd_template, const string &out, const string &in) { string ret = cmd_template; boost::replace_first(ret, "{OUT}", out); boost::replace_first(ret, "{IN}", in); return ret; } } namespace bohrium { namespace jitk { Compiler::Compiler(string cmd_template, bool verbose) : cmd_template(std::move(cmd_template)), verbose(verbose) {} void Compiler::compile(string object_abspath, const char* sourcecode, size_t source_len) const { const string cmd = expand_cmd(cmd_template, object_abspath, " - "); if (verbose) { cout << "compile command: " << cmd << endl; } FILE* cmd_stdin = popen(cmd.c_str(), "w"); // Open process and get stdin stream if (!cmd_stdin) { perror("popen()"); fprintf(stderr, "popen() failed for: [%s]", sourcecode); pclose(cmd_stdin); throw runtime_error("Compiler: popen() failed"); } // Write / pipe to stdin int write_res = fwrite(sourcecode, sizeof(char), source_len, cmd_stdin); if (write_res < (int)source_len) { perror("fwrite()"); fprintf(stderr, "fwrite() failed in file %s at line # %d\n", __FILE__, __LINE__-5); pclose(cmd_stdin); throw runtime_error("Compiler: error!"); } int flush_res = fflush(cmd_stdin); // Flush stdin if (EOF == flush_res) { perror("fflush()"); fprintf(stderr, "fflush() failed in file %s at line # %d\n", __FILE__, __LINE__-5); pclose(cmd_stdin); throw runtime_error("Compiler: fflush() failed"); } int exit_code = (pclose(cmd_stdin)/256); if (0!=exit_code) { perror("pclose()"); fprintf(stderr, "pclose() failed.\n"); throw runtime_error("Compiler: pclose() failed"); } } void Compiler::compile(string object_abspath, string src_abspath) const { const string cmd = expand_cmd(cmd_template, object_abspath, src_abspath); if (verbose) { cout << "compile command: " << cmd << endl; } // Execute the process FILE *cmd_stdin = NULL; // Handle for library-file cmd_stdin = popen(cmd.c_str(), "w"); // Execute the command if (!cmd_stdin) { std::cout << "Err: Could not execute process! ["<< cmd <<"]" << std::endl; throw runtime_error("Compiler: error!"); } fflush(cmd_stdin); int exit_code = (pclose(cmd_stdin)/256); if (0!=exit_code) { perror("pclose()"); fprintf(stderr, "pclose() failed.\n"); throw runtime_error("Compiler: pclose() failed"); } } }} <commit_msg>Fixed nullptr in function 'close'<commit_after>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <sstream> #include <stdexcept> #include <boost/algorithm/string/replace.hpp> #include <jitk/compiler.hpp> using namespace std; namespace { // Returns the command where {OUT} and {IN} are expanded. string expand_cmd(const string &cmd_template, const string &out, const string &in) { string ret = cmd_template; boost::replace_first(ret, "{OUT}", out); boost::replace_first(ret, "{IN}", in); return ret; } } namespace bohrium { namespace jitk { Compiler::Compiler(string cmd_template, bool verbose) : cmd_template(std::move(cmd_template)), verbose(verbose) {} void Compiler::compile(string object_abspath, const char* sourcecode, size_t source_len) const { const string cmd = expand_cmd(cmd_template, object_abspath, " - "); if (verbose) { cout << "compile command: " << cmd << endl; } FILE* cmd_stdin = popen(cmd.c_str(), "w"); // Open process and get stdin stream if (!cmd_stdin) { perror("popen()"); fprintf(stderr, "popen() failed for: [%s]", sourcecode); throw runtime_error("Compiler: popen() failed"); } // Write / pipe to stdin int write_res = fwrite(sourcecode, sizeof(char), source_len, cmd_stdin); if (write_res < (int)source_len) { perror("fwrite()"); fprintf(stderr, "fwrite() failed in file %s at line # %d\n", __FILE__, __LINE__-5); pclose(cmd_stdin); throw runtime_error("Compiler: error!"); } int flush_res = fflush(cmd_stdin); // Flush stdin if (EOF == flush_res) { perror("fflush()"); fprintf(stderr, "fflush() failed in file %s at line # %d\n", __FILE__, __LINE__-5); pclose(cmd_stdin); throw runtime_error("Compiler: fflush() failed"); } int exit_code = (pclose(cmd_stdin)/256); if (0!=exit_code) { perror("pclose()"); fprintf(stderr, "pclose() failed.\n"); throw runtime_error("Compiler: pclose() failed"); } } void Compiler::compile(string object_abspath, string src_abspath) const { const string cmd = expand_cmd(cmd_template, object_abspath, src_abspath); if (verbose) { cout << "compile command: " << cmd << endl; } // Execute the process FILE *cmd_stdin = NULL; // Handle for library-file cmd_stdin = popen(cmd.c_str(), "w"); // Execute the command if (!cmd_stdin) { std::cout << "Err: Could not execute process! ["<< cmd <<"]" << std::endl; throw runtime_error("Compiler: error!"); } fflush(cmd_stdin); int exit_code = (pclose(cmd_stdin)/256); if (0!=exit_code) { perror("pclose()"); fprintf(stderr, "pclose() failed.\n"); throw runtime_error("Compiler: pclose() failed"); } } }} <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/file_pool.hpp" #include "libtorrent/storage.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/create_torrent.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include <fstream> #include "test.hpp" #include "setup_transfer.hpp" using namespace boost::filesystem; using namespace libtorrent; // proxy: 0=none, 1=socks4, 2=socks5, 3=socks5_pw 4=http 5=http_pw void test_transfer(boost::intrusive_ptr<torrent_info> torrent_file, int proxy) { using namespace libtorrent; session ses(fingerprint(" ", 0,0,0,0), 0); session_settings settings; settings.ignore_limits_on_local_network = false; ses.set_settings(settings); ses.set_alert_mask(~alert::progress_notification); ses.listen_on(std::make_pair(51000, 52000)); ses.set_download_rate_limit(torrent_file->total_size() / 5); remove_all("./tmp1"); char const* test_name[] = {"no", "SOCKS4", "SOCKS5", "SOCKS5 password", "HTTP", "HTTP password"}; std::cerr << " ==== TESTING " << test_name[proxy] << " proxy ====" << std::endl; if (proxy) { start_proxy(8002, proxy); proxy_settings ps; ps.hostname = "127.0.0.1"; ps.port = 8002; ps.username = "testuser"; ps.password = "testpass"; ps.type = (proxy_settings::proxy_type)proxy; ses.set_web_seed_proxy(ps); } torrent_handle th = ses.add_torrent(*torrent_file, "./tmp1"); std::vector<announce_entry> empty; th.replace_trackers(empty); const size_type total_size = torrent_file->total_size(); float rate_sum = 0.f; float ses_rate_sum = 0.f; for (int i = 0; i < 30; ++i) { torrent_status s = th.status(); session_status ss = ses.status(); std::cerr << (s.progress * 100.f) << " %" << " torrent rate: " << (s.download_rate / 1000.f) << " kB/s" << " session rate: " << (ss.download_rate / 1000.f) << " kB/s" << " session total: " << ss.total_payload_download << " torrent total: " << s.total_payload_download << std::endl; rate_sum += s.download_payload_rate; ses_rate_sum += ss.payload_download_rate; print_alerts(ses, "ses"); if (th.is_seed() && ss.download_rate == 0.f) { TEST_CHECK(ses.status().total_payload_download == total_size); TEST_CHECK(th.status().total_payload_download == total_size); break; } test_sleep(1000); } std::cerr << "total_size: " << total_size << " rate_sum: " << rate_sum << " session_rate_sum: " << ses_rate_sum << std::endl; // the rates for each second should sum up to the total, with a 10% error margin TEST_CHECK(fabs(rate_sum - total_size) < total_size * .1f); TEST_CHECK(fabs(ses_rate_sum - total_size) < total_size * .1f); TEST_CHECK(th.is_seed()); if (proxy) stop_proxy(8002); TEST_CHECK(exists("./tmp1" / torrent_file->file_at(0).path)); remove_all("./tmp1"); } int test_main() { using namespace libtorrent; using namespace boost::filesystem; try { create_directory("test_torrent_dir"); } catch (std::exception&) {} char random_data[300000]; std::srand(std::time(0)); std::generate(random_data, random_data + sizeof(random_data), &std::rand); std::ofstream("./test_torrent_dir/test1").write(random_data, 35); std::ofstream("./test_torrent_dir/test2").write(random_data, 16536 - 35); std::ofstream("./test_torrent_dir/test3").write(random_data, 16536); std::ofstream("./test_torrent_dir/test4").write(random_data, 17); std::ofstream("./test_torrent_dir/test5").write(random_data, 16536); std::ofstream("./test_torrent_dir/test6").write(random_data, 300000); std::ofstream("./test_torrent_dir/test7").write(random_data, 300000); file_storage fs; add_files(fs, path("test_torrent_dir")); libtorrent::create_torrent t(fs, 16 * 1024); t.add_url_seed("http://127.0.0.1:8000/"); start_web_server(8000); // calculate the hash for all pieces int num = t.num_pieces(); char* buf = page_aligned_allocator::malloc(t.piece_length()); file_pool fp; boost::scoped_ptr<storage_interface> s(default_storage_constructor( fs, ".", fp)); for (int i = 0; i < num; ++i) { s->read(buf, i, 0, fs.piece_size(i)); hasher h(buf, fs.piece_size(i)); t.set_hash(i, h.final()); } boost::intrusive_ptr<torrent_info> torrent_file(new torrent_info(t.generate())); for (int i = 0; i < 6; ++i) test_transfer(torrent_file, i); torrent_file->rename_file(0, "./test_torrent_dir/renamed_test1"); test_transfer(torrent_file, 0); stop_web_server(8000); remove_all("./test_torrent_dir"); page_aligned_allocator::free(buf); return 0; } <commit_msg>made web seed test work<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/file_pool.hpp" #include "libtorrent/storage.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/create_torrent.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include <fstream> #include "test.hpp" #include "setup_transfer.hpp" using namespace boost::filesystem; using namespace libtorrent; // proxy: 0=none, 1=socks4, 2=socks5, 3=socks5_pw 4=http 5=http_pw void test_transfer(boost::intrusive_ptr<torrent_info> torrent_file, int proxy) { using namespace libtorrent; session ses(fingerprint(" ", 0,0,0,0), 0); session_settings settings; settings.ignore_limits_on_local_network = false; settings.max_outstanding_disk_bytes_per_connection = 64 * 1024; ses.set_settings(settings); ses.set_alert_mask(~alert::progress_notification); ses.listen_on(std::make_pair(51000, 52000)); ses.set_download_rate_limit(torrent_file->total_size() / 10); remove_all("./tmp1"); char const* test_name[] = {"no", "SOCKS4", "SOCKS5", "SOCKS5 password", "HTTP", "HTTP password"}; std::cerr << " ==== TESTING " << test_name[proxy] << " proxy ====" << std::endl; if (proxy) { start_proxy(8002, proxy); proxy_settings ps; ps.hostname = "127.0.0.1"; ps.port = 8002; ps.username = "testuser"; ps.password = "testpass"; ps.type = (proxy_settings::proxy_type)proxy; ses.set_web_seed_proxy(ps); } torrent_handle th = ses.add_torrent(*torrent_file, "./tmp1"); std::vector<announce_entry> empty; th.replace_trackers(empty); const size_type total_size = torrent_file->total_size(); float rate_sum = 0.f; float ses_rate_sum = 0.f; for (int i = 0; i < 30; ++i) { torrent_status s = th.status(); session_status ss = ses.status(); rate_sum += s.download_payload_rate; ses_rate_sum += ss.payload_download_rate; std::cerr << (s.progress * 100.f) << " %" << " torrent rate: " << (s.download_rate / 1000.f) << " kB/s" << " session rate: " << (ss.download_rate / 1000.f) << " kB/s" << " session total: " << ss.total_payload_download << " torrent total: " << s.total_payload_download << " rate sum:" << ses_rate_sum << std::endl; print_alerts(ses, "ses"); if (th.is_seed() && ss.download_rate == 0.f) { TEST_CHECK(ses.status().total_payload_download == total_size); TEST_CHECK(th.status().total_payload_download == total_size); break; } test_sleep(1000); } std::cerr << "total_size: " << total_size << " rate_sum: " << rate_sum << " session_rate_sum: " << ses_rate_sum << std::endl; // the rates for each second should sum up to the total, with a 10% error margin TEST_CHECK(fabs(rate_sum - total_size) < total_size * .1f); TEST_CHECK(fabs(ses_rate_sum - total_size) < total_size * .1f); TEST_CHECK(th.is_seed()); if (proxy) stop_proxy(8002); TEST_CHECK(exists("./tmp1" / torrent_file->file_at(0).path)); remove_all("./tmp1"); } int test_main() { using namespace libtorrent; using namespace boost::filesystem; try { create_directory("test_torrent_dir"); } catch (std::exception&) {} char random_data[300000]; std::srand(std::time(0)); std::generate(random_data, random_data + sizeof(random_data), &std::rand); std::ofstream("./test_torrent_dir/test1").write(random_data, 35); std::ofstream("./test_torrent_dir/test2").write(random_data, 16536 - 35); std::ofstream("./test_torrent_dir/test3").write(random_data, 16536); std::ofstream("./test_torrent_dir/test4").write(random_data, 17); std::ofstream("./test_torrent_dir/test5").write(random_data, 16536); std::ofstream("./test_torrent_dir/test6").write(random_data, 300000); std::ofstream("./test_torrent_dir/test7").write(random_data, 300000); file_storage fs; add_files(fs, path("test_torrent_dir")); libtorrent::create_torrent t(fs, 16 * 1024); t.add_url_seed("http://127.0.0.1:8000/"); start_web_server(8000); // calculate the hash for all pieces int num = t.num_pieces(); char* buf = page_aligned_allocator::malloc(t.piece_length()); file_pool fp; boost::scoped_ptr<storage_interface> s(default_storage_constructor( fs, ".", fp)); for (int i = 0; i < num; ++i) { s->read(buf, i, 0, fs.piece_size(i)); hasher h(buf, fs.piece_size(i)); t.set_hash(i, h.final()); } boost::intrusive_ptr<torrent_info> torrent_file(new torrent_info(t.generate())); for (int i = 0; i < 6; ++i) test_transfer(torrent_file, i); torrent_file->rename_file(0, "./test_torrent_dir/renamed_test1"); test_transfer(torrent_file, 0); stop_web_server(8000); remove_all("./test_torrent_dir"); page_aligned_allocator::free(buf); return 0; } <|endoftext|>
<commit_before>/* * SessionThemes.cpp * * Copyright (C) 2018 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * 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 "SessionThemes.hpp" #include <boost/bind.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <core/json/JsonRpc.hpp> #include <session/SessionModuleContext.hpp> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace themes { namespace { Error convertTheme(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // TODO: process arguments, call r method, populate response. return Success(); } Error addTheme(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // TODO: process arguments, call r method, populate response. return Success(); } Error applyTheme(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // TODO: process arguments, call r method, populate response. return Success(); } Error removeTheme(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // TODO: process arguments, call r method, populate response. return Success(); } } // anonymous namespace Error initialize() { using boost::bind; using namespace module_context; ExecBlock initBlock; initBlock.addFunctions() (bind(registerRpcMethod, "theme_convert", convertTheme)) (bind(registerRpcMethod, "theme_add", addTheme)) (bind(registerRpcMethod, "theme_apply", applyTheme)) (bind(registerRpcMethod, "theme_remove", removeTheme)) (bind(sourceModuleRFile, "SessionThemes.R")); return initBlock.execute(); } } // namespace themes } // namespace modules } // namespace session } // namespace rstudio <commit_msg>add C++ callback function to get the list of custom themes.<commit_after>/* * SessionThemes.cpp * * Copyright (C) 2018 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * 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 "SessionThemes.hpp" #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <core/json/JsonRpc.hpp> #include <session/SessionModuleContext.hpp> #include <r/RRoutines.hpp> #include <r/RSexp.hpp> #include <map> #include <regex> #include <string> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace themes { namespace { /** * @brief Parses a colour and returns an RGB array. * * @param colorStr The colour string to parse. * * @return An array of the integer RGB values. */ std::array<int, 3> parseColor(const std::string& colorStr) { // NOTE: This funciton is for internal use and assumes that the input has already been validated. std::array<int, 3> rgb; if (colorStr[0] == '#') { std::smatch matches; std::regex_search(colorStr, matches, std::regex("#(..)(..)(..)")); assert(matches.size() == 4); for (int i = 0; i < 3; ++i) { rgb[i] = std::stoi(matches[i + 1], nullptr, 16); } } else { std::smatch matches; std::regex_search(colorStr, matches, std::regex("rgba?\\(\\s*(\\d*)\\s*,\\s*(\\d*)\\s*,\\s*(\\d*)")); assert(matches.size() == 4); for (int i = 0; i < 3; ++i) { rgb[i] = std::stoi(matches[i + 1]); } } return rgb; } /** * @brief Checks whether a colour is dark or light. * * @param colorStr The colour to test. * * @return True if the colour is dark; false otherwise. */ bool isDarkColor(const std::string& colorStr) { std::array<int, 3> rgb = parseColor(colorStr); float luma = ((0.21f * rgb[0]) + (0.72f * rgb[1]) + (0.07f * rgb[2])) / 255.0f; return luma < 0.5f; } // A map from the name of the theme to the location of the file and a boolean representing // whether or not the theme is dark. typedef std::map<std::string, std::pair<std::string, bool> > ThemeMap; void getThemesInLocation(const boost::filesystem::path& location, ThemeMap& themeMap) { using namespace boost::filesystem; if (is_directory(location)) { for (directory_entry& themeFile : boost::make_iterator_range(directory_iterator(location), {})) { std::string fileLocation = themeFile.path().generic_string(); if (!std::regex_match( fileLocation, std::regex(".*\\.rstheme$", std::regex_constants::icase))) { std::ifstream themeIFStream(fileLocation); std::string themeContents( (std::istreambuf_iterator<char>(themeIFStream)), (std::istreambuf_iterator<char>())); themeIFStream.close(); std::smatch matches; std::regex_search( themeContents, matches, std::regex("rs-theme-name\\s*:\\s*([^\\*]+?)\\s*(?:\\*|$)"), std::regex_constants::match_default); // If there's at least one name specified, get the first one. if (matches.size() < 2) { std::regex_search( fileLocation, matches, std::regex("([^/\\\\]+?)\\.rstheme"), std::regex_constants::match_default); if (matches.size() < 2) { // TODO: warning / logging // No name so skip. continue; } } std::string name = matches[1]; // Find out if the theme is dark or not. std::regex defaultBlock( "\\.ace_editor, " "\\.rstudio-themes-flat\\.ace_editor_theme \\.profvis-flamegraph, " "\\.rstudio-themes-flat.ace_editor_theme, " "\\.rstudio-themes-flat .ace_editor_theme {.+?" "[^-]color:\\s*(#[A-Fa-f\\d]{6}|rgba?\\(\\s*\\d{1-3}\\s*,\\s*\\d{1-3}\\s*,\\s*\\d{1-3}*[^\\)]*\\))"); std::regex_search(themeContents, matches, defaultBlock); if (matches.size() < 2) { // TODO: warning / logging // Incorrectly formed rstheme file, so skip. continue; } themeMap[name] = std::pair<std::string, bool>(fileLocation, isDarkColor(matches[1])); } } } } /** * @brief Gets the list of all RStudio editor themes. * * @return The list of all RStudio editor themes. */ SEXP rs_getThemes() { // List all files in the global location first. // TODO: Windows using namespace boost::filesystem; #if defined(_WIN32) || defined(_WIN64) #else path globalPath("/etc/rstudio/themes/"); path localPath("~/.R/rstudio/themes/"); #endif // Intentionally get global themes before getting user specific themes so that user specific // themes will override global ones. ThemeMap themeMap; getThemesInLocation(globalPath, themeMap); getThemesInLocation(localPath, themeMap); // TODO: get default themes. // Convert to an R list. rstudio::r::sexp::Protect protect; rstudio::r::sexp::ListBuilder themeListBuilder(&protect); for (auto theme: themeMap) { rstudio::r::sexp::ListBuilder themeDetailsListBuilder(&protect); themeDetailsListBuilder.add("fileName", theme.second.first); themeDetailsListBuilder.add("isDark", theme.second.second); themeListBuilder.add(theme.first, themeDetailsListBuilder); } return rstudio::r::sexp::create(themeListBuilder, &protect); } } // anonymous namespace Error initialize() { using boost::bind; using namespace module_context; RS_REGISTER_CALL_METHOD(rs_getThemes, 0); ExecBlock initBlock; initBlock.addFunctions() (bind(sourceModuleRFile, "SessionThemes.R")); return initBlock.execute(); } } // namespace themes } // namespace modules } // namespace session } // namespace rstudio <|endoftext|>
<commit_before><commit_msg>New Java version (6u22). Relevant advisory: http://www.oracle.com/technetwork/topics/security/javacpuoct2010-176258.html BUG=None TEST=test_shell_tests<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2012-2013 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Thomas Grass * Andreas Hansson * Sascha Bischoff */ #include "base/random.hh" #include "cpu/testers/traffic_gen/generators.hh" #include "debug/TrafficGen.hh" #include "proto/packet.pb.h" BaseGen::BaseGen(QueuedMasterPort& _port, MasterID master_id, Tick _duration) : port(_port), masterID(master_id), duration(_duration) { } void BaseGen::send(Addr addr, unsigned size, const MemCmd& cmd, Request::FlagsType flags) { // Create new request Request *req = new Request(addr, size, flags, masterID); // Embed it in a packet PacketPtr pkt = new Packet(req, cmd); uint8_t* pkt_data = new uint8_t[req->getSize()]; pkt->dataDynamicArray(pkt_data); if (cmd.isWrite()) { memset(pkt_data, 0xA, req->getSize()); } port.schedTimingReq(pkt, curTick()); } void LinearGen::enter() { // reset the address and the data counter nextAddr = startAddr; dataManipulated = 0; // this test only needs to happen once, but cannot be performed // before init() is called and the ports are connected if (port.deviceBlockSize() && blocksize > port.deviceBlockSize()) fatal("TrafficGen %s block size (%d) is larger than port" " block size (%d)\n", blocksize, port.deviceBlockSize()); } void LinearGen::execute() { // choose if we generate a read or a write here bool isRead = readPercent != 0 && (readPercent == 100 || random_mt.random<uint8_t>(0, 100) < readPercent); assert((readPercent == 0 && !isRead) || (readPercent == 100 && isRead) || readPercent != 100); DPRINTF(TrafficGen, "LinearGen::execute: %c to addr %x, size %d\n", isRead ? 'r' : 'w', nextAddr, blocksize); send(nextAddr, blocksize, isRead ? MemCmd::ReadReq : MemCmd::WriteReq); // increment the address nextAddr += blocksize; // Add the amount of data manipulated to the total dataManipulated += blocksize; } Tick LinearGen::nextExecuteTick() { // If we have reached the end of the address space, reset the // address to the start of the range if (nextAddr + blocksize > endAddr) { DPRINTF(TrafficGen, "Wrapping address to the start of " "the range\n"); nextAddr = startAddr; } // Check to see if we have reached the data limit. If dataLimit is // zero we do not have a data limit and therefore we will keep // generating requests for the entire residency in this state. if (dataLimit && dataManipulated >= dataLimit) { DPRINTF(TrafficGen, "Data limit for LinearGen reached.\n"); // there are no more requests, therefore return MaxTick return MaxTick; } else { // return the time when the next request should take place return curTick() + random_mt.random<Tick>(minPeriod, maxPeriod); } } void RandomGen::enter() { // reset the counter to zero dataManipulated = 0; // this test only needs to happen once, but cannot be performed // before init() is called and the ports are connected if (port.deviceBlockSize() && blocksize > port.deviceBlockSize()) fatal("TrafficGen %s block size (%d) is larger than port" " block size (%d)\n", blocksize, port.deviceBlockSize()); } void RandomGen::execute() { // choose if we generate a read or a write here bool isRead = readPercent != 0 && (readPercent == 100 || random_mt.random<uint8_t>(0, 100) < readPercent); assert((readPercent == 0 && !isRead) || (readPercent == 100 && isRead) || readPercent != 100); // address of the request Addr addr = random_mt.random<Addr>(startAddr, endAddr - 1); // round down to start address of block addr -= addr % blocksize; DPRINTF(TrafficGen, "RandomGen::execute: %c to addr %x, size %d\n", isRead ? 'r' : 'w', addr, blocksize); // send a new request packet send(addr, blocksize, isRead ? MemCmd::ReadReq : MemCmd::WriteReq); // Add the amount of data manipulated to the total dataManipulated += blocksize; } Tick RandomGen::nextExecuteTick() { // Check to see if we have reached the data limit. If dataLimit is // zero we do not have a data limit and therefore we will keep // generating requests for the entire residency in this state. if (dataLimit && dataManipulated >= dataLimit) { DPRINTF(TrafficGen, "Data limit for RandomGen reached.\n"); // No more requests. Return MaxTick. return MaxTick; } else { // Return the time when the next request should take place. return curTick() + random_mt.random<Tick>(minPeriod, maxPeriod); } } TraceGen::InputStream::InputStream(const std::string& filename) : trace(filename) { // Create a protobuf message for the header and read it from the stream Message::PacketHeader header_msg; if (!trace.read(header_msg)) { panic("Failed to read packet header from %s\n", filename); if (header_msg.tick_freq() != SimClock::Frequency) { panic("Trace %s was recorded with a different tick frequency %d\n", header_msg.tick_freq()); } } } void TraceGen::InputStream::reset() { trace.reset(); } bool TraceGen::InputStream::read(TraceElement& element) { Message::Packet pkt_msg; if (trace.read(pkt_msg)) { element.cmd = pkt_msg.cmd(); element.addr = pkt_msg.addr(); element.blocksize = pkt_msg.size(); element.tick = pkt_msg.tick(); if (pkt_msg.has_flags()) element.flags = pkt_msg.flags(); return true; } // We have reached the end of the file return false; } Tick TraceGen::nextExecuteTick() { if (traceComplete) // We are at the end of the file, thus we have no more data in // the trace Return MaxTick to signal that there will be no // more transactions in this active period for the state. return MaxTick; //Reset the nextElement to the default values currElement = nextElement; nextElement.clear(); // We need to look at the next line to calculate the next time an // event occurs, or potentially return MaxTick to signal that // nothing has to be done. if (!trace.read(nextElement)) { traceComplete = true; return MaxTick; } DPRINTF(TrafficGen, "currElement: %c addr %d size %d tick %d (%d)\n", currElement.cmd.isRead() ? 'r' : 'w', currElement.addr, currElement.blocksize, currElement.tick + tickOffset, currElement.tick); DPRINTF(TrafficGen, "nextElement: %c addr %d size %d tick %d (%d)\n", nextElement.cmd.isRead() ? 'r' : 'w', nextElement.addr, nextElement.blocksize, nextElement.tick + tickOffset, nextElement.tick); return tickOffset + nextElement.tick; } void TraceGen::enter() { // update the trace offset to the time where the state was entered. tickOffset = curTick(); // clear everything nextElement.clear(); currElement.clear(); traceComplete = false; } void TraceGen::execute() { // it is the responsibility of nextExecuteTick to prevent the // state graph from executing the state if it should not assert(currElement.isValid()); DPRINTF(TrafficGen, "TraceGen::execute: %c %d %d %d 0x%x\n", currElement.cmd.isRead() ? 'r' : 'w', currElement.addr, currElement.blocksize, currElement.tick, currElement.flags); send(currElement.addr + addrOffset, currElement.blocksize, currElement.cmd, currElement.flags); } void TraceGen::exit() { // Check if we reached the end of the trace file. If we did not // then we want to generate a warning stating that not the entire // trace was played. if (!traceComplete) { warn("Trace player %s was unable to replay the entire trace!\n", name()); } // Clear any flags and start over again from the beginning of the // file trace.reset(); } <commit_msg>cpu: Fix TraceGen flag initalisation<commit_after>/* * Copyright (c) 2012-2013 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Thomas Grass * Andreas Hansson * Sascha Bischoff */ #include "base/random.hh" #include "cpu/testers/traffic_gen/generators.hh" #include "debug/TrafficGen.hh" #include "proto/packet.pb.h" BaseGen::BaseGen(QueuedMasterPort& _port, MasterID master_id, Tick _duration) : port(_port), masterID(master_id), duration(_duration) { } void BaseGen::send(Addr addr, unsigned size, const MemCmd& cmd, Request::FlagsType flags) { // Create new request Request *req = new Request(addr, size, flags, masterID); // Embed it in a packet PacketPtr pkt = new Packet(req, cmd); uint8_t* pkt_data = new uint8_t[req->getSize()]; pkt->dataDynamicArray(pkt_data); if (cmd.isWrite()) { memset(pkt_data, 0xA, req->getSize()); } port.schedTimingReq(pkt, curTick()); } void LinearGen::enter() { // reset the address and the data counter nextAddr = startAddr; dataManipulated = 0; // this test only needs to happen once, but cannot be performed // before init() is called and the ports are connected if (port.deviceBlockSize() && blocksize > port.deviceBlockSize()) fatal("TrafficGen %s block size (%d) is larger than port" " block size (%d)\n", blocksize, port.deviceBlockSize()); } void LinearGen::execute() { // choose if we generate a read or a write here bool isRead = readPercent != 0 && (readPercent == 100 || random_mt.random<uint8_t>(0, 100) < readPercent); assert((readPercent == 0 && !isRead) || (readPercent == 100 && isRead) || readPercent != 100); DPRINTF(TrafficGen, "LinearGen::execute: %c to addr %x, size %d\n", isRead ? 'r' : 'w', nextAddr, blocksize); send(nextAddr, blocksize, isRead ? MemCmd::ReadReq : MemCmd::WriteReq); // increment the address nextAddr += blocksize; // Add the amount of data manipulated to the total dataManipulated += blocksize; } Tick LinearGen::nextExecuteTick() { // If we have reached the end of the address space, reset the // address to the start of the range if (nextAddr + blocksize > endAddr) { DPRINTF(TrafficGen, "Wrapping address to the start of " "the range\n"); nextAddr = startAddr; } // Check to see if we have reached the data limit. If dataLimit is // zero we do not have a data limit and therefore we will keep // generating requests for the entire residency in this state. if (dataLimit && dataManipulated >= dataLimit) { DPRINTF(TrafficGen, "Data limit for LinearGen reached.\n"); // there are no more requests, therefore return MaxTick return MaxTick; } else { // return the time when the next request should take place return curTick() + random_mt.random<Tick>(minPeriod, maxPeriod); } } void RandomGen::enter() { // reset the counter to zero dataManipulated = 0; // this test only needs to happen once, but cannot be performed // before init() is called and the ports are connected if (port.deviceBlockSize() && blocksize > port.deviceBlockSize()) fatal("TrafficGen %s block size (%d) is larger than port" " block size (%d)\n", blocksize, port.deviceBlockSize()); } void RandomGen::execute() { // choose if we generate a read or a write here bool isRead = readPercent != 0 && (readPercent == 100 || random_mt.random<uint8_t>(0, 100) < readPercent); assert((readPercent == 0 && !isRead) || (readPercent == 100 && isRead) || readPercent != 100); // address of the request Addr addr = random_mt.random<Addr>(startAddr, endAddr - 1); // round down to start address of block addr -= addr % blocksize; DPRINTF(TrafficGen, "RandomGen::execute: %c to addr %x, size %d\n", isRead ? 'r' : 'w', addr, blocksize); // send a new request packet send(addr, blocksize, isRead ? MemCmd::ReadReq : MemCmd::WriteReq); // Add the amount of data manipulated to the total dataManipulated += blocksize; } Tick RandomGen::nextExecuteTick() { // Check to see if we have reached the data limit. If dataLimit is // zero we do not have a data limit and therefore we will keep // generating requests for the entire residency in this state. if (dataLimit && dataManipulated >= dataLimit) { DPRINTF(TrafficGen, "Data limit for RandomGen reached.\n"); // No more requests. Return MaxTick. return MaxTick; } else { // Return the time when the next request should take place. return curTick() + random_mt.random<Tick>(minPeriod, maxPeriod); } } TraceGen::InputStream::InputStream(const std::string& filename) : trace(filename) { // Create a protobuf message for the header and read it from the stream Message::PacketHeader header_msg; if (!trace.read(header_msg)) { panic("Failed to read packet header from %s\n", filename); if (header_msg.tick_freq() != SimClock::Frequency) { panic("Trace %s was recorded with a different tick frequency %d\n", header_msg.tick_freq()); } } } void TraceGen::InputStream::reset() { trace.reset(); } bool TraceGen::InputStream::read(TraceElement& element) { Message::Packet pkt_msg; if (trace.read(pkt_msg)) { element.cmd = pkt_msg.cmd(); element.addr = pkt_msg.addr(); element.blocksize = pkt_msg.size(); element.tick = pkt_msg.tick(); element.flags = pkt_msg.has_flags() ? pkt_msg.flags() : 0; return true; } // We have reached the end of the file return false; } Tick TraceGen::nextExecuteTick() { if (traceComplete) // We are at the end of the file, thus we have no more data in // the trace Return MaxTick to signal that there will be no // more transactions in this active period for the state. return MaxTick; //Reset the nextElement to the default values currElement = nextElement; nextElement.clear(); // We need to look at the next line to calculate the next time an // event occurs, or potentially return MaxTick to signal that // nothing has to be done. if (!trace.read(nextElement)) { traceComplete = true; return MaxTick; } DPRINTF(TrafficGen, "currElement: %c addr %d size %d tick %d (%d)\n", currElement.cmd.isRead() ? 'r' : 'w', currElement.addr, currElement.blocksize, currElement.tick + tickOffset, currElement.tick); DPRINTF(TrafficGen, "nextElement: %c addr %d size %d tick %d (%d)\n", nextElement.cmd.isRead() ? 'r' : 'w', nextElement.addr, nextElement.blocksize, nextElement.tick + tickOffset, nextElement.tick); return tickOffset + nextElement.tick; } void TraceGen::enter() { // update the trace offset to the time where the state was entered. tickOffset = curTick(); // clear everything nextElement.clear(); currElement.clear(); traceComplete = false; } void TraceGen::execute() { // it is the responsibility of nextExecuteTick to prevent the // state graph from executing the state if it should not assert(currElement.isValid()); DPRINTF(TrafficGen, "TraceGen::execute: %c %d %d %d 0x%x\n", currElement.cmd.isRead() ? 'r' : 'w', currElement.addr, currElement.blocksize, currElement.tick, currElement.flags); send(currElement.addr + addrOffset, currElement.blocksize, currElement.cmd, currElement.flags); } void TraceGen::exit() { // Check if we reached the end of the trace file. If we did not // then we want to generate a warning stating that not the entire // trace was played. if (!traceComplete) { warn("Trace player %s was unable to replay the entire trace!\n", name()); } // Clear any flags and start over again from the beginning of the // file trace.reset(); } <|endoftext|>
<commit_before><commit_msg>Update minimum plug-in versions to reflect latest Adobe 0-day.<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DEBUG_HPP_INCLUDED #define TORRENT_DEBUG_HPP_INCLUDED #ifdef TORRENT_DEBUG #include <string> #include "libtorrent/config.hpp" #if TORRENT_USE_IOSTREAM #include <fstream> #include <iostream> #endif #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/lexical_cast.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/convenience.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif namespace libtorrent { // DEBUG API namespace fs = boost::filesystem; struct logger { logger(fs::path const& logpath, fs::path const& filename, int instance, bool append = true) { #if TORRENT_USE_IOSTREAM #ifndef BOOST_NO_EXCEPTIONS try { #endif fs::path dir(fs::complete(logpath / ("libtorrent_logs" + boost::lexical_cast<std::string>(instance)))); if (!fs::exists(dir)) fs::create_directories(dir); m_file.open((dir / filename).string().c_str(), std::ios_base::out | (append ? std::ios_base::app : std::ios_base::out)); *this << "\n\n\n*** starting log ***\n"; #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception& e) { std::cerr << "failed to create log '" << filename.string() << "': " << e.what() << std::endl; } #endif #endif } template <class T> logger& operator<<(T const& v) { #if TORRENT_USE_IOSTREAM m_file << v; m_file.flush(); #endif return *this; } #if TORRENT_USE_IOSTREAM std::ofstream m_file; #endif }; } #endif // TORRENT_DEBUG #endif // TORRENT_DEBUG_HPP_INCLUDED <commit_msg>fix release logging build<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DEBUG_HPP_INCLUDED #define TORRENT_DEBUG_HPP_INCLUDED #include <string> #include "libtorrent/config.hpp" #if TORRENT_USE_IOSTREAM #include <fstream> #include <iostream> #endif #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/lexical_cast.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/convenience.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif namespace libtorrent { // DEBUG API namespace fs = boost::filesystem; struct logger { logger(fs::path const& logpath, fs::path const& filename, int instance, bool append = true) { #if TORRENT_USE_IOSTREAM #ifndef BOOST_NO_EXCEPTIONS try { #endif fs::path dir(fs::complete(logpath / ("libtorrent_logs" + boost::lexical_cast<std::string>(instance)))); if (!fs::exists(dir)) fs::create_directories(dir); m_file.open((dir / filename).string().c_str(), std::ios_base::out | (append ? std::ios_base::app : std::ios_base::out)); *this << "\n\n\n*** starting log ***\n"; #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception& e) { std::cerr << "failed to create log '" << filename.string() << "': " << e.what() << std::endl; } #endif #endif } template <class T> logger& operator<<(T const& v) { #if TORRENT_USE_IOSTREAM m_file << v; m_file.flush(); #endif return *this; } #if TORRENT_USE_IOSTREAM std::ofstream m_file; #endif }; } #endif // TORRENT_DEBUG_HPP_INCLUDED <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <stdexcept> #include "calc.h" #include "sevensegment.h" namespace pocketcalculator { void display_result_for(std::istream &input, std::ostream &output) try { std::string term {}; std::getline(input, term); auto result = calc(term); printLargeNumber(result, output, 3); } catch(std::logic_error) { printLargeError(output, 3); } void start(std::istream &input, std::ostream &output) { while (input) { output << "Please type your input term: "; display_result_for(input, output); } } } <commit_msg>take scale argument<commit_after>#include <iostream> #include <string> #include <stdexcept> #include "calc.h" #include "sevensegment.h" namespace pocketcalculator { void display_result_for(std::istream &input, std::ostream &output, unsigned n) try { std::string term {}; std::getline(input, term); auto result = calc(term); printLargeNumber(result, output, n); } catch(std::logic_error) { printLargeError(output, n); } void start(std::istream &input, std::ostream &output, unsigned n=3) { while (input) { output << "Please type your input term: "; display_result_for(input, output, n); } } } <|endoftext|>
<commit_before>/* Copyright (c) 2010, The Barbarian Group 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. 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 "cinder/ip/Trim.h" namespace cinder { namespace ip { template<typename T> bool transparentHorizontalScanline( const SurfaceT<T> &surface, int32_t row, int32_t x1, int32_t x2 ) { const T *dstPtr = surface.getDataAlpha( Vec2i( x1, row ) ); uint8_t inc = surface.getPixelInc(); for( int32_t x = x1; x < x2; ++x ) { if( *dstPtr ) return false; dstPtr += inc; } return true; } template<typename T> bool transparentVerticalScanline( const SurfaceT<T> &surface, int32_t column, int32_t y1, int32_t y2 ) { const T *dstPtr = surface.getDataAlpha( Vec2i( column, y1 ) ); int32_t rowBytes = surface.getRowBytes(); for( int32_t y = y1; y < y2; ++y ) { if( *dstPtr ) return false; dstPtr += rowBytes; } return true; } template<typename T> Area findNonTransparentArea( const SurfaceT<T> &surface, const Area &unclippedBounds ) { const Area bounds = unclippedBounds.getClipBy( surface.getBounds() ); // if no alpha we'll fail over the to alpha-less fill if( ! surface.hasAlpha() ) { return surface.getBounds(); } int32_t topLine, bottomLine; int32_t leftColumn, rightColumn; // find the top and bottom lines for( topLine = bounds.getY1(); topLine < bounds.getY2(); ++topLine ) { if( ! transparentHorizontalScanline( surface, topLine, bounds.getX1(), bounds.getX2() ) ) { break; } } for( bottomLine = bounds.getY2() - 1; bottomLine > topLine; --bottomLine ) { if( ! transparentHorizontalScanline( surface, bottomLine, bounds.getX1(), bounds.getX2() ) ) { break; } } // find the left and right columns for( leftColumn = bounds.getX1(); leftColumn < bounds.getX2(); ++leftColumn ) { if( ! transparentVerticalScanline( surface, leftColumn, topLine, bottomLine ) ) { break; } } for( rightColumn = bounds.getX2(); rightColumn > leftColumn; --rightColumn ) { if( ! transparentVerticalScanline( surface, rightColumn, topLine, bottomLine ) ) { break; } } // we add one to right and bottom because Area represents an inclusive range on top/left and exclusive range on bottom/right return Area( leftColumn, topLine, rightColumn + 1, bottomLine + 1 ); } #define TRIM_PROTOTYPES(r,data,T)\ template Area findNonTransparentArea( const SurfaceT<T> &surface, const Area &unclippedBounds ); BOOST_PP_SEQ_FOR_EACH( TRIM_PROTOTYPES, ~, CHANNEL_TYPES ) } } // namespace cinder::ip <commit_msg>Fix for oversize bounds when Trimming.<commit_after>/* Copyright (c) 2010, The Barbarian Group 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. 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 "cinder/ip/Trim.h" namespace cinder { namespace ip { template<typename T> bool transparentHorizontalScanline( const SurfaceT<T> &surface, int32_t row, int32_t x1, int32_t x2 ) { const T *dstPtr = surface.getDataAlpha( Vec2i( x1, row ) ); uint8_t inc = surface.getPixelInc(); for( int32_t x = x1; x < x2; ++x ) { if( *dstPtr ) return false; dstPtr += inc; } return true; } template<typename T> bool transparentVerticalScanline( const SurfaceT<T> &surface, int32_t column, int32_t y1, int32_t y2 ) { const T *dstPtr = surface.getDataAlpha( Vec2i( column, y1 ) ); int32_t rowBytes = surface.getRowBytes(); for( int32_t y = y1; y < y2; ++y ) { if( *dstPtr ) return false; dstPtr += rowBytes; } return true; } template<typename T> Area findNonTransparentArea( const SurfaceT<T> &surface, const Area &unclippedBounds ) { const Area bounds = unclippedBounds.getClipBy( surface.getBounds() ); // if no alpha we'll fail over the to alpha-less fill if( ! surface.hasAlpha() ) { return surface.getBounds(); } int32_t topLine, bottomLine; int32_t leftColumn, rightColumn; // find the top and bottom lines for( topLine = bounds.getY1(); topLine < bounds.getY2(); ++topLine ) { if( ! transparentHorizontalScanline( surface, topLine, bounds.getX1(), bounds.getX2() ) ) { break; } } for( bottomLine = bounds.getY2() - 1; bottomLine > topLine; --bottomLine ) { if( ! transparentHorizontalScanline( surface, bottomLine, bounds.getX1(), bounds.getX2() ) ) { break; } } // find the left and right columns for( leftColumn = bounds.getX1(); leftColumn < bounds.getX2(); ++leftColumn ) { if( ! transparentVerticalScanline( surface, leftColumn, topLine, bottomLine ) ) { break; } } for( rightColumn = bounds.getX2(); rightColumn > leftColumn; --rightColumn ) { if( ! transparentVerticalScanline( surface, rightColumn, topLine, bottomLine ) ) { break; } } // we add one to right and bottom because Area represents an inclusive range on top/left and exclusive range on bottom/right rightColumn = std::min( bounds.getX2(), rightColumn + 1 ); bottomLine = std::min( bounds.getY2(), bottomLine + 1 ); return Area( leftColumn, topLine, rightColumn, bottomLine ); } #define TRIM_PROTOTYPES(r,data,T)\ template Area findNonTransparentArea( const SurfaceT<T> &surface, const Area &unclippedBounds ); BOOST_PP_SEQ_FOR_EACH( TRIM_PROTOTYPES, ~, CHANNEL_TYPES ) } } // namespace cinder::ip <|endoftext|>
<commit_before>/* main.C * * Copyright (C) 2009 Marcel Schumann * * This file is part of QuEasy -- A Toolbox for Automated QSAR Model * Construction and Validation. * QuEasy is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * QuEasy is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include <fstream> #include <BALL/QSAR/registry.h> #include <BALL/QSAR/featureSelection.h> #include <BALL/QSAR/configIO.h> #include <BALL/SYSTEM/path.h> #define EXT_MAIN #include "inputReader.C" #include "inputPartitioner.C" #include "modelCreator.C" #include "featureSelector.C" #include "validator.C" #include "predictor.C" using namespace BALL::QSAR; using namespace BALL; void set_fpu (unsigned int mode) { asm ("fldcw %0" : : "m" (*&mode)); } int main(int argc, char* argv[]) { if(argc<2) { cout<<"Please specify configuration file!"<<endl; return 0; } ifstream in(argv[1]); if(!in) { cout<<"Configuration file '"<<argv[1]<<"' not found!"<<endl; return 0; } set_fpu (0x27F); /* enforce IEEE754 double-precision */ String line; QSARData* q = new QSARData; // try to reload data as seldom as possible... String data_filename = "none"; // -- set data-path if enviroment-variable BALL_DATA_PATH is not set -- Path p; String executable_directory = argv[0]; String sep = BALL::FileSystem::PATH_SEPARATOR; executable_directory = executable_directory.substr(0,executable_directory.find_last_of(sep)); String file = "QSAR"+sep+"atomic_electron_affinities.data"; String dir = p.find(file); String data_folder = ""; if(dir=="") { data_folder = executable_directory+sep+"data"+sep; } // ----- ----- for(int i=0;!in.eof();i++) // process all sections { getline(in,line); try { if(line.hasPrefix("[InputReader]")) { ConfigIO::putbackLine(&in,line); startInputReading(in,data_folder,q,&data_filename); } else if(line.hasPrefix("[InputPartitioner]")) { ConfigIO::putbackLine(&in,line); startInputPartitioning(in,q,&data_filename); } else if(line.hasPrefix("[ModelCreator]")) { ConfigIO::putbackLine(&in,line); startModelCreation(in,q,&data_filename); } else if(line.hasPrefix("[FeatureSelector]")) { ConfigIO::putbackLine(&in,line); startFeatureSelection(in,q,&data_filename); } else if(line.hasPrefix("[Validator]")) { ConfigIO::putbackLine(&in,line); startValidation(in,q,&data_filename); } else if(line.hasPrefix("[Predictor]")) { ConfigIO::putbackLine(&in,line); startPrediction(in,q,&data_filename); } } catch(BALL::Exception::GeneralException e) { cout<<e.getName()<<" : "<<e.getMessage()<<endl; continue; } } } <commit_msg>Made QuEasyRun compileable on Windows.<commit_after>/* main.C * * Copyright (C) 2009 Marcel Schumann * * This file is part of QuEasy -- A Toolbox for Automated QSAR Model * Construction and Validation. * QuEasy is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * QuEasy is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include <fstream> #include <BALL/QSAR/registry.h> #include <BALL/QSAR/featureSelection.h> #include <BALL/QSAR/configIO.h> #include <BALL/SYSTEM/path.h> #define EXT_MAIN #include "inputReader.C" #include "inputPartitioner.C" #include "modelCreator.C" #include "featureSelector.C" #include "validator.C" #include "predictor.C" #ifdef BALL_COMPILER_MSVC #define WINDOWS_LEAN_AND_MEAN #include <windows.h> #endif using namespace BALL::QSAR; using namespace BALL; void set_fpu (unsigned int mode) { #if defined(BALL_COMPILER_GXX) asm ("fldcw %0" : : "m" (*&mode)); #elif defined(BALL_COMPILER_MSVC) // TODO: implement! //__asm ("fldcw %0" : : "m" (*&mode)); #endif } #ifndef BALL_OS_WINDOWS int main(int argc, char **argv) { #else int WINAPI WinMain(HINSTANCE, HINSTANCE, PSTR cmd_line, int) { int argc = __argc; char** argv = __argv; #endif if(argc<2) { cout<<"Please specify configuration file!"<<endl; return 0; } ifstream in(argv[1]); if(!in) { cout<<"Configuration file '"<<argv[1]<<"' not found!"<<endl; return 0; } set_fpu (0x27F); /* enforce IEEE754 double-precision */ String line; QSARData* q = new QSARData; // try to reload data as seldom as possible... String data_filename = "none"; // -- set data-path if enviroment-variable BALL_DATA_PATH is not set -- Path p; String executable_directory = argv[0]; String sep = BALL::FileSystem::PATH_SEPARATOR; executable_directory = executable_directory.substr(0,executable_directory.find_last_of(sep)); String file = "QSAR"+sep+"atomic_electron_affinities.data"; String dir = p.find(file); String data_folder = ""; if(dir=="") { data_folder = executable_directory+sep+"data"+sep; } // ----- ----- for(int i=0;!in.eof();i++) // process all sections { getline(in,line); try { if(line.hasPrefix("[InputReader]")) { ConfigIO::putbackLine(&in,line); startInputReading(in,data_folder,q,&data_filename); } else if(line.hasPrefix("[InputPartitioner]")) { ConfigIO::putbackLine(&in,line); startInputPartitioning(in,q,&data_filename); } else if(line.hasPrefix("[ModelCreator]")) { ConfigIO::putbackLine(&in,line); startModelCreation(in,q,&data_filename); } else if(line.hasPrefix("[FeatureSelector]")) { ConfigIO::putbackLine(&in,line); startFeatureSelection(in,q,&data_filename); } else if(line.hasPrefix("[Validator]")) { ConfigIO::putbackLine(&in,line); startValidation(in,q,&data_filename); } else if(line.hasPrefix("[Predictor]")) { ConfigIO::putbackLine(&in,line); startPrediction(in,q,&data_filename); } } catch(BALL::Exception::GeneralException e) { cout<<e.getName()<<" : "<<e.getMessage()<<endl; continue; } } } <|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: b3dpolypolygontools.cxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_basegfx.hxx" #include <basegfx/polygon/b3dpolypolygontools.hxx> #include <basegfx/range/b3drange.hxx> #include <basegfx/polygon/b3dpolypolygon.hxx> #include <basegfx/polygon/b3dpolygon.hxx> #include <basegfx/polygon/b3dpolygontools.hxx> #include <basegfx/numeric/ftools.hxx> #include <numeric> ////////////////////////////////////////////////////////////////////////////// namespace basegfx { namespace tools { // B3DPolyPolygon tools ::basegfx::B3DRange getRange(const ::basegfx::B3DPolyPolygon& rCandidate) { ::basegfx::B3DRange aRetval; const sal_uInt32 nPolygonCount(rCandidate.count()); for(sal_uInt32 a(0L); a < nPolygonCount; a++) { ::basegfx::B3DPolygon aCandidate = rCandidate.getB3DPolygon(a); aRetval.expand(::basegfx::tools::getRange(aCandidate)); } return aRetval; } ::basegfx::B3DPolyPolygon applyLineDashing(const ::basegfx::B3DPolyPolygon& rCandidate, const ::std::vector<double>& raDashDotArray, double fFullDashDotLen) { ::basegfx::B3DPolyPolygon aRetval; if(0.0 == fFullDashDotLen && raDashDotArray.size()) { // calculate fFullDashDotLen from raDashDotArray fFullDashDotLen = ::std::accumulate(raDashDotArray.begin(), raDashDotArray.end(), 0.0); } if(rCandidate.count() && fFullDashDotLen > 0.0) { for(sal_uInt32 a(0L); a < rCandidate.count(); a++) { ::basegfx::B3DPolygon aCandidate = rCandidate.getB3DPolygon(a); aRetval.append(applyLineDashing(aCandidate, raDashDotArray, fFullDashDotLen)); } } return aRetval; } ////////////////////////////////////////////////////////////////////// // comparators with tolerance for 3D PolyPolygons bool equal(const B3DPolyPolygon& rCandidateA, const B3DPolyPolygon& rCandidateB, const double& rfSmallValue) { const sal_uInt32 nPolygonCount(rCandidateA.count()); if(nPolygonCount != rCandidateB.count()) return false; for(sal_uInt32 a(0); a < nPolygonCount; a++) { const B3DPolygon aCandidate(rCandidateA.getB3DPolygon(a)); if(!equal(aCandidate, rCandidateB.getB3DPolygon(a), rfSmallValue)) return false; } return true; } bool equal(const B3DPolyPolygon& rCandidateA, const B3DPolyPolygon& rCandidateB) { const double fSmallValue(fTools::getSmallValue()); return equal(rCandidateA, rCandidateB, fSmallValue); } } // end of namespace tools } // end of namespace basegfx ////////////////////////////////////////////////////////////////////////////// // eof <commit_msg>INTEGRATION: CWS aw033 (1.4.2); FILE MERGED 2008/05/15 14:36:28 aw 1.4.2.8: changes after resync 2008/05/14 14:41:06 aw 1.4.2.7: RESYNC: (1.5-1.7); FILE MERGED 2008/05/14 09:16:32 aw 1.4.2.6: #i39532# aw033 progresses from git 2007/11/07 14:24:30 aw 1.4.2.5: #i39532# committing to have a base for HDU 2006/12/12 10:15:10 aw 1.4.2.4: #i39532# changes after resync 2006/09/27 16:29:23 aw 1.4.2.3: #i39532# changes after resync to m185 2006/09/26 14:51:09 aw 1.4.2.2: RESYNC: (1.4-1.5); FILE MERGED 2006/05/12 11:36:07 aw 1.4.2.1: code changes for primitive support<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: b3dpolypolygontools.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_basegfx.hxx" #include <basegfx/polygon/b3dpolypolygontools.hxx> #include <basegfx/range/b3drange.hxx> #include <basegfx/polygon/b3dpolypolygon.hxx> #include <basegfx/polygon/b3dpolygon.hxx> #include <basegfx/polygon/b3dpolygontools.hxx> #include <numeric> #include <basegfx/matrix/b3dhommatrix.hxx> #include <basegfx/numeric/ftools.hxx> #include <osl/mutex.hxx> ////////////////////////////////////////////////////////////////////////////// namespace basegfx { namespace tools { // B3DPolyPolygon tools B3DRange getRange(const B3DPolyPolygon& rCandidate) { B3DRange aRetval; const sal_uInt32 nPolygonCount(rCandidate.count()); for(sal_uInt32 a(0L); a < nPolygonCount; a++) { B3DPolygon aCandidate = rCandidate.getB3DPolygon(a); aRetval.expand(getRange(aCandidate)); } return aRetval; } void applyLineDashing(const B3DPolyPolygon& rCandidate, const ::std::vector<double>& rDotDashArray, B3DPolyPolygon* pLineTarget, B3DPolyPolygon* pGapTarget, double fFullDashDotLen) { if(0.0 == fFullDashDotLen && rDotDashArray.size()) { // calculate fFullDashDotLen from rDotDashArray fFullDashDotLen = ::std::accumulate(rDotDashArray.begin(), rDotDashArray.end(), 0.0); } if(rCandidate.count() && fFullDashDotLen > 0.0) { B3DPolyPolygon aLineTarget, aGapTarget; for(sal_uInt32 a(0L); a < rCandidate.count(); a++) { const B3DPolygon aCandidate(rCandidate.getB3DPolygon(a)); applyLineDashing( aCandidate, rDotDashArray, pLineTarget ? &aLineTarget : 0, pGapTarget ? &aGapTarget : 0, fFullDashDotLen); if(pLineTarget) { pLineTarget->append(aLineTarget); } if(pGapTarget) { pGapTarget->append(aGapTarget); } } } } B3DPolyPolygon createUnitCubePolyPolygon() { static B3DPolyPolygon aRetval; ::osl::Mutex m_mutex; if(!aRetval.count()) { B3DPolygon aTemp; aTemp.append(B3DPoint(0.0, 0.0, 1.0)); aTemp.append(B3DPoint(0.0, 1.0, 1.0)); aTemp.append(B3DPoint(1.0, 1.0, 1.0)); aTemp.append(B3DPoint(1.0, 0.0, 1.0)); aTemp.setClosed(true); aRetval.append(aTemp); aTemp.clear(); aTemp.append(B3DPoint(0.0, 0.0, 0.0)); aTemp.append(B3DPoint(0.0, 1.0, 0.0)); aTemp.append(B3DPoint(1.0, 1.0, 0.0)); aTemp.append(B3DPoint(1.0, 0.0, 0.0)); aTemp.setClosed(true); aRetval.append(aTemp); aTemp.clear(); aTemp.append(B3DPoint(0.0, 0.0, 0.0)); aTemp.append(B3DPoint(0.0, 0.0, 1.0)); aRetval.append(aTemp); aTemp.clear(); aTemp.append(B3DPoint(0.0, 1.0, 0.0)); aTemp.append(B3DPoint(0.0, 1.0, 1.0)); aRetval.append(aTemp); aTemp.clear(); aTemp.append(B3DPoint(1.0, 1.0, 0.0)); aTemp.append(B3DPoint(1.0, 1.0, 1.0)); aRetval.append(aTemp); aTemp.clear(); aTemp.append(B3DPoint(1.0, 0.0, 0.0)); aTemp.append(B3DPoint(1.0, 0.0, 1.0)); aRetval.append(aTemp); } return aRetval; } B3DPolyPolygon createUnitCubeFillPolyPolygon() { static B3DPolyPolygon aRetval; ::osl::Mutex m_mutex; if(!aRetval.count()) { B3DPolygon aTemp; // all points const B3DPoint A(0.0, 0.0, 0.0); const B3DPoint B(0.0, 1.0, 0.0); const B3DPoint C(1.0, 1.0, 0.0); const B3DPoint D(1.0, 0.0, 0.0); const B3DPoint E(0.0, 0.0, 1.0); const B3DPoint F(0.0, 1.0, 1.0); const B3DPoint G(1.0, 1.0, 1.0); const B3DPoint H(1.0, 0.0, 1.0); // create bottom aTemp.append(D); aTemp.append(A); aTemp.append(E); aTemp.append(H); aTemp.setClosed(true); aRetval.append(aTemp); // create front aTemp.clear(); aTemp.append(B); aTemp.append(A); aTemp.append(D); aTemp.append(C); aTemp.setClosed(true); aRetval.append(aTemp); // create left aTemp.clear(); aTemp.append(E); aTemp.append(A); aTemp.append(B); aTemp.append(F); aTemp.setClosed(true); aRetval.append(aTemp); // create top aTemp.clear(); aTemp.append(C); aTemp.append(G); aTemp.append(F); aTemp.append(B); aTemp.setClosed(true); aRetval.append(aTemp); // create right aTemp.clear(); aTemp.append(H); aTemp.append(G); aTemp.append(C); aTemp.append(D); aTemp.setClosed(true); aRetval.append(aTemp); // create back aTemp.clear(); aTemp.append(F); aTemp.append(G); aTemp.append(H); aTemp.append(E); aTemp.setClosed(true); aRetval.append(aTemp); } return aRetval; } B3DPolyPolygon createCubePolyPolygonFromB3DRange( const B3DRange& rRange) { B3DPolyPolygon aRetval; if(!rRange.isEmpty()) { aRetval = createUnitCubePolyPolygon(); B3DHomMatrix aTrans; aTrans.scale(rRange.getWidth(), rRange.getHeight(), rRange.getDepth()); aTrans.translate(rRange.getMinX(), rRange.getMinY(), rRange.getMinZ()); aRetval.transform(aTrans); aRetval.removeDoublePoints(); } return aRetval; } B3DPolyPolygon createCubeFillPolyPolygonFromB3DRange( const B3DRange& rRange) { B3DPolyPolygon aRetval; if(!rRange.isEmpty()) { aRetval = createUnitCubeFillPolyPolygon(); B3DHomMatrix aTrans; aTrans.scale(rRange.getWidth(), rRange.getHeight(), rRange.getDepth()); aTrans.translate(rRange.getMinX(), rRange.getMinY(), rRange.getMinZ()); aRetval.transform(aTrans); aRetval.removeDoublePoints(); } return aRetval; } // helper for getting the 3D Point from given cartesian coordiantes. fVer is defined from // [F_PI2 .. -F_PI2], fHor from [0.0 .. F_2PI] inline B3DPoint getPointFromCartesian(double fVer, double fHor) { const double fCosHor(cos(fHor)); return B3DPoint(fCosHor * cos(fVer), sin(fHor), fCosHor * -sin(fVer)); } B3DPolyPolygon createUnitSpherePolyPolygon( sal_uInt32 nHorSeg, sal_uInt32 nVerSeg, double fVerStart, double fVerStop, double fHorStart, double fHorStop) { B3DPolyPolygon aRetval; sal_uInt32 a, b; if(!nHorSeg) { nHorSeg = fround(fabs(fHorStop - fHorStart) / (F_2PI / 24.0)); } if(!nHorSeg) { nHorSeg = 1L; } if(!nVerSeg) { nVerSeg = fround(fabs(fVerStop - fVerStart) / (F_2PI / 24.0)); } if(!nVerSeg) { nVerSeg = 1L; } // create constants const double fVerDiffPerStep((fVerStop - fVerStart) / (double)nVerSeg); const double fHorDiffPerStep((fHorStop - fHorStart) / (double)nHorSeg); bool bHorClosed(fTools::equal(fHorStop - fHorStart, F_2PI)); bool bVerFromTop(fTools::equal(fVerStart, F_PI2)); bool bVerToBottom(fTools::equal(fVerStop, -F_PI2)); // create horizontal rings const sal_uInt32 nLoopVerInit(bVerFromTop ? 1L : 0L); const sal_uInt32 nLoopVerLimit(bVerToBottom ? nVerSeg : nVerSeg + 1L); const sal_uInt32 nLoopHorLimit(bHorClosed ? nHorSeg : nHorSeg + 1L); for(a = nLoopVerInit; a < nLoopVerLimit; a++) { const double fVer(fVerStart + ((double)(a) * fVerDiffPerStep)); B3DPolygon aNew; for(b = 0L; b < nLoopHorLimit; b++) { const double fHor(fHorStart + ((double)(b) * fHorDiffPerStep)); aNew.append(getPointFromCartesian(fHor, fVer)); } aNew.setClosed(bHorClosed); aRetval.append(aNew); } // create vertical half-rings for(a = 0L; a < nLoopHorLimit; a++) { const double fHor(fHorStart + ((double)(a) * fHorDiffPerStep)); B3DPolygon aNew; if(bVerFromTop) { aNew.append(B3DPoint(0.0, 1.0, 0.0)); } for(b = nLoopVerInit; b < nLoopVerLimit; b++) { const double fVer(fVerStart + ((double)(b) * fVerDiffPerStep)); aNew.append(getPointFromCartesian(fHor, fVer)); } if(bVerToBottom) { aNew.append(B3DPoint(0.0, -1.0, 0.0)); } aRetval.append(aNew); } return aRetval; } B3DPolyPolygon createSpherePolyPolygonFromB3DRange( const B3DRange& rRange, sal_uInt32 nHorSeg, sal_uInt32 nVerSeg, double fVerStart, double fVerStop, double fHorStart, double fHorStop) { B3DPolyPolygon aRetval(createUnitSpherePolyPolygon(nHorSeg, nVerSeg, fVerStart, fVerStop, fHorStart, fHorStop)); if(aRetval.count()) { // move and scale whole construct which is now in [-1.0 .. 1.0] in all directions B3DHomMatrix aTrans; aTrans.translate(1.0, 1.0, 1.0); aTrans.scale(rRange.getWidth() / 2.0, rRange.getHeight() / 2.0, rRange.getDepth() / 2.0); aTrans.translate(rRange.getMinX(), rRange.getMinY(), rRange.getMinZ()); aRetval.transform(aTrans); } return aRetval; } B3DPolyPolygon createUnitSphereFillPolyPolygon( sal_uInt32 nHorSeg, sal_uInt32 nVerSeg, bool bNormals, double fVerStart, double fVerStop, double fHorStart, double fHorStop) { B3DPolyPolygon aRetval; if(!nHorSeg) { nHorSeg = fround(fabs(fHorStop - fHorStart) / (F_2PI / 24.0)); } if(!nHorSeg) { nHorSeg = 1L; } if(!nVerSeg) { nVerSeg = fround(fabs(fVerStop - fVerStart) / (F_2PI / 24.0)); } if(!nVerSeg) { nVerSeg = 1L; } // vertical loop for(sal_uInt32 a(0L); a < nVerSeg; a++) { const double fVer(fVerStart + (((fVerStop - fVerStart) * a) / nVerSeg)); const double fVer2(fVerStart + (((fVerStop - fVerStart) * (a + 1)) / nVerSeg)); // horizontal loop for(sal_uInt32 b(0L); b < nHorSeg; b++) { const double fHor(fHorStart + (((fHorStop - fHorStart) * b) / nHorSeg)); const double fHor2(fHorStart + (((fHorStop - fHorStart) * (b + 1)) / nHorSeg)); B3DPolygon aNew; aNew.append(getPointFromCartesian(fHor, fVer)); aNew.append(getPointFromCartesian(fHor2, fVer)); aNew.append(getPointFromCartesian(fHor2, fVer2)); aNew.append(getPointFromCartesian(fHor, fVer2)); if(bNormals) { for(sal_uInt32 c(0L); c < aNew.count(); c++) { aNew.setNormal(c, ::basegfx::B3DVector(aNew.getB3DPoint(c))); } } aNew.setClosed(true); aRetval.append(aNew); } } return aRetval; } B3DPolyPolygon createSphereFillPolyPolygonFromB3DRange( const B3DRange& rRange, sal_uInt32 nHorSeg, sal_uInt32 nVerSeg, bool bNormals, double fVerStart, double fVerStop, double fHorStart, double fHorStop) { B3DPolyPolygon aRetval(createUnitSphereFillPolyPolygon(nHorSeg, nVerSeg, bNormals, fVerStart, fVerStop, fHorStart, fHorStop)); if(aRetval.count()) { // move and scale whole construct which is now in [-1.0 .. 1.0] in all directions B3DHomMatrix aTrans; aTrans.translate(1.0, 1.0, 1.0); aTrans.scale(rRange.getWidth() / 2.0, rRange.getHeight() / 2.0, rRange.getDepth() / 2.0); aTrans.translate(rRange.getMinX(), rRange.getMinY(), rRange.getMinZ()); aRetval.transform(aTrans); } return aRetval; } B3DPolyPolygon applyDefaultNormalsSphere( const B3DPolyPolygon& rCandidate, const B3DPoint& rCenter) { B3DPolyPolygon aRetval; for(sal_uInt32 a(0L); a < rCandidate.count(); a++) { aRetval.append(applyDefaultNormalsSphere(rCandidate.getB3DPolygon(a), rCenter)); } return aRetval; } B3DPolyPolygon invertNormals( const B3DPolyPolygon& rCandidate) { B3DPolyPolygon aRetval; for(sal_uInt32 a(0L); a < rCandidate.count(); a++) { aRetval.append(invertNormals(rCandidate.getB3DPolygon(a))); } return aRetval; } B3DPolyPolygon applyDefaultTextureCoordinatesParallel( const B3DPolyPolygon& rCandidate, const B3DRange& rRange, bool bChangeX, bool bChangeY) { B3DPolyPolygon aRetval; for(sal_uInt32 a(0L); a < rCandidate.count(); a++) { aRetval.append(applyDefaultTextureCoordinatesParallel(rCandidate.getB3DPolygon(a), rRange, bChangeX, bChangeY)); } return aRetval; } B3DPolyPolygon applyDefaultTextureCoordinatesSphere( const B3DPolyPolygon& rCandidate, const B3DPoint& rCenter, bool bChangeX, bool bChangeY) { B3DPolyPolygon aRetval; for(sal_uInt32 a(0L); a < rCandidate.count(); a++) { aRetval.append(applyDefaultTextureCoordinatesSphere(rCandidate.getB3DPolygon(a), rCenter, bChangeX, bChangeY)); } return aRetval; } ////////////////////////////////////////////////////////////////////// // comparators with tolerance for 3D PolyPolygons bool equal(const B3DPolyPolygon& rCandidateA, const B3DPolyPolygon& rCandidateB, const double& rfSmallValue) { const sal_uInt32 nPolygonCount(rCandidateA.count()); if(nPolygonCount != rCandidateB.count()) return false; for(sal_uInt32 a(0); a < nPolygonCount; a++) { const B3DPolygon aCandidate(rCandidateA.getB3DPolygon(a)); if(!equal(aCandidate, rCandidateB.getB3DPolygon(a), rfSmallValue)) return false; } return true; } bool equal(const B3DPolyPolygon& rCandidateA, const B3DPolyPolygon& rCandidateB) { const double fSmallValue(fTools::getSmallValue()); return equal(rCandidateA, rCandidateB, fSmallValue); } } // end of namespace tools } // end of namespace basegfx ////////////////////////////////////////////////////////////////////////////// // eof <|endoftext|>
<commit_before>#include <tiramisu/tiramisu.h> #include <string.h> #include "baryon_wrapper.h" using namespace tiramisu; /* * The goal is to generate code that implements the reference. * baryon_ref.cpp */ void generate_function(std::string name, int size) { tiramisu::init(name); constant N("N", size); constant T("T", BT); constant a1("a1", 0); constant a2("a2", 0); constant a3("a3", 0); constant xp0("xp0", 0); constant K("K", BK); constant b0("b0", 0); constant b1("b1", 0); constant b2("b2", 0); var i1("i1", 0, N), i2("i2", 0, N), i3("i3", 0, N), k("k", 1, K), t("t", 0, T), k0("k", 0, 1); input fc1("fc1", {k}, p_int32); input fc2("fc2", {k}, p_int32); input fc3("fc3", {k}, p_int32); input S("S", {"xp0", "a1", "t", "i1", "i2", "i3", "d1"}, {1, 1, T, N, N, N, 1}, p_float32); input wp("wp", {"k", "b0", "b1", "b2"}, {K, 1, 1, 1}, p_float32); computation d1("d1", {t, i1, i2, i3, k}, fc1(k)); computation d2("d2", {t, i1, i2, i3, k}, fc2(k)); computation d3("d3", {t, i1, i2, i3, k}, fc3(k)); computation Res2("Res2", {t}, expr((float) 0)); computation Res1("Res1", {t, i1, i2, i3}, expr((float) 0)); computation Res0("Res0", {t, i1, i2, i3, k}, p_float32); Res0.set_expression(S(xp0, a1, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d3(0,0,0,0,0)) + S(xp0, a1, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d1(0,0,0,0,0)) + S(xp0, a1, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d2(0,0,0,0,0)) - S(xp0, a1, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d3(0,0,0,0,0)) - S(xp0, a1, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d1(0,0,0,0,0)) - S(xp0, a1, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d2(0,0,0,0,0))); computation Res1_update_0("Res1_update_0", {t, i1, i2, i3, k}, p_float32); Res1_update_0.set_expression(Res1(t, i1, i2, i3) + wp(k, b2, b1, b0) * Res0(t, i1, i2, i3, k)); computation Res2_update_0("Res2_update_0", {t, i1, i2, i3}, p_float32); Res2_update_0.set_expression(Res2_update_0(t, i1, i2, i3) + /* exp(i(i3*px+i2*py+i1*pz)) */ Res1(t, i1, i2, i3)); global::get_implicit_function()->add_context_constraints("[N, M, K, T]->{:N=16}, T=16"); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer buf_fc1("buf_fc1", {K}, p_int32, a_input); buffer buf_fc2("buf_fc2", {K}, p_int32, a_input); buffer buf_fc3("buf_fc3", {K}, p_int32, a_input); buffer buf_res0("buf_res0", {BZ}, p_float32, a_temporary); buf_res0.set_auto_allocate(false); computation *alloc_res0 = buf_res0.allocate_at(Res2, t); buffer buf_res1("buf_res1", {N}, p_float32, a_temporary); buf_res1.set_auto_allocate(false); computation *alloc_res1 = buf_res1.allocate_at(Res2, t); buffer buf_res2("buf_res2", {T}, p_float32, a_output); buffer buf_d1("buf_d1", {K}, p_int32, a_temporary); buf_d1.set_auto_allocate(false); computation *alloc_d1 = buf_d1.allocate_at(Res2, t); buffer buf_d2("buf_d2", {K}, p_int32, a_temporary); buf_d2.set_auto_allocate(false); computation *alloc_d2 = buf_d2.allocate_at(Res2, t); buffer buf_d3("buf_d3", {K}, p_int32, a_temporary); buf_d3.set_auto_allocate(false); computation *alloc_d3 = buf_d3.allocate_at(Res2, t); // S(d1, i3, i2, i1, t, a1, x’0) buffer buf_S("buf_S", {BARYON_P, BARYON_P, BARYON_P, N, N, N, BARYON_P1}, p_float32, a_input); buffer buf_wp("buf_wp", {BARYON_N, BARYON_P, BARYON_P, BARYON_P}, p_float32, a_input); fc1.store_in(&buf_fc1); fc2.store_in(&buf_fc2); fc3.store_in(&buf_fc3); d1.store_in(&buf_d1, {0}); d2.store_in(&buf_d2, {0}); d3.store_in(&buf_d3, {0}); Res0.store_in(&buf_res0, {i3}); Res1.store_in(&buf_res1, {i3}); Res1_update_0.store_in(&buf_res1, {i3}); Res2.store_in(&buf_res2, {t}); Res2_update_0.store_in(&buf_res2, {t}); S.store_in(&buf_S); wp.store_in(&buf_wp); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- Res2.then(*alloc_res1, t) .then(*alloc_res0, t) .then(*alloc_d1, t) .then(*alloc_d2, t) .then(*alloc_d3, t) .then(Res1, i3) .then(d1, i3) .then(d2, k) .then(d3, k) .then(Res0, k) .then(Res1_update_0, k) .then(Res2_update_0, i2); Res0.tag_vector_level(i3, BARYON_N); Res2.tag_parallel_level(t); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- tiramisu::codegen({&buf_res2, &buf_S, &buf_wp, &buf_fc1, &buf_fc2, &buf_fc3}, "generated_" + std::string(TEST_NAME_STR) + ".o"); } int main(int argc, char **argv) { generate_function("tiramisu_generated_code", BARYON_N); return 0; } <commit_msg>Make Res1 in Baryon benchmark use the update Res1 computation<commit_after>#include <tiramisu/tiramisu.h> #include <string.h> #include "baryon_wrapper.h" using namespace tiramisu; /* * The goal is to generate code that implements the reference. * baryon_ref.cpp */ void generate_function(std::string name, int size) { tiramisu::init(name); constant N("N", size); constant T("T", BT); constant a1("a1", 0); constant a2("a2", 0); constant a3("a3", 0); constant xp0("xp0", 0); constant K("K", BK); constant b0("b0", 0); constant b1("b1", 0); constant b2("b2", 0); var i1("i1", 0, N), i2("i2", 0, N), i3("i3", 0, N), k("k", 1, K), t("t", 0, T), k0("k", 0, 1); input fc1("fc1", {k}, p_int32); input fc2("fc2", {k}, p_int32); input fc3("fc3", {k}, p_int32); computation d1("d1", {t, i1, i2, i3, k}, fc1(k)); computation d2("d2", {t, i1, i2, i3, k}, fc2(k)); computation d3("d3", {t, i1, i2, i3, k}, fc3(k)); input S("S", {"xp0", "a1", "t", "i1", "i2", "i3", "d1"}, {1, 1, T, N, N, N, 1}, p_float32); input wp("wp", {"k", "b0", "b1", "b2"}, {K, 1, 1, 1}, p_float32); computation Res2("Res2", {t}, expr((float) 0)); computation Res1("Res1", {t, i1, i2, i3}, expr((float) 0)); computation Res0("Res0", {t, i1, i2, i3, k}, p_float32); Res0.set_expression(S(xp0, a1, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d3(0,0,0,0,0)) + S(xp0, a1, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d1(0,0,0,0,0)) + S(xp0, a1, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d2(0,0,0,0,0)) - S(xp0, a1, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d3(0,0,0,0,0)) - S(xp0, a1, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d1(0,0,0,0,0)) - S(xp0, a1, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d2(0,0,0,0,0))); computation Res1_update_0("Res1_update_0", {t, i1, i2, i3, k}, p_float32); Res1_update_0.set_expression(Res1_update_0(t, i1, i2, i3, k-1) + wp(k, b2, b1, b0) * Res0(t, i1, i2, i3, k)); computation Res2_update_0("Res2_update_0", {t, i1, i2, i3}, p_float32); Res2_update_0.set_expression(Res2_update_0(t, i1, i2, i3) + /* exp(i(i3*px+i2*py+i1*pz)) */ Res1(t, i1, i2, i3)); global::get_implicit_function()->add_context_constraints("[N, M, K, T]->{:N=16}, T=16"); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer buf_fc1("buf_fc1", {K}, p_int32, a_input); buffer buf_fc2("buf_fc2", {K}, p_int32, a_input); buffer buf_fc3("buf_fc3", {K}, p_int32, a_input); buffer buf_res0("buf_res0", {BZ}, p_float32, a_temporary); buf_res0.set_auto_allocate(false); computation *alloc_res0 = buf_res0.allocate_at(Res2, t); buffer buf_res1("buf_res1", {N}, p_float32, a_temporary); buf_res1.set_auto_allocate(false); computation *alloc_res1 = buf_res1.allocate_at(Res2, t); buffer buf_res2("buf_res2", {T}, p_float32, a_output); buffer buf_d1("buf_d1", {K}, p_int32, a_temporary); buf_d1.set_auto_allocate(false); computation *alloc_d1 = buf_d1.allocate_at(Res2, t); buffer buf_d2("buf_d2", {K}, p_int32, a_temporary); buf_d2.set_auto_allocate(false); computation *alloc_d2 = buf_d2.allocate_at(Res2, t); buffer buf_d3("buf_d3", {K}, p_int32, a_temporary); buf_d3.set_auto_allocate(false); computation *alloc_d3 = buf_d3.allocate_at(Res2, t); // S(d1, i3, i2, i1, t, a1, x’0) buffer buf_S("buf_S", {BARYON_P, BARYON_P, BARYON_P, N, N, N, BARYON_P1}, p_float32, a_input); buffer buf_wp("buf_wp", {BARYON_N, BARYON_P, BARYON_P, BARYON_P}, p_float32, a_input); fc1.store_in(&buf_fc1); fc2.store_in(&buf_fc2); fc3.store_in(&buf_fc3); d1.store_in(&buf_d1, {0}); d2.store_in(&buf_d2, {0}); d3.store_in(&buf_d3, {0}); Res0.store_in(&buf_res0, {i3}); Res1.store_in(&buf_res1, {i3}); Res1_update_0.store_in(&buf_res1, {i3}); Res2.store_in(&buf_res2, {t}); Res2_update_0.store_in(&buf_res2, {t}); S.store_in(&buf_S); wp.store_in(&buf_wp); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- Res2.then(*alloc_res1, t) .then(*alloc_res0, t) .then(*alloc_d1, t) .then(*alloc_d2, t) .then(*alloc_d3, t) .then(Res1, i3) .then(d1, i3) .then(d2, k) .then(d3, k) .then(Res0, k) .then(Res1_update_0, k) .then(Res2_update_0, i2); Res0.tag_vector_level(i3, BARYON_N); Res2.tag_parallel_level(t); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- tiramisu::codegen({&buf_res2, &buf_S, &buf_wp, &buf_fc1, &buf_fc2, &buf_fc3}, "generated_" + std::string(TEST_NAME_STR) + ".o"); } int main(int argc, char **argv) { generate_function("tiramisu_generated_code", BARYON_N); return 0; } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * * FILE * pqxx/tablestream.hxx * * DESCRIPTION * definition of the pqxx::tablestream class. * pqxx::tablestream provides optimized batch access to a database table * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/tablestream instead. * * Copyright (c) 2001-2005, Jeroen T. Vermeulen <jtv@xs4all.nl> * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. * *------------------------------------------------------------------------- */ #include "pqxx/compiler-public.hxx" #include "pqxx/transaction_base" /* Methods tested in eg. self-test program test001 are marked with "//[t1]" */ namespace pqxx { class transaction_base; /// Base class for streaming data to/from database tables. /** A Tablestream enables optimized batch read or write access to a database * table using PostgreSQL's COPY TO STDOUT and COPY FROM STDIN commands, * respectively. These capabilities are implemented by its subclasses * tablereader and tablewriter. * * A Tablestream exists in the context of a transaction, and no other streams * or queries may be applied to that transaction as long as the stream remains * open. */ class PQXX_LIBEXPORT tablestream : public internal::transactionfocus { public: explicit tablestream(transaction_base &Trans, const PGSTD::string &Null=PGSTD::string()); //[t6] virtual ~tablestream() throw () =0; //[t6] /// Finish stream action, check for errors, and detach from transaction /** It is recommended that you call this function before the tablestream's * destructor is run. This function will check any final errors which may not * become apparent until the transaction is committed otherwise. * * As an added benefit, this will free up the transaction while the * tablestream object itself still exists. */ virtual void complete() =0; #ifdef PQXX_DEPRECATED_HEADERS /// @deprecated Use name() instead PGSTD::string Name() const { return name(); } #endif protected: const PGSTD::string &NullStr() const { return m_Null; } bool is_finished() const throw () { return m_Finished; } void base_close(); /// Construct a comma-separated column list from given sequence template<typename ITER> static PGSTD::string columnlist(ITER colbegin, ITER colend); private: PGSTD::string m_Null; bool m_Finished; // Not allowed: tablestream(); tablestream(const tablestream &); tablestream &operator=(const tablestream &); }; template<typename ITER> inline PGSTD::string tablestream::columnlist(ITER colbegin, ITER colend) { return separated_list(",", colbegin, colend); } } // namespace pqxx <commit_msg>Comment update<commit_after>/*------------------------------------------------------------------------- * * FILE * pqxx/tablestream.hxx * * DESCRIPTION * definition of the pqxx::tablestream class. * pqxx::tablestream provides optimized batch access to a database table * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/tablestream instead. * * Copyright (c) 2001-2006, Jeroen T. Vermeulen <jtv@xs4all.nl> * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. * *------------------------------------------------------------------------- */ #include "pqxx/compiler-public.hxx" #include "pqxx/transaction_base" /* Methods tested in eg. self-test program test001 are marked with "//[t1]" */ namespace pqxx { class transaction_base; /// Base class for streaming data to/from database tables. /** A Tablestream enables optimized batch read or write access to a database * table using PostgreSQL's COPY TO STDOUT and COPY FROM STDIN commands, * respectively. These capabilities are implemented by its subclasses * tablereader and tablewriter. * * A Tablestream exists in the context of a transaction, and no other streams * or queries may be applied to that transaction as long as the stream remains * open. */ class PQXX_LIBEXPORT tablestream : public internal::transactionfocus { public: explicit tablestream(transaction_base &Trans, const PGSTD::string &Null=PGSTD::string()); //[t6] virtual ~tablestream() throw () =0; //[t6] /// Finish stream action, check for errors, and detach from transaction /** It is recommended that you call this function before the tablestream's * destructor is run. This function will check for any final errors which may * not become apparent until the transaction is committed otherwise. * * As an added benefit, this will free up the transaction while the * tablestream object itself still exists. */ virtual void complete() =0; #ifdef PQXX_DEPRECATED_HEADERS /// @deprecated Use name() instead PGSTD::string Name() const { return name(); } #endif protected: const PGSTD::string &NullStr() const { return m_Null; } bool is_finished() const throw () { return m_Finished; } void base_close(); /// Construct a comma-separated column list from given sequence template<typename ITER> static PGSTD::string columnlist(ITER colbegin, ITER colend); private: PGSTD::string m_Null; bool m_Finished; // Not allowed: tablestream(); tablestream(const tablestream &); tablestream &operator=(const tablestream &); }; template<typename ITER> inline PGSTD::string tablestream::columnlist(ITER colbegin, ITER colend) { return separated_list(",", colbegin, colend); } } // namespace pqxx <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include <seastar/core/future.hh> #include <seastar/core/queue.hh> #include <seastar/util/std-compat.hh> /// \defgroup fiber-module Fibers /// /// \brief Fibers of execution /// /// Seastar continuations are normally short, but often chained to one /// another, so that one continuation does a bit of work and then schedules /// another continuation for later. Such chains can be long, and often even /// involve loopings - see for example \ref repeat. We call such chains /// "fibers" of execution. /// /// These fibers are not threads - each is just a string of continuations - /// but they share some common requirements with traditional threads. /// For example, we want to avoid one fiber getting starved while a second /// fiber continuously runs its continuations one after another. /// As another example, fibers may want to communicate - e.g., one fiber /// produces data that a second fiber consumes, and we wish to ensure that /// both fibers get a chance to run, and that if one stops prematurely, /// the other doesn't hang forever. /// /// Consult the following table to see which APIs are useful for fiber tasks: /// /// Task | APIs /// -----------------------------------------------|------------------- /// Repeat a blocking task indefinitely | \ref keep_doing() /// Repeat a blocking task, then exit | \ref repeat(), \ref do_until() /// Provide mutual exclusion between two tasks | \ref semaphore, \ref shared_mutex /// Pass a stream of data between two fibers | \ref seastar::pipe /// Safely shut down a resource | \ref seastar::gate, \ref seastar::with_gate() /// Hold on to an object while a fiber is running | \ref do_with() /// /// Seastar API namespace namespace seastar { /// \addtogroup fiber-module /// @{ class broken_pipe_exception : public std::exception { public: virtual const char* what() const noexcept { return "Broken pipe"; } }; class unread_overflow_exception : public std::exception { public: virtual const char* what() const noexcept { return "pipe_reader::unread() overflow"; } }; /// \cond internal namespace internal { template <typename T> class pipe_buffer { private: queue<std::optional<T>> _buf; bool _read_open = true; bool _write_open = true; public: pipe_buffer(size_t size) : _buf(size) {} future<std::optional<T>> read() { return _buf.pop_eventually(); } future<> write(T&& data) { return _buf.push_eventually(std::move(data)); } bool readable() const { return _write_open || !_buf.empty(); } bool writeable() const { return _read_open; } bool close_read() { // If a writer blocking (on a full queue), need to stop it. if (_buf.full()) { _buf.abort(std::make_exception_ptr(broken_pipe_exception())); } _read_open = false; return !_write_open; } bool close_write() { // If the queue is empty, write the EOF (disengaged optional) to the // queue to wake a blocked reader. If the queue is not empty, there is // no need to write the EOF to the queue - the reader will return an // EOF when it sees that _write_open == false. if (_buf.empty()) { _buf.push({}); } _write_open = false; return !_read_open; } }; } // namespace internal /// \endcond template <typename T> class pipe; /// \brief Read side of a \ref seastar::pipe /// /// The read side of a pipe, which allows only reading from the pipe. /// A pipe_reader object cannot be created separately, but only as part of a /// reader/writer pair through \ref seastar::pipe. template <typename T> class pipe_reader { private: internal::pipe_buffer<T> *_bufp; std::optional<T> _unread; pipe_reader(internal::pipe_buffer<T> *bufp) : _bufp(bufp) { } friend class pipe<T>; public: /// \brief Read next item from the pipe /// /// Returns a future value, which is fulfilled when the pipe's buffer /// becomes non-empty, or the write side is closed. The value returned /// is an optional<T>, which is disengaged to mark and end of file /// (i.e., the write side was closed, and we've read everything it sent). future<std::optional<T>> read() { if (_unread) { auto ret = std::move(*_unread); _unread = {}; return make_ready_future<std::optional<T>>(std::move(ret)); } if (_bufp->readable()) { return _bufp->read(); } else { return make_ready_future<std::optional<T>>(); } } /// \brief Return an item to the front of the pipe /// /// Pushes the given item to the front of the pipe, so it will be /// returned by the next read() call. The typical use case is to /// unread() the last item returned by read(). /// More generally, it is legal to unread() any item, not just one /// previously returned by read(), but note that the unread() is limited /// to just one item - two calls to unread() without an intervening call /// to read() will cause an exception. void unread(T&& item) { if (_unread) { throw unread_overflow_exception(); } _unread = std::move(item); } ~pipe_reader() { if (_bufp && _bufp->close_read()) { delete _bufp; } } // Allow move, but not copy, of pipe_reader pipe_reader(pipe_reader&& other) : _bufp(other._bufp) { other._bufp = nullptr; } pipe_reader& operator=(pipe_reader&& other) { std::swap(_bufp, other._bufp); } }; /// \brief Write side of a \ref seastar::pipe /// /// The write side of a pipe, which allows only writing to the pipe. /// A pipe_writer object cannot be created separately, but only as part of a /// reader/writer pair through \ref seastar::pipe. template <typename T> class pipe_writer { private: internal::pipe_buffer<T> *_bufp; pipe_writer(internal::pipe_buffer<T> *bufp) : _bufp(bufp) { } friend class pipe<T>; public: /// \brief Write an item to the pipe /// /// Returns a future value, which is fulfilled when the data was written /// to the buffer (when it become non-full). If the data could not be /// written because the read side was closed, an exception /// \ref broken_pipe_exception is returned in the future. future<> write(T&& data) { if (_bufp->writeable()) { return _bufp->write(std::move(data)); } else { return make_exception_future<>(broken_pipe_exception()); } } ~pipe_writer() { if (_bufp && _bufp->close_write()) { delete _bufp; } } // Allow move, but not copy, of pipe_writer pipe_writer(pipe_writer&& other) : _bufp(other._bufp) { other._bufp = nullptr; } pipe_writer& operator=(pipe_writer&& other) { std::swap(_bufp, other._bufp); } }; /// \brief A fixed-size pipe for communicating between two fibers. /// /// A pipe<T> is a mechanism to transfer data between two fibers, one /// producing data, and the other consuming it. The fixed-size buffer also /// ensures a balanced execution of the two fibers, because the producer /// fiber blocks when it writes to a full pipe, until the consumer fiber gets /// to run and read from the pipe. /// /// A pipe<T> resembles a Unix pipe, in that it has a read side, a write side, /// and a fixed-sized buffer between them, and supports either end to be closed /// independently (and EOF or broken pipe when using the other side). /// A pipe<T> object holds the reader and write sides of the pipe as two /// separate objects. These objects can be moved into two different fibers. /// Importantly, if one of the pipe ends is destroyed (i.e., the continuations /// capturing it end), the other end of the pipe will stop blocking, so the /// other fiber will not hang. /// /// The pipe's read and write interfaces are future-based blocking. I.e., the /// write() and read() methods return a future which is fulfilled when the /// operation is complete. The pipe is single-reader single-writer, meaning /// that until the future returned by read() is fulfilled, read() must not be /// called again (and same for write). /// /// Note: The pipe reader and writer are movable, but *not* copyable. It is /// often convenient to wrap each end in a shared pointer, so it can be /// copied (e.g., used in an std::function which needs to be copyable) or /// easily captured into multiple continuations. template <typename T> class pipe { public: pipe_reader<T> reader; pipe_writer<T> writer; explicit pipe(size_t size) : pipe(new internal::pipe_buffer<T>(size)) { } private: pipe(internal::pipe_buffer<T> *bufp) : reader(bufp), writer(bufp) { } }; /// @} } // namespace seastar <commit_msg>doc: pipe: remove \ref seastar::with_gate()<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include <seastar/core/future.hh> #include <seastar/core/queue.hh> #include <seastar/util/std-compat.hh> /// \defgroup fiber-module Fibers /// /// \brief Fibers of execution /// /// Seastar continuations are normally short, but often chained to one /// another, so that one continuation does a bit of work and then schedules /// another continuation for later. Such chains can be long, and often even /// involve loopings - see for example \ref repeat. We call such chains /// "fibers" of execution. /// /// These fibers are not threads - each is just a string of continuations - /// but they share some common requirements with traditional threads. /// For example, we want to avoid one fiber getting starved while a second /// fiber continuously runs its continuations one after another. /// As another example, fibers may want to communicate - e.g., one fiber /// produces data that a second fiber consumes, and we wish to ensure that /// both fibers get a chance to run, and that if one stops prematurely, /// the other doesn't hang forever. /// /// Consult the following table to see which APIs are useful for fiber tasks: /// /// Task | APIs /// -----------------------------------------------|------------------- /// Repeat a blocking task indefinitely | \ref keep_doing() /// Repeat a blocking task, then exit | \ref repeat(), \ref do_until() /// Provide mutual exclusion between two tasks | \ref semaphore, \ref shared_mutex /// Pass a stream of data between two fibers | \ref seastar::pipe /// Safely shut down a resource | \ref seastar::gate /// Hold on to an object while a fiber is running | \ref do_with() /// /// Seastar API namespace namespace seastar { /// \addtogroup fiber-module /// @{ class broken_pipe_exception : public std::exception { public: virtual const char* what() const noexcept { return "Broken pipe"; } }; class unread_overflow_exception : public std::exception { public: virtual const char* what() const noexcept { return "pipe_reader::unread() overflow"; } }; /// \cond internal namespace internal { template <typename T> class pipe_buffer { private: queue<std::optional<T>> _buf; bool _read_open = true; bool _write_open = true; public: pipe_buffer(size_t size) : _buf(size) {} future<std::optional<T>> read() { return _buf.pop_eventually(); } future<> write(T&& data) { return _buf.push_eventually(std::move(data)); } bool readable() const { return _write_open || !_buf.empty(); } bool writeable() const { return _read_open; } bool close_read() { // If a writer blocking (on a full queue), need to stop it. if (_buf.full()) { _buf.abort(std::make_exception_ptr(broken_pipe_exception())); } _read_open = false; return !_write_open; } bool close_write() { // If the queue is empty, write the EOF (disengaged optional) to the // queue to wake a blocked reader. If the queue is not empty, there is // no need to write the EOF to the queue - the reader will return an // EOF when it sees that _write_open == false. if (_buf.empty()) { _buf.push({}); } _write_open = false; return !_read_open; } }; } // namespace internal /// \endcond template <typename T> class pipe; /// \brief Read side of a \ref seastar::pipe /// /// The read side of a pipe, which allows only reading from the pipe. /// A pipe_reader object cannot be created separately, but only as part of a /// reader/writer pair through \ref seastar::pipe. template <typename T> class pipe_reader { private: internal::pipe_buffer<T> *_bufp; std::optional<T> _unread; pipe_reader(internal::pipe_buffer<T> *bufp) : _bufp(bufp) { } friend class pipe<T>; public: /// \brief Read next item from the pipe /// /// Returns a future value, which is fulfilled when the pipe's buffer /// becomes non-empty, or the write side is closed. The value returned /// is an optional<T>, which is disengaged to mark and end of file /// (i.e., the write side was closed, and we've read everything it sent). future<std::optional<T>> read() { if (_unread) { auto ret = std::move(*_unread); _unread = {}; return make_ready_future<std::optional<T>>(std::move(ret)); } if (_bufp->readable()) { return _bufp->read(); } else { return make_ready_future<std::optional<T>>(); } } /// \brief Return an item to the front of the pipe /// /// Pushes the given item to the front of the pipe, so it will be /// returned by the next read() call. The typical use case is to /// unread() the last item returned by read(). /// More generally, it is legal to unread() any item, not just one /// previously returned by read(), but note that the unread() is limited /// to just one item - two calls to unread() without an intervening call /// to read() will cause an exception. void unread(T&& item) { if (_unread) { throw unread_overflow_exception(); } _unread = std::move(item); } ~pipe_reader() { if (_bufp && _bufp->close_read()) { delete _bufp; } } // Allow move, but not copy, of pipe_reader pipe_reader(pipe_reader&& other) : _bufp(other._bufp) { other._bufp = nullptr; } pipe_reader& operator=(pipe_reader&& other) { std::swap(_bufp, other._bufp); } }; /// \brief Write side of a \ref seastar::pipe /// /// The write side of a pipe, which allows only writing to the pipe. /// A pipe_writer object cannot be created separately, but only as part of a /// reader/writer pair through \ref seastar::pipe. template <typename T> class pipe_writer { private: internal::pipe_buffer<T> *_bufp; pipe_writer(internal::pipe_buffer<T> *bufp) : _bufp(bufp) { } friend class pipe<T>; public: /// \brief Write an item to the pipe /// /// Returns a future value, which is fulfilled when the data was written /// to the buffer (when it become non-full). If the data could not be /// written because the read side was closed, an exception /// \ref broken_pipe_exception is returned in the future. future<> write(T&& data) { if (_bufp->writeable()) { return _bufp->write(std::move(data)); } else { return make_exception_future<>(broken_pipe_exception()); } } ~pipe_writer() { if (_bufp && _bufp->close_write()) { delete _bufp; } } // Allow move, but not copy, of pipe_writer pipe_writer(pipe_writer&& other) : _bufp(other._bufp) { other._bufp = nullptr; } pipe_writer& operator=(pipe_writer&& other) { std::swap(_bufp, other._bufp); } }; /// \brief A fixed-size pipe for communicating between two fibers. /// /// A pipe<T> is a mechanism to transfer data between two fibers, one /// producing data, and the other consuming it. The fixed-size buffer also /// ensures a balanced execution of the two fibers, because the producer /// fiber blocks when it writes to a full pipe, until the consumer fiber gets /// to run and read from the pipe. /// /// A pipe<T> resembles a Unix pipe, in that it has a read side, a write side, /// and a fixed-sized buffer between them, and supports either end to be closed /// independently (and EOF or broken pipe when using the other side). /// A pipe<T> object holds the reader and write sides of the pipe as two /// separate objects. These objects can be moved into two different fibers. /// Importantly, if one of the pipe ends is destroyed (i.e., the continuations /// capturing it end), the other end of the pipe will stop blocking, so the /// other fiber will not hang. /// /// The pipe's read and write interfaces are future-based blocking. I.e., the /// write() and read() methods return a future which is fulfilled when the /// operation is complete. The pipe is single-reader single-writer, meaning /// that until the future returned by read() is fulfilled, read() must not be /// called again (and same for write). /// /// Note: The pipe reader and writer are movable, but *not* copyable. It is /// often convenient to wrap each end in a shared pointer, so it can be /// copied (e.g., used in an std::function which needs to be copyable) or /// easily captured into multiple continuations. template <typename T> class pipe { public: pipe_reader<T> reader; pipe_writer<T> writer; explicit pipe(size_t size) : pipe(new internal::pipe_buffer<T>(size)) { } private: pipe(internal::pipe_buffer<T> *bufp) : reader(bufp), writer(bufp) { } }; /// @} } // namespace seastar <|endoftext|>
<commit_before>// Copyright (C) 2016 Jonathan Müller <jonathanmueller.dev@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef TYPE_SAFE_CONFIG_HPP_INCLUDED #define TYPE_SAFE_CONFIG_HPP_INCLUDED #include <cstddef> #include <cstdlib> #ifndef TYPE_SAFE_ENABLE_ASSERTIONS #define TYPE_SAFE_ENABLE_ASSERTIONS 0 #endif #ifndef TYPE_SAFE_ENABLE_PRECONDITION_CHECKS #define TYPE_SAFE_ENABLE_PRECONDITION_CHECKS 1 #endif #ifndef TYPE_SAFE_ENABLE_WRAPPER #define TYPE_SAFE_ENABLE_WRAPPER 1 #endif #ifndef TYPE_SAFE_ARITHMETIC_UB #define TYPE_SAFE_ARITHMETIC_UB 1 #endif #ifndef TYPE_SAFE_USE_REF_QUALIFIERS #if defined(__cpp_ref_qualifiers) && __cpp_ref_qualifiers >= 200710 #define TYPE_SAFE_USE_REF_QUALIFIERS 1 #elif defined(_MSC_VER) && _MSC_VER >= 1900 #define TYPE_SAFE_USE_REF_QUALIFIERS 1 #else #define TYPE_SAFE_USE_REF_QUALIFIERS 0 #endif #endif #if TYPE_SAFE_USE_REF_QUALIFIERS #define TYPE_SAFE_LVALUE_REF & #define TYPE_SAFE_RVALUE_REF && #else #define TYPE_SAFE_LVALUE_REF #define TYPE_SAFE_RVALUE_REF #endif #ifndef TYPE_SAFE_USE_NOEXCEPT_DEFAULT #if defined(__GNUC__) && __GNUC__ < 5 // GCC before 5.0 doesn't handle noexcept and = default properly #define TYPE_SAFE_USE_NOEXCEPT_DEFAULT 0 #else #define TYPE_SAFE_USE_NOEXCEPT_DEFAULT 1 #endif #endif #if TYPE_SAFE_USE_NOEXCEPT_DEFAULT #define TYPE_SAFE_NOEXCEPT_DEFAULT(Val) noexcept(Val) #else #define TYPE_SAFE_NOEXCEPT_DEFAULT(Val) #endif #ifndef TYPE_SAFE_USE_EXCEPTIONS #if __cpp_exceptions #define TYPE_SAFE_USE_EXCEPTIONS 1 #elif defined(__GNUC__) && defined(__EXCEPTIONS) #define TYPE_SAFE_USE_EXCEPTIONS 1 #elif defined(_MSC_VER) && defined(_CPPUNWIND) #define TYPE_SAFE_USE_EXCEPTIONS 1 #else #define TYPE_SAFE_USE_EXCEPTIONS 0 #endif #endif #if TYPE_SAFE_USE_EXCEPTIONS #define TYPE_SAFE_THROW(Ex) throw Ex #define TYPE_SAFE_TRY try #define TYPE_SAFE_CATCH_ALL catch (...) #define TYPE_SAFE_RETHROW throw #else #define TYPE_SAFE_THROW(Ex) (Ex, std::abort()) #define TYPE_SAFE_TRY if (true) #define TYPE_SAFE_CATCH_ALL if (false) #define TYPE_SAFE_RETHROW std::abort() #endif /// \entity type_safe /// \unique_name ts #endif // TYPE_SAFE_CONFIG_HPP_INCLUDED <commit_msg>Update documentation of config.hpp<commit_after>// Copyright (C) 2016 Jonathan Müller <jonathanmueller.dev@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef TYPE_SAFE_CONFIG_HPP_INCLUDED #define TYPE_SAFE_CONFIG_HPP_INCLUDED #include <cstddef> #include <cstdlib> #ifndef TYPE_SAFE_ENABLE_ASSERTIONS /// Controls whether internal assertions are enabled. /// /// It is disabled by default. #define TYPE_SAFE_ENABLE_ASSERTIONS 0 #endif #ifndef TYPE_SAFE_ENABLE_PRECONDITION_CHECKS /// Controls whether preconditions are checked. /// /// It is enabled by default. #define TYPE_SAFE_ENABLE_PRECONDITION_CHECKS 1 #endif #ifndef TYPE_SAFE_ENABLE_WRAPPER /// Controls whether the typedefs in [types.hpp]() use the type safe wrapper types. /// /// It is enabled by default. #define TYPE_SAFE_ENABLE_WRAPPER 1 #endif #ifndef TYPE_SAFE_ARITHMETIC_UB /// Controls whether [ts::arithmetic_policy_default]() is [ts::undefined_behavior_arithmetic]() or [ts::default_arithmetic](). /// /// It is [ts::undefined_behavior_arithmetic]() by default. #define TYPE_SAFE_ARITHMETIC_UB 1 #endif #ifndef TYPE_SAFE_USE_REF_QUALIFIERS #if defined(__cpp_ref_qualifiers) && __cpp_ref_qualifiers >= 200710 /// \exclude #define TYPE_SAFE_USE_REF_QUALIFIERS 1 #elif defined(_MSC_VER) && _MSC_VER >= 1900 #define TYPE_SAFE_USE_REF_QUALIFIERS 1 #else #define TYPE_SAFE_USE_REF_QUALIFIERS 0 #endif #endif #if TYPE_SAFE_USE_REF_QUALIFIERS /// \exclude #define TYPE_SAFE_LVALUE_REF & /// \exclude #define TYPE_SAFE_RVALUE_REF && #else #define TYPE_SAFE_LVALUE_REF #define TYPE_SAFE_RVALUE_REF #endif #ifndef TYPE_SAFE_USE_NOEXCEPT_DEFAULT #if defined(__GNUC__) && __GNUC__ < 5 // GCC before 5.0 doesn't handle noexcept and = default properly /// \exclude #define TYPE_SAFE_USE_NOEXCEPT_DEFAULT 0 #else /// \exclude #define TYPE_SAFE_USE_NOEXCEPT_DEFAULT 1 #endif #endif #if TYPE_SAFE_USE_NOEXCEPT_DEFAULT /// \exclude #define TYPE_SAFE_NOEXCEPT_DEFAULT(Val) noexcept(Val) #else /// \exclude #define TYPE_SAFE_NOEXCEPT_DEFAULT(Val) #endif #ifndef TYPE_SAFE_USE_EXCEPTIONS #if __cpp_exceptions /// \exclude #define TYPE_SAFE_USE_EXCEPTIONS 1 #elif defined(__GNUC__) && defined(__EXCEPTIONS) /// \exclude #define TYPE_SAFE_USE_EXCEPTIONS 1 #elif defined(_MSC_VER) && defined(_CPPUNWIND) /// \exclude #define TYPE_SAFE_USE_EXCEPTIONS 1 #else /// \exclude #define TYPE_SAFE_USE_EXCEPTIONS 0 #endif #endif #if TYPE_SAFE_USE_EXCEPTIONS /// \exclude #define TYPE_SAFE_THROW(Ex) throw Ex /// \exclude #define TYPE_SAFE_TRY try /// \exclude #define TYPE_SAFE_CATCH_ALL catch (...) /// \exclude #define TYPE_SAFE_RETHROW throw #else #define TYPE_SAFE_THROW(Ex) (Ex, std::abort()) #define TYPE_SAFE_TRY if (true) #define TYPE_SAFE_CATCH_ALL if (false) #define TYPE_SAFE_RETHROW std::abort() #endif /// \entity type_safe /// \unique_name ts #endif // TYPE_SAFE_CONFIG_HPP_INCLUDED <|endoftext|>
<commit_before>#pragma once #include <vector> #include <cstdint> namespace Kunlaboro { namespace detail { class DynamicBitfield { public: DynamicBitfield(); ~DynamicBitfield() = default; void clear(); inline void ensure(std::size_t bit) { const auto count = bit + 1; const std::size_t bytes = static_cast<std::size_t>(std::ceil(count / 64.f)); if (mCapacity < bytes) { mBits.resize(bytes, 0); mCapacity = bytes; } if (mSize < count) mSize = count; } inline void shrink() { // TODO: Shrink size properly while (!hasBit(mSize - 1)) --mSize; } inline std::size_t getSize() const { return mSize; } std::size_t countBits() const; bool operator==(const DynamicBitfield& rhs) const; bool operator!=(const DynamicBitfield& rhs) const; inline bool hasBit(std::size_t bit) const { return mSize > bit && (mBits[bit / 64] & (1ull << (bit % 64))) != 0; } inline void setBit(std::size_t bit) { ensure(bit); mBits[bit / 64] |= (1ull << (bit % 64)); } inline void clearBit(std::size_t bit) { if (mSize < bit) return; mBits[bit / 64] &= ~(1ull << (bit % 64)); shrink(); } private: std::vector<std::uint64_t> mBits; std::size_t mSize, mCapacity; }; } } <commit_msg>Fix stupid issue with wraparound<commit_after>#pragma once #include <vector> #include <cstdint> namespace Kunlaboro { namespace detail { class DynamicBitfield { public: DynamicBitfield(); ~DynamicBitfield() = default; void clear(); inline void ensure(std::size_t bit) { const auto count = bit + 1; const std::size_t bytes = static_cast<std::size_t>(std::ceil(count / 64.f)); if (mCapacity < bytes) { mBits.resize(bytes, 0); mCapacity = bytes; } if (mSize < count) mSize = count; } inline void shrink() { // TODO: Shrink size properly while (mSize > 0 && !hasBit(mSize - 1)) --mSize; } inline std::size_t getSize() const { return mSize; } std::size_t countBits() const; bool operator==(const DynamicBitfield& rhs) const; bool operator!=(const DynamicBitfield& rhs) const; inline bool hasBit(std::size_t bit) const { return mSize > bit && (mBits[bit / 64] & (1ull << (bit % 64))) != 0; } inline void setBit(std::size_t bit) { ensure(bit); mBits[bit / 64] |= (1ull << (bit % 64)); } inline void clearBit(std::size_t bit) { if (mSize < bit) return; mBits[bit / 64] &= ~(1ull << (bit % 64)); shrink(); } private: std::vector<std::uint64_t> mBits; std::size_t mSize, mCapacity; }; } } <|endoftext|>
<commit_before>#pragma once // TODO: this file should be removed, and all configurations passed to device via USB // (e.g over config_h2d) #include <climits> #include <unordered_map> #include <vector> #include "stream/stream_info.hpp" #include "metadata/frame_metadata.hpp" #include "metadata/capture_metadata.hpp" #define MONO_RES_AUTO (-2) #define MONO_MAX_W 1280 #define MONO_MAX_H 800 constexpr int MONO_MAX_SIZE(int n_planes, int elem_size) { return (MONO_MAX_W * MONO_MAX_H * (n_planes) * (elem_size) + sizeof(FrameMetadata)); } // TODO: remove next constant std::unordered_map<std::string, StreamInfo> g_streams_pc_to_myriad = { {"config_h2d", StreamInfo("config_h2d", 5000)}, {"host_capture", StreamInfo("host_capture", sizeof(CaptureMetadata))} }; std::unordered_map<std::string, StreamInfo> c_streams_myriad_to_pc = { {"left", StreamInfo("left", MONO_MAX_SIZE(1,1), { MONO_RES_AUTO, 0} )}, {"right", StreamInfo("right", MONO_MAX_SIZE(1,1), { MONO_RES_AUTO, 0} )}, {"disparity", StreamInfo("disparity", MONO_MAX_SIZE(1,1), { MONO_RES_AUTO, 0} )}, // {"depth", StreamInfo("depth", 921600, { 720, 1280} )}, {"depth_raw", StreamInfo("depth_raw", MONO_MAX_SIZE(1,2), { MONO_RES_AUTO, 0}, 2 )}, {"disparity_color", StreamInfo("disparity_color", MONO_MAX_SIZE(3,1), { MONO_RES_AUTO, 0, 3} )}, {"metaout", StreamInfo("metaout", 4*1024*1024)}, // 4 mb max metaout size {"previewout", StreamInfo("previewout", 1920256)}, {"meta_d2h", StreamInfo("meta_d2h", 1024*1024)}, {"jpegout", StreamInfo("jpegout", 10*1024*1024)}, {"video", StreamInfo("video", 10*1024*1024)}, {"object_tracker", StreamInfo("object_tracker", 2000)} }; <commit_msg>Added raw_color stream<commit_after>#pragma once // TODO: this file should be removed, and all configurations passed to device via USB // (e.g over config_h2d) #include <climits> #include <unordered_map> #include <vector> #include "stream/stream_info.hpp" #include "metadata/frame_metadata.hpp" #include "metadata/capture_metadata.hpp" #define MONO_RES_AUTO (-2) #define MONO_MAX_W 1280 #define MONO_MAX_H 800 constexpr int MONO_MAX_SIZE(int n_planes, int elem_size) { return (MONO_MAX_W * MONO_MAX_H * (n_planes) * (elem_size) + sizeof(FrameMetadata)); } // TODO: remove next constant std::unordered_map<std::string, StreamInfo> g_streams_pc_to_myriad = { {"config_h2d", StreamInfo("config_h2d", 5000)}, {"host_capture", StreamInfo("host_capture", sizeof(CaptureMetadata))} }; std::unordered_map<std::string, StreamInfo> c_streams_myriad_to_pc = { {"left", StreamInfo("left", MONO_MAX_SIZE(1,1), { MONO_RES_AUTO, 0} )}, {"right", StreamInfo("right", MONO_MAX_SIZE(1,1), { MONO_RES_AUTO, 0} )}, {"disparity", StreamInfo("disparity", MONO_MAX_SIZE(1,1), { MONO_RES_AUTO, 0} )}, // {"depth", StreamInfo("depth", 921600, { 720, 1280} )}, {"depth_raw", StreamInfo("depth_raw", MONO_MAX_SIZE(1,2), { MONO_RES_AUTO, 0}, 2 )}, {"disparity_color", StreamInfo("disparity_color", MONO_MAX_SIZE(3,1), { MONO_RES_AUTO, 0, 3} )}, {"metaout", StreamInfo("metaout", 4*1024*1024)}, // 4 mb max metaout size {"previewout", StreamInfo("previewout", 1920256)}, {"meta_d2h", StreamInfo("meta_d2h", 1024*1024)}, {"jpegout", StreamInfo("jpegout", 10*1024*1024)}, {"video", StreamInfo("video", 10*1024*1024)}, {"object_tracker", StreamInfo("object_tracker", 2000)}, {"raw_color", StreamInfo("raw_color", 20*1024*1024)}, }; <|endoftext|>
<commit_before>/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu) * Project website: http://www.rit.edu/~jpw9607/ * * 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 */ /* expointers example * * This is more of a test to make sure that the code compiles under all of the * supported compilers because of flaky support for class and class member * templates. * * However, you can see all of the possible combonations of operations that * you can perform on the smart pointers. */ #include <gnelib.h> #include <iostream> #include <vector> #include <cassert> #include <string> using namespace std; class Base { public: int x; Base( int x ) : x(x) { cout << "Base ctor: " << x << endl; } virtual ~Base() { cout << "Base dtor: " << x << endl; } }; class Derived : public Base { public: Derived( int x ) : Base( x ) { cout << "Derived ctor: " << x << endl; } virtual ~Derived() { cout << "Derived dtor: " << x << endl; } }; //Provide a CustomDeleter just for testing. The nifty thing about the smart //pointers is you can use your own memory allocation scheme, or you can do any //operation in addition to or instead of "delete" when an object dies. template<class T> class CustomDeleter { public: void operator()( T* t ) const { cout << "Custom deleter called!" << endl; delete t; } }; typedef GNE::SmartPtr<Base> BasePtr; typedef GNE::SmartPtr<Derived> DerivedPtr; typedef GNE::WeakPtr<Base> BaseWeakPtr; typedef GNE::WeakPtr<Derived> BaseDerivedPtr; //Tests strong pointers void testStrong(); void testWeak(); int main( int argc, char* argv[] ) { GNE::initGNE( GNE::NO_NET, atexit ); GNE::Console::initConsole( atexit ); GNE::Console::setTitle( "GNE Smart Pointers Example/Test" ); testStrong(); testWeak(); return 0; } void testStrong() { //Tests with no objects BasePtr nPtr; assert( !nPtr ); //Test assignments and other things on a single object. BasePtr bPtr( new Derived( 10 ) ); assert( bPtr ); BasePtr bPtr2( bPtr ); assert( bPtr == bPtr2 ); bPtr2 = bPtr; assert( bPtr2 == bPtr ); GNE::swap( bPtr, bPtr2 ); assert( bPtr2 == bPtr ); DerivedPtr dPtr; dPtr = GNE::static_pointer_cast<Derived>( bPtr ); cout << dPtr << "->x = " << dPtr->x << endl; DerivedPtr dPtr2( dPtr ); assert( dPtr == dPtr2 ); assert( !(dPtr != dPtr2) ); assert( !(dPtr < dPtr2) ); bPtr = dPtr = dPtr2; bPtr.reset(); dPtr.reset(); dPtr2.reset(); bPtr2.reset(); //Testing with multiple objects bPtr.reset( new Base( 15 ) ); bPtr2.reset( new Base( 20 ) ); cout << "bPtr = " << bPtr << "->x = " << bPtr->x << endl; cout << "bPtr2 = " << bPtr2 << "->x = " << bPtr2->x << endl; cout << "swapping" << endl; bPtr.swap( bPtr2 ); cout << "bPtr = " << bPtr << "->x = " << bPtr->x << endl; cout << "bPtr2 = " << bPtr2 << "->x = " << bPtr2->x << endl; //Hidden functions that should be used for debugging purposes ONLY! assert( bPtr.use_count() == 1 ); assert( bPtr.unique() ); assert( bPtr2.use_count() == 1 ); assert( bPtr2.unique() ); assert( (bPtr.get() < bPtr2.get()) == (bPtr < bPtr2) ); //Test use of the CustomDeleter. There's no reason why we need one here. GNE::SmartPtr<int> intPtr( new int, CustomDeleter<int>() ); *intPtr = 5; cout << *intPtr << endl; //Superficial test placing objects in an STL container std::vector<BasePtr> bPtrs; bPtrs.push_back( bPtr ); bPtrs.push_back( bPtr2 ); assert( bPtrs[0].get() == bPtr.get() ); assert( bPtr.use_count() > 1 ); assert( !bPtr.unique() ); cout << "Strong pointer tests completed. You should see destructors after this." << endl; cout << " Press any key to continue" << endl; GNE::Console::getch(); } void testWeak() { cout << endl << "Weak pointer test begin:" << endl; BasePtr bPtr( new Base( 100 ) ); BaseWeakPtr bwPtr( bPtr ); //again use_count and expired are for debugging only! These methods are //inheriently unsafe in real usage (definitely unsafe in multithreaded apps). assert( bPtr.use_count() == 1 ); assert( !bwPtr.expired() ); BasePtr bPtr2( bwPtr.lock() ); assert( bPtr.use_count() == 2 ); bPtr.reset(); bPtr2.reset(); assert( bPtr.use_count() == 0 ); assert( bwPtr.expired() ); bPtr = bwPtr.lock(); assert( !bPtr ); cout << "Weak pointer tests completed. Press any key to continue."; GNE::Console::getch(); } <commit_msg>one of the asserts is not always true.<commit_after>/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu) * Project website: http://www.rit.edu/~jpw9607/ * * 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 */ /* expointers example * * This is more of a test to make sure that the code compiles under all of the * supported compilers because of flaky support for class and class member * templates. * * However, you can see all of the possible combonations of operations that * you can perform on the smart pointers. */ #include <gnelib.h> #include <iostream> #include <vector> #include <cassert> #include <string> using namespace std; class Base { public: int x; Base( int x ) : x(x) { cout << "Base ctor: " << x << endl; } virtual ~Base() { cout << "Base dtor: " << x << endl; } }; class Derived : public Base { public: Derived( int x ) : Base( x ) { cout << "Derived ctor: " << x << endl; } virtual ~Derived() { cout << "Derived dtor: " << x << endl; } }; //Provide a CustomDeleter just for testing. The nifty thing about the smart //pointers is you can use your own memory allocation scheme, or you can do any //operation in addition to or instead of "delete" when an object dies. template<class T> class CustomDeleter { public: void operator()( T* t ) const { cout << "Custom deleter called!" << endl; delete t; } }; typedef GNE::SmartPtr<Base> BasePtr; typedef GNE::SmartPtr<Derived> DerivedPtr; typedef GNE::WeakPtr<Base> BaseWeakPtr; typedef GNE::WeakPtr<Derived> BaseDerivedPtr; //Tests strong pointers void testStrong(); void testWeak(); int main( int argc, char* argv[] ) { GNE::initGNE( GNE::NO_NET, atexit ); GNE::Console::initConsole( atexit ); GNE::Console::setTitle( "GNE Smart Pointers Example/Test" ); testStrong(); testWeak(); return 0; } void testStrong() { //Tests with no objects BasePtr nPtr; assert( !nPtr ); //Test assignments and other things on a single object. BasePtr bPtr( new Derived( 10 ) ); assert( bPtr ); BasePtr bPtr2( bPtr ); assert( bPtr == bPtr2 ); bPtr2 = bPtr; assert( bPtr2 == bPtr ); GNE::swap( bPtr, bPtr2 ); assert( bPtr2 == bPtr ); DerivedPtr dPtr; dPtr = GNE::static_pointer_cast<Derived>( bPtr ); cout << dPtr << "->x = " << dPtr->x << endl; DerivedPtr dPtr2( dPtr ); assert( dPtr == dPtr2 ); assert( !(dPtr != dPtr2) ); assert( !(dPtr < dPtr2) ); bPtr = dPtr = dPtr2; bPtr.reset(); dPtr.reset(); dPtr2.reset(); bPtr2.reset(); //Testing with multiple objects bPtr.reset( new Base( 15 ) ); bPtr2.reset( new Base( 20 ) ); cout << "bPtr = " << bPtr << "->x = " << bPtr->x << endl; cout << "bPtr2 = " << bPtr2 << "->x = " << bPtr2->x << endl; cout << "swapping" << endl; bPtr.swap( bPtr2 ); cout << "bPtr = " << bPtr << "->x = " << bPtr->x << endl; cout << "bPtr2 = " << bPtr2 << "->x = " << bPtr2->x << endl; //Hidden functions that should be used for debugging purposes ONLY! assert( bPtr.use_count() == 1 ); assert( bPtr.unique() ); assert( bPtr2.use_count() == 1 ); assert( bPtr2.unique() ); //Test use of the CustomDeleter. There's no reason why we need one here. GNE::SmartPtr<int> intPtr( new int, CustomDeleter<int>() ); *intPtr = 5; cout << *intPtr << endl; //Superficial test placing objects in an STL container std::vector<BasePtr> bPtrs; bPtrs.push_back( bPtr ); bPtrs.push_back( bPtr2 ); assert( bPtrs[0].get() == bPtr.get() ); assert( bPtr.use_count() > 1 ); assert( !bPtr.unique() ); cout << "Strong pointer tests completed. You should see destructors after this." << endl; cout << " Press any key to continue" << endl; GNE::Console::getch(); } void testWeak() { cout << endl << "Weak pointer test begin:" << endl; BasePtr bPtr( new Base( 100 ) ); BaseWeakPtr bwPtr( bPtr ); //again use_count and expired are for debugging only! These methods are //inheriently unsafe in real usage (definitely unsafe in multithreaded apps). assert( bPtr.use_count() == 1 ); assert( !bwPtr.expired() ); BasePtr bPtr2( bwPtr.lock() ); assert( bPtr.use_count() == 2 ); bPtr.reset(); bPtr2.reset(); assert( bPtr.use_count() == 0 ); assert( bwPtr.expired() ); bPtr = bwPtr.lock(); assert( !bPtr ); cout << "Weak pointer tests completed. Press any key to continue."; GNE::Console::getch(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: source.cxx,v $ * * $Revision: 1.17 $ * * last change: $Author: rt $ $Date: 2004-10-22 07:54:58 $ * * 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 _COM_SUN_STAR_DATATRANSFER_DND_DNDCONSTANTS_HPP_ #include <com/sun/star/datatransfer/dnd/DNDConstants.hpp> #endif #ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_ #include <com/sun/star/datatransfer/XTransferable.hpp> #endif #ifndef _COM_SUN_STAR_AWT_MOUSEBUTTON_HPP_ #include <com/sun/star/awt/MouseButton.hpp> #endif #ifndef _COM_SUN_STAR_AWT_MOUSEEVENT_HPP_ #include <com/sun/star/awt/MouseEvent.hpp> #endif #ifndef _RTL_UNLOAD_H_ #include <rtl/unload.h> #endif #include <process.h> #include <memory> #include "source.hxx" #include "globals.hxx" #include "sourcecontext.hxx" #include "../../inc/DtObjFactory.hxx" #include <rtl/ustring.h> #include <process.h> #include <winuser.h> #include <stdio.h> using namespace rtl; using namespace cppu; using namespace osl; using namespace com::sun::star::datatransfer; using namespace com::sun::star::datatransfer::dnd; using namespace com::sun::star::datatransfer::dnd::DNDConstants; using namespace com::sun::star::uno; using namespace com::sun::star::awt::MouseButton; using namespace com::sun::star::awt; using namespace com::sun::star::lang; extern rtl_StandardModuleCount g_moduleCount; //--> TRA extern Reference< XTransferable > g_XTransferable; //<-- TRA unsigned __stdcall DndOleSTAFunc(LPVOID pParams); //---------------------------------------------------- /** Ctor */ DragSource::DragSource( const Reference<XMultiServiceFactory>& sf): m_serviceFactory( sf), WeakComponentImplHelper3< XDragSource, XInitialization, XServiceInfo >(m_mutex), // m_pcurrentContext_impl(0), m_hAppWindow(0), m_MouseButton(0), m_RunningDndOperationCount(0) { g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt ); } //---------------------------------------------------- /** Dtor */ DragSource::~DragSource() { g_moduleCount.modCnt.release( &g_moduleCount.modCnt ); } //---------------------------------------------------- /** First start a new drag and drop thread if the last one has finished ???? Do we really need a separate thread for every Dnd opeartion or only if the source thread is an MTA thread ???? */ void DragSource::StartDragImpl( const DragGestureEvent& trigger, sal_Int8 sourceActions, sal_Int32 cursor, sal_Int32 image, const Reference<XTransferable >& trans, const Reference<XDragSourceListener >& listener ) { // The actions supported by the drag source m_sourceActions= sourceActions; // We need to know which mouse button triggered the operation. // If it was the left one, then the drop occurs when that button // has been released and if it was the right one then the drop // occurs when the right button has been released. If the event is not // set then we assume that the left button is pressed. MouseEvent evtMouse; trigger.Event >>= evtMouse; m_MouseButton= evtMouse.Buttons; // The SourceContext class administers the XDragSourceListener s and // fires events to them. An instance only exists in the scope of this // functions. However, the drag and drop operation causes callbacks // to the IDropSource interface implemented in this class (but only // while this function executes). The source context is also used // in DragSource::QueryContinueDrag. m_currentContext= static_cast<XDragSourceContext*>( new SourceContext( static_cast<DragSource*>(this), listener ) ); // Convert the XTransferable data object into an IDataObject object; //--> TRA g_XTransferable = trans; //<-- TRA m_spDataObject= m_aDataConverter.createDataObjFromTransferable( m_serviceFactory, trans); // Obtain the id of the thread that created the window DWORD processId; m_threadIdWindow= GetWindowThreadProcessId( m_hAppWindow, &processId); // hold the instance for the DnD thread, it's to late // to acquire at the start of the thread procedure // the thread procedure is responsible for the release acquire(); // The thread acccesses members of this instance but does not call acquire. // Hopefully this instance is not destroyed before the thread has terminated. unsigned threadId; HANDLE hThread= reinterpret_cast<HANDLE>(_beginthreadex( 0, 0, DndOleSTAFunc, reinterpret_cast<void*>(this), 0, &threadId)); // detach from thread CloseHandle(hThread); } // XInitialization //---------------------------------------------------- /** aArguments contains a machine id */ void SAL_CALL DragSource::initialize( const Sequence< Any >& aArguments ) throw(Exception, RuntimeException) { if( aArguments.getLength() >=2) m_hAppWindow= *(HWND*)aArguments[1].getValue(); OSL_ASSERT( IsWindow( m_hAppWindow) ); } //---------------------------------------------------- /** XDragSource */ sal_Bool SAL_CALL DragSource::isDragImageSupported( ) throw(RuntimeException) { return 0; } //---------------------------------------------------- /** */ sal_Int32 SAL_CALL DragSource::getDefaultCursor( sal_Int8 dragAction ) throw( IllegalArgumentException, RuntimeException) { return 0; } //---------------------------------------------------- /** Notifies the XDragSourceListener by calling dragDropEnd */ void SAL_CALL DragSource::startDrag( const DragGestureEvent& trigger, sal_Int8 sourceActions, sal_Int32 cursor, sal_Int32 image, const Reference<XTransferable >& trans, const Reference<XDragSourceListener >& listener ) throw( RuntimeException) { // Allow only one running dnd operation at a time, // see XDragSource documentation long cnt = InterlockedIncrement(&m_RunningDndOperationCount); if (1 == cnt) { StartDragImpl(trigger, sourceActions, cursor, image, trans, listener); } else { //OSL_ENSURE(false, "Overlapping Drag&Drop operation rejected!"); cnt = InterlockedDecrement(&m_RunningDndOperationCount); DragSourceDropEvent dsde; dsde.DropAction = ACTION_NONE; dsde.DropSuccess = false; try { listener->dragDropEnd(dsde); } catch(RuntimeException&) { OSL_ENSURE(false, "Runtime exception during event dispatching"); } } } //---------------------------------------------------- /** */ #if OSL_DEBUG_LEVEL > 1 void SAL_CALL DragSource::release() { if( m_refCount == 1) { int a = m_refCount; } WeakComponentImplHelper3< XDragSource, XInitialization, XServiceInfo>::release(); } #endif //---------------------------------------------------- /**IDropTarget */ HRESULT STDMETHODCALLTYPE DragSource::QueryInterface( REFIID riid, void **ppvObject) { if( !ppvObject) return E_POINTER; *ppvObject= NULL; if( riid == __uuidof( IUnknown) ) *ppvObject= static_cast<IUnknown*>( this); else if ( riid == __uuidof( IDropSource) ) *ppvObject= static_cast<IDropSource*>( this); if(*ppvObject) { AddRef(); return S_OK; } else return E_NOINTERFACE; } //---------------------------------------------------- /** */ ULONG STDMETHODCALLTYPE DragSource::AddRef( void) { acquire(); return (ULONG) m_refCount; } //---------------------------------------------------- /** */ ULONG STDMETHODCALLTYPE DragSource::Release( void) { ULONG ref= m_refCount; release(); return --ref; } //---------------------------------------------------- /** IDropSource */ HRESULT STDMETHODCALLTYPE DragSource::QueryContinueDrag( /* [in] */ BOOL fEscapePressed, /* [in] */ DWORD grfKeyState) { #if DBG_CONSOLE_OUT printf("\nDragSource::QueryContinueDrag"); #endif HRESULT retVal= S_OK; // default continue DnD if (fEscapePressed) { retVal= DRAGDROP_S_CANCEL; } else { if( ( m_MouseButton == MouseButton::RIGHT && !(grfKeyState & MK_RBUTTON) ) || ( m_MouseButton == MouseButton::MIDDLE && !(grfKeyState & MK_MBUTTON) ) || ( m_MouseButton == MouseButton::LEFT && !(grfKeyState & MK_LBUTTON) ) || ( m_MouseButton == 0 && !(grfKeyState & MK_LBUTTON) ) ) { retVal= DRAGDROP_S_DROP; } } // fire dropActionChanged event. // this is actually done by the context, which also detects whether the action // changed at all sal_Int8 dropAction= fEscapePressed ? ACTION_NONE : dndOleKeysToAction( grfKeyState, m_sourceActions); sal_Int8 userAction= fEscapePressed ? ACTION_NONE : dndOleKeysToAction( grfKeyState, -1 ); static_cast<SourceContext*>(m_currentContext.get())->fire_dropActionChanged( dropAction, userAction); return retVal; } //---------------------------------------------------- /** */ HRESULT STDMETHODCALLTYPE DragSource::GiveFeedback( /* [in] */ DWORD dwEffect) { #if DBG_CONSOLE_OUT printf("\nDragSource::GiveFeedback %d", dwEffect); #endif return DRAGDROP_S_USEDEFAULTCURSORS; } // XServiceInfo OUString SAL_CALL DragSource::getImplementationName( ) throw (RuntimeException) { return OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_IMPL_NAME));; } // XServiceInfo sal_Bool SAL_CALL DragSource::supportsService( const OUString& ServiceName ) throw (RuntimeException) { if( ServiceName.equals(OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_SERVICE_NAME )))) return sal_True; return sal_False; } Sequence< OUString > SAL_CALL DragSource::getSupportedServiceNames( ) throw (RuntimeException) { OUString names[1]= {OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_SERVICE_NAME))}; return Sequence<OUString>(names, 1); } //---------------------------------------------------- /**This function is called as extra thread from DragSource::executeDrag. The function carries out a drag and drop operation by calling DoDragDrop. The thread also notifies all XSourceListener. */ unsigned __stdcall DndOleSTAFunc(LPVOID pParams) { // The structure contains all arguments for DoDragDrop and other DragSource *pSource= (DragSource*)pParams; // Drag and drop only works in a thread in which OleInitialize is called. HRESULT hr= OleInitialize( NULL); if(SUCCEEDED(hr)) { // We force the creation of a thread message queue. This is necessary // for a later call to AttachThreadInput MSG msgtemp; PeekMessage( &msgtemp, NULL, WM_USER, WM_USER, PM_NOREMOVE); DWORD threadId= GetCurrentThreadId(); // This thread is attached to the thread that created the window. Hence // this thread also receives all mouse and keyboard messages which are // needed by DoDragDrop AttachThreadInput( threadId , pSource->m_threadIdWindow, TRUE ); DWORD dwEffect= 0; hr= DoDragDrop( pSource->m_spDataObject.get(), static_cast<IDropSource*>(pSource), dndActionsToDropEffects( pSource->m_sourceActions), &dwEffect); // #105428 detach my message queue from the other threads // message queue before calling fire_dragDropEnd else // the office may appear to hang sometimes AttachThreadInput( threadId, pSource->m_threadIdWindow, FALSE); //--> TRA // clear the global transferable again g_XTransferable = Reference< XTransferable >( ); //<-- TRA OSL_ENSURE( hr != E_INVALIDARG, "IDataObject impl does not contain valid data"); //Fire event sal_Int8 action= hr == DRAGDROP_S_DROP ? dndOleDropEffectsToActions( dwEffect) : ACTION_NONE; static_cast<SourceContext*>(pSource->m_currentContext.get())->fire_dragDropEnd( hr == DRAGDROP_S_DROP ? sal_True : sal_False, action); // Destroy SourceContextslkfgj pSource->m_currentContext= 0; // Destroy the XTransferable wrapper pSource->m_spDataObject=0; OleUninitialize(); } long cnt = InterlockedDecrement(&pSource->m_RunningDndOperationCount); // the DragSource was manually acquired by // thread starting method DelayedStartDrag pSource->release(); return 0; } <commit_msg>INTEGRATION: CWS ooo19126 (1.17.12); FILE MERGED 2005/09/05 18:48:18 rt 1.17.12.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: source.cxx,v $ * * $Revision: 1.18 $ * * last change: $Author: rt $ $Date: 2005-09-08 18:18: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 * ************************************************************************/ #ifndef _COM_SUN_STAR_DATATRANSFER_DND_DNDCONSTANTS_HPP_ #include <com/sun/star/datatransfer/dnd/DNDConstants.hpp> #endif #ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_ #include <com/sun/star/datatransfer/XTransferable.hpp> #endif #ifndef _COM_SUN_STAR_AWT_MOUSEBUTTON_HPP_ #include <com/sun/star/awt/MouseButton.hpp> #endif #ifndef _COM_SUN_STAR_AWT_MOUSEEVENT_HPP_ #include <com/sun/star/awt/MouseEvent.hpp> #endif #ifndef _RTL_UNLOAD_H_ #include <rtl/unload.h> #endif #include <process.h> #include <memory> #include "source.hxx" #include "globals.hxx" #include "sourcecontext.hxx" #include "../../inc/DtObjFactory.hxx" #include <rtl/ustring.h> #include <process.h> #include <winuser.h> #include <stdio.h> using namespace rtl; using namespace cppu; using namespace osl; using namespace com::sun::star::datatransfer; using namespace com::sun::star::datatransfer::dnd; using namespace com::sun::star::datatransfer::dnd::DNDConstants; using namespace com::sun::star::uno; using namespace com::sun::star::awt::MouseButton; using namespace com::sun::star::awt; using namespace com::sun::star::lang; extern rtl_StandardModuleCount g_moduleCount; //--> TRA extern Reference< XTransferable > g_XTransferable; //<-- TRA unsigned __stdcall DndOleSTAFunc(LPVOID pParams); //---------------------------------------------------- /** Ctor */ DragSource::DragSource( const Reference<XMultiServiceFactory>& sf): m_serviceFactory( sf), WeakComponentImplHelper3< XDragSource, XInitialization, XServiceInfo >(m_mutex), // m_pcurrentContext_impl(0), m_hAppWindow(0), m_MouseButton(0), m_RunningDndOperationCount(0) { g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt ); } //---------------------------------------------------- /** Dtor */ DragSource::~DragSource() { g_moduleCount.modCnt.release( &g_moduleCount.modCnt ); } //---------------------------------------------------- /** First start a new drag and drop thread if the last one has finished ???? Do we really need a separate thread for every Dnd opeartion or only if the source thread is an MTA thread ???? */ void DragSource::StartDragImpl( const DragGestureEvent& trigger, sal_Int8 sourceActions, sal_Int32 cursor, sal_Int32 image, const Reference<XTransferable >& trans, const Reference<XDragSourceListener >& listener ) { // The actions supported by the drag source m_sourceActions= sourceActions; // We need to know which mouse button triggered the operation. // If it was the left one, then the drop occurs when that button // has been released and if it was the right one then the drop // occurs when the right button has been released. If the event is not // set then we assume that the left button is pressed. MouseEvent evtMouse; trigger.Event >>= evtMouse; m_MouseButton= evtMouse.Buttons; // The SourceContext class administers the XDragSourceListener s and // fires events to them. An instance only exists in the scope of this // functions. However, the drag and drop operation causes callbacks // to the IDropSource interface implemented in this class (but only // while this function executes). The source context is also used // in DragSource::QueryContinueDrag. m_currentContext= static_cast<XDragSourceContext*>( new SourceContext( static_cast<DragSource*>(this), listener ) ); // Convert the XTransferable data object into an IDataObject object; //--> TRA g_XTransferable = trans; //<-- TRA m_spDataObject= m_aDataConverter.createDataObjFromTransferable( m_serviceFactory, trans); // Obtain the id of the thread that created the window DWORD processId; m_threadIdWindow= GetWindowThreadProcessId( m_hAppWindow, &processId); // hold the instance for the DnD thread, it's to late // to acquire at the start of the thread procedure // the thread procedure is responsible for the release acquire(); // The thread acccesses members of this instance but does not call acquire. // Hopefully this instance is not destroyed before the thread has terminated. unsigned threadId; HANDLE hThread= reinterpret_cast<HANDLE>(_beginthreadex( 0, 0, DndOleSTAFunc, reinterpret_cast<void*>(this), 0, &threadId)); // detach from thread CloseHandle(hThread); } // XInitialization //---------------------------------------------------- /** aArguments contains a machine id */ void SAL_CALL DragSource::initialize( const Sequence< Any >& aArguments ) throw(Exception, RuntimeException) { if( aArguments.getLength() >=2) m_hAppWindow= *(HWND*)aArguments[1].getValue(); OSL_ASSERT( IsWindow( m_hAppWindow) ); } //---------------------------------------------------- /** XDragSource */ sal_Bool SAL_CALL DragSource::isDragImageSupported( ) throw(RuntimeException) { return 0; } //---------------------------------------------------- /** */ sal_Int32 SAL_CALL DragSource::getDefaultCursor( sal_Int8 dragAction ) throw( IllegalArgumentException, RuntimeException) { return 0; } //---------------------------------------------------- /** Notifies the XDragSourceListener by calling dragDropEnd */ void SAL_CALL DragSource::startDrag( const DragGestureEvent& trigger, sal_Int8 sourceActions, sal_Int32 cursor, sal_Int32 image, const Reference<XTransferable >& trans, const Reference<XDragSourceListener >& listener ) throw( RuntimeException) { // Allow only one running dnd operation at a time, // see XDragSource documentation long cnt = InterlockedIncrement(&m_RunningDndOperationCount); if (1 == cnt) { StartDragImpl(trigger, sourceActions, cursor, image, trans, listener); } else { //OSL_ENSURE(false, "Overlapping Drag&Drop operation rejected!"); cnt = InterlockedDecrement(&m_RunningDndOperationCount); DragSourceDropEvent dsde; dsde.DropAction = ACTION_NONE; dsde.DropSuccess = false; try { listener->dragDropEnd(dsde); } catch(RuntimeException&) { OSL_ENSURE(false, "Runtime exception during event dispatching"); } } } //---------------------------------------------------- /** */ #if OSL_DEBUG_LEVEL > 1 void SAL_CALL DragSource::release() { if( m_refCount == 1) { int a = m_refCount; } WeakComponentImplHelper3< XDragSource, XInitialization, XServiceInfo>::release(); } #endif //---------------------------------------------------- /**IDropTarget */ HRESULT STDMETHODCALLTYPE DragSource::QueryInterface( REFIID riid, void **ppvObject) { if( !ppvObject) return E_POINTER; *ppvObject= NULL; if( riid == __uuidof( IUnknown) ) *ppvObject= static_cast<IUnknown*>( this); else if ( riid == __uuidof( IDropSource) ) *ppvObject= static_cast<IDropSource*>( this); if(*ppvObject) { AddRef(); return S_OK; } else return E_NOINTERFACE; } //---------------------------------------------------- /** */ ULONG STDMETHODCALLTYPE DragSource::AddRef( void) { acquire(); return (ULONG) m_refCount; } //---------------------------------------------------- /** */ ULONG STDMETHODCALLTYPE DragSource::Release( void) { ULONG ref= m_refCount; release(); return --ref; } //---------------------------------------------------- /** IDropSource */ HRESULT STDMETHODCALLTYPE DragSource::QueryContinueDrag( /* [in] */ BOOL fEscapePressed, /* [in] */ DWORD grfKeyState) { #if DBG_CONSOLE_OUT printf("\nDragSource::QueryContinueDrag"); #endif HRESULT retVal= S_OK; // default continue DnD if (fEscapePressed) { retVal= DRAGDROP_S_CANCEL; } else { if( ( m_MouseButton == MouseButton::RIGHT && !(grfKeyState & MK_RBUTTON) ) || ( m_MouseButton == MouseButton::MIDDLE && !(grfKeyState & MK_MBUTTON) ) || ( m_MouseButton == MouseButton::LEFT && !(grfKeyState & MK_LBUTTON) ) || ( m_MouseButton == 0 && !(grfKeyState & MK_LBUTTON) ) ) { retVal= DRAGDROP_S_DROP; } } // fire dropActionChanged event. // this is actually done by the context, which also detects whether the action // changed at all sal_Int8 dropAction= fEscapePressed ? ACTION_NONE : dndOleKeysToAction( grfKeyState, m_sourceActions); sal_Int8 userAction= fEscapePressed ? ACTION_NONE : dndOleKeysToAction( grfKeyState, -1 ); static_cast<SourceContext*>(m_currentContext.get())->fire_dropActionChanged( dropAction, userAction); return retVal; } //---------------------------------------------------- /** */ HRESULT STDMETHODCALLTYPE DragSource::GiveFeedback( /* [in] */ DWORD dwEffect) { #if DBG_CONSOLE_OUT printf("\nDragSource::GiveFeedback %d", dwEffect); #endif return DRAGDROP_S_USEDEFAULTCURSORS; } // XServiceInfo OUString SAL_CALL DragSource::getImplementationName( ) throw (RuntimeException) { return OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_IMPL_NAME));; } // XServiceInfo sal_Bool SAL_CALL DragSource::supportsService( const OUString& ServiceName ) throw (RuntimeException) { if( ServiceName.equals(OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_SERVICE_NAME )))) return sal_True; return sal_False; } Sequence< OUString > SAL_CALL DragSource::getSupportedServiceNames( ) throw (RuntimeException) { OUString names[1]= {OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_SERVICE_NAME))}; return Sequence<OUString>(names, 1); } //---------------------------------------------------- /**This function is called as extra thread from DragSource::executeDrag. The function carries out a drag and drop operation by calling DoDragDrop. The thread also notifies all XSourceListener. */ unsigned __stdcall DndOleSTAFunc(LPVOID pParams) { // The structure contains all arguments for DoDragDrop and other DragSource *pSource= (DragSource*)pParams; // Drag and drop only works in a thread in which OleInitialize is called. HRESULT hr= OleInitialize( NULL); if(SUCCEEDED(hr)) { // We force the creation of a thread message queue. This is necessary // for a later call to AttachThreadInput MSG msgtemp; PeekMessage( &msgtemp, NULL, WM_USER, WM_USER, PM_NOREMOVE); DWORD threadId= GetCurrentThreadId(); // This thread is attached to the thread that created the window. Hence // this thread also receives all mouse and keyboard messages which are // needed by DoDragDrop AttachThreadInput( threadId , pSource->m_threadIdWindow, TRUE ); DWORD dwEffect= 0; hr= DoDragDrop( pSource->m_spDataObject.get(), static_cast<IDropSource*>(pSource), dndActionsToDropEffects( pSource->m_sourceActions), &dwEffect); // #105428 detach my message queue from the other threads // message queue before calling fire_dragDropEnd else // the office may appear to hang sometimes AttachThreadInput( threadId, pSource->m_threadIdWindow, FALSE); //--> TRA // clear the global transferable again g_XTransferable = Reference< XTransferable >( ); //<-- TRA OSL_ENSURE( hr != E_INVALIDARG, "IDataObject impl does not contain valid data"); //Fire event sal_Int8 action= hr == DRAGDROP_S_DROP ? dndOleDropEffectsToActions( dwEffect) : ACTION_NONE; static_cast<SourceContext*>(pSource->m_currentContext.get())->fire_dragDropEnd( hr == DRAGDROP_S_DROP ? sal_True : sal_False, action); // Destroy SourceContextslkfgj pSource->m_currentContext= 0; // Destroy the XTransferable wrapper pSource->m_spDataObject=0; OleUninitialize(); } long cnt = InterlockedDecrement(&pSource->m_RunningDndOperationCount); // the DragSource was manually acquired by // thread starting method DelayedStartDrag pSource->release(); return 0; } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2018) // René Fritze (2018) // Tobias Leibner (2018) #ifndef DUNE_GDT_INTERPOLATIONS_DEFAULT_HH #define DUNE_GDT_INTERPOLATIONS_DEFAULT_HH #include <vector> #include <dune/grid/common/rangegenerators.hh> #include <dune/xt/grid/type_traits.hh> #include <dune/xt/grid/functors/interfaces.hh> #include <dune/xt/grid/walker.hh> #include <dune/xt/functions/interfaces/grid-function.hh> #include <dune/xt/functions/interfaces/function.hh> #include <dune/xt/functions/generic/function.hh> #include <dune/gdt/discretefunction/default.hh> namespace Dune { namespace GDT { // ### Variants for GridFunctionInterface template <class GV, size_t r, size_t rC, class R, class V, class IGV> class DefaultInterpolationElementFunctor : public XT::Grid::ElementFunctor<IGV> { using BaseType = typename XT::Grid::ElementFunctor<IGV>; public: using typename BaseType::E; using SourceType = XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r, rC, R>; using LocalSourceType = typename SourceType::LocalFunctionType; using TargetType = DiscreteFunction<V, GV, r, rC, R>; using LocalDofVectorType = typename TargetType::DofVectorType::LocalDofVectorType; using TargetBasisType = typename TargetType::SpaceType::GlobalBasisType::LocalizedType; DefaultInterpolationElementFunctor(const SourceType& source, TargetType& target) : source_(source) , target_(target) , local_dof_vector_(target.dofs().localize()) , local_source_(source_.local_function()) , target_basis_(target.space().basis().localize()) { DUNE_THROW_IF(target_.space().type() == SpaceType::raviart_thomas, Exceptions::interpolation_error, "Use the correct one from interpolations/raviart-thomas.hh instead!"); } DefaultInterpolationElementFunctor(const DefaultInterpolationElementFunctor& other) : BaseType(other) , source_(other.source_) , target_(other.target_) , local_dof_vector_(target_.dofs().localize()) , local_source_(source_.local_function()) , target_basis_(target_.space().basis().localize()) {} XT::Grid::ElementFunctor<IGV>* copy() override final { return new DefaultInterpolationElementFunctor(*this); } void apply_local(const E& element) override final { local_source_->bind(element); local_dof_vector_.bind(element); target_basis_->bind(element); target_basis_->interpolate( [&](const auto& xx) { return local_source_->evaluate(xx); }, local_source_->order(), local_dof_vector_); } private: const SourceType& source_; TargetType& target_; LocalDofVectorType local_dof_vector_; std::unique_ptr<LocalSourceType> local_source_; std::unique_ptr<TargetBasisType> target_basis_; }; /** * \brief Interpolates a localizable function within a given space [most general variant]. * * Simply uses interpolate() of the target spaces global basis(). * * * \note This does not clear target.dofs().vector(). Thus, if interpolation_grid_view only covers a part of the domain * of target.space().grid_view(), other contributions in target remain (which is on purpose). * * \note This might not be optimal for all spaces. For instance, the polynomial order of source is not taken into * account for local L^2-projection based interpolation. This is a limitation in dune-localfunctions and we need * to completely replace the interpolation of the respective local finite element. * * \note This might not be correct for all spaces, in particular if source is not continuous. */ template <class GV, size_t r, size_t rC, class R, class V, class IGVT> std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<GV>, typename IGVT::Grid::template Codim<0>::Entity>::value, void> default_interpolation(const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r, rC, R>& source, DiscreteFunction<V, GV, r, rC, R>& target, const GridView<IGVT>& interpolation_grid_view) { DefaultInterpolationElementFunctor<GV, r, rC, R, V, GridView<IGVT>> functor(source, target); auto walker = XT::Grid::Walker<GridView<IGVT>>(interpolation_grid_view); walker.append(functor); // Basis functions other than FV do not seem to be thread safe. TODO: fix walker.walk(target.space().type() == SpaceType::finite_volume); } // ... default_interpolation(...) /** * \brief Interpolates a localizable function within a given space [uses target.space().grid_view() as * interpolation_grid_view]. **/ template <class GV, size_t r, size_t rC, class R, class V> void default_interpolation(const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r, rC, R>& source, DiscreteFunction<V, GV, r, rC, R>& target) { default_interpolation(source, target, target.space().grid_view()); } /** * \brief Interpolates a localizable function within a given space [creates a suitable target function]. **/ template <class VectorType, class GV, size_t r, size_t rC, class R, class IGVT> std::enable_if_t< XT::LA::is_vector<VectorType>::value && std::is_same<XT::Grid::extract_entity_t<GV>, typename IGVT::Grid::template Codim<0>::Entity>::value, DiscreteFunction<VectorType, GV, r, rC, R>> default_interpolation(const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r, rC, R>& source, const SpaceInterface<GV, r, rC, R>& target_space, const GridView<IGVT>& interpolation_grid_view) { auto target_function = make_discrete_function<VectorType>(target_space); default_interpolation(source, target_function, interpolation_grid_view); return target_function; } /** * \brief Interpolates a localizable function within a given space [creates a suitable target function, uses * target_space.grid_view() as interpolation_grid_view]. **/ template <class VectorType, class GV, size_t r, size_t rC, class R> std::enable_if_t<XT::LA::is_vector<VectorType>::value, DiscreteFunction<VectorType, GV, r, rC, R>> default_interpolation(const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r, rC, R>& source, const SpaceInterface<GV, r, rC, R>& target_space) { auto target_function = make_discrete_function<VectorType>(target_space); default_interpolation(source, target_function); return target_function; } // ### Variants for FunctionInterface /** * \brief Interpolates a function within a given space [most general variant]. * * Simply calls as_grid_function<>() and redirects to the appropriate default_interpolation() function. */ template <class GV, size_t r, size_t rC, class R, class V, class IGVT> std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<GV>, typename IGVT::Grid::template Codim<0>::Entity>::value, void> default_interpolation(const XT::Functions::FunctionInterface<GridView<IGVT>::dimension, r, rC, R>& source, DiscreteFunction<V, GV, r, rC, R>& target, const GridView<IGVT>& interpolation_grid_view) { default_interpolation(source.as_grid_function(interpolation_grid_view), target, interpolation_grid_view); } /** * \brief Interpolates a function within a given space [uses target.space().grid_view() as * interpolation_grid_view]. **/ template <class GV, size_t r, size_t rC, class R, class V> void default_interpolation(const XT::Functions::FunctionInterface<GV::dimension, r, rC, R>& source, DiscreteFunction<V, GV, r, rC, R>& target) { default_interpolation(source, target, target.space().grid_view()); } /** * \brief Interpolates a function within a given space [creates a suitable target function]. **/ template <class VectorType, class GV, size_t r, size_t rC, class R, class IGVT> std::enable_if_t< XT::LA::is_vector<VectorType>::value && std::is_same<XT::Grid::extract_entity_t<GV>, typename IGVT::Grid::template Codim<0>::Entity>::value, DiscreteFunction<VectorType, GV, r, rC, R>> default_interpolation(const XT::Functions::FunctionInterface<GridView<IGVT>::dimension, r, rC, R>& source, const SpaceInterface<GV, r, rC, R>& target_space, const GridView<IGVT>& interpolation_grid_view) { return default_interpolation<VectorType>( source.as_grid_function(interpolation_grid_view), target_space, interpolation_grid_view); } /** * \brief Interpolates a function within a given space [creates a suitable target function, uses * target_space.grid_view() as interpolation_grid_view]. **/ template <class VectorType, class GV, size_t r, size_t rC, class R> std::enable_if_t<XT::LA::is_vector<VectorType>::value, DiscreteFunction<VectorType, GV, r, rC, R>> default_interpolation(const XT::Functions::FunctionInterface<GV::dimension, r, rC, R>& source, const SpaceInterface<GV, r, rC, R>& target_space) { return default_interpolation<VectorType>(source, target_space, target_space.grid_view()); } // ### Variants for GenericFunction /** * \brief Interpolates a function given as a lambda expression within a given space [most general variant]. * * Simply creates a XT::Functions::GenericFunction and redirects to the appropriate default_interpolation() function. */ template <class GV, size_t r, size_t rC, class R, class V, class IGVT> std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<GV>, typename IGVT::Grid::template Codim<0>::Entity>::value, void> default_interpolation( const int source_order, const std::function<typename XT::Functions::GenericFunction<GridView<IGVT>::dimension, r, rC, R>::RangeReturnType( const typename XT::Functions::GenericFunction<GridView<IGVT>::dimension, r, rC, R>::DomainType&, const XT::Common::Parameter&)> source_evaluate_lambda, DiscreteFunction<V, GV, r, rC, R>& target, const GridView<IGVT>& interpolation_grid_view) { default_interpolation( XT::Functions::GenericFunction<GridView<IGVT>::dimension, r, rC, R>(source_order, source_evaluate_lambda), target, interpolation_grid_view); } /** * \brief Interpolates a function given as a lambda expression within a given space [uses * target.space().grid_view() as interpolation_grid_view]. **/ template <class GV, size_t r, size_t rC, class R, class V> void default_interpolation( const int source_order, const std::function<typename XT::Functions::GenericFunction<GV::dimension, r, rC, R>::RangeReturnType( const typename XT::Functions::GenericFunction<GV::dimension, r, rC, R>::DomainType&, const XT::Common::Parameter&)> source_evaluate_lambda, DiscreteFunction<V, GV, r, rC, R>& target) { default_interpolation(XT::Functions::GenericFunction<GV::dimension, r, rC, R>(source_order, source_evaluate_lambda), target); } /** * \brief Interpolates a function given as a lambda expression within a given space [creates a suitable target * function]. **/ template <class VectorType, class GV, size_t r, size_t rC, class R, class IGVT> std::enable_if_t< XT::LA::is_vector<VectorType>::value && std::is_same<XT::Grid::extract_entity_t<GV>, typename IGVT::Grid::template Codim<0>::Entity>::value, DiscreteFunction<VectorType, GV, r, rC, R>> default_interpolation( const int source_order, const std::function<typename XT::Functions::GenericFunction<GridView<IGVT>::dimension, r, rC, R>::RangeReturnType( const typename XT::Functions::GenericFunction<GridView<IGVT>::dimension, r, rC, R>::DomainType&, const XT::Common::Parameter&)> source_evaluate_lambda, const SpaceInterface<GV, r, rC, R>& target_space, const GridView<IGVT>& interpolation_grid_view) { return default_interpolation<VectorType>( XT::Functions::GenericFunction<GridView<IGVT>::dimension, r, rC, R>(source_order, source_evaluate_lambda), target_space, interpolation_grid_view); } /** * \brief Interpolates a function given as a lambda expression within a given space [creates a suitable target * function, uses target_space.grid_view() as interpolation_grid_view]. **/ template <class VectorType, class GV, size_t r, size_t rC, class R> std::enable_if_t<XT::LA::is_vector<VectorType>::value, DiscreteFunction<VectorType, GV, r, rC, R>> default_interpolation( const int source_order, const std::function<typename XT::Functions::GenericFunction<GV::dimension, r, rC, R>::RangeReturnType( const typename XT::Functions::GenericFunction<GV::dimension, r, rC, R>::DomainType&, const XT::Common::Parameter&)> source_evaluate_lambda, const SpaceInterface<GV, r, rC, R>& target_space) { return default_interpolation<VectorType>( XT::Functions::GenericFunction<GV::dimension, r, rC, R>(source_order, source_evaluate_lambda), target_space); } } // namespace GDT } // namespace Dune #endif // DUNE_GDT_INTERPOLATIONS_DEFAULT_HH <commit_msg>[interpolations.default] simplify functor by using GridFunction<commit_after>// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2018) // René Fritze (2018) // Tobias Leibner (2018) #ifndef DUNE_GDT_INTERPOLATIONS_DEFAULT_HH #define DUNE_GDT_INTERPOLATIONS_DEFAULT_HH #include <vector> #include <dune/grid/common/rangegenerators.hh> #include <dune/xt/grid/type_traits.hh> #include <dune/xt/grid/functors/interfaces.hh> #include <dune/xt/grid/walker.hh> #include <dune/xt/functions/grid-function.hh> #include <dune/xt/functions/interfaces/grid-function.hh> #include <dune/xt/functions/interfaces/function.hh> #include <dune/xt/functions/generic/function.hh> #include <dune/gdt/discretefunction/default.hh> namespace Dune { namespace GDT { template <class GV, size_t r, size_t rC, class R, class V, class IGV> class DefaultInterpolationElementFunctor : public XT::Grid::ElementFunctor<IGV> { using BaseType = typename XT::Grid::ElementFunctor<IGV>; public: using typename BaseType::E; using SourceType = XT::Functions::GridFunction<XT::Grid::extract_entity_t<GV>, r, rC, R>; using LocalSourceType = typename SourceType::LocalFunctionType; using TargetType = DiscreteFunction<V, GV, r, rC, R>; using LocalDofVectorType = typename TargetType::DofVectorType::LocalDofVectorType; using TargetBasisType = typename TargetType::SpaceType::GlobalBasisType::LocalizedType; DefaultInterpolationElementFunctor(SourceType source, TargetType& target) : source_(source) , target_(target) , local_dof_vector_(target.dofs().localize()) , local_source_(source_.local_function()) , target_basis_(target.space().basis().localize()) { DUNE_THROW_IF(target_.space().type() == SpaceType::raviart_thomas, Exceptions::interpolation_error, "Use the correct one from interpolations/raviart-thomas.hh instead!"); } DefaultInterpolationElementFunctor(const DefaultInterpolationElementFunctor& other) : BaseType(other) , source_(other.source_) , target_(other.target_) , local_dof_vector_(target_.dofs().localize()) , local_source_(source_.local_function()) , target_basis_(target_.space().basis().localize()) {} XT::Grid::ElementFunctor<IGV>* copy() override final { return new DefaultInterpolationElementFunctor(*this); } void apply_local(const E& element) override final { local_source_->bind(element); local_dof_vector_.bind(element); target_basis_->bind(element); target_basis_->interpolate( [&](const auto& xx) { return local_source_->evaluate(xx); }, local_source_->order(), local_dof_vector_); } private: const SourceType source_; TargetType& target_; LocalDofVectorType local_dof_vector_; std::unique_ptr<LocalSourceType> local_source_; std::unique_ptr<TargetBasisType> target_basis_; }; // class DefaultInterpolationElementFunctor /** * \brief Interpolates a localizable function within a given space [most general variant]. * * Simply uses interpolate() of the target spaces global basis(). * * \note This does not clear target.dofs().vector(). Thus, if interpolation_grid_view only covers a part of the domain * of target.space().grid_view(), other contributions in target remain (which is on purpose). * * \note This might not be optimal for all spaces. For instance, the polynomial order of source is not taken into * account for local L^2-projection based interpolation. This is a limitation in dune-localfunctions and we need * to completely replace the interpolation of the respective local finite element. * * \note This might not be correct for all spaces, in particular if source is not continuous. */ template <class GV, size_t r, size_t rC, class R, class V, class IGVT> std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<GV>, typename IGVT::Grid::template Codim<0>::Entity>::value, void> default_interpolation(const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r, rC, R>& source, DiscreteFunction<V, GV, r, rC, R>& target, const GridView<IGVT>& interpolation_grid_view) { DefaultInterpolationElementFunctor<GV, r, rC, R, V, GridView<IGVT>> functor(source, target); auto walker = XT::Grid::Walker<GridView<IGVT>>(interpolation_grid_view); walker.append(functor); // Basis functions other than FV do not seem to be thread safe. TODO: fix walker.walk(/*parallel=*/target.space().type() == SpaceType::finite_volume); } // ... default_interpolation(...) /** * \brief Interpolates a localizable function within a given space [uses target.space().grid_view() as * interpolation_grid_view]. **/ template <class GV, size_t r, size_t rC, class R, class V> void default_interpolation(const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r, rC, R>& source, DiscreteFunction<V, GV, r, rC, R>& target) { default_interpolation(source, target, target.space().grid_view()); } /** * \brief Interpolates a localizable function within a given space [creates a suitable target function]. **/ template <class VectorType, class GV, size_t r, size_t rC, class R, class IGVT> std::enable_if_t< XT::LA::is_vector<VectorType>::value && std::is_same<XT::Grid::extract_entity_t<GV>, typename IGVT::Grid::template Codim<0>::Entity>::value, DiscreteFunction<VectorType, GV, r, rC, R>> default_interpolation(const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r, rC, R>& source, const SpaceInterface<GV, r, rC, R>& target_space, const GridView<IGVT>& interpolation_grid_view) { auto target_function = make_discrete_function<VectorType>(target_space); default_interpolation(source, target_function, interpolation_grid_view); return target_function; } /** * \brief Interpolates a localizable function within a given space [creates a suitable target function, uses * target_space.grid_view() as interpolation_grid_view]. **/ template <class VectorType, class GV, size_t r, size_t rC, class R> std::enable_if_t<XT::LA::is_vector<VectorType>::value, DiscreteFunction<VectorType, GV, r, rC, R>> default_interpolation(const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r, rC, R>& source, const SpaceInterface<GV, r, rC, R>& target_space) { auto target_function = make_discrete_function<VectorType>(target_space); default_interpolation(source, target_function); return target_function; } // ### Variants for FunctionInterface /** * \brief Interpolates a function within a given space [most general variant]. * * Simply calls as_grid_function<>() and redirects to the appropriate default_interpolation() function. */ template <class GV, size_t r, size_t rC, class R, class V, class IGVT> std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<GV>, typename IGVT::Grid::template Codim<0>::Entity>::value, void> default_interpolation(const XT::Functions::FunctionInterface<GridView<IGVT>::dimension, r, rC, R>& source, DiscreteFunction<V, GV, r, rC, R>& target, const GridView<IGVT>& interpolation_grid_view) { default_interpolation(source.as_grid_function(interpolation_grid_view), target, interpolation_grid_view); } /** * \brief Interpolates a function within a given space [uses target.space().grid_view() as * interpolation_grid_view]. **/ template <class GV, size_t r, size_t rC, class R, class V> void default_interpolation(const XT::Functions::FunctionInterface<GV::dimension, r, rC, R>& source, DiscreteFunction<V, GV, r, rC, R>& target) { default_interpolation(source, target, target.space().grid_view()); } /** * \brief Interpolates a function within a given space [creates a suitable target function]. **/ template <class VectorType, class GV, size_t r, size_t rC, class R, class IGVT> std::enable_if_t< XT::LA::is_vector<VectorType>::value && std::is_same<XT::Grid::extract_entity_t<GV>, typename IGVT::Grid::template Codim<0>::Entity>::value, DiscreteFunction<VectorType, GV, r, rC, R>> default_interpolation(const XT::Functions::FunctionInterface<GridView<IGVT>::dimension, r, rC, R>& source, const SpaceInterface<GV, r, rC, R>& target_space, const GridView<IGVT>& interpolation_grid_view) { return default_interpolation<VectorType>( source.as_grid_function(interpolation_grid_view), target_space, interpolation_grid_view); } /** * \brief Interpolates a function within a given space [creates a suitable target function, uses * target_space.grid_view() as interpolation_grid_view]. **/ template <class VectorType, class GV, size_t r, size_t rC, class R> std::enable_if_t<XT::LA::is_vector<VectorType>::value, DiscreteFunction<VectorType, GV, r, rC, R>> default_interpolation(const XT::Functions::FunctionInterface<GV::dimension, r, rC, R>& source, const SpaceInterface<GV, r, rC, R>& target_space) { return default_interpolation<VectorType>(source, target_space, target_space.grid_view()); } // ### Variants for GenericFunction /** * \brief Interpolates a function given as a lambda expression within a given space [most general variant]. * * Simply creates a XT::Functions::GenericFunction and redirects to the appropriate default_interpolation() function. */ template <class GV, size_t r, size_t rC, class R, class V, class IGVT> std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<GV>, typename IGVT::Grid::template Codim<0>::Entity>::value, void> default_interpolation( const int source_order, const std::function<typename XT::Functions::GenericFunction<GridView<IGVT>::dimension, r, rC, R>::RangeReturnType( const typename XT::Functions::GenericFunction<GridView<IGVT>::dimension, r, rC, R>::DomainType&, const XT::Common::Parameter&)> source_evaluate_lambda, DiscreteFunction<V, GV, r, rC, R>& target, const GridView<IGVT>& interpolation_grid_view) { default_interpolation( XT::Functions::GenericFunction<GridView<IGVT>::dimension, r, rC, R>(source_order, source_evaluate_lambda), target, interpolation_grid_view); } /** * \brief Interpolates a function given as a lambda expression within a given space [uses * target.space().grid_view() as interpolation_grid_view]. **/ template <class GV, size_t r, size_t rC, class R, class V> void default_interpolation( const int source_order, const std::function<typename XT::Functions::GenericFunction<GV::dimension, r, rC, R>::RangeReturnType( const typename XT::Functions::GenericFunction<GV::dimension, r, rC, R>::DomainType&, const XT::Common::Parameter&)> source_evaluate_lambda, DiscreteFunction<V, GV, r, rC, R>& target) { default_interpolation(XT::Functions::GenericFunction<GV::dimension, r, rC, R>(source_order, source_evaluate_lambda), target); } /** * \brief Interpolates a function given as a lambda expression within a given space [creates a suitable target * function]. **/ template <class VectorType, class GV, size_t r, size_t rC, class R, class IGVT> std::enable_if_t< XT::LA::is_vector<VectorType>::value && std::is_same<XT::Grid::extract_entity_t<GV>, typename IGVT::Grid::template Codim<0>::Entity>::value, DiscreteFunction<VectorType, GV, r, rC, R>> default_interpolation( const int source_order, const std::function<typename XT::Functions::GenericFunction<GridView<IGVT>::dimension, r, rC, R>::RangeReturnType( const typename XT::Functions::GenericFunction<GridView<IGVT>::dimension, r, rC, R>::DomainType&, const XT::Common::Parameter&)> source_evaluate_lambda, const SpaceInterface<GV, r, rC, R>& target_space, const GridView<IGVT>& interpolation_grid_view) { return default_interpolation<VectorType>( XT::Functions::GenericFunction<GridView<IGVT>::dimension, r, rC, R>(source_order, source_evaluate_lambda), target_space, interpolation_grid_view); } /** * \brief Interpolates a function given as a lambda expression within a given space [creates a suitable target * function, uses target_space.grid_view() as interpolation_grid_view]. **/ template <class VectorType, class GV, size_t r, size_t rC, class R> std::enable_if_t<XT::LA::is_vector<VectorType>::value, DiscreteFunction<VectorType, GV, r, rC, R>> default_interpolation( const int source_order, const std::function<typename XT::Functions::GenericFunction<GV::dimension, r, rC, R>::RangeReturnType( const typename XT::Functions::GenericFunction<GV::dimension, r, rC, R>::DomainType&, const XT::Common::Parameter&)> source_evaluate_lambda, const SpaceInterface<GV, r, rC, R>& target_space) { return default_interpolation<VectorType>( XT::Functions::GenericFunction<GV::dimension, r, rC, R>(source_order, source_evaluate_lambda), target_space); } } // namespace GDT } // namespace Dune #endif // DUNE_GDT_INTERPOLATIONS_DEFAULT_HH <|endoftext|>
<commit_before>#pragma once #include <utility> template <class Func> class Defer { Func func_; public: Defer(Func func) : func_(std::move(func)) {} Defer(const Defer&) = delete; Defer(Defer&&) = delete; Defer& operator=(const Defer&) = delete; Defer& operator=(Defer&&) = delete; ~Defer() { try { func_(); } catch (...) { } } }; <commit_msg>defer.hh: fixed handling exceptions when moving func<commit_after>#pragma once #include <utility> template <class Func> class Defer { Func func_; public: Defer(Func func) try : func_(std::move(func)) { } catch (...) { func(); throw; } Defer(const Defer&) = delete; Defer(Defer&&) = delete; Defer& operator=(const Defer&) = delete; Defer& operator=(Defer&&) = delete; ~Defer() { try { func_(); } catch (...) { } } }; <|endoftext|>
<commit_before>/** * \file */ #pragma once #include <rleahylib/rleahylib.hpp> #include <functional> #include <type_traits> /** * \cond */ namespace std { template <> struct hash<String> { public: size_t operator () (String str) const { // Normalize string str.Normalize(NormalizationForm::NFC); // djb2 size_t retr=5381; for (auto cp : str.CodePoints()) { retr*=33; retr^=cp; } return retr; } }; template <> struct hash<IPAddress> { public: size_t operator () (IPAddress ip) const noexcept { // Is this an IPv4 or IPv6 // address? if (ip.IsV6()) { // This static assert ensures the operation // planned will work static_assert( (sizeof(UInt128)%sizeof(size_t))==0, "Hash for IP addresses not compatible with integer sizes on this platform" ); union { UInt128 raw_ip; size_t split [sizeof(UInt128)/sizeof(size_t)]; }; raw_ip=static_cast<UInt128>(ip); size_t retr=23; for (auto m : split) { retr*=31; retr+=m; } return retr; } // Just return the IPv4 address // to use as the hash return static_cast<size_t>( static_cast<UInt32>(ip) ); } }; template <typename... Args> struct hash<Tuple<Args...>> { private: template <Word i> typename std::enable_if< i<sizeof...(Args), size_t >::type compute_hash (size_t curr, const Tuple<Args...> & t) const { curr*=31; curr+=std::hash< typename std::decay< decltype(t.template Item<i>()) >::type >()(t.template Item<i>()); return compute_hash<i+1>(curr,t); } template <Word i> typename std::enable_if< i>=sizeof...(Args), size_t >::type compute_hash (size_t curr, const Tuple<Args...> &) const noexcept { return curr; } public: size_t operator () (const Tuple<Args...> & t) const { return compute_hash<0>(23,t); } }; template <typename T> struct hash<SmartPointer<T>> { public: size_t operator () (const SmartPointer<T> & sp) const noexcept { return hash<const T *>()(static_cast<const T *>(sp)); } }; } /** * \endcond */ <commit_msg>Hash Changes<commit_after>/** * \file */ #pragma once #include <rleahylib/rleahylib.hpp> #include <functional> #include <type_traits> /** * \cond */ namespace std { template <> struct hash<String> { public: size_t operator () (String str) const { // Normalize string str.Normalize(NormalizationForm::NFC); // djb2 size_t retr=5381; for (auto cp : str.CodePoints()) { retr*=33; retr^=cp; } return retr; } }; template <> struct hash<IPAddress> { public: size_t operator () (IPAddress ip) const noexcept { // Is this an IPv4 or IPv6 // address? if (ip.IsV6()) { // This static assert ensures the operation // planned will work static_assert( (sizeof(UInt128)%sizeof(size_t))==0, "Hash for IP addresses not compatible with integer sizes on this platform" ); union { UInt128 raw_ip; size_t split [sizeof(UInt128)/sizeof(size_t)]; }; raw_ip=static_cast<UInt128>(ip); size_t retr=23; for (auto m : split) { retr*=31; retr+=m; } return retr; } // Just return the IPv4 address // to use as the hash return static_cast<size_t>( static_cast<UInt32>(ip) ); } }; template <typename... Args> struct hash<Tuple<Args...>> { private: template <Word i> typename std::enable_if< i<sizeof...(Args), size_t >::type compute_hash (size_t curr, const Tuple<Args...> & t) const { curr*=31; curr+=std::hash< typename std::decay< decltype(t.template Item<i>()) >::type >()(t.template Item<i>()); return compute_hash<i+1>(curr,t); } template <Word i> typename std::enable_if< i>=sizeof...(Args), size_t >::type compute_hash (size_t curr, const Tuple<Args...> &) const noexcept { return curr; } public: size_t operator () (const Tuple<Args...> & t) const { return compute_hash<0>(23,t); } }; template <typename T> struct hash<Vector<T>> { private: typedef hash<typename std::decay<T>::type> hasher; public: size_t operator () (const Vector<T> & vec) const noexcept( std::is_nothrow_constructible<hasher>::value && noexcept( declval<hasher>()(declval<const T &>()) ) ) { hasher h; size_t retr=(23*31)+vec.Count(); for (const auto & i : vec) { retr*=31; retr+=h(i); } return retr; } }; } /** * \endcond */ <|endoftext|>
<commit_before>// // Copyright (C) 2011-15 DyND Developers // BSD 2-Clause License, see LICENSE.txt // #pragma once #include <Python.h> #include <dynd/type_registry.hpp> #include <type_traits> #include "pyobject_type.hpp" using namespace dynd; // Unpack and convert a single element to a PyObject. template <typename T> inline std::enable_if_t<std::is_signed<T>::value && std::numeric_limits<T>::max() <= INT64_MAX, PyObject *> unpack_single(const char *data) { return PyLong_FromLongLong(*reinterpret_cast<const T *>(data)); } template <typename T> inline std::enable_if_t<std::is_unsigned<T>::value && std::numeric_limits<T>::max() <= UINT64_MAX, PyObject *> unpack_single(const char *data) { return PyLong_FromUnsignedLongLong(*reinterpret_cast<const T *>(data)); } template <typename T> inline std::enable_if_t<std::is_same<T, bool1>::value, PyObject *> unpack_single(const char *data) { return PyBool_FromLong(*reinterpret_cast<const T *>(data)); } template <typename T> inline std::enable_if_t<std::is_same<T, float64>::value, PyObject *> unpack_single(const char *data) { return PyFloat_FromDouble(*reinterpret_cast<const T *>(data)); } template <typename T> inline std::enable_if_t<std::is_same<T, complex128>::value, PyObject *> unpack_single(const char *data) { complex128 c = *reinterpret_cast<const T *>(data); return PyComplex_FromDoubles(c.real(), c.imag()); } template <typename T> inline std::enable_if_t<std::is_same<T, std::string>::value, PyObject *> unpack_single(const char *data) { const std::string &s = *reinterpret_cast<const T *>(data); return PyUnicode_FromString(s.data()); } template <typename T> inline std::enable_if_t<std::is_same<T, ndt::type>::value, PyObject *> unpack_single(const char *data) { return pydynd::type_from_cpp(*reinterpret_cast<const T *>(data)); } // Convert a single element to a PyObject. template <typename T> inline std::enable_if_t<std::is_signed<T>::value && std::numeric_limits<T>::max() <= INT64_MAX, PyObject *> convert_single(T value) { return PyLong_FromLongLong(value); } template <typename T> inline std::enable_if_t<std::is_unsigned<T>::value && std::numeric_limits<T>::max() <= UINT64_MAX, PyObject *> convert_single(T value) { return PyLong_FromUnsignedLongLong(value); } template <typename T> inline std::enable_if_t<std::is_same<T, bool1>::value, PyObject *> convert_single(T value) { return PyBool_FromLong(value); } template <typename T> inline std::enable_if_t<std::is_same<T, float64>::value, PyObject *> convert_single(T value) { return PyFloat_FromDouble(value); } template <typename T> inline std::enable_if_t<std::is_same<T, complex128>::value, PyObject *> convert_single(T value) { return PyComplex_FromDoubles(value.real(), value.imag()); } template <typename T> inline std::enable_if_t<std::is_same<T, std::string>::value, PyObject *> convert_single(const T &value) { return PyUnicode_FromString(value.data()); } template <typename T> inline std::enable_if_t<std::is_same<T, ndt::type>::value, PyObject *> convert_single(const T &value) { return pydynd::type_from_cpp(value); } template <typename T> PyObject *unpack_vector(const char *data) { auto &vec = *reinterpret_cast<const std::vector<T> *>(data); PyObject *lst, *item; lst = PyList_New(vec.size()); if (lst == NULL) { return NULL; } for (size_t i = 0; i < vec.size(); ++i) { item = convert_single<T>(vec[i]); if (item == NULL) { Py_DECREF(lst); return NULL; } PyList_SET_ITEM(lst, i, item); } return lst; } template <typename T> inline PyObject *unpack(bool is_vector, const char *data) { if (is_vector) { return unpack_vector<T>(data); } else { return unpack_single<T>(data); } } PyObject *from_type_property(const std::pair<ndt::type, const char *> &pair) { type_id_t id = pair.first.get_id(); bool is_vector = false; if (id == fixed_dim_id) { id = pair.first.get_dtype().get_id(); is_vector = true; } switch (id) { case bool_id: return unpack<bool1>(is_vector, pair.second); case int8_id: return unpack<int8>(is_vector, pair.second); case int16_id: return unpack<int16>(is_vector, pair.second); case int32_id: return unpack<int32>(is_vector, pair.second); case int64_id: return unpack<int64>(is_vector, pair.second); case uint8_id: return unpack<uint8>(is_vector, pair.second); case uint16_id: return unpack<uint16>(is_vector, pair.second); case uint32_id: return unpack<uint32>(is_vector, pair.second); case uint64_id: return unpack<uint64>(is_vector, pair.second); case float64_id: return unpack<float64>(is_vector, pair.second); case complex_float64_id: return unpack<complex128>(is_vector, pair.second); case type_id: return unpack<ndt::type>(is_vector, pair.second); case string_id: return unpack<std::string>(is_vector, pair.second); default: throw std::runtime_error("invalid type property"); } } <commit_msg>Try a different placement of enable_if_t for Visual Studio.<commit_after>// // Copyright (C) 2011-15 DyND Developers // BSD 2-Clause License, see LICENSE.txt // #pragma once #include <Python.h> #include <dynd/type_registry.hpp> #include <type_traits> #include "pyobject_type.hpp" using namespace dynd; // Unpack and convert a single element to a PyObject. template <typename T, typename std::enable_if_t<std::is_signed<T>::value && std::numeric_limits<T>::max() <= INT64_MAX, int> = 0> inline PyObject * unpack_single(const char *data) { return PyLong_FromLongLong(*reinterpret_cast<const T *>(data)); } template <typename T, std::enable_if_t<std::is_unsigned<T>::value && std::numeric_limits<T>::max() <= UINT64_MAX, int> = 0> inline PyObject * unpack_single(const char *data) { return PyLong_FromUnsignedLongLong(*reinterpret_cast<const T *>(data)); } template <typename T, typename std::enable_if_t<std::is_same<T, bool1>::value, int> = 0> inline PyObject * unpack_single(const char *data) { return PyBool_FromLong(*reinterpret_cast<const T *>(data)); } template <typename T, typename std::enable_if_t<std::is_same<T, float64>::value, int> = 0> inline PyObject * unpack_single(const char *data) { return PyFloat_FromDouble(*reinterpret_cast<const T *>(data)); } template <typename T, typename std::enable_if_t<std::is_same<T, complex128>::value, int> = 0> inline PyObject * unpack_single(const char *data) { complex128 c = *reinterpret_cast<const T *>(data); return PyComplex_FromDoubles(c.real(), c.imag()); } template <typename T, typename std::enable_if_t<std::is_same<T, std::string>::value, int> = 0> inline PyObject * unpack_single(const char *data) { const std::string &s = *reinterpret_cast<const T *>(data); return PyUnicode_FromString(s.data()); } template <typename T, typename std::enable_if_t<std::is_same<T, ndt::type>::value, int> = 0> inline PyObject * unpack_single(const char *data) { return pydynd::type_from_cpp(*reinterpret_cast<const T *>(data)); } // Convert a single element to a PyObject. template <typename T, typename std::enable_if_t<std::is_signed<T>::value && std::numeric_limits<T>::max() <= INT64_MAX, int> = 0> inline PyObject * convert_single(T value) { return PyLong_FromLongLong(value); } template <typename T, typename std::enable_if_t<std::is_unsigned<T>::value && std::numeric_limits<T>::max() <= UINT64_MAX, int> = 0> inline PyObject * convert_single(T value) { return PyLong_FromUnsignedLongLong(value); } template <typename T, typename std::enable_if_t<std::is_same<T, bool1>::value, int> = 0> inline PyObject * convert_single(T value) { return PyBool_FromLong(value); } template <typename T, typename std::enable_if_t<std::is_same<T, float64>::value, int> = 0> inline PyObject * convert_single(T value) { return PyFloat_FromDouble(value); } template <typename T, typename std::enable_if_t<std::is_same<T, complex128>::value, int> = 0> inline PyObject * convert_single(T value) { return PyComplex_FromDoubles(value.real(), value.imag()); } template <typename T, typename std::enable_if_t<std::is_same<T, std::string>::value, int> = 0> inline PyObject * convert_single(const T &value) { return PyUnicode_FromString(value.data()); } template <typename T, typename std::enable_if_t<std::is_same<T, ndt::type>::value, int> = 0> inline PyObject * convert_single(const T &value) { return pydynd::type_from_cpp(value); } template <typename T> PyObject *unpack_vector(const char *data) { auto &vec = *reinterpret_cast<const std::vector<T> *>(data); PyObject *lst, *item; lst = PyList_New(vec.size()); if (lst == NULL) { return NULL; } for (size_t i = 0; i < vec.size(); ++i) { item = convert_single<T>(vec[i]); if (item == NULL) { Py_DECREF(lst); return NULL; } PyList_SET_ITEM(lst, i, item); } return lst; } template <typename T> inline PyObject *unpack(bool is_vector, const char *data) { if (is_vector) { return unpack_vector<T>(data); } else { return unpack_single<T>(data); } } PyObject *from_type_property(const std::pair<ndt::type, const char *> &pair) { type_id_t id = pair.first.get_id(); bool is_vector = false; if (id == fixed_dim_id) { id = pair.first.get_dtype().get_id(); is_vector = true; } switch (id) { case bool_id: return unpack<bool1>(is_vector, pair.second); case int8_id: return unpack<int8>(is_vector, pair.second); case int16_id: return unpack<int16>(is_vector, pair.second); case int32_id: return unpack<int32>(is_vector, pair.second); case int64_id: return unpack<int64>(is_vector, pair.second); case uint8_id: return unpack<uint8>(is_vector, pair.second); case uint16_id: return unpack<uint16>(is_vector, pair.second); case uint32_id: return unpack<uint32>(is_vector, pair.second); case uint64_id: return unpack<uint64>(is_vector, pair.second); case float64_id: return unpack<float64>(is_vector, pair.second); case complex_float64_id: return unpack<complex128>(is_vector, pair.second); case type_id: return unpack<ndt::type>(is_vector, pair.second); case string_id: return unpack<std::string>(is_vector, pair.second); default: throw std::runtime_error("invalid type property"); } } <|endoftext|>
<commit_before>/// \file ROOT/TDrawingOptsBase.hxx /// \ingroup Gpad ROOT7 /// \author Axel Naumann <axel@cern.ch> /// \date 2017-09-26 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TDrawingAttrs #define ROOT7_TDrawingAttrs #include <ROOT/TColor.hxx> #include <RStringView.h> #include <map> #include <string> #include <vector> namespace ROOT { namespace Experimental { class TCanvas; class TPadBase; class TDrawingOptsBaseNoDefault; namespace Internal { template <class PRIMITIVE> class TDrawingAttrTable; } /** \class ROOT::Experimental::TDrawingAttrRef The `TCanvas` keep track of `TColor`s, integer and floating point attributes used by the drawing options, making them accessible from other drawing options. The index into the table of the active attributes is wrapped into `TDrawingAttrRef` to make them type-safe (i.e. distinct for `TColor`, `long long` and `double`). */ template <class PRIMITIVE> class TDrawingAttrRef { private: size_t fIdx = (size_t)-1; ///< The index in the relevant attribute table of `TCanvas`. /// Construct a reference given the index. explicit TDrawingAttrRef(size_t idx): fIdx(idx) {} friend class Internal::TDrawingAttrTable<PRIMITIVE>; public: /// Construct an invalid reference. TDrawingAttrRef() = default; /// Construct a reference from its options object, name, default value and set of string options. /// /// Initializes the PRIMITIVE to the default value, as available in TDrawingOptsBase::GetDefaultCanvas(), /// or to `deflt` if no entry exists under the attribute name. The attribute name is `opts.GetName() + "." + attrName`. /// `optStrings` is only be used if `PRIMITIVE` is `long long`; the style setting is expected to be one of /// the strings, with the attribute's value the index of the string. TDrawingAttrRef(TDrawingOptsBaseNoDefault &opts, const std::string &attrName, const PRIMITIVE &deflt, const std::vector<std::string_view> &optStrings = {}); /// Get the underlying index. operator size_t() const { return fIdx; } /// Whether the reference is valid. explicit operator bool() const { return fIdx != (size_t)-1; } }; extern template class TDrawingAttrRef<TColor>; extern template class TDrawingAttrRef<long long>; extern template class TDrawingAttrRef<double>; namespace Internal { template <class PRIMITIVE> class TDrawingAttrAndUseCount { /// The value. PRIMITIVE fVal; /// The value's use count. size_t fUseCount = 1; /// Clear the value; use count must be 0. void Clear(); public: /// Default constructor: a default-constructed value that is unused. TDrawingAttrAndUseCount(): fVal(), fUseCount(0) {} /// Initialize with a value, setting use count to 1. explicit TDrawingAttrAndUseCount(const PRIMITIVE &val): fVal(val) {} /// Create a value, initializing use count to 1. void Create(const PRIMITIVE &val); /// Increase the use count; use count must be >= 1 before (i.e. does not create or "resurrect" values). void IncrUse(); /// Decrease the use count; use count must be >= 1 before the call. Calls Clear() if use count drops to 0. void DecrUse(); /// Whether the use count is 0 and this object has space for a new value. bool IsFree() const { return fUseCount == 0; } /// Value access (non-const). PRIMITIVE &Get() { return fVal; } /// Value access (const). const PRIMITIVE &Get() const { return fVal; } }; // Only these specializations are used and provided: extern template class TDrawingAttrAndUseCount<TColor>; extern template class TDrawingAttrAndUseCount<long long>; extern template class TDrawingAttrAndUseCount<double>; template <class PRIMITIVE> class TDrawingAttrTable { public: using value_type = Internal::TDrawingAttrAndUseCount<PRIMITIVE>; private: /// Table of attribute primitives. Slots can be freed and re-used. /// Drawing options will reference slots in here through their index. std::vector<value_type> fTable; public: /// Register an attribute with the table. /// \returns the index in the table. TDrawingAttrRef<PRIMITIVE> Register(const PRIMITIVE &val); /// Add a use of the attribute at table index idx. void IncrUse(TDrawingAttrRef<PRIMITIVE> idx) { fTable[idx].IncrUse(); } /// Remove a use of the attribute at table index idx. void DecrUse(TDrawingAttrRef<PRIMITIVE> idx) { fTable[idx].DecrUse(); } /// Update an existing attribute entry in the table. void Update(TDrawingAttrRef<PRIMITIVE> idx, const PRIMITIVE &val) { fTable[idx] = value_type(val); } /// Get the value at index `idx` (const version). const PRIMITIVE &Get(TDrawingAttrRef<PRIMITIVE> idx) const { return fTable[idx].Get(); } /// Get the value at index `idx` (non-const version). PRIMITIVE &Get(TDrawingAttrRef<PRIMITIVE> idx) { return fTable[idx].Get(); } /// Find the index belonging to the attribute at the given address and add a use. /// \returns the reference to `val`, which might be `IsInvalid()` if `val` is not part of this table. TDrawingAttrRef<PRIMITIVE> SameAs(const PRIMITIVE &val); /// Access to the underlying attribute table (non-const version). std::vector<value_type> &GetTable() { return fTable; } /// Access to the underlying attribute table (const version). const std::vector<value_type> &GetTable() const { return fTable; } }; extern template class TDrawingAttrTable<TColor>; extern template class TDrawingAttrTable<long long>; extern template class TDrawingAttrTable<double>; } // namespace Internal class TLineAttrs { TOptsAttrRef<TColor> fColor{*this} public: TLineAttrs(TPadBase &pad, const std::vector<string_view> &configPrefix) = default; /// Construct from the pad that holds our `TDrawable`, passing the parent config prefix. /// TLineDrawingOpts will add a `"Line"` element to the config prefix. TLineDrawingOpts(TPadBase &pad, string_view configPrefix): TDrawingOptsBase(pad, AddPrefix(configPrefix, "Line")) {} }; } // namespace Experimental } // namespace ROOT #endif // ROOT7_TDrawingAttrs <commit_msg>Add TLineAttrs, TFillAttrs.<commit_after>/// \file ROOT/TDrawingOptsBase.hxx /// \ingroup Gpad ROOT7 /// \author Axel Naumann <axel@cern.ch> /// \date 2017-09-26 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TDrawingAttrs #define ROOT7_TDrawingAttrs #include <ROOT/TColor.hxx> #include <RStringView.h> #include <map> #include <string> #include <vector> namespace ROOT { namespace Experimental { class TCanvas; class TPadBase; class TDrawingOptsBaseNoDefault; namespace Internal { template <class PRIMITIVE> class TDrawingAttrTable; } /** \class ROOT::Experimental::TDrawingAttrRef The `TCanvas` keep track of `TColor`s, integer and floating point attributes used by the drawing options, making them accessible from other drawing options. The index into the table of the active attributes is wrapped into `TDrawingAttrRef` to make them type-safe (i.e. distinct for `TColor`, `long long` and `double`). */ template <class PRIMITIVE> class TDrawingAttrRef { private: size_t fIdx = (size_t)-1; ///< The index in the relevant attribute table of `TCanvas`. /// Construct a reference given the index. explicit TDrawingAttrRef(size_t idx): fIdx(idx) {} friend class Internal::TDrawingAttrTable<PRIMITIVE>; public: /// Construct an invalid reference. TDrawingAttrRef() = default; /// Construct a reference from its options object, name, default value and set of string options. /// /// Initializes the PRIMITIVE to the default value, as available in TDrawingOptsBase::GetDefaultCanvas(), /// or to `deflt` if no entry exists under the attribute name. The attribute name is `opts.GetName() + "." + attrName`. /// `optStrings` is only be used if `PRIMITIVE` is `long long`; the style setting is expected to be one of /// the strings, with the attribute's value the index of the string. TDrawingAttrRef(TDrawingOptsBaseNoDefault &opts, const std::string &attrName, const PRIMITIVE &deflt, const std::vector<std::string_view> &optStrings = {}); /// Get the underlying index. operator size_t() const { return fIdx; } /// Whether the reference is valid. explicit operator bool() const { return fIdx != (size_t)-1; } }; extern template class TDrawingAttrRef<TColor>; extern template class TDrawingAttrRef<long long>; extern template class TDrawingAttrRef<double>; namespace Internal { template <class PRIMITIVE> class TDrawingAttrAndUseCount { /// The value. PRIMITIVE fVal; /// The value's use count. size_t fUseCount = 1; /// Clear the value; use count must be 0. void Clear(); public: /// Default constructor: a default-constructed value that is unused. TDrawingAttrAndUseCount(): fVal(), fUseCount(0) {} /// Initialize with a value, setting use count to 1. explicit TDrawingAttrAndUseCount(const PRIMITIVE &val): fVal(val) {} /// Create a value, initializing use count to 1. void Create(const PRIMITIVE &val); /// Increase the use count; use count must be >= 1 before (i.e. does not create or "resurrect" values). void IncrUse(); /// Decrease the use count; use count must be >= 1 before the call. Calls Clear() if use count drops to 0. void DecrUse(); /// Whether the use count is 0 and this object has space for a new value. bool IsFree() const { return fUseCount == 0; } /// Value access (non-const). PRIMITIVE &Get() { return fVal; } /// Value access (const). const PRIMITIVE &Get() const { return fVal; } }; // Only these specializations are used and provided: extern template class TDrawingAttrAndUseCount<TColor>; extern template class TDrawingAttrAndUseCount<long long>; extern template class TDrawingAttrAndUseCount<double>; template <class PRIMITIVE> class TDrawingAttrTable { public: using value_type = Internal::TDrawingAttrAndUseCount<PRIMITIVE>; private: /// Table of attribute primitives. Slots can be freed and re-used. /// Drawing options will reference slots in here through their index. std::vector<value_type> fTable; public: /// Register an attribute with the table. /// \returns the index in the table. TDrawingAttrRef<PRIMITIVE> Register(const PRIMITIVE &val); /// Add a use of the attribute at table index idx. void IncrUse(TDrawingAttrRef<PRIMITIVE> idx) { fTable[idx].IncrUse(); } /// Remove a use of the attribute at table index idx. void DecrUse(TDrawingAttrRef<PRIMITIVE> idx) { fTable[idx].DecrUse(); } /// Update an existing attribute entry in the table. void Update(TDrawingAttrRef<PRIMITIVE> idx, const PRIMITIVE &val) { fTable[idx] = value_type(val); } /// Get the value at index `idx` (const version). const PRIMITIVE &Get(TDrawingAttrRef<PRIMITIVE> idx) const { return fTable[idx].Get(); } /// Get the value at index `idx` (non-const version). PRIMITIVE &Get(TDrawingAttrRef<PRIMITIVE> idx) { return fTable[idx].Get(); } /// Find the index belonging to the attribute at the given address and add a use. /// \returns the reference to `val`, which might be `IsInvalid()` if `val` is not part of this table. TDrawingAttrRef<PRIMITIVE> SameAs(const PRIMITIVE &val); /// Access to the underlying attribute table (non-const version). std::vector<value_type> &GetTable() { return fTable; } /// Access to the underlying attribute table (const version). const std::vector<value_type> &GetTable() const { return fTable; } }; extern template class TDrawingAttrTable<TColor>; extern template class TDrawingAttrTable<long long>; extern template class TDrawingAttrTable<double>; } // namespace Internal struct TLineAttrs { TDrawingAttrRef<TColor> fColor; ///< Line color TDrawingAttrRef<long long> fWidth; ///< Line width struct Width { long long fVal; explicit operator long long() const { return fVal; } }; /// Construct from the pad that holds our `TDrawable`, passing the configuration name of this line attribute. TLineAttrs(TDrawingOptsBaseNoDefault &opts, const std::string &name, const TColor &col, Width width) : fColor(opts, name + ".Color", col), fWidth(opts, name + ".Width", (long long)width) {} }; struct TFillAttrs { TDrawingAttrRef<TColor> fColor; ///< Line color /// Construct from the pad that holds our `TDrawable`, passing the configuration name of this line attribute. TFillAttrs(TDrawingOptsBaseNoDefault &opts, const std::string &name, const TColor &col) : fColor(opts, name + ".Color", col) {} }; } // namespace Experimental } // namespace ROOT #endif // ROOT7_TDrawingAttrs <|endoftext|>
<commit_before><commit_msg>Influxdb: don't remove comas in get_data().<commit_after><|endoftext|>
<commit_before>// https://www.hackerrank.com/contests/w19/challenges/two-robots // Two Robots #include <iostream> #include <cstdlib> #include <map> using namespace std; class Node { public: Node(int _a = -1, int _b = -1) : a(_a), b(_b) {} int a, b; bool operator <(const Node &n) const { return (a == n.a ? b < n.b : a < n.a); } }; int m, n; int in[1000][2]; map<Node, int> mm; void input() { cin >> m >> n; for (int i = 0; i < n; i++) { cin >> in[i][0] >> in[i][1]; } } void solve() { mm[Node(-1, -1)] = 0; for (int i = 0; i < n; i++) { map<Node, int> temp; for (auto &x: mm) { int a = x.first.a; int b = x.first.b; int dist = x.second; const int &from = in[i][0]; const int &to = in[i][1]; int dist1 = (a == -1 ? 0 : abs(from - a)) + abs(to - from) + dist; int dist2 = (b == -1 ? 0 : abs(from - b)) + abs(to - from) + dist; // move a { Node node(min(to,b), max(to,b)); if (temp.find(node) == temp.end()) { temp[Node(node)] = dist1; } else { temp[node] = min(temp[node], dist1); } } // move b { Node node(min(a, to), max(a, to)); if (temp.find(node) == temp.end()) { temp[node] = dist2; } else { temp[node] = min(temp[node], dist2); } } } mm.swap(temp); } int best = 0x00FFFFFF; for (auto &x : mm) { best = min(best, x.second); } cout << best << endl; } int main() { int t; cin >> t; while (t--) { input(); solve(); } return 0; } <commit_msg>improve performance<commit_after>// https://www.hackerrank.com/contests/w19/challenges/two-robots // Two Robots #include <iostream> #include <cstdlib> #include <map> using namespace std; class Node { public: Node(int _a = -1, int _b = -1) : a(_a), b(_b) {} int a, b; bool operator <(const Node &n) const { return (a == n.a ? b < n.b : a < n.a); } }; int m, n; int in[1000][2]; map<Node, int> mm; void input() { cin >> m >> n; for (int i = 0; i < n; i++) { cin >> in[i][0] >> in[i][1]; } } void solve() { mm[Node(0, 0)] = 0; for (int i = 0; i < n; i++) { map<Node, int> temp; for (auto &x: mm) { const int &a = x.first.a; const int &b = x.first.b; const int &dist = x.second; const int &from = in[i][0]; const int &to = in[i][1]; int dist1 = (a == 0 ? 0 : abs(from - a)) + abs(to - from) + dist; int dist2 = (b == 0 ? 0 : abs(from - b)) + abs(to - from) + dist; Node node; // move a { if (to < b) { node.a = to; node.b = b;} else { node.a = b; node.b = to; } auto it = temp.find(node); if (it == temp.end()) { temp[node] = dist1; } else { it->second = min(it->second, dist1); } } // move b { if (to < a) { node.a = to; node.b = a;} else { node.a = a; node.b = to; } auto it = temp.find(node); if (it == temp.end()) { temp[node] = dist2; } else { it->second = min(it->second, dist2); } } } mm.swap(temp); } int best = 0x00FFFFFF; for (auto &x : mm) { best = min(best, x.second); } cout << best << endl; } int main() { int t; cin >> t; while (t--) { input(); solve(); } return 0; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "linear_mixer.hpp" #include <iostream> #include "../mixable.hpp" using namespace std; using pfi::lang::shared_ptr; namespace jubatus { namespace framework { namespace mixer { namespace { vector<string> make_vector(const string& s) { vector<string> v; v.push_back(s); return v; } jubatus::common::mprpc::rpc_response_t make_response(const string& s) { jubatus::common::mprpc::rpc_response_t res; res.zone = shared_ptr<msgpack::zone>(new msgpack::zone); res.response.a3 = msgpack::object(make_vector(s), res.zone.get()); return res; } } class linear_communication_stub : public linear_communication { public: size_t update_members() { return 4; } pfi::lang::shared_ptr<common::try_lockable> create_lock() {} void get_diff(common::mprpc::rpc_result_object& result) const { result.response.push_back(make_response("1")); result.response.push_back(make_response("2")); result.response.push_back(make_response("3")); result.response.push_back(make_response("4")); } void put_diff(const vector<string>& mixed) const { mixed_ = mixed; } const vector<string>& get_mixed() const { return mixed_; } private: mutable vector<string> mixed_; }; struct mixable_string : public mixable0 { public: string get_diff() const { return string(); } void put_diff(const string&) {} void mix(const string& lhs, const string& rhs, string& mixed) const { stringstream ss; ss << "(" << lhs << "+" << rhs << ")"; mixed = ss.str(); } void save(ostream&) {} void load(istream&) {} void clear() {} }; TEST(linear_mixer, mix_order) { shared_ptr<linear_communication_stub> com(new linear_communication_stub); linear_mixer m(com, 1, 1); pfi::lang::shared_ptr<mixable_holder> holder(new mixable_holder()); m.set_mixable_holder(holder); mixable_string s; holder->register_mixable(&s); m.mix(); vector<string> mixed = com->get_mixed(); ASSERT_EQ(1u, mixed.size()); EXPECT_EQ("(4+(3+(2+1)))", mixed[0]); } } } } <commit_msg>Eliminate warning in linear_mixer_test<commit_after>#include <gtest/gtest.h> #include "linear_mixer.hpp" #include <iostream> #include "../mixable.hpp" using namespace std; using pfi::lang::shared_ptr; namespace jubatus { namespace framework { namespace mixer { namespace { vector<string> make_vector(const string& s) { vector<string> v; v.push_back(s); return v; } jubatus::common::mprpc::rpc_response_t make_response(const string& s) { jubatus::common::mprpc::rpc_response_t res; res.zone = shared_ptr<msgpack::zone>(new msgpack::zone); res.response.a3 = msgpack::object(make_vector(s), res.zone.get()); return res; } } class linear_communication_stub : public linear_communication { public: size_t update_members() { return 4; } pfi::lang::shared_ptr<common::try_lockable> create_lock() { return pfi::lang::shared_ptr<common::try_lockable>(); } void get_diff(common::mprpc::rpc_result_object& result) const { result.response.push_back(make_response("1")); result.response.push_back(make_response("2")); result.response.push_back(make_response("3")); result.response.push_back(make_response("4")); } void put_diff(const vector<string>& mixed) const { mixed_ = mixed; } const vector<string>& get_mixed() const { return mixed_; } private: mutable vector<string> mixed_; }; struct mixable_string : public mixable0 { public: string get_diff() const { return string(); } void put_diff(const string&) {} void mix(const string& lhs, const string& rhs, string& mixed) const { stringstream ss; ss << "(" << lhs << "+" << rhs << ")"; mixed = ss.str(); } void save(ostream&) {} void load(istream&) {} void clear() {} }; TEST(linear_mixer, mix_order) { shared_ptr<linear_communication_stub> com(new linear_communication_stub); linear_mixer m(com, 1, 1); pfi::lang::shared_ptr<mixable_holder> holder(new mixable_holder()); m.set_mixable_holder(holder); mixable_string s; holder->register_mixable(&s); m.mix(); vector<string> mixed = com->get_mixed(); ASSERT_EQ(1u, mixed.size()); EXPECT_EQ("(4+(3+(2+1)))", mixed[0]); } } } } <|endoftext|>
<commit_before>#include "gui/qrchaosmainwindow.h" #include <QtCore/qdebug.h> #include <QtWidgets/qaction.h> #include <QtWidgets/qdesktopwidget.h> #include <QtWidgets/qapplication.h> #include "gui/framewindow/qrframewindow.h" #include "gui/qrworkspace.h" #include "gui/qrstatusbar.h" NS_CHAOS_BASE_BEGIN class QrChaosMainwindowPrivate { QR_DECLARE_PUBLIC(QrChaosMainwindow) public: QrChaosMainwindowPrivate(QrChaosMainwindow* q):q_ptr(q){} public: void loadUIFramework(); void initShortcuts(); void setMiniumSize(); public: QrFrameWindow *frameWindow = nullptr; }; void QrChaosMainwindowPrivate::loadUIFramework() { Q_Q(QrChaosMainwindow); frameWindow = new QrFrameWindow(q); q->setCentralWidget(frameWindow); } void QrChaosMainwindowPrivate::initShortcuts() { Q_Q(QrChaosMainwindow); auto quickCloseWorkspace = new QAction(q); quickCloseWorkspace->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_W)); q->addAction(quickCloseWorkspace); QObject::connect(quickCloseWorkspace, &QAction::triggered, [this](){ auto workspace = this->frameWindow->getWorkspace(); workspace->removeTab(workspace->currentIndex()); }); auto quickSwitchWorkspace = new QAction(q); quickSwitchWorkspace->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Tab)); q->addAction(quickSwitchWorkspace); QObject::connect(quickSwitchWorkspace, &QAction::triggered, [this](){ auto workspace = this->frameWindow->getWorkspace(); workspace->setCurrentIndex((workspace->currentIndex()+1) % workspace->count()); }); // TODO auto switchNormalMode = new QAction(q); switchNormalMode->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1)); q->addAction(switchNormalMode); QObject::connect(switchNormalMode, &QAction::triggered, this->frameWindow->getStatusbar(), &QrStatusBar::onNormalMode); auto switchSimpleMode = new QAction(q); switchSimpleMode->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2)); q->addAction(switchSimpleMode); QObject::connect(switchSimpleMode, &QAction::triggered, this->frameWindow->getStatusbar(), &QrStatusBar::onSimpleMode); auto switchFullMode = new QAction(q); switchFullMode->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3)); q->addAction(switchFullMode); QObject::connect(switchFullMode, &QAction::triggered, this->frameWindow->getStatusbar(), &QrStatusBar::onFullScreenMode); } void QrChaosMainwindowPrivate::setMiniumSize() { Q_Q(QrChaosMainwindow); const QRect& screenRect = QApplication::desktop()->availableGeometry(); QSize scrSize(screenRect.width()*0.6,screenRect.height()*0.6); q->setMinimumSize(scrSize); } NS_CHAOS_BASE_END USING_NS_CHAOS_BASE; QrChaosMainwindow::QrChaosMainwindow(QWidget* parent) : QrMainWindow(parent), d_ptr(new QrChaosMainwindowPrivate(this)) { setWindowFlags(Qt::FramelessWindowHint); } QrFrameWindow *QrChaosMainwindow::getFrameWindow() { Q_D(QrChaosMainwindow); return d->frameWindow; } bool QrChaosMainwindow::init() { Q_D(QrChaosMainwindow); d->loadUIFramework(); d->initShortcuts(); d->setMiniumSize(); return true; } <commit_msg>not set minimumsize to chaos mainwindow<commit_after>#include "gui/qrchaosmainwindow.h" #include <QtCore/qdebug.h> #include <QtWidgets/qaction.h> #include <QtWidgets/qdesktopwidget.h> #include <QtWidgets/qapplication.h> #include "gui/framewindow/qrframewindow.h" #include "gui/qrworkspace.h" #include "gui/qrstatusbar.h" NS_CHAOS_BASE_BEGIN class QrChaosMainwindowPrivate { QR_DECLARE_PUBLIC(QrChaosMainwindow) public: QrChaosMainwindowPrivate(QrChaosMainwindow* q):q_ptr(q){} public: void loadUIFramework(); void initShortcuts(); void initSize(); public: QrFrameWindow *frameWindow = nullptr; }; void QrChaosMainwindowPrivate::loadUIFramework() { Q_Q(QrChaosMainwindow); frameWindow = new QrFrameWindow(q); q->setCentralWidget(frameWindow); } void QrChaosMainwindowPrivate::initShortcuts() { Q_Q(QrChaosMainwindow); auto quickCloseWorkspace = new QAction(q); quickCloseWorkspace->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_W)); q->addAction(quickCloseWorkspace); QObject::connect(quickCloseWorkspace, &QAction::triggered, [this](){ auto workspace = this->frameWindow->getWorkspace(); workspace->removeTab(workspace->currentIndex()); }); auto quickSwitchWorkspace = new QAction(q); quickSwitchWorkspace->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Tab)); q->addAction(quickSwitchWorkspace); QObject::connect(quickSwitchWorkspace, &QAction::triggered, [this](){ auto workspace = this->frameWindow->getWorkspace(); workspace->setCurrentIndex((workspace->currentIndex()+1) % workspace->count()); }); // TODO auto switchNormalMode = new QAction(q); switchNormalMode->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1)); q->addAction(switchNormalMode); QObject::connect(switchNormalMode, &QAction::triggered, this->frameWindow->getStatusbar(), &QrStatusBar::onNormalMode); auto switchSimpleMode = new QAction(q); switchSimpleMode->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2)); q->addAction(switchSimpleMode); QObject::connect(switchSimpleMode, &QAction::triggered, this->frameWindow->getStatusbar(), &QrStatusBar::onSimpleMode); auto switchFullMode = new QAction(q); switchFullMode->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3)); q->addAction(switchFullMode); QObject::connect(switchFullMode, &QAction::triggered, this->frameWindow->getStatusbar(), &QrStatusBar::onFullScreenMode); } void QrChaosMainwindowPrivate::initSize() { Q_Q(QrChaosMainwindow); const QRect& screenRect = QApplication::desktop()->availableGeometry(); QSize scrSize(screenRect.width()*0.6,screenRect.height()*0.6); q->resize(scrSize); } NS_CHAOS_BASE_END USING_NS_CHAOS_BASE; QrChaosMainwindow::QrChaosMainwindow(QWidget* parent) : QrMainWindow(parent), d_ptr(new QrChaosMainwindowPrivate(this)) { setWindowFlags(Qt::FramelessWindowHint); } QrFrameWindow *QrChaosMainwindow::getFrameWindow() { Q_D(QrChaosMainwindow); return d->frameWindow; } bool QrChaosMainwindow::init() { Q_D(QrChaosMainwindow); d->loadUIFramework(); d->initShortcuts(); d->initSize(); return true; } <|endoftext|>
<commit_before>#if !defined(DOUBLETAKE_XSYNC_H) #define DOUBLETAKE_XSYNC_H /* * @file xsync.h * @brief Mapping between pthread_t and internal thread information. * @author Tongping Liu <http://www.cs.umass.edu/~tonyliu> */ #include <assert.h> #include <pthread.h> #include <stddef.h> #include "globalinfo.hh" #include "hashfuncs.hh" #include "hashmap.hh" #include "internalheap.hh" #include "list.hh" #include "log.hh" #include "mm.hh" #include "recordentries.hh" #include "semaphore.hh" #include "spinlock.hh" #include "synceventlist.hh" #include "threadstruct.hh" #include "xdefines.hh" class xsync { struct SyncEntry { void* realEntry; SyncEventList* list; }; public: xsync() {} void initialize() { _syncvars.initialize(HashFuncs::hashAddr, HashFuncs::compareAddr, xdefines::SYNCMAP_SIZE); } void insertSyncMap(void* key, void* realentry, SyncEventList* list) { struct SyncEntry* entry = (struct SyncEntry*)InternalHeap::getInstance().malloc(sizeof(struct SyncEntry)); entry->realEntry = realentry; entry->list = list; _syncvars.insert(key, sizeof(key), entry); PRINF("insertSyncMap entry %p entry %p\n", realentry, entry); } void deleteMap(void* key) { struct SyncEntry* entry; if(_syncvars.find(key, sizeof(key), &entry)) { InternalHeap::getInstance().free(entry); } _syncvars.erase(key, sizeof(void*)); } // Signal next thread on the same synchronization variable. void signalNextThread(struct syncEvent* event) { thread_t* thread = (thread_t*)event->thread; // Whether this event is on the top of thread? if(isThreadNextEvent(event, thread)) { // If yes, signal to this thread. There is no difference between // current thread or other thread. signalThread(thread); PRINF("Thread %d actually signal next thread %d on event %p", current->index, thread->index, event); } else { PRINF("Thread %d adding pending event to next thread %d on event %p", current->index, thread->index, event); addPendingSyncEvent(event, thread); } } // Signal current thread if event is one of pending events. void signalCurrentThread(struct syncEvent* event) { thread_t* thread = (thread_t*)event->thread; list_t* eventlist = &thread->pendingSyncevents; assert(thread == current); // PRINF("singalCurrentThread: event %p on variable %p command %d", event, // event->eventlist->getSyncVariable(), event->eventlist->getSyncCmd()); if(!isListEmpty(eventlist)) { // PRINF("singalCurrentThread: event %p thread %p, pending list is not empty!!!\n", event, // thread); // Only signal itself when current event is first event of this thread. struct pendingSyncEvent* pe = NULL; // Search the whole list for given tid. pe = (struct pendingSyncEvent*)nextEntry(eventlist); while(true) { // We found this event if(pe->event == event) { PRINF("singalCurrentThread: signal myself, retrieve event %p pe->event %p", event, pe->event); // Remove this event from the list. listRemoveNode(&pe->list); // Release corresponding memory to avoid memory leakage. InternalHeap::getInstance().free(pe); // Now signal current thread. signalThread(thread); break; } // Update to the next thread. if(isListTail(&pe->list, eventlist)) { break; } else { pe = (struct pendingSyncEvent*)nextEntry(&pe->list); } } // while (true) } else { PRINF("thread pending list is empty now!!!"); } } // Update the synchronization list. void advanceThreadSyncList() { struct syncEvent* nextEvent = NULL; global_lock(); // Update next event of thread eventlist. nextEvent = current->syncevents.nextIterEntry(); if(nextEvent != NULL) { signalCurrentThread(nextEvent); } global_unlock(); } // peekSyncEvent return the saved event value for current synchronization. inline int peekSyncEvent() { int result = -1; struct syncEvent* event = (struct syncEvent*)current->syncevents.getEntry(); if(event) { REQUIRE(event->thread == current, "Event %p belongs to thread %p, not the current thread (%p)", event, event->thread, current); result = event->ret; } else { // ERROR("Event not exising now at thread %p!!!!\n", current); } return result; } void cleanSyncEvents() { // Remove all events in the global map and event list. syncvarsHashMap::iterator i; for(i = _syncvars.begin(); i != _syncvars.end(); i++) { struct SyncEntry* entry = (struct SyncEntry*)i.getData(); SyncEventList* eventlist = (SyncEventList*)entry->list; PRINF("cleaningup the eventlist %p!!!\n", eventlist); eventlist->cleanup(); } } inline void setSyncVariable(void** syncvariable, void* realvariable) { *syncvariable = realvariable; } /* Prepare rollback. Only one thread can call this function. It basically check every synchronization variable. If a synchronization variable is in the head of a thread, then we try to UP corresponding thread's semaphore. */ void prepareRollback() { syncvarsHashMap::iterator i; struct SyncEntry* entry; SyncEventList* eventlist = NULL; void* syncvariable; for(i = _syncvars.begin(); i != _syncvars.end(); i++) { syncvariable = i.getkey(); entry = (struct SyncEntry*)i.getData(); PRINF("prepareRollback syncvariable %p pointintto %p entry %p realentry %p\n", syncvariable, (*((void **)syncvariable)), entry, entry->realEntry); // If syncvariable is not equal to the entry->realEntry, // those are mutex locks, conditional variables or mutexlocks // The starting address of tose variables are cleaning up at epochBegin() (by backingup) // We have to make them to pointing to actual synchronization entries since there are not // mutex_init or something else. if((*((void **)syncvariable)) != entry->realEntry) { // Setting the address setSyncVariable((void**)syncvariable, entry->realEntry); } eventlist = entry->list; prepareEventListRollback(eventlist); } } /* Prepare the rollback for an event list. It will check whether the first event in the event list is also the head of specific thread. If yes, then we will signal specific thread so that this thread can acquire the semaphore immediately. */ inline void prepareEventListRollback(SyncEventList* eventlist) { struct syncEvent* event = eventlist->prepareRollback(); PRINF("prepareEventListRollback eventlist %p event %p\n", eventlist, event); if(event) { // Signal to next thread with the top event signalNextThread(event); } } // Add one synchronization event into the pending list of a thread. void addPendingSyncEvent(struct syncEvent* event, thread_t* thread) { struct pendingSyncEvent* pendingEvent = NULL; pendingEvent = (struct pendingSyncEvent*)InternalHeap::getInstance().malloc( sizeof(struct pendingSyncEvent)); listInit(&pendingEvent->list); pendingEvent->event = event; // Add this pending event into corresponding thread. listInsertTail(&pendingEvent->list, &thread->pendingSyncevents); } // Check whether this event is the first event of corresponding thread. bool isThreadNextEvent(struct syncEvent* event, thread_t* thread) { return (event == thread->syncevents.firstIterEntry()); } void signalThread(thread_t* thread) { semaphore* sema = &thread->sema; PRINF("Signal semaphore to thread%d (at %p)\n", thread->index, thread); sema->put(); } private: size_t getThreadSyncSeqNum() { return 0; } semaphore* getThreadSemaphore(thread_t* thread) { return &thread->sema; } // We are maintainning a private hash map for each thread. typedef HashMap<void*, struct SyncEntry*, spinlock, InternalHeapAllocator> syncvarsHashMap; // Synchronization related to different sync variable should be recorded into // the synchronization variable related list. syncvarsHashMap _syncvars; }; #endif <commit_msg>Adding the lock protection for pendingSyncevents to avoid race<commit_after>#if !defined(DOUBLETAKE_XSYNC_H) #define DOUBLETAKE_XSYNC_H /* * @file xsync.h * @brief Mapping between pthread_t and internal thread information. * @author Tongping Liu <http://www.cs.umass.edu/~tonyliu> */ #include <assert.h> #include <pthread.h> #include <stddef.h> #include "globalinfo.hh" #include "hashfuncs.hh" #include "hashmap.hh" #include "internalheap.hh" #include "list.hh" #include "log.hh" #include "mm.hh" #include "recordentries.hh" #include "semaphore.hh" #include "spinlock.hh" #include "synceventlist.hh" #include "threadstruct.hh" #include "xdefines.hh" class xsync { struct SyncEntry { void* realEntry; SyncEventList* list; }; public: xsync() {} void initialize() { _syncvars.initialize(HashFuncs::hashAddr, HashFuncs::compareAddr, xdefines::SYNCMAP_SIZE); } void insertSyncMap(void* key, void* realentry, SyncEventList* list) { struct SyncEntry* entry = (struct SyncEntry*)InternalHeap::getInstance().malloc(sizeof(struct SyncEntry)); entry->realEntry = realentry; entry->list = list; _syncvars.insert(key, sizeof(key), entry); PRINF("insertSyncMap entry %p entry %p\n", realentry, entry); } void deleteMap(void* key) { struct SyncEntry* entry; if(_syncvars.find(key, sizeof(key), &entry)) { InternalHeap::getInstance().free(entry); } _syncvars.erase(key, sizeof(void*)); } // Signal next thread on the same synchronization variable. void signalNextThread(struct syncEvent* event) { thread_t* thread = (thread_t*)event->thread; // Acquire the lock before adding an event to the pending list // since the thread may try to check whether it can proceed or not lock_thread(thread); // Add this pending event into corresponding thread. // Whether this event is on the top of thread? if(isThreadNextEvent(event, thread)) { // If yes, signal to this thread. There is no difference between // current thread or other thread. PRINT("Thread %d actually signal next thread %d on event %p", current->index, thread->index, event); signalThread(thread); } else { PRINT("Thread %d adding pending event to next thread %d on event %p", current->index, thread->index, event); addPendingSyncEvent(event, thread); } unlock_thread(thread); } // Signal current thread if event is one of pending events. void signalCurrentThread(struct syncEvent* event) { thread_t* thread = (thread_t*)event->thread; list_t* eventlist = &thread->pendingSyncevents; assert(thread == current); lock_thread(current); if(!isListEmpty(eventlist)) { // PRINF("singalCurrentThread: event %p thread %p, pending list is not empty!!!\n", event, // thread); // Only signal itself when current event is first event of this thread. struct pendingSyncEvent* pe = NULL; // Search the whole list for given tid. pe = (struct pendingSyncEvent*)nextEntry(eventlist); while(true) { // We found this event if(pe->event == event) { PRINT("singalCurrentThread: signal myself thread %d, retrieve event %p pe->event %p", current->index, event, pe->event); // Remove this event from the list. listRemoveNode(&pe->list); // Release corresponding memory to avoid memory leakage. InternalHeap::getInstance().free(pe); // Now signal current thread. signalThread(thread); PRINT("singalCurrentThread %d: event %p", thread->index, event); break; } // Update to the next thread. if(isListTail(&pe->list, eventlist)) { break; } else { pe = (struct pendingSyncEvent*)nextEntry(&pe->list); } } // while (true) } else { PRINF("thread pending list is empty now!!!"); } unlock_thread(current); } // Update the synchronization list. void advanceThreadSyncList() { struct syncEvent* nextEvent = NULL; global_lock(); // Update next event of thread eventlist. nextEvent = current->syncevents.nextIterEntry(); if(nextEvent != NULL) { signalCurrentThread(nextEvent); } global_unlock(); } // peekSyncEvent return the saved event value for current synchronization. inline int peekSyncEvent(void* tlist) { int result = -1; struct syncEvent* event = (struct syncEvent*)current->syncevents.getEntry(); PRINT("peekSyncEvent at thread %d: event %p event thread %d\n", current->index, event, ((thread_t*)event->thread)->index); if(event) { REQUIRE(event->thread == current, "Event %p belongs to thread %p, not the current thread (%p)", event, event->thread, current); // If the event pointing to a different thread, or the target event // is not the current one, warn about this situaion. Something wrong! if((event->thread != current) || (event->eventlist != tlist)) { PRINT("Assertion:peekSyncEvent at thread %d: event %p event thread %d. eventlist %p targetlist %p\n", current->index, event, ((thread_t*)event->thread)->index, event->eventlist, tlist); assert(event->thread == current); assert(event->eventlist == tlist); } result = event->ret; } else { // ERROR("Event not exising now at thread %p!!!!\n", current); } return result; } void cleanSyncEvents() { // Remove all events in the global map and event list. syncvarsHashMap::iterator i; for(i = _syncvars.begin(); i != _syncvars.end(); i++) { struct SyncEntry* entry = (struct SyncEntry*)i.getData(); SyncEventList* eventlist = (SyncEventList*)entry->list; PRINF("cleaningup the eventlist %p!!!\n", eventlist); eventlist->cleanup(); } } inline void setSyncVariable(void** syncvariable, void* realvariable) { *syncvariable = realvariable; } /* Prepare rollback. Only one thread can call this function. It basically check every synchronization variable. If a synchronization variable is in the head of a thread, then we try to UP corresponding thread's semaphore. */ void prepareRollback() { syncvarsHashMap::iterator i; struct SyncEntry* entry; void* syncvariable; for(i = _syncvars.begin(); i != _syncvars.end(); i++) { syncvariable = i.getkey(); entry = (struct SyncEntry*)i.getData(); // If syncvariable is not equal to the entry->realEntry, // those are mutex locks, conditional variables or mutexlocks // The starting address of tose variables are cleaning up at epochBegin() (by backingup) // We have to make them to pointing to actual synchronization entries since there are not // mutex_init or something else. if((*((void **)syncvariable)) != entry->realEntry) { // Setting the address setSyncVariable((void**)syncvariable, entry->realEntry); } PRINT("prepareRollback syncvariable %p pointintto %p entry %p realentry %p, eventlist %p\n", syncvariable, (*((void **)syncvariable)), entry, entry->realEntry, entry->list); prepareEventListRollback(entry->list); } } /* Prepare the rollback for an event list. It will check whether the first event in the event list is also the head of specific thread. If yes, then we will signal specific thread so that this thread can acquire the semaphore immediately. */ inline void prepareEventListRollback(SyncEventList* eventlist) { struct syncEvent* event = eventlist->prepareRollback(); PRINT("prepareEventListRollback eventlist %p event %p\n", eventlist, event); if(event) { // Signal to next thread with the top event signalNextThread(event); } } // Add one synchronization event into the pending list of a thread. void addPendingSyncEvent(struct syncEvent* event, thread_t* thread) { struct pendingSyncEvent* pendingEvent = NULL; pendingEvent = (struct pendingSyncEvent*)InternalHeap::getInstance().malloc( sizeof(struct pendingSyncEvent)); listInit(&pendingEvent->list); pendingEvent->event = event; listInsertTail(&pendingEvent->list, &thread->pendingSyncevents); } // Check whether this event is the first event of corresponding thread. bool isThreadNextEvent(struct syncEvent* event, thread_t* thread) { return (event == thread->syncevents.firstIterEntry()); } void signalThread(thread_t* thread) { semaphore* sema = &thread->sema; PRINT("Thread %d: ^^^^^Signal semaphore to thread %d\n", current->index, thread->index); sema->put(); } private: size_t getThreadSyncSeqNum() { return 0; } semaphore* getThreadSemaphore(thread_t* thread) { return &thread->sema; } // We are maintainning a private hash map for each thread. typedef HashMap<void*, struct SyncEntry*, spinlock, InternalHeapAllocator> syncvarsHashMap; // Synchronization related to different sync variable should be recorded into // the synchronization variable related list. syncvarsHashMap _syncvars; }; #endif <|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 "cmakeeditor.h" #include "cmakehighlighter.h" #include "cmakeeditorfactory.h" #include "cmakeprojectconstants.h" #include <coreplugin/uniqueidmanager.h> #include <texteditor/fontsettings.h> #include <texteditor/texteditoractionhandler.h> #include <texteditor/texteditorconstants.h> #include <texteditor/texteditorsettings.h> #include <QtCore/QFileInfo> using namespace CMakeProjectManager; using namespace CMakeProjectManager::Internal; // // ProFileEditorEditable // CMakeEditorEditable::CMakeEditorEditable(CMakeEditor *editor) : BaseTextEditorEditable(editor) { Core::UniqueIDManager *uidm = Core::UniqueIDManager::instance(); m_context << uidm->uniqueIdentifier(CMakeProjectManager::Constants::C_CMAKEEDITOR); m_context << uidm->uniqueIdentifier(TextEditor::Constants::C_TEXTEDITOR); } QList<int> CMakeEditorEditable::context() const { return m_context; } Core::IEditor *CMakeEditorEditable::duplicate(QWidget *parent) { CMakeEditor *ret = new CMakeEditor(parent, qobject_cast<CMakeEditor*>(editor())->factory(), qobject_cast<CMakeEditor*>(editor())->actionHandler()); ret->duplicateFrom(editor()); TextEditor::TextEditorSettings::instance()->initializeEditor(ret); return ret->editableInterface(); } QString CMakeEditorEditable::id() const { return QLatin1String(CMakeProjectManager::Constants::CMAKE_EDITOR_ID); } // // CMakeEditor // CMakeEditor::CMakeEditor(QWidget *parent, CMakeEditorFactory *factory, TextEditor::TextEditorActionHandler *ah) : BaseTextEditor(parent), m_factory(factory), m_ah(ah) { CMakeDocument *doc = new CMakeDocument(); doc->setMimeType(QLatin1String(CMakeProjectManager::Constants::CMAKEMIMETYPE)); setBaseTextDocument(doc); ah->setupActions(this); baseTextDocument()->setSyntaxHighlighter(new CMakeHighlighter); } CMakeEditor::~CMakeEditor() { } TextEditor::BaseTextEditorEditable *CMakeEditor::createEditableInterface() { return new CMakeEditorEditable(this); } void CMakeEditor::setFontSettings(const TextEditor::FontSettings &fs) { CMakeHighlighter *highlighter = qobject_cast<CMakeHighlighter*>(baseTextDocument()->syntaxHighlighter()); if (!highlighter) return; static QVector<QString> categories; if (categories.isEmpty()) { categories << QLatin1String(TextEditor::Constants::C_LABEL) // variables << QLatin1String(TextEditor::Constants::C_LINK) // functions << QLatin1String(TextEditor::Constants::C_COMMENT) << QLatin1String(TextEditor::Constants::C_STRING); } const QVector<QTextCharFormat> formats = fs.toTextCharFormats(categories); highlighter->setFormats(formats.constBegin(), formats.constEnd()); highlighter->rehighlight(); } // // ProFileDocument // CMakeDocument::CMakeDocument() : TextEditor::BaseTextDocument() { } QString CMakeDocument::defaultPath() const { QFileInfo fi(fileName()); return fi.absolutePath(); } QString CMakeDocument::suggestedFileName() const { QFileInfo fi(fileName()); return fi.fileName(); } <commit_msg>Fix CMake highlighting with dark theme<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 "cmakeeditor.h" #include "cmakehighlighter.h" #include "cmakeeditorfactory.h" #include "cmakeprojectconstants.h" #include <coreplugin/uniqueidmanager.h> #include <texteditor/fontsettings.h> #include <texteditor/texteditoractionhandler.h> #include <texteditor/texteditorconstants.h> #include <texteditor/texteditorsettings.h> #include <QtCore/QFileInfo> using namespace CMakeProjectManager; using namespace CMakeProjectManager::Internal; // // ProFileEditorEditable // CMakeEditorEditable::CMakeEditorEditable(CMakeEditor *editor) : BaseTextEditorEditable(editor) { Core::UniqueIDManager *uidm = Core::UniqueIDManager::instance(); m_context << uidm->uniqueIdentifier(CMakeProjectManager::Constants::C_CMAKEEDITOR); m_context << uidm->uniqueIdentifier(TextEditor::Constants::C_TEXTEDITOR); } QList<int> CMakeEditorEditable::context() const { return m_context; } Core::IEditor *CMakeEditorEditable::duplicate(QWidget *parent) { CMakeEditor *ret = new CMakeEditor(parent, qobject_cast<CMakeEditor*>(editor())->factory(), qobject_cast<CMakeEditor*>(editor())->actionHandler()); ret->duplicateFrom(editor()); TextEditor::TextEditorSettings::instance()->initializeEditor(ret); return ret->editableInterface(); } QString CMakeEditorEditable::id() const { return QLatin1String(CMakeProjectManager::Constants::CMAKE_EDITOR_ID); } // // CMakeEditor // CMakeEditor::CMakeEditor(QWidget *parent, CMakeEditorFactory *factory, TextEditor::TextEditorActionHandler *ah) : BaseTextEditor(parent), m_factory(factory), m_ah(ah) { CMakeDocument *doc = new CMakeDocument(); doc->setMimeType(QLatin1String(CMakeProjectManager::Constants::CMAKEMIMETYPE)); setBaseTextDocument(doc); ah->setupActions(this); baseTextDocument()->setSyntaxHighlighter(new CMakeHighlighter); } CMakeEditor::~CMakeEditor() { } TextEditor::BaseTextEditorEditable *CMakeEditor::createEditableInterface() { return new CMakeEditorEditable(this); } void CMakeEditor::setFontSettings(const TextEditor::FontSettings &fs) { TextEditor::BaseTextEditor::setFontSettings(fs); CMakeHighlighter *highlighter = qobject_cast<CMakeHighlighter*>(baseTextDocument()->syntaxHighlighter()); if (!highlighter) return; static QVector<QString> categories; if (categories.isEmpty()) { categories << QLatin1String(TextEditor::Constants::C_LABEL) // variables << QLatin1String(TextEditor::Constants::C_LINK) // functions << QLatin1String(TextEditor::Constants::C_COMMENT) << QLatin1String(TextEditor::Constants::C_STRING); } const QVector<QTextCharFormat> formats = fs.toTextCharFormats(categories); highlighter->setFormats(formats.constBegin(), formats.constEnd()); highlighter->rehighlight(); } // // ProFileDocument // CMakeDocument::CMakeDocument() : TextEditor::BaseTextDocument() { } QString CMakeDocument::defaultPath() const { QFileInfo fi(fileName()); return fi.absolutePath(); } QString CMakeDocument::suggestedFileName() const { QFileInfo fi(fileName()); return fi.fileName(); } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: http://www.qt-project.org/ ** ** ** GNU Lesser General Public License Usage ** ** 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. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** **************************************************************************/ #include "debuggerkitinformation.h" #include "debuggerkitconfigwidget.h" #include <projectexplorer/abi.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/toolchain.h> #include <utils/environment.h> #include <utils/qtcassert.h> #include <QDir> #include <QPair> using namespace ProjectExplorer; using namespace Utils; // -------------------------------------------------------------------------- // Helpers: // -------------------------------------------------------------------------- static QPair<QString, QString> autoDetectCdbDebugger() { QPair<QString, QString> result; QList<FileName> cdbs; QStringList programDirs; programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramFiles"))); programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramFiles(x86)"))); programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramW6432"))); foreach (const QString &dirName, programDirs) { if (dirName.isEmpty()) continue; QDir dir(dirName); // Windows SDK's starting from version 8 live in // "ProgramDir\Windows Kits\<version>" const QString windowsKitsFolderName = QLatin1String("Windows Kits"); if (dir.exists(windowsKitsFolderName)) { QDir windowKitsFolder = dir; if (windowKitsFolder.cd(windowsKitsFolderName)) { // Check in reverse order (latest first) const QFileInfoList kitFolders = windowKitsFolder.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Time | QDir::Reversed); foreach (const QFileInfo &kitFolderFi, kitFolders) { const QString path = kitFolderFi.absoluteFilePath(); const QFileInfo cdb32(path + QLatin1String("/Debuggers/x86/cdb.exe")); if (cdb32.isExecutable()) cdbs.push_back(FileName::fromString(cdb32.absoluteFilePath())); const QFileInfo cdb64(path + QLatin1String("/Debuggers/x64/cdb.exe")); if (cdb64.isExecutable()) cdbs.push_back(FileName::fromString(cdb64.absoluteFilePath())); } // for Kits } // can cd to "Windows Kits" } // "Windows Kits" exists // Pre Windows SDK 8: Check 'Debugging Tools for Windows' foreach (const QFileInfo &fi, dir.entryInfoList(QStringList(QLatin1String("Debugging Tools for Windows*")), QDir::Dirs | QDir::NoDotAndDotDot)) { FileName filePath(fi); filePath.appendPath(QLatin1String("cdb.exe")); if (!cdbs.contains(filePath)) cdbs.append(filePath); } } foreach (const FileName &cdb, cdbs) { QList<Abi> abis = Abi::abisOfBinary(cdb); if (abis.isEmpty()) continue; if (abis.first().wordWidth() == 32) result.first = cdb.toString(); else if (abis.first().wordWidth() == 64) result.second = cdb.toString(); } // prefer 64bit debugger, even for 32bit binaries: if (!result.second.isEmpty()) result.first = result.second; return result; } namespace Debugger { static DebuggerEngineType engineTypeFromBinary(const QString &binary) { if (binary.contains(QLatin1String("cdb"), Qt::CaseInsensitive)) return CdbEngineType; if (binary.contains(QLatin1String("lldb"), Qt::CaseInsensitive)) return LldbEngineType; return GdbEngineType; } // -------------------------------------------------------------------------- // DebuggerKitInformation: // -------------------------------------------------------------------------- static const char DEBUGGER_INFORMATION[] = "Debugger.Information"; DebuggerKitInformation::DebuggerItem::DebuggerItem() : engineType(NoEngineType) { } DebuggerKitInformation::DebuggerItem::DebuggerItem(DebuggerEngineType et, const Utils::FileName &fn) : engineType(et) , binary(fn) { } DebuggerKitInformation::DebuggerKitInformation() { setObjectName(QLatin1String("DebuggerKitInformation")); } Core::Id DebuggerKitInformation::dataId() const { static Core::Id id = Core::Id(DEBUGGER_INFORMATION); return id; } unsigned int DebuggerKitInformation::priority() const { return 28000; } DebuggerKitInformation::DebuggerItem DebuggerKitInformation::autoDetectItem(const Kit *k) { DebuggerItem result; const ToolChain *tc = ToolChainKitInformation::toolChain(k); Abi abi = Abi::hostAbi(); if (tc) abi = tc->targetAbi(); // CDB for windows: if (abi.os() == Abi::WindowsOS && abi.osFlavor() != Abi::WindowsMSysFlavor) { QPair<QString, QString> cdbs = autoDetectCdbDebugger(); result.binary = Utils::FileName::fromString(abi.wordWidth() == 32 ? cdbs.first : cdbs.second); result.engineType = CdbEngineType; return result; } // Check suggestions from the SDK. const Environment env = Environment::systemEnvironment(); if (tc) { QString path = tc->suggestedDebugger().toString(); if (!path.isEmpty()) { const QFileInfo fi(path); if (!fi.isAbsolute()) path = env.searchInPath(path); result.binary = Utils::FileName::fromString(path); result.engineType = engineTypeFromBinary(path); return result; } } // Default to GDB, system GDB result.engineType = GdbEngineType; QString gdb; const QString systemGdb = QLatin1String("gdb"); // MinGW: Search for the python-enabled gdb first. if (abi.os() == Abi::WindowsOS && abi.osFlavor() == Abi::WindowsMSysFlavor) gdb = env.searchInPath(QLatin1String("gdb-i686-pc-mingw32")); if (gdb.isEmpty()) gdb = env.searchInPath(systemGdb); result.binary = Utils::FileName::fromString(env.searchInPath(gdb.isEmpty() ? systemGdb : gdb)); return result; } // Check the configuration errors and return a flag mask. Provide a quick check and // a verbose one with a list of errors. enum DebuggerConfigurationErrors { NoDebugger = 0x1, DebuggerNotFound = 0x2, DebuggerNotExecutable = 0x4, DebuggerNeedsAbsolutePath = 0x8 }; static unsigned debuggerConfigurationErrors(const ProjectExplorer::Kit *k) { unsigned result = 0; const DebuggerKitInformation::DebuggerItem item = DebuggerKitInformation::debuggerItem(k); if (item.engineType == NoEngineType || item.binary.isEmpty()) return NoDebugger; const QFileInfo fi = item.binary.toFileInfo(); if (!fi.exists() || fi.isDir()) { result |= DebuggerNotFound; } else if (!fi.isExecutable()) { result |= DebuggerNotExecutable; } if (!fi.exists() || fi.isDir()) // We need an absolute path to be able to locate Python on Windows. if (item.engineType == GdbEngineType) if (const ToolChain *tc = ToolChainKitInformation::toolChain(k)) if (tc->targetAbi().os() == Abi::WindowsOS && !fi.isAbsolute()) result |= DebuggerNeedsAbsolutePath; return result; } bool DebuggerKitInformation::isValidDebugger(const ProjectExplorer::Kit *k) { return debuggerConfigurationErrors(k) == 0; } QList<ProjectExplorer::Task> DebuggerKitInformation::validateDebugger(const ProjectExplorer::Kit *k) { const unsigned errors = debuggerConfigurationErrors(k); const Core::Id id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM); QList<Task> result; if (errors & NoDebugger) result << Task(Task::Warning, tr("No debugger set up."), FileName(), -1, id); if (errors & DebuggerNotFound) { const QString path = DebuggerKitInformation::debuggerCommand(k).toUserOutput(); result << Task(Task::Error, tr("Debugger '%1' not found.").arg(path), FileName(), -1, id); } if (errors & DebuggerNotExecutable) { const QString path = DebuggerKitInformation::debuggerCommand(k).toUserOutput(); result << Task(Task::Error, tr("Debugger '%1' not executable.").arg(path), FileName(), -1, id); } if (errors & DebuggerNeedsAbsolutePath) { const QString path = DebuggerKitInformation::debuggerCommand(k).toUserOutput(); const QString message = tr("The debugger location must be given as an " "absolute path (%1).").arg(path); result << Task(Task::Error, message, FileName(), -1, id); } return result; } KitConfigWidget *DebuggerKitInformation::createConfigWidget(Kit *k) const { return new Internal::DebuggerKitConfigWidget(k, this); } QString DebuggerKitInformation::userOutput(const DebuggerItem &item) { const QString binary = item.binary.toUserOutput(); return binary.isEmpty() ? tr("%1 <None>").arg(debuggerEngineName(item.engineType)) : tr("%1 using '%2'").arg(debuggerEngineName(item.engineType), binary); } KitInformation::ItemList DebuggerKitInformation::toUserOutput(Kit *k) const { return ItemList() << qMakePair(tr("Debugger"), DebuggerKitInformation::userOutput(DebuggerKitInformation::debuggerItem(k))); } static const char engineTypeKeyC[] = "EngineType"; static const char binaryKeyC[] = "Binary"; DebuggerKitInformation::DebuggerItem DebuggerKitInformation::variantToItem(const QVariant &v) { DebuggerItem result; if (v.type() == QVariant::String) { // Convert legacy config items, remove later. const QString binary = v.toString(); result.binary = Utils::FileName::fromString(binary); result.engineType = engineTypeFromBinary(binary); return result; } QTC_ASSERT(v.type() == QVariant::Map, return result); const QVariantMap vmap = v.toMap(); result.binary = Utils::FileName::fromString(vmap.value(QLatin1String(binaryKeyC)).toString()); result.engineType = static_cast<DebuggerEngineType>(vmap.value(QLatin1String(engineTypeKeyC)).toInt()); return result; } QVariant DebuggerKitInformation::itemToVariant(const DebuggerItem &i) { QVariantMap vmap; vmap.insert(QLatin1String(binaryKeyC), QVariant(i.binary.toUserOutput())); vmap.insert(QLatin1String(engineTypeKeyC), QVariant(int(i.engineType))); return QVariant(vmap); } DebuggerKitInformation::DebuggerItem DebuggerKitInformation::debuggerItem(const ProjectExplorer::Kit *k) { return k ? DebuggerKitInformation::variantToItem(k->value(Core::Id(DEBUGGER_INFORMATION))) : DebuggerItem(); } void DebuggerKitInformation::setDebuggerItem(ProjectExplorer::Kit *k, const DebuggerItem &item) { QTC_ASSERT(k, return); k->setValue(Core::Id(DEBUGGER_INFORMATION), itemToVariant(item)); } void DebuggerKitInformation::setDebuggerCommand(ProjectExplorer::Kit *k, const FileName &command) { setDebuggerItem(k, DebuggerItem(engineType(k), command)); } void DebuggerKitInformation::setEngineType(ProjectExplorer::Kit *k, DebuggerEngineType type) { setDebuggerItem(k, DebuggerItem(type, debuggerCommand(k))); } QString DebuggerKitInformation::debuggerEngineName(DebuggerEngineType t) { switch (t) { case Debugger::GdbEngineType: return tr("GDB Engine"); case Debugger::CdbEngineType: return tr("CDB Engine"); case Debugger::LldbEngineType: return tr("LLDB Engine"); default: break; } return QString(); } } // namespace Debugger <commit_msg>debugger: fix quotes in tooltip<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: http://www.qt-project.org/ ** ** ** GNU Lesser General Public License Usage ** ** 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. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** **************************************************************************/ #include "debuggerkitinformation.h" #include "debuggerkitconfigwidget.h" #include <projectexplorer/abi.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/toolchain.h> #include <utils/environment.h> #include <utils/qtcassert.h> #include <QDir> #include <QPair> using namespace ProjectExplorer; using namespace Utils; // -------------------------------------------------------------------------- // Helpers: // -------------------------------------------------------------------------- static QPair<QString, QString> autoDetectCdbDebugger() { QPair<QString, QString> result; QList<FileName> cdbs; QStringList programDirs; programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramFiles"))); programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramFiles(x86)"))); programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramW6432"))); foreach (const QString &dirName, programDirs) { if (dirName.isEmpty()) continue; QDir dir(dirName); // Windows SDK's starting from version 8 live in // "ProgramDir\Windows Kits\<version>" const QString windowsKitsFolderName = QLatin1String("Windows Kits"); if (dir.exists(windowsKitsFolderName)) { QDir windowKitsFolder = dir; if (windowKitsFolder.cd(windowsKitsFolderName)) { // Check in reverse order (latest first) const QFileInfoList kitFolders = windowKitsFolder.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Time | QDir::Reversed); foreach (const QFileInfo &kitFolderFi, kitFolders) { const QString path = kitFolderFi.absoluteFilePath(); const QFileInfo cdb32(path + QLatin1String("/Debuggers/x86/cdb.exe")); if (cdb32.isExecutable()) cdbs.push_back(FileName::fromString(cdb32.absoluteFilePath())); const QFileInfo cdb64(path + QLatin1String("/Debuggers/x64/cdb.exe")); if (cdb64.isExecutable()) cdbs.push_back(FileName::fromString(cdb64.absoluteFilePath())); } // for Kits } // can cd to "Windows Kits" } // "Windows Kits" exists // Pre Windows SDK 8: Check 'Debugging Tools for Windows' foreach (const QFileInfo &fi, dir.entryInfoList(QStringList(QLatin1String("Debugging Tools for Windows*")), QDir::Dirs | QDir::NoDotAndDotDot)) { FileName filePath(fi); filePath.appendPath(QLatin1String("cdb.exe")); if (!cdbs.contains(filePath)) cdbs.append(filePath); } } foreach (const FileName &cdb, cdbs) { QList<Abi> abis = Abi::abisOfBinary(cdb); if (abis.isEmpty()) continue; if (abis.first().wordWidth() == 32) result.first = cdb.toString(); else if (abis.first().wordWidth() == 64) result.second = cdb.toString(); } // prefer 64bit debugger, even for 32bit binaries: if (!result.second.isEmpty()) result.first = result.second; return result; } namespace Debugger { static DebuggerEngineType engineTypeFromBinary(const QString &binary) { if (binary.contains(QLatin1String("cdb"), Qt::CaseInsensitive)) return CdbEngineType; if (binary.contains(QLatin1String("lldb"), Qt::CaseInsensitive)) return LldbEngineType; return GdbEngineType; } // -------------------------------------------------------------------------- // DebuggerKitInformation: // -------------------------------------------------------------------------- static const char DEBUGGER_INFORMATION[] = "Debugger.Information"; DebuggerKitInformation::DebuggerItem::DebuggerItem() : engineType(NoEngineType) { } DebuggerKitInformation::DebuggerItem::DebuggerItem(DebuggerEngineType et, const Utils::FileName &fn) : engineType(et) , binary(fn) { } DebuggerKitInformation::DebuggerKitInformation() { setObjectName(QLatin1String("DebuggerKitInformation")); } Core::Id DebuggerKitInformation::dataId() const { static Core::Id id = Core::Id(DEBUGGER_INFORMATION); return id; } unsigned int DebuggerKitInformation::priority() const { return 28000; } DebuggerKitInformation::DebuggerItem DebuggerKitInformation::autoDetectItem(const Kit *k) { DebuggerItem result; const ToolChain *tc = ToolChainKitInformation::toolChain(k); Abi abi = Abi::hostAbi(); if (tc) abi = tc->targetAbi(); // CDB for windows: if (abi.os() == Abi::WindowsOS && abi.osFlavor() != Abi::WindowsMSysFlavor) { QPair<QString, QString> cdbs = autoDetectCdbDebugger(); result.binary = Utils::FileName::fromString(abi.wordWidth() == 32 ? cdbs.first : cdbs.second); result.engineType = CdbEngineType; return result; } // Check suggestions from the SDK. const Environment env = Environment::systemEnvironment(); if (tc) { QString path = tc->suggestedDebugger().toString(); if (!path.isEmpty()) { const QFileInfo fi(path); if (!fi.isAbsolute()) path = env.searchInPath(path); result.binary = Utils::FileName::fromString(path); result.engineType = engineTypeFromBinary(path); return result; } } // Default to GDB, system GDB result.engineType = GdbEngineType; QString gdb; const QString systemGdb = QLatin1String("gdb"); // MinGW: Search for the python-enabled gdb first. if (abi.os() == Abi::WindowsOS && abi.osFlavor() == Abi::WindowsMSysFlavor) gdb = env.searchInPath(QLatin1String("gdb-i686-pc-mingw32")); if (gdb.isEmpty()) gdb = env.searchInPath(systemGdb); result.binary = Utils::FileName::fromString(env.searchInPath(gdb.isEmpty() ? systemGdb : gdb)); return result; } // Check the configuration errors and return a flag mask. Provide a quick check and // a verbose one with a list of errors. enum DebuggerConfigurationErrors { NoDebugger = 0x1, DebuggerNotFound = 0x2, DebuggerNotExecutable = 0x4, DebuggerNeedsAbsolutePath = 0x8 }; static unsigned debuggerConfigurationErrors(const ProjectExplorer::Kit *k) { unsigned result = 0; const DebuggerKitInformation::DebuggerItem item = DebuggerKitInformation::debuggerItem(k); if (item.engineType == NoEngineType || item.binary.isEmpty()) return NoDebugger; const QFileInfo fi = item.binary.toFileInfo(); if (!fi.exists() || fi.isDir()) { result |= DebuggerNotFound; } else if (!fi.isExecutable()) { result |= DebuggerNotExecutable; } if (!fi.exists() || fi.isDir()) // We need an absolute path to be able to locate Python on Windows. if (item.engineType == GdbEngineType) if (const ToolChain *tc = ToolChainKitInformation::toolChain(k)) if (tc->targetAbi().os() == Abi::WindowsOS && !fi.isAbsolute()) result |= DebuggerNeedsAbsolutePath; return result; } bool DebuggerKitInformation::isValidDebugger(const ProjectExplorer::Kit *k) { return debuggerConfigurationErrors(k) == 0; } QList<ProjectExplorer::Task> DebuggerKitInformation::validateDebugger(const ProjectExplorer::Kit *k) { const unsigned errors = debuggerConfigurationErrors(k); const Core::Id id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM); QList<Task> result; if (errors & NoDebugger) result << Task(Task::Warning, tr("No debugger set up."), FileName(), -1, id); if (errors & DebuggerNotFound) { const QString path = DebuggerKitInformation::debuggerCommand(k).toUserOutput(); result << Task(Task::Error, tr("Debugger '%1' not found.").arg(path), FileName(), -1, id); } if (errors & DebuggerNotExecutable) { const QString path = DebuggerKitInformation::debuggerCommand(k).toUserOutput(); result << Task(Task::Error, tr("Debugger '%1' not executable.").arg(path), FileName(), -1, id); } if (errors & DebuggerNeedsAbsolutePath) { const QString path = DebuggerKitInformation::debuggerCommand(k).toUserOutput(); const QString message = tr("The debugger location must be given as an " "absolute path (%1).").arg(path); result << Task(Task::Error, message, FileName(), -1, id); } return result; } KitConfigWidget *DebuggerKitInformation::createConfigWidget(Kit *k) const { return new Internal::DebuggerKitConfigWidget(k, this); } QString DebuggerKitInformation::userOutput(const DebuggerItem &item) { const QString binary = item.binary.toUserOutput(); const QString name = debuggerEngineName(item.engineType); return binary.isEmpty() ? tr("%1 <None>").arg(name) : tr("%1 using \"%2\"").arg(name, binary); } KitInformation::ItemList DebuggerKitInformation::toUserOutput(Kit *k) const { return ItemList() << qMakePair(tr("Debugger"), DebuggerKitInformation::userOutput(DebuggerKitInformation::debuggerItem(k))); } static const char engineTypeKeyC[] = "EngineType"; static const char binaryKeyC[] = "Binary"; DebuggerKitInformation::DebuggerItem DebuggerKitInformation::variantToItem(const QVariant &v) { DebuggerItem result; if (v.type() == QVariant::String) { // Convert legacy config items, remove later. const QString binary = v.toString(); result.binary = Utils::FileName::fromString(binary); result.engineType = engineTypeFromBinary(binary); return result; } QTC_ASSERT(v.type() == QVariant::Map, return result); const QVariantMap vmap = v.toMap(); result.binary = Utils::FileName::fromString(vmap.value(QLatin1String(binaryKeyC)).toString()); result.engineType = static_cast<DebuggerEngineType>(vmap.value(QLatin1String(engineTypeKeyC)).toInt()); return result; } QVariant DebuggerKitInformation::itemToVariant(const DebuggerItem &i) { QVariantMap vmap; vmap.insert(QLatin1String(binaryKeyC), QVariant(i.binary.toUserOutput())); vmap.insert(QLatin1String(engineTypeKeyC), QVariant(int(i.engineType))); return QVariant(vmap); } DebuggerKitInformation::DebuggerItem DebuggerKitInformation::debuggerItem(const ProjectExplorer::Kit *k) { return k ? DebuggerKitInformation::variantToItem(k->value(Core::Id(DEBUGGER_INFORMATION))) : DebuggerItem(); } void DebuggerKitInformation::setDebuggerItem(ProjectExplorer::Kit *k, const DebuggerItem &item) { QTC_ASSERT(k, return); k->setValue(Core::Id(DEBUGGER_INFORMATION), itemToVariant(item)); } void DebuggerKitInformation::setDebuggerCommand(ProjectExplorer::Kit *k, const FileName &command) { setDebuggerItem(k, DebuggerItem(engineType(k), command)); } void DebuggerKitInformation::setEngineType(ProjectExplorer::Kit *k, DebuggerEngineType type) { setDebuggerItem(k, DebuggerItem(type, debuggerCommand(k))); } QString DebuggerKitInformation::debuggerEngineName(DebuggerEngineType t) { switch (t) { case Debugger::GdbEngineType: return tr("GDB Engine"); case Debugger::CdbEngineType: return tr("CDB Engine"); case Debugger::LldbEngineType: return tr("LLDB Engine"); default: break; } return QString(); } } // namespace Debugger <|endoftext|>
<commit_before>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2012 Belledonne Communications SARL. 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 <sys/types.h> #include <dirent.h> #include "pushnotificationservice.hh" #include "pushnotificationclient.hh" #include "common.hh" #include <boost/bind.hpp> #include <sstream> const char *APN_DEV_ADDRESS = "gateway.sandbox.push.apple.com"; const char *APN_PROD_ADDRESS = "gateway.push.apple.com"; const char *APN_PORT = "2195"; const char *GPN_ADDRESS = "android.googleapis.com"; const char *GPN_PORT = "443"; const char *WPPN_PORT = "80"; int MAX_QUEUE_SIZE = 10; using namespace ::std; namespace ssl = boost::asio::ssl; int PushNotificationService::sendRequest(const std::shared_ptr<PushNotificationRequest> &pn) { std::shared_ptr<PushNotificationClient> client=mClients[pn->getAppIdentifier()]; if (client==0){ if (pn->getType().compare(string("wp"))==0) { string wpClient = pn->getAppIdentifier(); std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code err; ctx->set_options(ssl::context::default_workarounds, err); ctx->set_verify_mode(ssl::context::verify_none); mClients[wpClient] = std::make_shared<PushNotificationClient>(wpClient, this, ctx, pn->getAppIdentifier(), WPPN_PORT, MAX_QUEUE_SIZE, FALSE); LOGD("Creating PNclient for client %s",pn->getAppIdentifier().c_str()); client = mClients[wpClient]; } else { LOGE("No push notification certificate for client %s",pn->getAppIdentifier().c_str()); return -1; } } //this method is called from flexisip main thread, while service is running in its own thread. //To avoid using dedicated mutex, use the server post() method to delegate the processing of the push notification to the service thread. mIOService.post(std::bind(&PushNotificationClient::sendRequest,client,pn)); return 0; } void PushNotificationService::start() { if (mThread == NULL || !mThread->joinable()) { delete mThread; mThread = NULL; } if (mThread == NULL) { LOGD("Start PushNotificationService"); mHaveToStop = false; mThread = new thread(&PushNotificationService::run, this); } } void PushNotificationService::stop() { if (mThread != NULL) { LOGD("Stopping PushNotificationService"); mHaveToStop = true; mIOService.stop(); if (mThread->joinable()) { mThread->join(); } delete mThread; mThread = NULL; } } void PushNotificationService::waitEnd() { if (mThread != NULL) { LOGD("Waiting for PushNotificationService to end"); bool finished = false; while (!finished) { finished = true; map<string, std::shared_ptr<PushNotificationClient> >::const_iterator it; for (it = mClients.begin(); it != mClients.end(); ++it) { if (!it->second->isIdle()) { finished = false; break; } } } } } void PushNotificationService::setupClients(const string &certdir, const string &ca, int maxQueueSize) { struct dirent *dirent; DIR *dirp; MAX_QUEUE_SIZE = maxQueueSize; // Android Client string googleClient = string("google"); std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code err; ctx->set_options(ssl::context::default_workarounds, err); ctx->set_verify_mode(ssl::context::verify_none); mClients[googleClient]=std::make_shared<PushNotificationClient>(googleClient, this, ctx, GPN_ADDRESS, GPN_PORT, maxQueueSize, TRUE); dirp=opendir(certdir.c_str()); if (dirp==NULL){ LOGE("Could not open push notification certificates directory (%s): %s",certdir.c_str(),strerror(errno)); return; } while((dirent=readdir(dirp))!=NULL){ if (dirent->d_type!=DT_REG && dirent->d_type!=DT_LNK) continue; string cert=string(dirent->d_name); string certpath= string(certdir)+"/"+cert; std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code err; ctx->set_options(ssl::context::default_workarounds, err); ctx->set_password_callback(bind(&PushNotificationService::handle_password_callback, this, _1, _2)); if (!ca.empty()) { ctx->set_verify_mode(ssl::context::verify_peer); #if BOOST_VERSION >= 104800 ctx->set_verify_callback(bind(&PushNotificationService::handle_verify_callback, this, _1, _2)); #endif ctx->load_verify_file(ca, err); if (err) { LOGE("load_verify_file: %s",err.message().c_str()); } } else { ctx->set_verify_mode(ssl::context::verify_none); } ctx->add_verify_path("/etc/ssl/certs"); if (!cert.empty()) { ctx->use_certificate_file(certpath, ssl::context::file_format::pem, err); if (err) { LOGE("use_certificate_file %s: %s",certpath.c_str(), err.message().c_str()); } } string key=certpath; if (!key.empty()) { ctx->use_private_key_file(key, ssl::context::file_format::pem, err); if (err) { LOGE("use_private_key_file: %s",err.message().c_str()); } } string certName = cert.substr(0, cert.size() - 4); // Remove .pem at the end of cert const char *apn_server; if (certName.find(".dev")!=string::npos) apn_server=APN_DEV_ADDRESS; else apn_server=APN_PROD_ADDRESS; mClients[certName]=std::make_shared<PushNotificationClient>(cert, this, ctx, apn_server, APN_PORT, maxQueueSize, TRUE); } closedir(dirp); } PushNotificationService::PushNotificationService(const std::string &certdir, const std::string &cafile, int maxQueueSize, StatCounter64 *countFailed, StatCounter64 *countSent) : mIOService(), mThread(NULL), mCountFailed(countFailed), mCountSent(countSent) { setupClients(certdir, cafile, maxQueueSize); } PushNotificationService::~PushNotificationService() { stop(); } int PushNotificationService::run() { LOGD("PushNotificationService Start"); boost::asio::io_service::work work(mIOService); mIOService.run(); LOGD("PushNotificationService End"); return 0; } void PushNotificationService::clientEnded() { } boost::asio::io_service &PushNotificationService::getService() { return mIOService; } string PushNotificationService::handle_password_callback(size_t max_length, ssl::context_base::password_purpose purpose) const { return mPassword; } #if BOOST_VERSION >= 104800 bool PushNotificationService::handle_verify_callback(bool preverified, ssl::verify_context& ctx) const { char subject_name[256]; #if not(__GNUC__ == 4 && __GNUC_MINOR__ < 5 ) SLOGD << "Verifying " << [&] () { X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle()); X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256); return subject_name; }(); #else X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle()); X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256); SLOGD << "Verifying " << subject_name; #endif return preverified; } #endif <commit_msg>Fix Google push notifs (wasn't working since april)<commit_after>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2012 Belledonne Communications SARL. 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 <sys/types.h> #include <dirent.h> #include "pushnotificationservice.hh" #include "pushnotificationclient.hh" #include "common.hh" #include <boost/bind.hpp> #include <sstream> const char *APN_DEV_ADDRESS = "gateway.sandbox.push.apple.com"; const char *APN_PROD_ADDRESS = "gateway.push.apple.com"; const char *APN_PORT = "2195"; const char *GPN_ADDRESS = "gcm.googleapis.com"; const char *GPN_PORT = "5235"; const char *WPPN_PORT = "80"; int MAX_QUEUE_SIZE = 10; using namespace ::std; namespace ssl = boost::asio::ssl; int PushNotificationService::sendRequest(const std::shared_ptr<PushNotificationRequest> &pn) { std::shared_ptr<PushNotificationClient> client=mClients[pn->getAppIdentifier()]; if (client==0){ if (pn->getType().compare(string("wp"))==0) { string wpClient = pn->getAppIdentifier(); std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code err; ctx->set_options(ssl::context::default_workarounds, err); ctx->set_verify_mode(ssl::context::verify_none); mClients[wpClient] = std::make_shared<PushNotificationClient>(wpClient, this, ctx, pn->getAppIdentifier(), WPPN_PORT, MAX_QUEUE_SIZE, FALSE); LOGD("Creating PNclient for client %s",pn->getAppIdentifier().c_str()); client = mClients[wpClient]; } else { LOGE("No push notification certificate for client %s",pn->getAppIdentifier().c_str()); return -1; } } //this method is called from flexisip main thread, while service is running in its own thread. //To avoid using dedicated mutex, use the server post() method to delegate the processing of the push notification to the service thread. mIOService.post(std::bind(&PushNotificationClient::sendRequest,client,pn)); return 0; } void PushNotificationService::start() { if (mThread == NULL || !mThread->joinable()) { delete mThread; mThread = NULL; } if (mThread == NULL) { LOGD("Start PushNotificationService"); mHaveToStop = false; mThread = new thread(&PushNotificationService::run, this); } } void PushNotificationService::stop() { if (mThread != NULL) { LOGD("Stopping PushNotificationService"); mHaveToStop = true; mIOService.stop(); if (mThread->joinable()) { mThread->join(); } delete mThread; mThread = NULL; } } void PushNotificationService::waitEnd() { if (mThread != NULL) { LOGD("Waiting for PushNotificationService to end"); bool finished = false; while (!finished) { finished = true; map<string, std::shared_ptr<PushNotificationClient> >::const_iterator it; for (it = mClients.begin(); it != mClients.end(); ++it) { if (!it->second->isIdle()) { finished = false; break; } } } } } void PushNotificationService::setupClients(const string &certdir, const string &ca, int maxQueueSize) { struct dirent *dirent; DIR *dirp; MAX_QUEUE_SIZE = maxQueueSize; // Android Client string googleClient = string("google"); std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code err; ctx->set_options(ssl::context::default_workarounds, err); ctx->set_verify_mode(ssl::context::verify_none); mClients[googleClient]=std::make_shared<PushNotificationClient>(googleClient, this, ctx, GPN_ADDRESS, GPN_PORT, maxQueueSize, TRUE); dirp=opendir(certdir.c_str()); if (dirp==NULL){ LOGE("Could not open push notification certificates directory (%s): %s",certdir.c_str(),strerror(errno)); return; } while((dirent=readdir(dirp))!=NULL){ if (dirent->d_type!=DT_REG && dirent->d_type!=DT_LNK) continue; string cert=string(dirent->d_name); string certpath= string(certdir)+"/"+cert; std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code err; ctx->set_options(ssl::context::default_workarounds, err); ctx->set_password_callback(bind(&PushNotificationService::handle_password_callback, this, _1, _2)); if (!ca.empty()) { ctx->set_verify_mode(ssl::context::verify_peer); #if BOOST_VERSION >= 104800 ctx->set_verify_callback(bind(&PushNotificationService::handle_verify_callback, this, _1, _2)); #endif ctx->load_verify_file(ca, err); if (err) { LOGE("load_verify_file: %s",err.message().c_str()); } } else { ctx->set_verify_mode(ssl::context::verify_none); } ctx->add_verify_path("/etc/ssl/certs"); if (!cert.empty()) { ctx->use_certificate_file(certpath, ssl::context::file_format::pem, err); if (err) { LOGE("use_certificate_file %s: %s",certpath.c_str(), err.message().c_str()); } } string key=certpath; if (!key.empty()) { ctx->use_private_key_file(key, ssl::context::file_format::pem, err); if (err) { LOGE("use_private_key_file: %s",err.message().c_str()); } } string certName = cert.substr(0, cert.size() - 4); // Remove .pem at the end of cert const char *apn_server; if (certName.find(".dev")!=string::npos) apn_server=APN_DEV_ADDRESS; else apn_server=APN_PROD_ADDRESS; mClients[certName]=std::make_shared<PushNotificationClient>(cert, this, ctx, apn_server, APN_PORT, maxQueueSize, TRUE); } closedir(dirp); } PushNotificationService::PushNotificationService(const std::string &certdir, const std::string &cafile, int maxQueueSize, StatCounter64 *countFailed, StatCounter64 *countSent) : mIOService(), mThread(NULL), mCountFailed(countFailed), mCountSent(countSent) { setupClients(certdir, cafile, maxQueueSize); } PushNotificationService::~PushNotificationService() { stop(); } int PushNotificationService::run() { LOGD("PushNotificationService Start"); boost::asio::io_service::work work(mIOService); mIOService.run(); LOGD("PushNotificationService End"); return 0; } void PushNotificationService::clientEnded() { } boost::asio::io_service &PushNotificationService::getService() { return mIOService; } string PushNotificationService::handle_password_callback(size_t max_length, ssl::context_base::password_purpose purpose) const { return mPassword; } #if BOOST_VERSION >= 104800 bool PushNotificationService::handle_verify_callback(bool preverified, ssl::verify_context& ctx) const { char subject_name[256]; #if not(__GNUC__ == 4 && __GNUC_MINOR__ < 5 ) SLOGD << "Verifying " << [&] () { X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle()); X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256); return subject_name; }(); #else X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle()); X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256); SLOGD << "Verifying " << subject_name; #endif return preverified; } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2013 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 lower_named_interface_blocks.cpp * * This lowering pass converts all interface blocks with instance names * into interface blocks without an instance name. * * For example, the following shader: * * out block { * float block_var; * } inst_name; * * main() * { * inst_name.block_var = 0.0; * } * * Is rewritten to: * * out block { * float block_var; * }; * * main() * { * block_var = 0.0; * } * * This takes place after the shader code has already been verified with * the interface name in place. * * The linking phase will use the interface block name rather than the * interface's instance name when linking interfaces. * * This modification to the ir allows our currently existing dead code * elimination to work with interface blocks without changes. */ #include "glsl_symbol_table.h" #include "ir.h" #include "ir_optimization.h" #include "ir_rvalue_visitor.h" #include "program/hash_table.h" namespace { class flatten_named_interface_blocks_declarations : public ir_rvalue_visitor { public: void * const mem_ctx; hash_table *interface_namespace; flatten_named_interface_blocks_declarations(void *mem_ctx) : mem_ctx(mem_ctx), interface_namespace(NULL) { } void run(exec_list *instructions); virtual ir_visitor_status visit_leave(ir_assignment *); virtual void handle_rvalue(ir_rvalue **rvalue); }; } /* anonymous namespace */ void flatten_named_interface_blocks_declarations::run(exec_list *instructions) { interface_namespace = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare); /* First pass: adjust instance block variables with an instance name * to not have an instance name. * * The interface block variables are stored in the interface_namespace * hash table so they can be used in the second pass. */ foreach_in_list_safe(ir_instruction, node, instructions) { ir_variable *var = node->as_variable(); if (!var || !var->is_interface_instance()) continue; /* It should be possible to handle uniforms during this pass, * but, this will require changes to the other uniform block * support code. */ if (var->data.mode == ir_var_uniform || var->data.mode == ir_var_shader_storage) continue; const glsl_type * iface_t = var->type; const glsl_type * array_t = NULL; exec_node *insert_pos = var; if (iface_t->is_array()) { array_t = iface_t; iface_t = array_t->fields.array; } assert (iface_t->is_interface()); for (unsigned i = 0; i < iface_t->length; i++) { const char * field_name = iface_t->fields.structure[i].name; char *iface_field_name = ralloc_asprintf(mem_ctx, "%s %s.%s.%s", var->data.mode == ir_var_shader_in ? "in" : "out", iface_t->name, var->name, field_name); ir_variable *found_var = (ir_variable *) hash_table_find(interface_namespace, iface_field_name); if (!found_var) { ir_variable *new_var; char *var_name = ralloc_strdup(mem_ctx, iface_t->fields.structure[i].name); if (array_t == NULL) { new_var = new(mem_ctx) ir_variable(iface_t->fields.structure[i].type, var_name, (ir_variable_mode) var->data.mode); new_var->data.from_named_ifc_block_nonarray = 1; } else { const glsl_type *new_array_type = glsl_type::get_array_instance( iface_t->fields.structure[i].type, array_t->length); new_var = new(mem_ctx) ir_variable(new_array_type, var_name, (ir_variable_mode) var->data.mode); new_var->data.from_named_ifc_block_array = 1; } new_var->data.location = iface_t->fields.structure[i].location; new_var->data.explicit_location = (new_var->data.location >= 0); new_var->data.interpolation = iface_t->fields.structure[i].interpolation; new_var->data.centroid = iface_t->fields.structure[i].centroid; new_var->data.sample = iface_t->fields.structure[i].sample; new_var->data.patch = iface_t->fields.structure[i].patch; new_var->init_interface_type(iface_t); hash_table_insert(interface_namespace, new_var, iface_field_name); insert_pos->insert_after(new_var); insert_pos = new_var; } } var->remove(); } /* Second pass: visit all ir_dereference_record instances, and if they * reference an interface block, then flatten the refererence out. */ visit_list_elements(this, instructions); hash_table_dtor(interface_namespace); interface_namespace = NULL; } ir_visitor_status flatten_named_interface_blocks_declarations::visit_leave(ir_assignment *ir) { ir_dereference_record *lhs_rec = ir->lhs->as_dereference_record(); if (lhs_rec) { ir_rvalue *lhs_rec_tmp = lhs_rec; handle_rvalue(&lhs_rec_tmp); if (lhs_rec_tmp != lhs_rec) { ir->set_lhs(lhs_rec_tmp); } } return rvalue_visit(ir); } void flatten_named_interface_blocks_declarations::handle_rvalue(ir_rvalue **rvalue) { if (*rvalue == NULL) return; ir_dereference_record *ir = (*rvalue)->as_dereference_record(); if (ir == NULL) return; ir_variable *var = ir->variable_referenced(); if (var == NULL) return; if (!var->is_interface_instance()) return; /* It should be possible to handle uniforms during this pass, * but, this will require changes to the other uniform block * support code. */ if (var->data.mode == ir_var_uniform || var->data.mode == ir_var_shader_storage) return; if (var->get_interface_type() != NULL) { char *iface_field_name = ralloc_asprintf(mem_ctx, "%s %s.%s.%s", var->data.mode == ir_var_shader_in ? "in" : "out", var->get_interface_type()->name, var->name, ir->field); /* Find the variable in the set of flattened interface blocks */ ir_variable *found_var = (ir_variable *) hash_table_find(interface_namespace, iface_field_name); assert(found_var); ir_dereference_variable *deref_var = new(mem_ctx) ir_dereference_variable(found_var); ir_dereference_array *deref_array = ir->record->as_dereference_array(); if (deref_array != NULL) { *rvalue = new(mem_ctx) ir_dereference_array(deref_var, deref_array->array_index); } else { *rvalue = deref_var; } } } void lower_named_interface_blocks(void *mem_ctx, gl_shader *shader) { flatten_named_interface_blocks_declarations v_decl(mem_ctx); v_decl.run(shader->ir); } <commit_msg>glsl: Add support for lowering interface block arrays of arrays<commit_after>/* * Copyright (c) 2013 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 lower_named_interface_blocks.cpp * * This lowering pass converts all interface blocks with instance names * into interface blocks without an instance name. * * For example, the following shader: * * out block { * float block_var; * } inst_name; * * main() * { * inst_name.block_var = 0.0; * } * * Is rewritten to: * * out block { * float block_var; * }; * * main() * { * block_var = 0.0; * } * * This takes place after the shader code has already been verified with * the interface name in place. * * The linking phase will use the interface block name rather than the * interface's instance name when linking interfaces. * * This modification to the ir allows our currently existing dead code * elimination to work with interface blocks without changes. */ #include "glsl_symbol_table.h" #include "ir.h" #include "ir_optimization.h" #include "ir_rvalue_visitor.h" #include "program/hash_table.h" static const glsl_type * process_array_type(const glsl_type *type, unsigned idx) { const glsl_type *element_type = type->fields.array; if (element_type->is_array()) { const glsl_type *new_array_type = process_array_type(element_type, idx); return glsl_type::get_array_instance(new_array_type, type->length); } else { return glsl_type::get_array_instance( element_type->fields.structure[idx].type, type->length); } } static ir_rvalue * process_array_ir(void * const mem_ctx, ir_dereference_array *deref_array_prev, ir_rvalue *deref_var) { ir_dereference_array *deref_array = deref_array_prev->array->as_dereference_array(); if (deref_array == NULL) { return new(mem_ctx) ir_dereference_array(deref_var, deref_array_prev->array_index); } else { deref_array = (ir_dereference_array *) process_array_ir(mem_ctx, deref_array, deref_var); return new(mem_ctx) ir_dereference_array(deref_array, deref_array_prev->array_index); } } namespace { class flatten_named_interface_blocks_declarations : public ir_rvalue_visitor { public: void * const mem_ctx; hash_table *interface_namespace; flatten_named_interface_blocks_declarations(void *mem_ctx) : mem_ctx(mem_ctx), interface_namespace(NULL) { } void run(exec_list *instructions); virtual ir_visitor_status visit_leave(ir_assignment *); virtual void handle_rvalue(ir_rvalue **rvalue); }; } /* anonymous namespace */ void flatten_named_interface_blocks_declarations::run(exec_list *instructions) { interface_namespace = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare); /* First pass: adjust instance block variables with an instance name * to not have an instance name. * * The interface block variables are stored in the interface_namespace * hash table so they can be used in the second pass. */ foreach_in_list_safe(ir_instruction, node, instructions) { ir_variable *var = node->as_variable(); if (!var || !var->is_interface_instance()) continue; /* It should be possible to handle uniforms during this pass, * but, this will require changes to the other uniform block * support code. */ if (var->data.mode == ir_var_uniform || var->data.mode == ir_var_shader_storage) continue; const glsl_type * iface_t = var->type->without_array(); exec_node *insert_pos = var; assert (iface_t->is_interface()); for (unsigned i = 0; i < iface_t->length; i++) { const char * field_name = iface_t->fields.structure[i].name; char *iface_field_name = ralloc_asprintf(mem_ctx, "%s %s.%s.%s", var->data.mode == ir_var_shader_in ? "in" : "out", iface_t->name, var->name, field_name); ir_variable *found_var = (ir_variable *) hash_table_find(interface_namespace, iface_field_name); if (!found_var) { ir_variable *new_var; char *var_name = ralloc_strdup(mem_ctx, iface_t->fields.structure[i].name); if (!var->type->is_array()) { new_var = new(mem_ctx) ir_variable(iface_t->fields.structure[i].type, var_name, (ir_variable_mode) var->data.mode); new_var->data.from_named_ifc_block_nonarray = 1; } else { const glsl_type *new_array_type = process_array_type(var->type, i); new_var = new(mem_ctx) ir_variable(new_array_type, var_name, (ir_variable_mode) var->data.mode); new_var->data.from_named_ifc_block_array = 1; } new_var->data.location = iface_t->fields.structure[i].location; new_var->data.explicit_location = (new_var->data.location >= 0); new_var->data.interpolation = iface_t->fields.structure[i].interpolation; new_var->data.centroid = iface_t->fields.structure[i].centroid; new_var->data.sample = iface_t->fields.structure[i].sample; new_var->data.patch = iface_t->fields.structure[i].patch; new_var->init_interface_type(iface_t); hash_table_insert(interface_namespace, new_var, iface_field_name); insert_pos->insert_after(new_var); insert_pos = new_var; } } var->remove(); } /* Second pass: visit all ir_dereference_record instances, and if they * reference an interface block, then flatten the refererence out. */ visit_list_elements(this, instructions); hash_table_dtor(interface_namespace); interface_namespace = NULL; } ir_visitor_status flatten_named_interface_blocks_declarations::visit_leave(ir_assignment *ir) { ir_dereference_record *lhs_rec = ir->lhs->as_dereference_record(); if (lhs_rec) { ir_rvalue *lhs_rec_tmp = lhs_rec; handle_rvalue(&lhs_rec_tmp); if (lhs_rec_tmp != lhs_rec) { ir->set_lhs(lhs_rec_tmp); } } return rvalue_visit(ir); } void flatten_named_interface_blocks_declarations::handle_rvalue(ir_rvalue **rvalue) { if (*rvalue == NULL) return; ir_dereference_record *ir = (*rvalue)->as_dereference_record(); if (ir == NULL) return; ir_variable *var = ir->variable_referenced(); if (var == NULL) return; if (!var->is_interface_instance()) return; /* It should be possible to handle uniforms during this pass, * but, this will require changes to the other uniform block * support code. */ if (var->data.mode == ir_var_uniform || var->data.mode == ir_var_shader_storage) return; if (var->get_interface_type() != NULL) { char *iface_field_name = ralloc_asprintf(mem_ctx, "%s %s.%s.%s", var->data.mode == ir_var_shader_in ? "in" : "out", var->get_interface_type()->name, var->name, ir->field); /* Find the variable in the set of flattened interface blocks */ ir_variable *found_var = (ir_variable *) hash_table_find(interface_namespace, iface_field_name); assert(found_var); ir_dereference_variable *deref_var = new(mem_ctx) ir_dereference_variable(found_var); ir_dereference_array *deref_array = ir->record->as_dereference_array(); if (deref_array != NULL) { *rvalue = process_array_ir(mem_ctx, deref_array, (ir_rvalue *)deref_var); } else { *rvalue = deref_var; } } } void lower_named_interface_blocks(void *mem_ctx, gl_shader *shader) { flatten_named_interface_blocks_declarations v_decl(mem_ctx); v_decl.run(shader->ir); } <|endoftext|>
<commit_before>/* ** License Applicability. Except to the extent portions of this file are ** made subject to an alternative license as permitted in the SGI Free ** Software License B, Version 1.1 (the "License"), the contents of this ** file are subject only to the provisions of the License. You may not use ** this file except in compliance with the License. You may obtain a copy ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: ** ** http://oss.sgi.com/projects/FreeB ** ** Note that, as provided in the License, the Software is distributed on an ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. ** ** Original Code. The Original Code is: OpenGL Sample Implementation, ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, ** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. ** Copyright in any portions created by third parties is as indicated ** elsewhere herein. All Rights Reserved. ** ** Additional Notice Provisions: The application programming interfaces ** established by SGI in conjunction with the Original Code are The ** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released ** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version ** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X ** Window System(R) (Version 1.3), released October 19, 1998. This software ** was created using the OpenGL(R) version 1.2.1 Sample Implementation ** published by SGI, but has not been independently verified as being ** compliant with the OpenGL(R) version 1.2.1 Specification. */ /* * bufpool.c++ * */ #include "glimports.h" #include "myassert.h" #include "bufpool.h" /*----------------------------------------------------------------------------- * Pool - allocate a new pool of buffers *----------------------------------------------------------------------------- */ Pool::Pool( int _buffersize, int initpoolsize, const char *n ) { if((unsigned)_buffersize < sizeof(Buffer)) buffersize = sizeof(Buffer); else buffersize = _buffersize; initsize = initpoolsize * buffersize; nextsize = initsize; name = n; magic = is_allocated; nextblock = 0; curblock = 0; freelist = 0; nextfree = 0; } /*----------------------------------------------------------------------------- * ~Pool - free a pool of buffers and the pool itself *----------------------------------------------------------------------------- */ Pool::~Pool( void ) { assert( (this != 0) && (magic == is_allocated) ); while( nextblock ) { delete [] blocklist[--nextblock]; blocklist[nextblock] = 0; } magic = is_free; } void Pool::grow( void ) { assert( (this != 0) && (magic == is_allocated) ); curblock = new char[nextsize]; blocklist[nextblock++] = curblock; nextfree = nextsize; nextsize *= 2; } /*----------------------------------------------------------------------------- * Pool::clear - free buffers associated with pool but keep pool *----------------------------------------------------------------------------- */ void Pool::clear( void ) { assert( (this != 0) && (magic == is_allocated) ); while( nextblock ) { delete [] blocklist[--nextblock]; blocklist[nextblock] = 0; } curblock = 0; freelist = 0; nextfree = 0; if( nextsize > initsize ) nextsize /= 2; } <commit_msg>glu/sgi: Initialize member of class Pool.<commit_after>/* ** License Applicability. Except to the extent portions of this file are ** made subject to an alternative license as permitted in the SGI Free ** Software License B, Version 1.1 (the "License"), the contents of this ** file are subject only to the provisions of the License. You may not use ** this file except in compliance with the License. You may obtain a copy ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: ** ** http://oss.sgi.com/projects/FreeB ** ** Note that, as provided in the License, the Software is distributed on an ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. ** ** Original Code. The Original Code is: OpenGL Sample Implementation, ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, ** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. ** Copyright in any portions created by third parties is as indicated ** elsewhere herein. All Rights Reserved. ** ** Additional Notice Provisions: The application programming interfaces ** established by SGI in conjunction with the Original Code are The ** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released ** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version ** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X ** Window System(R) (Version 1.3), released October 19, 1998. This software ** was created using the OpenGL(R) version 1.2.1 Sample Implementation ** published by SGI, but has not been independently verified as being ** compliant with the OpenGL(R) version 1.2.1 Specification. */ /* * bufpool.c++ * */ #include "glimports.h" #include "myassert.h" #include "bufpool.h" /*----------------------------------------------------------------------------- * Pool - allocate a new pool of buffers *----------------------------------------------------------------------------- */ Pool::Pool( int _buffersize, int initpoolsize, const char *n ) { if((unsigned)_buffersize < sizeof(Buffer)) buffersize = sizeof(Buffer); else buffersize = _buffersize; initsize = initpoolsize * buffersize; nextsize = initsize; name = n; magic = is_allocated; nextblock = 0; curblock = 0; freelist = 0; nextfree = 0; for (int i = 0; i < NBLOCKS; i++) { blocklist[i] = 0; } } /*----------------------------------------------------------------------------- * ~Pool - free a pool of buffers and the pool itself *----------------------------------------------------------------------------- */ Pool::~Pool( void ) { assert( (this != 0) && (magic == is_allocated) ); while( nextblock ) { delete [] blocklist[--nextblock]; blocklist[nextblock] = 0; } magic = is_free; } void Pool::grow( void ) { assert( (this != 0) && (magic == is_allocated) ); curblock = new char[nextsize]; blocklist[nextblock++] = curblock; nextfree = nextsize; nextsize *= 2; } /*----------------------------------------------------------------------------- * Pool::clear - free buffers associated with pool but keep pool *----------------------------------------------------------------------------- */ void Pool::clear( void ) { assert( (this != 0) && (magic == is_allocated) ); while( nextblock ) { delete [] blocklist[--nextblock]; blocklist[nextblock] = 0; } curblock = 0; freelist = 0; nextfree = 0; if( nextsize > initsize ) nextsize /= 2; } <|endoftext|>
<commit_before>#ifndef BENCHMARKS_DESCRIPTORS_SWIG_HPP #define BENCHMARKS_DESCRIPTORS_SWIG_HPP #include <joint/devkit/JointException.hpp> #include <joint/devkit/Logger.hpp> #include <joint/devkit/ManifestReader.hpp> #include <joint/devkit/StringBuilder.hpp> #include <jni.h> #include <implementations/swig/ISwigBenchmarks.hpp> #if defined(_DEBUG) # undef _DEBUG # include <Python.h> # define _DEBUG #else # include <Python.h> #endif namespace descriptors { namespace swig { namespace detail { template < typename T_ > T_ SwigJavaCallImpl(JNIEnv* env, T_ val, const char* msg) { if (env->ExceptionOccurred()) { env->ExceptionDescribe(); env->ExceptionClear(); throw std::runtime_error(msg); } return val; } } #define SWIG_JAVA_CALL(...) ::descriptors::swig::detail::SwigJavaCallImpl(env, (__VA_ARGS__), #__VA_ARGS__ " failed at " JOINT_SOURCE_LOCATION) struct Desc { JOINT_DEVKIT_LOGGER("Benchmarks.Swig"); class Invokable : public IBasicInvokable { public: void VoidToVoid() { } void I32ToVoid(int32_t) { } int32_t VoidToI32() { return 0; } void StringToVoid(const std::string& s) { } std::string VoidToString3() { return "abc"; } std::string VoidToString100() { return "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; } }; using BenchmarksPtr = IBasicBenchmarks*; class BenchmarkCtx { class Jvm { JOINT_DEVKIT_LOGGER("Benchmarks.Swig.Java"); public: JavaVM* jvm; jclass SwigBenchmarks_cls; public: static Jvm& Instance(const std::string& jar, const std::string& className) { static std::string jar_static = jar; JOINT_CHECK(jar_static == jar, "Java configuration mismatch!"); static std::string class_name_static = className; JOINT_CHECK(class_name_static == className, "Java configuration mismatch!"); static Jvm inst(jar, className); return inst; } JNIEnv* GetEnv() const { JNIEnv* env = nullptr; int retcode = jvm->GetEnv((void**)&env, JNI_VERSION_1_6); JOINT_CHECK(retcode == JNI_OK, ::joint::devkit::StringBuilder() % "jvm->GetEnv failed: " % retcode); return env; } private: Jvm(const std::string& jar, const std::string& className) { using namespace ::joint::devkit; std::string class_path_opt = "-Djava.class.path=" + jar; std::string lib_path_opt = "-Djava.library.path=/home/koplyarov/work/joint/build/bin"; JavaVMOption opt[] = { { const_cast<char*>(class_path_opt.c_str()), nullptr }, { const_cast<char*>(lib_path_opt.c_str()), nullptr } }; JavaVMInitArgs vm_args = { }; vm_args.version = 0x00010006; jint ret = JNI_GetDefaultJavaVMInitArgs(&vm_args); JOINT_CHECK(ret == 0, StringBuilder() % "JNI_GetDefaultJavaVMInitArgs failed: " % ret); vm_args.options = opt; vm_args.nOptions = sizeof(opt) / sizeof(opt[0]); JNIEnv* env = nullptr; ret = JNI_CreateJavaVM(&jvm, reinterpret_cast<void**>(&env), &vm_args); JOINT_CHECK(ret == 0, StringBuilder() % "JNI_CreateJavaVM failed: " % ret); JOINT_CHECK(jvm, "JNI_CreateJavaVM failed!"); auto s = SWIG_JAVA_CALL(env->FindClass(className.c_str())); SwigBenchmarks_cls = SWIG_JAVA_CALL((jclass)env->NewGlobalRef((jobject)s)); env->DeleteLocalRef(s); } ~Jvm() { auto env = GetEnv(); env->DeleteGlobalRef(SwigBenchmarks_cls); jvm->DestroyJavaVM(); } }; struct PyModuleManifest : public ::joint::devkit::ModuleManifestBase { std::string ModuleName; template < typename Archive_ > void Deserialize(const Archive_& ar) { ar.Deserialize("module", ModuleName); } }; struct JavaModuleManifest : public ::joint::devkit::ModuleManifestBase { std::string Jar; std::string ClassName; template < typename Archive_ > void Deserialize(const Archive_& ar) { ar.Deserialize("class", ClassName).Deserialize("jar", Jar); } }; private: std::string _jar; std::string _className; PyObject* _pyBenchmarks = nullptr; jobject _javaBenchmarks = nullptr; public: BenchmarkCtx(const std::string& language) { std::string module_manifest_path = "benchmarks/implementations/swig/" + language + ".manifest"; using namespace ::joint::devkit; JointCore_ManifestHandle m; JointCore_Error err = Joint_ReadManifestFromFile(module_manifest_path.c_str(), &m); JOINT_CHECK(err == JOINT_CORE_ERROR_NONE, err); auto sg = ScopeExit([&]{ Joint_DeleteManifest(m); }); ModuleManifestBase md; ManifestReader::Read(m, md); auto binding_name = md.GetBindingName(); if (binding_name == "python") { PyModuleManifest md; ManifestReader::Read(m, md); Py_Initialize(); PyObject* py_module_name = PyUnicode_FromString(md.ModuleName.c_str()); PyObject* py_module = PyImport_Import(py_module_name); if (!py_module) throw std::runtime_error("Could not import " + md.ModuleName); const char* getter_name = "GetBenchmarks"; PyObject* py_getter = PyObject_GetAttrString(py_module, getter_name); if (!py_getter) throw std::runtime_error("Could not find " + std::string(getter_name) + " function in " + md.ModuleName); _pyBenchmarks = PyObject_CallObject(py_getter, nullptr); if (!_pyBenchmarks) throw std::runtime_error("Could not get benchmarks object!"); } else if (binding_name == "java") { JavaModuleManifest md; ManifestReader::Read(m, md); _jar = md.Jar; _className = md.ClassName; auto& jctx = Jvm::Instance(_jar, _className); auto env = jctx.GetEnv(); jmethodID ctor = SWIG_JAVA_CALL(env->GetMethodID(jctx.SwigBenchmarks_cls, "<init>", "()V")); auto b = SWIG_JAVA_CALL(env->NewObject(jctx.SwigBenchmarks_cls, ctor)); _javaBenchmarks = SWIG_JAVA_CALL(env->NewGlobalRef(b)); } else throw std::runtime_error("Binding not supported!"); } BenchmarkCtx(const BenchmarkCtx&) = delete; BenchmarkCtx& operator = (const BenchmarkCtx&) = delete; ~BenchmarkCtx() { using namespace ::joint::devkit; if (_pyBenchmarks) { Py_DECREF(_pyBenchmarks); Py_Finalize(); } if (_javaBenchmarks) { auto env = Jvm::Instance(_jar, _className).GetEnv(); env->DeleteGlobalRef(_javaBenchmarks); } } IBasicBenchmarks* CreateBenchmarks() const { auto result = GetGlobalBenchmarks(); if (!result) throw std::runtime_error("Global benchmarks not set!"); return result; } IBasicInvokable* CreateLocalInvokable() { return new Invokable; } }; static std::string GetName() { return "swig"; } }; }} #endif <commit_msg>Removed hardcoded path from Java swig runner<commit_after>#ifndef BENCHMARKS_DESCRIPTORS_SWIG_HPP #define BENCHMARKS_DESCRIPTORS_SWIG_HPP #include <joint/devkit/JointException.hpp> #include <joint/devkit/Logger.hpp> #include <joint/devkit/ManifestReader.hpp> #include <joint/devkit/StringBuilder.hpp> #include <joint/devkit/system/CurrentLibraryPath.hpp> #include <implementations/swig/ISwigBenchmarks.hpp> #include <jni.h> #if defined(_DEBUG) # undef _DEBUG # include <Python.h> # define _DEBUG #else # include <Python.h> #endif namespace descriptors { namespace swig { namespace detail { template < typename T_ > T_ SwigJavaCallImpl(JNIEnv* env, T_ val, const char* msg) { if (env->ExceptionOccurred()) { env->ExceptionDescribe(); env->ExceptionClear(); throw std::runtime_error(msg); } return val; } } #define SWIG_JAVA_CALL(...) ::descriptors::swig::detail::SwigJavaCallImpl(env, (__VA_ARGS__), #__VA_ARGS__ " failed at " JOINT_SOURCE_LOCATION) struct Desc { JOINT_DEVKIT_LOGGER("Benchmarks.Swig"); class Invokable : public IBasicInvokable { public: void VoidToVoid() { } void I32ToVoid(int32_t) { } int32_t VoidToI32() { return 0; } void StringToVoid(const std::string& s) { } std::string VoidToString3() { return "abc"; } std::string VoidToString100() { return "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; } }; using BenchmarksPtr = IBasicBenchmarks*; class BenchmarkCtx { class Jvm { JOINT_DEVKIT_LOGGER("Benchmarks.Swig.Java"); public: JavaVM* jvm; jclass SwigBenchmarks_cls; public: static Jvm& Instance(const std::string& jar, const std::string& className) { static std::string jar_static = jar; JOINT_CHECK(jar_static == jar, "Java configuration mismatch!"); static std::string class_name_static = className; JOINT_CHECK(class_name_static == className, "Java configuration mismatch!"); static Jvm inst(jar, className); return inst; } JNIEnv* GetEnv() const { JNIEnv* env = nullptr; int retcode = jvm->GetEnv((void**)&env, JNI_VERSION_1_6); JOINT_CHECK(retcode == JNI_OK, ::joint::devkit::StringBuilder() % "jvm->GetEnv failed: " % retcode); return env; } private: Jvm(const std::string& jar, const std::string& className) { using namespace ::joint::devkit; auto current_lib_path = CurrentLibraryPath::Get(); auto last_slash_index = current_lib_path.find_last_of("/\\"); auto current_lib_dir = (last_slash_index == std::string::npos) ? std::string() : current_lib_path.substr(0, last_slash_index); std::string class_path_opt = "-Djava.class.path=" + jar; std::string lib_path_opt = "-Djava.library.path=" + current_lib_dir; JavaVMOption opt[] = { { const_cast<char*>(class_path_opt.c_str()), nullptr }, { const_cast<char*>(lib_path_opt.c_str()), nullptr } }; JavaVMInitArgs vm_args = { }; vm_args.version = 0x00010006; jint ret = JNI_GetDefaultJavaVMInitArgs(&vm_args); JOINT_CHECK(ret == 0, StringBuilder() % "JNI_GetDefaultJavaVMInitArgs failed: " % ret); vm_args.options = opt; vm_args.nOptions = sizeof(opt) / sizeof(opt[0]); JNIEnv* env = nullptr; ret = JNI_CreateJavaVM(&jvm, reinterpret_cast<void**>(&env), &vm_args); JOINT_CHECK(ret == 0, StringBuilder() % "JNI_CreateJavaVM failed: " % ret); JOINT_CHECK(jvm, "JNI_CreateJavaVM failed!"); auto s = SWIG_JAVA_CALL(env->FindClass(className.c_str())); SwigBenchmarks_cls = SWIG_JAVA_CALL((jclass)env->NewGlobalRef((jobject)s)); env->DeleteLocalRef(s); } ~Jvm() { auto env = GetEnv(); env->DeleteGlobalRef(SwigBenchmarks_cls); jvm->DestroyJavaVM(); } }; struct PyModuleManifest : public ::joint::devkit::ModuleManifestBase { std::string ModuleName; template < typename Archive_ > void Deserialize(const Archive_& ar) { ar.Deserialize("module", ModuleName); } }; struct JavaModuleManifest : public ::joint::devkit::ModuleManifestBase { std::string Jar; std::string ClassName; template < typename Archive_ > void Deserialize(const Archive_& ar) { ar.Deserialize("class", ClassName).Deserialize("jar", Jar); } }; private: std::string _jar; std::string _className; PyObject* _pyBenchmarks = nullptr; jobject _javaBenchmarks = nullptr; public: BenchmarkCtx(const std::string& language) { std::string module_manifest_path = "benchmarks/implementations/swig/" + language + ".manifest"; using namespace ::joint::devkit; JointCore_ManifestHandle m; JointCore_Error err = Joint_ReadManifestFromFile(module_manifest_path.c_str(), &m); JOINT_CHECK(err == JOINT_CORE_ERROR_NONE, err); auto sg = ScopeExit([&]{ Joint_DeleteManifest(m); }); ModuleManifestBase md; ManifestReader::Read(m, md); auto binding_name = md.GetBindingName(); if (binding_name == "python") { PyModuleManifest md; ManifestReader::Read(m, md); Py_Initialize(); PyObject* py_module_name = PyUnicode_FromString(md.ModuleName.c_str()); PyObject* py_module = PyImport_Import(py_module_name); if (!py_module) throw std::runtime_error("Could not import " + md.ModuleName); const char* getter_name = "GetBenchmarks"; PyObject* py_getter = PyObject_GetAttrString(py_module, getter_name); if (!py_getter) throw std::runtime_error("Could not find " + std::string(getter_name) + " function in " + md.ModuleName); _pyBenchmarks = PyObject_CallObject(py_getter, nullptr); if (!_pyBenchmarks) throw std::runtime_error("Could not get benchmarks object!"); } else if (binding_name == "java") { JavaModuleManifest md; ManifestReader::Read(m, md); _jar = md.Jar; _className = md.ClassName; auto& jctx = Jvm::Instance(_jar, _className); auto env = jctx.GetEnv(); jmethodID ctor = SWIG_JAVA_CALL(env->GetMethodID(jctx.SwigBenchmarks_cls, "<init>", "()V")); auto b = SWIG_JAVA_CALL(env->NewObject(jctx.SwigBenchmarks_cls, ctor)); _javaBenchmarks = SWIG_JAVA_CALL(env->NewGlobalRef(b)); } else throw std::runtime_error("Binding not supported!"); } BenchmarkCtx(const BenchmarkCtx&) = delete; BenchmarkCtx& operator = (const BenchmarkCtx&) = delete; ~BenchmarkCtx() { using namespace ::joint::devkit; if (_pyBenchmarks) { Py_DECREF(_pyBenchmarks); Py_Finalize(); } if (_javaBenchmarks) { auto env = Jvm::Instance(_jar, _className).GetEnv(); env->DeleteGlobalRef(_javaBenchmarks); } } IBasicBenchmarks* CreateBenchmarks() const { auto result = GetGlobalBenchmarks(); if (!result) throw std::runtime_error("Global benchmarks not set!"); return result; } IBasicInvokable* CreateLocalInvokable() { return new Invokable; } }; static std::string GetName() { return "swig"; } }; }} #endif <|endoftext|>
<commit_before>#include <benchmark/benchmark.h> #include <flexcore/range/actions.hpp> #include <flexcore/core/connection.hpp> #include <random> #include <algorithm> // Benchmark of flexcore range functions using fc::operator>>; struct loop { decltype(auto) operator()(std::vector<float> in, float x, float y) { for (size_t i = 0; i != in.size(); ++i) { in[i] = y + x * in[i]; } return in; } }; struct fc_map_inline { decltype(auto) operator()(std::vector<float> in, float x, float y) { return (fc::actions::map([x](auto in) {return x * in;}) >> fc::actions::map([y](auto in) {return y + in;}))(std::move(in)); } }; struct fc_map { decltype(auto) operator()(std::vector<float> in, float x, float y) { return fc::actions::map([x,y](auto in) {return y + x * in;})(std::move(in)); } }; constexpr auto benchmark_size = 2 << 15; /// Copying a std::vector serves as a simple baseline static void VectorCopy(benchmark::State& state) { std::vector<int> vec(state.range(0)); while (state.KeepRunning()) std::vector<int> copy(vec); } template<class T> void vector_muladd_f(benchmark::State& state) { T f; std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> d(0, 10000); std::vector<float> a(state.range(0)); std::vector<float> b(state.range(0)); std::generate(a.begin(), a.end(), [&]() {return d(gen);}); std::generate(b.begin(), b.end(), [&]() {return d(gen);}); float x = d(gen); float y = d(gen); while (state.KeepRunning()) { auto tmp = b; benchmark::DoNotOptimize(tmp); a = f(tmp,x,y); benchmark::DoNotOptimize(a); } } BENCHMARK(VectorCopy) ->RangeMultiplier(2)->Range(64, benchmark_size); BENCHMARK_TEMPLATE(vector_muladd_f, loop) ->RangeMultiplier(2)->Range(64, benchmark_size); BENCHMARK_TEMPLATE(vector_muladd_f, fc_map) ->RangeMultiplier(2)->Range(64, benchmark_size); BENCHMARK_TEMPLATE(vector_muladd_f, fc_map_inline) ->RangeMultiplier(2)->Range(64, benchmark_size); BENCHMARK_MAIN() <commit_msg>add benchmark for filter and map loop<commit_after>#include <benchmark/benchmark.h> #include <flexcore/range/actions.hpp> #include <flexcore/core/connection.hpp> #include <random> #include <algorithm> // Benchmark of flexcore range functions using fc::operator>>; struct map_loop { decltype(auto) operator()(std::vector<float> in, float x, float y) { for (size_t i = 0; i != in.size(); ++i) { in[i] = y + x * in[i]; } return in; } }; struct fc_map_inline { decltype(auto) operator()(std::vector<float> in, float x, float y) { return (fc::actions::map([x](auto in) {return x * in;}) >> fc::actions::map([y](auto in) {return y + in;}))(std::move(in)); } }; struct fc_map { decltype(auto) operator()(std::vector<float> in, float x, float y) { return fc::actions::map([x,y](auto in) {return y + x * in;})(std::move(in)); } }; constexpr auto filter_factor = 0.25; constexpr auto filter_value = filter_factor * 10000; struct filter_loop { decltype(auto) operator()(std::vector<float> in, float x, float y) { for (size_t i = 0; i != in.size(); ++i) { if(in[i] > filter_value) in[i] = y + x * in[i]; } return in; } }; struct fc_filter_map { decltype(auto) operator()(std::vector<float> in, float x, float y) { return (fc::actions::filter([](auto in){ return in > filter_value;}) >> fc::actions::map([x](auto in) {return x * in;}) >> fc::actions::map([y](auto in) {return y + in;}))(std::move(in)); } }; constexpr auto benchmark_size = 2 << 15; /// Copying a std::vector serves as a simple baseline static void VectorCopy(benchmark::State& state) { std::vector<int> vec(state.range(0)); while (state.KeepRunning()) std::vector<int> copy(vec); } template<class T> void vector_f(benchmark::State& state) { T f; std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> d(0, 10000); std::vector<float> a(state.range(0)); std::vector<float> b(state.range(0)); std::generate(b.begin(), b.end(), [&]() {return d(gen);}); float x = d(gen); float y = d(gen); while (state.KeepRunning()) { auto tmp = b; benchmark::DoNotOptimize(tmp); a = f(tmp,x,y); benchmark::DoNotOptimize(a); } } //BENCHMARK(VectorCopy) // ->RangeMultiplier(2)->Range(64, benchmark_size); //BENCHMARK_TEMPLATE(vector_f, map_loop) // ->RangeMultiplier(2)->Range(64, benchmark_size); //BENCHMARK_TEMPLATE(vector_f, fc_map) // ->RangeMultiplier(2)->Range(64, benchmark_size); //BENCHMARK_TEMPLATE(vector_f, fc_map_inline) // ->RangeMultiplier(2)->Range(64, benchmark_size); BENCHMARK_TEMPLATE(vector_f, filter_loop) ->RangeMultiplier(2)->Range(64, benchmark_size); BENCHMARK_TEMPLATE(vector_f, fc_filter_map) ->RangeMultiplier(2)->Range(64, benchmark_size); BENCHMARK_MAIN() <|endoftext|>
<commit_before>/** * @file ncl.cpp * * @date Apr 10, 2013 * @author peramaki */ #include "ncl.h" #include "plugin_factory.h" #include "logger_factory.h" #include <boost/lexical_cast.hpp> #include "level.h" #include "forecast_time.h" #define HIMAN_AUXILIARY_INCLUDE #include "neons.h" #include "radon.h" #undef HIMAN_AUXILIARY_INCLUDE using namespace std; using namespace himan::plugin; const string itsName("ncl"); ncl::ncl() : itsBottomLevel(kHPMissingInt), itsTopLevel(kHPMissingInt) { itsClearTextFormula = "???"; itsLogger = logger_factory::Instance()->GetLog(itsName); } void ncl::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); HPDatabaseType dbtype = conf->DatabaseType(); if (dbtype == kNeons || dbtype == kNeonsAndRadon) { auto n = GET_PLUGIN(neons); itsBottomLevel = boost::lexical_cast<int> (n->ProducerMetaData(itsConfiguration->SourceProducer().Id(), "last hybrid level number")); itsTopLevel = boost::lexical_cast<int> (n->ProducerMetaData(itsConfiguration->SourceProducer().Id(), "first hybrid level number")); } if ((dbtype == kRadon || dbtype == kNeonsAndRadon) && (itsBottomLevel == kHPMissingInt || itsTopLevel == kHPMissingInt)) { auto r = GET_PLUGIN(radon); itsBottomLevel = boost::lexical_cast<int> (r->ProducerMetaData(itsConfiguration->SourceProducer().Id(), "last hybrid level number")); itsTopLevel = boost::lexical_cast<int> (r->ProducerMetaData(itsConfiguration->SourceProducer().Id(), "first hybrid level number")); } param theRequestedParam; if (itsConfiguration->Exists("temp") && itsConfiguration->GetValue("temp") == "-20" ) { theRequestedParam.Name("HM20C-M"); theRequestedParam.UnivId(28); itsTargetTemperature = -20; } if (itsConfiguration->Exists("temp") && itsConfiguration->GetValue("temp") == "0" ) { theRequestedParam.Name("H0C-M"); theRequestedParam.UnivId(270); itsTargetTemperature = 0; } SetParams({theRequestedParam}); Start(); } /* * Calculate() * * This function does the actual calculation. */ void ncl::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex) { const param HParam("HL-M"); const param TParam("T-K"); int levelNumber = itsBottomLevel; level HLevel(himan::kHybrid, static_cast<float> (levelNumber), "HYBRID"); auto myThreadedLogger = logger_factory::Instance()->GetLog(itsName + "Thread #" + boost::lexical_cast<string> (threadIndex)); forecast_time forecastTime = myTargetInfo->Time(); level forecastLevel = myTargetInfo->Level(); forecast_type forecastType = myTargetInfo->ForecastType(); myThreadedLogger->Info("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + " level " + static_cast<string> (forecastLevel)); info_t HInfo = Fetch(forecastTime, HLevel, HParam, forecastType, false); info_t TInfo = Fetch(forecastTime, HLevel, TParam, forecastType, false); if (!HInfo || !TInfo) { myThreadedLogger->Warning("Skipping step " + boost::lexical_cast<string> (forecastTime.Step()) + ", level " + static_cast<string> (forecastLevel)); return; } bool firstLevel = true; myTargetInfo->Data().Fill(-1); HInfo->ResetLocation(); TInfo->ResetLocation(); level curLevel = HLevel; level prevLevel; string deviceType = "CPU"; info_t prevHInfo, prevTInfo; while (--levelNumber >= itsTopLevel) { myThreadedLogger->Trace("Level: " + boost::lexical_cast<string> (levelNumber)); if (prevHInfo) { prevHInfo->ResetLocation(); } if (prevTInfo) { prevTInfo->ResetLocation(); } assert(HInfo && TInfo); LOCKSTEP(myTargetInfo, TInfo, HInfo) { double height = HInfo->Value(); double temp = TInfo->Value(); double prevHeight(kFloatMissing); double prevTemp(kFloatMissing); double targetHeight = myTargetInfo->Value(); if (!firstLevel) { prevHInfo->NextLocation(); prevHeight = prevHInfo->Value(); prevTInfo->NextLocation(); prevTemp = prevTInfo->Value(); } if (height == kFloatMissing || temp == kFloatMissing || (!firstLevel && (prevHeight == kFloatMissing || prevTemp == kFloatMissing))) { continue; } temp -= himan::constants::kKelvin; prevTemp -= himan::constants::kKelvin; if (targetHeight != -1) { if (temp >= itsTargetTemperature) // && levelNumber >= (itsBottomLevel - 5)) { /* * Lowest 5 model levels and "inversion fix". * * Especially in winter time surface inversion is common: temperature * close to ground surfaceis colder than the temperature above it. * This inversion is usually very limited in height, maybe 10 .. 200 * meters. When calculating height of zero level, we can take into * account this inversion so we test if the temperature at lowest level * is already below target temperature (0 or -20), and if that is the * situation we do not directly set height to kFloatMissing but * move onwards and only if the temperature stays below target for * the first 5 levels (in Hirlam lowest hybrid levels are spaced ~30m * apart) we can say that surface inversion does not exist and the * air temperature is simply too cold for this target temperature. * * In order to imitate hilake however the inversion fix limitation for * bottom 5 has been disabled, since what hilake does is it applies * the fix as long as the process is running, at least up to hybrid * level 29 which on Hirlam is on average 3700m above ground. * * This seems like a non-optimal approach but this is how hilake * does it and until we have confirmation that the inversion * height should be limited, use the hilake way also in himan. * * Inversion: http://blogi.foreca.fi/2012/01/pakkanen-ja-inversio/ */ myTargetInfo->Value(-1); } // No inversion fix, value already found for this gridpoint // (real value or missing value) continue; } if ((firstLevel && temp < itsTargetTemperature) || (prevTemp < itsTargetTemperature && temp < itsTargetTemperature)) { /* * Height is below ground (first model level) or its so cold * in the lower atmosphere that we cannot find the requested * temperature, set height to to missing value. */ targetHeight = kFloatMissing; } else if (prevTemp > itsTargetTemperature && temp < itsTargetTemperature) { // Found value, interpolate double p_rel = (itsTargetTemperature - temp) / (prevTemp - temp); targetHeight = height + (prevHeight - height) * p_rel; } else { // Too warm continue; } myTargetInfo->Value(targetHeight); } prevLevel = curLevel; curLevel = level(himan::kHybrid, static_cast<float> (levelNumber), "HYBRID"); HInfo = Fetch(forecastTime, curLevel, HParam, forecastType, false); TInfo = Fetch(forecastTime, curLevel, TParam, forecastType, false); prevHInfo = Fetch(forecastTime, prevLevel, HParam, forecastType, false); prevTInfo = Fetch(forecastTime, prevLevel, TParam, forecastType, false); firstLevel = false; if (CountValues(myTargetInfo)) { break; } } /* * Replaces all unset values */ myTargetInfo->ResetLocation(); while(myTargetInfo->NextLocation()) { if ( myTargetInfo->Value() == -1) { myTargetInfo->Value(kFloatMissing); } } myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string> (myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<string> (myTargetInfo->Data().Size())); } bool ncl::CountValues(const shared_ptr<himan::info> values) { size_t s = values->Data().Size(); for (size_t j = 0; j < s; j++) { if (values->Data().At(j) == -1) return false; } return true; } <commit_msg>bugfix for the case when source data runs out before zero level has been found<commit_after>/** * @file ncl.cpp * * @date Apr 10, 2013 * @author peramaki */ #include "ncl.h" #include "plugin_factory.h" #include "logger_factory.h" #include <boost/lexical_cast.hpp> #include "level.h" #include "forecast_time.h" #define HIMAN_AUXILIARY_INCLUDE #include "neons.h" #include "radon.h" #undef HIMAN_AUXILIARY_INCLUDE using namespace std; using namespace himan::plugin; const string itsName("ncl"); ncl::ncl() : itsBottomLevel(kHPMissingInt), itsTopLevel(kHPMissingInt) { itsClearTextFormula = "???"; itsLogger = logger_factory::Instance()->GetLog(itsName); } void ncl::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); HPDatabaseType dbtype = conf->DatabaseType(); if (dbtype == kNeons || dbtype == kNeonsAndRadon) { auto n = GET_PLUGIN(neons); itsBottomLevel = boost::lexical_cast<int> (n->ProducerMetaData(itsConfiguration->SourceProducer().Id(), "last hybrid level number")); itsTopLevel = boost::lexical_cast<int> (n->ProducerMetaData(itsConfiguration->SourceProducer().Id(), "first hybrid level number")); } if ((dbtype == kRadon || dbtype == kNeonsAndRadon) && (itsBottomLevel == kHPMissingInt || itsTopLevel == kHPMissingInt)) { auto r = GET_PLUGIN(radon); itsBottomLevel = boost::lexical_cast<int> (r->ProducerMetaData(itsConfiguration->SourceProducer().Id(), "last hybrid level number")); itsTopLevel = boost::lexical_cast<int> (r->ProducerMetaData(itsConfiguration->SourceProducer().Id(), "first hybrid level number")); } param theRequestedParam; if (itsConfiguration->Exists("temp") && itsConfiguration->GetValue("temp") == "-20" ) { theRequestedParam.Name("HM20C-M"); theRequestedParam.UnivId(28); itsTargetTemperature = -20; } if (itsConfiguration->Exists("temp") && itsConfiguration->GetValue("temp") == "0" ) { theRequestedParam.Name("H0C-M"); theRequestedParam.UnivId(270); itsTargetTemperature = 0; } SetParams({theRequestedParam}); Start(); } /* * Calculate() * * This function does the actual calculation. */ void ncl::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex) { const param HParam("HL-M"); const param TParam("T-K"); int levelNumber = itsBottomLevel; level HLevel(himan::kHybrid, static_cast<float> (levelNumber), "HYBRID"); auto myThreadedLogger = logger_factory::Instance()->GetLog(itsName + "Thread #" + boost::lexical_cast<string> (threadIndex)); forecast_time forecastTime = myTargetInfo->Time(); level forecastLevel = myTargetInfo->Level(); forecast_type forecastType = myTargetInfo->ForecastType(); myThreadedLogger->Info("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + " level " + static_cast<string> (forecastLevel)); info_t HInfo = Fetch(forecastTime, HLevel, HParam, forecastType, false); info_t TInfo = Fetch(forecastTime, HLevel, TParam, forecastType, false); if (!HInfo || !TInfo) { myThreadedLogger->Error("Skipping step " + boost::lexical_cast<string> (forecastTime.Step()) + ", level " + static_cast<string> (forecastLevel)); return; } bool firstLevel = true; myTargetInfo->Data().Fill(-1); HInfo->ResetLocation(); TInfo->ResetLocation(); level curLevel = HLevel; level prevLevel; string deviceType = "CPU"; info_t prevHInfo, prevTInfo; while (--levelNumber >= itsTopLevel) { myThreadedLogger->Trace("Level: " + boost::lexical_cast<string> (levelNumber)); if (prevHInfo) { prevHInfo->ResetLocation(); } if (prevTInfo) { prevTInfo->ResetLocation(); } assert(HInfo && TInfo); LOCKSTEP(myTargetInfo, TInfo, HInfo) { double height = HInfo->Value(); double temp = TInfo->Value(); double prevHeight(kFloatMissing); double prevTemp(kFloatMissing); double targetHeight = myTargetInfo->Value(); if (!firstLevel) { prevHInfo->NextLocation(); prevHeight = prevHInfo->Value(); prevTInfo->NextLocation(); prevTemp = prevTInfo->Value(); } if (height == kFloatMissing || temp == kFloatMissing || (!firstLevel && (prevHeight == kFloatMissing || prevTemp == kFloatMissing))) { continue; } temp -= himan::constants::kKelvin; prevTemp -= himan::constants::kKelvin; if (targetHeight != -1) { if (temp >= itsTargetTemperature) // && levelNumber >= (itsBottomLevel - 5)) { /* * Lowest 5 model levels and "inversion fix". * * Especially in winter time surface inversion is common: temperature * close to ground surfaceis colder than the temperature above it. * This inversion is usually very limited in height, maybe 10 .. 200 * meters. When calculating height of zero level, we can take into * account this inversion so we test if the temperature at lowest level * is already below target temperature (0 or -20), and if that is the * situation we do not directly set height to kFloatMissing but * move onwards and only if the temperature stays below target for * the first 5 levels (in Hirlam lowest hybrid levels are spaced ~30m * apart) we can say that surface inversion does not exist and the * air temperature is simply too cold for this target temperature. * * In order to imitate hilake however the inversion fix limitation for * bottom 5 has been disabled, since what hilake does is it applies * the fix as long as the process is running, at least up to hybrid * level 29 which on Hirlam is on average 3700m above ground. * * This seems like a non-optimal approach but this is how hilake * does it and until we have confirmation that the inversion * height should be limited, use the hilake way also in himan. * * Inversion: http://blogi.foreca.fi/2012/01/pakkanen-ja-inversio/ */ myTargetInfo->Value(-1); } // No inversion fix, value already found for this gridpoint // (real value or missing value) continue; } if ((firstLevel && temp < itsTargetTemperature) || (prevTemp < itsTargetTemperature && temp < itsTargetTemperature)) { /* * Height is below ground (first model level) or its so cold * in the lower atmosphere that we cannot find the requested * temperature, set height to to missing value. */ targetHeight = kFloatMissing; } else if (prevTemp > itsTargetTemperature && temp < itsTargetTemperature) { // Found value, interpolate double p_rel = (itsTargetTemperature - temp) / (prevTemp - temp); targetHeight = height + (prevHeight - height) * p_rel; } else { // Too warm continue; } myTargetInfo->Value(targetHeight); } if (CountValues(myTargetInfo)) { break; } prevLevel = curLevel; curLevel = level(himan::kHybrid, static_cast<float> (levelNumber), "HYBRID"); HInfo = Fetch(forecastTime, curLevel, HParam, forecastType, false); TInfo = Fetch(forecastTime, curLevel, TParam, forecastType, false); prevHInfo = Fetch(forecastTime, prevLevel, HParam, forecastType, false); prevTInfo = Fetch(forecastTime, prevLevel, TParam, forecastType, false); if (!HInfo || !TInfo || !prevHInfo || !prevTInfo) { myThreadedLogger->Error("Not enough data for step " + boost::lexical_cast<string> (forecastTime.Step()) + ", level " + static_cast<string> (forecastLevel)); break; } firstLevel = false; } /* * Replaces all unset values */ myTargetInfo->ResetLocation(); while(myTargetInfo->NextLocation()) { if ( myTargetInfo->Value() == -1.) { myTargetInfo->Value(kFloatMissing); } } myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string> (myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<string> (myTargetInfo->Data().Size())); } bool ncl::CountValues(const shared_ptr<himan::info> values) { size_t s = values->Data().Size(); #ifdef DEBUG size_t foundVals = s; #endif for (size_t j = 0; j < s; j++) { if (values->Data().At(j) == -1) { #ifdef DEBUG foundVals--; #else return false; #endif } } #ifdef DEBUG itsLogger->Debug("Found value for " + boost::lexical_cast<string> (foundVals) + "/" + boost::lexical_cast<string> (s) + " gridpoints"); if (foundVals != s) return false; #endif return true; } <|endoftext|>
<commit_before>/** * @file */ #include "bi/io/cpp/CppClassGenerator.hpp" #include "bi/io/cpp/CppMemberFiberGenerator.hpp" #include "bi/primitive/encode.hpp" bi::CppClassGenerator::CppClassGenerator(std::ostream& base, const int level, const bool header) : CppBaseGenerator(base, level, header), type(nullptr) { // } void bi::CppClassGenerator::visit(const Class* o) { if (o->isAlias() || !o->braces->isEmpty()) { type = o; Gatherer<MemberFunction> memberFunctions; Gatherer<MemberFiber> memberFibers; Gatherer<MemberVariable> memberVariables; o->accept(&memberFunctions); o->accept(&memberFibers); o->accept(&memberVariables); /* start boilerplate */ if (header) { if (!o->isAlias()) { genTemplateParams(o); start("class " << o->name); if (o->isGeneric() && o->isBound()) { genTemplateArgs(o); } if (o->has(FINAL)) { middle(" final"); } if (o->isBound() && !o->base->isEmpty()) { middle(" : public "); ++inPointer; middle(o->base); } if (o->base->isEmpty()) { middle(" : public libbirch::Any"); } finish(" {"); line("public:"); in(); if (o->isBound()) { start("using class_type_ = " << o->name); genTemplateArgs(o); finish(';'); line("using this_type_ = class_type_;"); if (o->base->isEmpty()) { line("using super_type_ = libbirch::Any;"); } else { ++inPointer; line("using super_type_ = " << o->base << ';'); } line(""); line("using super_type_::operator=;"); line(""); /* using declarations for member functions and fibers in base classes * that are overridden */ std::set<std::string> names; for (auto f : memberFunctions) { if (o->scope->override(f)) { names.insert(f->name->str()); } } for (auto f : memberFibers) { if (o->scope->override(f)) { names.insert(f->name->str()); } } for (auto name : names) { line("using super_type_::" << internalise(name) << ';'); } line(""); } } } if (!o->isAlias() && o->isBound()) { if (header) { out(); line("protected:"); in(); } /* constructor */ if (!header) { start("bi::type::" << o->name); genTemplateArgs(o); middle("::"); } else { start(""); } middle(o->name); CppBaseGenerator aux(base, level, header); aux << '(' << o->params << ')'; if (header) { finish(";\n"); } else { finish(" :"); in(); in(); start("super_type_("); if (!o->args->isEmpty()) { middle(o->args); } middle(')'); ++inConstructor; for (auto o : memberVariables) { if (!o->value->isEmpty()) { finish(','); start(o->name << '(' << o->value << ')'); } else if (o->type->isClass()) { finish(','); start(o->name << '('); ++inPointer; middle(o->type << "::create_(" << o->args << ')'); middle(')'); } else if (o->type->isArray() && !o->brackets->isEmpty()) { finish(','); start(o->name << "(libbirch::make_frame(" << o->brackets << ')'); if (!o->args->isEmpty()) { middle(", " << o->args); } middle(')'); } } --inConstructor; out(); out(); finish(" {"); in(); line("//"); out(); line("}\n"); } /* copy constructor, destructor, assignment operator */ if (header) { line(o->name << "(const " << o->name << "&) = default;"); line("virtual ~" << o->name << "() = default;"); line(o->name << "& operator=(const " << o->name << "&) = default;"); } if (header) { out(); line("public:"); in(); } /* standard functions */ if (header) { line("libbirch_create_function_"); line("libbirch_emplace_function_"); line("libbirch_clone_function_"); line("libbirch_destroy_function_"); } /* name function */ if (header) { line("virtual const char* name_() const {"); in(); line("return \"" << o->name << "\";"); out(); line("}\n"); } /* freeze function */ if (header) { start("virtual void "); } else { start("void bi::type::" << o->name); genTemplateArgs(o); middle("::"); } middle("doFreeze_()"); if (header) { finish(';'); } else { finish(" {"); in(); line("super_type_::doFreeze_();"); for (auto o : memberVariables) { line("libbirch::freeze(" << o->name << ");"); } out(); line("}\n"); } /* finish function */ if (header) { start("virtual void "); } else { start("void bi::type::" << o->name); genTemplateArgs(o); middle("::"); } middle("doFinish_()"); if (header) { finish(';'); } else { finish(" {"); in(); line("super_type_::doFinish_();"); for (auto o : memberVariables) { line("libbirch::finish(" << o->name << ");"); } out(); line("}\n"); } /* member variables and functions */ *this << o->braces->strip(); } /* end class */ if (!o->isAlias() && header) { out(); line("};\n"); } /* C linkage function */ if (!o->isGeneric() && o->params->isEmpty()) { if (header) { line("extern \"C\" " << o->name << "* make_" << o->name << "_();"); } else { line( "bi::type::" << o->name << "* bi::type::make_" << o->name << "_() {"); in(); line("return bi::type::" << o->name << "::create_();"); out(); line("}"); } line(""); } } } void bi::CppClassGenerator::visit(const MemberVariable* o) { if (header) { line(o->type << ' ' << o->name << ';'); } } void bi::CppClassGenerator::visit(const MemberFunction* o) { if (header) { start("virtual "); } else { start(""); } middle(o->returnType << ' '); if (!header) { middle("bi::type::" << type->name); genTemplateArgs(type); middle("::"); } middle(internalise(o->name->str()) << '(' << o->params << ')'); if (header) { finish(';'); } else { finish(" {"); in(); genTraceFunction(o->name->str(), o->loc); line("libbirch_swap_context_"); line("libbirch_declare_self_"); /* body */ CppBaseGenerator auxBase(base, level, header); auxBase << o->braces->strip(); out(); finish("}\n"); } } void bi::CppClassGenerator::visit(const MemberFiber* o) { CppMemberFiberGenerator auxMemberFiber(type, base, level, header); auxMemberFiber << o; } void bi::CppClassGenerator::visit(const AssignmentOperator* o) { if (!o->braces->isEmpty()) { if (header) { start("virtual "); } else { start("bi::type::"); } middle(type->name); genTemplateArgs(type); middle("& "); if (!header) { middle("bi::type::" << type->name); genTemplateArgs(type); middle("::"); } middle("operator=(" << o->single << ')'); if (header) { finish(';'); } else { finish(" {"); in(); genTraceFunction("<assignment>", o->loc); line("libbirch_swap_context_"); line("libbirch_declare_self_"); CppBaseGenerator auxBase(base, level, header); auxBase << o->braces->strip(); line("return *this;"); out(); finish("}\n"); } } } void bi::CppClassGenerator::visit(const ConversionOperator* o) { if (!o->braces->isEmpty()) { if (!header) { start("bi::type::" << type->name); genTemplateArgs(type); middle("::"); } else { start("virtual "); } middle("operator " << o->returnType << "()"); if (header) { finish(';'); } else { finish(" {"); in(); genTraceFunction("<conversion>", o->loc); line("libbirch_swap_context_"); line("libbirch_declare_self_"); CppBaseGenerator auxBase(base, level, header); auxBase << o->braces->strip(); out(); finish("}\n"); } } } <commit_msg>In C++ code generation, wrapped freeze() and finish() functions to disable when lazy deep cloning is disabled.<commit_after>/** * @file */ #include "bi/io/cpp/CppClassGenerator.hpp" #include "bi/io/cpp/CppMemberFiberGenerator.hpp" #include "bi/primitive/encode.hpp" bi::CppClassGenerator::CppClassGenerator(std::ostream& base, const int level, const bool header) : CppBaseGenerator(base, level, header), type(nullptr) { // } void bi::CppClassGenerator::visit(const Class* o) { if (o->isAlias() || !o->braces->isEmpty()) { type = o; Gatherer<MemberFunction> memberFunctions; Gatherer<MemberFiber> memberFibers; Gatherer<MemberVariable> memberVariables; o->accept(&memberFunctions); o->accept(&memberFibers); o->accept(&memberVariables); /* start boilerplate */ if (header) { if (!o->isAlias()) { genTemplateParams(o); start("class " << o->name); if (o->isGeneric() && o->isBound()) { genTemplateArgs(o); } if (o->has(FINAL)) { middle(" final"); } if (o->isBound() && !o->base->isEmpty()) { middle(" : public "); ++inPointer; middle(o->base); } if (o->base->isEmpty()) { middle(" : public libbirch::Any"); } finish(" {"); line("public:"); in(); if (o->isBound()) { start("using class_type_ = " << o->name); genTemplateArgs(o); finish(';'); line("using this_type_ = class_type_;"); if (o->base->isEmpty()) { line("using super_type_ = libbirch::Any;"); } else { ++inPointer; line("using super_type_ = " << o->base << ';'); } line(""); line("using super_type_::operator=;"); line(""); /* using declarations for member functions and fibers in base classes * that are overridden */ std::set<std::string> names; for (auto f : memberFunctions) { if (o->scope->override(f)) { names.insert(f->name->str()); } } for (auto f : memberFibers) { if (o->scope->override(f)) { names.insert(f->name->str()); } } for (auto name : names) { line("using super_type_::" << internalise(name) << ';'); } line(""); } } } if (!o->isAlias() && o->isBound()) { if (header) { out(); line("protected:"); in(); } /* constructor */ if (!header) { start("bi::type::" << o->name); genTemplateArgs(o); middle("::"); } else { start(""); } middle(o->name); CppBaseGenerator aux(base, level, header); aux << '(' << o->params << ')'; if (header) { finish(";\n"); } else { finish(" :"); in(); in(); start("super_type_("); if (!o->args->isEmpty()) { middle(o->args); } middle(')'); ++inConstructor; for (auto o : memberVariables) { if (!o->value->isEmpty()) { finish(','); start(o->name << '(' << o->value << ')'); } else if (o->type->isClass()) { finish(','); start(o->name << '('); ++inPointer; middle(o->type << "::create_(" << o->args << ')'); middle(')'); } else if (o->type->isArray() && !o->brackets->isEmpty()) { finish(','); start(o->name << "(libbirch::make_frame(" << o->brackets << ')'); if (!o->args->isEmpty()) { middle(", " << o->args); } middle(')'); } } --inConstructor; out(); out(); finish(" {"); in(); line("//"); out(); line("}\n"); } /* copy constructor, destructor, assignment operator */ if (header) { line(o->name << "(const " << o->name << "&) = default;"); line("virtual ~" << o->name << "() = default;"); line(o->name << "& operator=(const " << o->name << "&) = default;"); } if (header) { out(); line("public:"); in(); } /* standard functions */ if (header) { line("libbirch_create_function_"); line("libbirch_emplace_function_"); line("libbirch_clone_function_"); line("libbirch_destroy_function_"); } /* name function */ if (header) { line("virtual const char* name_() const {"); in(); line("return \"" << o->name << "\";"); out(); line("}\n"); } /* freeze function */ line("#if ENABLE_LAZY_DEEP_CLONE"); if (header) { start("virtual void "); } else { start("void bi::type::" << o->name); genTemplateArgs(o); middle("::"); } middle("doFreeze_()"); if (header) { finish(';'); } else { finish(" {"); in(); line("super_type_::doFreeze_();"); for (auto o : memberVariables) { line("libbirch::freeze(" << o->name << ");"); } out(); line("}"); } line("#endif\n"); /* finish function */ line("#if ENABLE_LAZY_DEEP_CLONE"); if (header) { start("virtual void "); } else { start("void bi::type::" << o->name); genTemplateArgs(o); middle("::"); } middle("doFinish_()"); if (header) { finish(';'); } else { finish(" {"); in(); line("super_type_::doFinish_();"); for (auto o : memberVariables) { line("libbirch::finish(" << o->name << ");"); } out(); line("}"); } line("#endif\n"); /* member variables and functions */ *this << o->braces->strip(); } /* end class */ if (!o->isAlias() && header) { out(); line("};\n"); } /* C linkage function */ if (!o->isGeneric() && o->params->isEmpty()) { if (header) { line("extern \"C\" " << o->name << "* make_" << o->name << "_();"); } else { line( "bi::type::" << o->name << "* bi::type::make_" << o->name << "_() {"); in(); line("return bi::type::" << o->name << "::create_();"); out(); line("}"); } line(""); } } } void bi::CppClassGenerator::visit(const MemberVariable* o) { if (header) { line(o->type << ' ' << o->name << ';'); } } void bi::CppClassGenerator::visit(const MemberFunction* o) { if (header) { start("virtual "); } else { start(""); } middle(o->returnType << ' '); if (!header) { middle("bi::type::" << type->name); genTemplateArgs(type); middle("::"); } middle(internalise(o->name->str()) << '(' << o->params << ')'); if (header) { finish(';'); } else { finish(" {"); in(); genTraceFunction(o->name->str(), o->loc); line("libbirch_swap_context_"); line("libbirch_declare_self_"); /* body */ CppBaseGenerator auxBase(base, level, header); auxBase << o->braces->strip(); out(); finish("}\n"); } } void bi::CppClassGenerator::visit(const MemberFiber* o) { CppMemberFiberGenerator auxMemberFiber(type, base, level, header); auxMemberFiber << o; } void bi::CppClassGenerator::visit(const AssignmentOperator* o) { if (!o->braces->isEmpty()) { if (header) { start("virtual "); } else { start("bi::type::"); } middle(type->name); genTemplateArgs(type); middle("& "); if (!header) { middle("bi::type::" << type->name); genTemplateArgs(type); middle("::"); } middle("operator=(" << o->single << ')'); if (header) { finish(';'); } else { finish(" {"); in(); genTraceFunction("<assignment>", o->loc); line("libbirch_swap_context_"); line("libbirch_declare_self_"); CppBaseGenerator auxBase(base, level, header); auxBase << o->braces->strip(); line("return *this;"); out(); finish("}\n"); } } } void bi::CppClassGenerator::visit(const ConversionOperator* o) { if (!o->braces->isEmpty()) { if (!header) { start("bi::type::" << type->name); genTemplateArgs(type); middle("::"); } else { start("virtual "); } middle("operator " << o->returnType << "()"); if (header) { finish(';'); } else { finish(" {"); in(); genTraceFunction("<conversion>", o->loc); line("libbirch_swap_context_"); line("libbirch_declare_self_"); CppBaseGenerator auxBase(base, level, header); auxBase << o->braces->strip(); out(); finish("}\n"); } } } <|endoftext|>
<commit_before>#pragma once #include "fwd.hpp" #include <memory> #include "generator_impl.hpp" template <class T> class generator { std::unique_ptr<generator_impl<T>> p; template <class U> friend bool operator==(const generator<U>& a, const generator<U>& b); public: generator() = default; generator(const generator_function<T>& gen); T& operator*() const; typename std::remove_reference<T>::type* operator->() const {return &**this;} generator& operator++(); explicit operator bool() {return bool(p);} }; template <class T> generator<T>::generator(const generator_function<T>& gen) { bool not_empty; p.reset(new generator_impl<T>(gen, not_empty)); if (!not_empty) p = {}; } template <class T> T& generator<T>::operator*() const { if (!p) throw std::out_of_range("generator::operator*"); return p->get(); } template <class T> generator<T>& generator<T>::operator++() { if (!p) throw std::out_of_range("generator::operator++"); if (!p->next()) p = {}; return *this; } template <class T> bool operator==(const generator<T>& a, const generator<T>& b) {return a.p == b.p;} template <class T> bool operator!=(const generator<T>& a, const generator<T>& b) {return !(a == b);} <commit_msg>Fix const-correctness.<commit_after>#pragma once #include "fwd.hpp" #include <memory> #include "generator_impl.hpp" template <class T> class generator { std::unique_ptr<generator_impl<T>> p; template <class U> friend bool operator==(const generator<U>& a, const generator<U>& b); public: generator() = default; generator(const generator_function<T>& gen); auto operator*() -> T&; auto operator*() const -> const T&; auto operator->() -> typename std::remove_reference<T>::type* {return &**this;} auto operator->() const -> const typename std::remove_reference<T>::type* {return &**this;} generator& operator++(); explicit operator bool() {return bool(p);} }; template <class T> generator<T>::generator(const generator_function<T>& gen) { bool not_empty; p.reset(new generator_impl<T>(gen, not_empty)); if (!not_empty) p = {}; } template <class T> auto generator<T>::operator*() -> T& { if (!p) throw std::out_of_range("generator::operator*"); return p->get(); } template <class T> auto generator<T>::operator*() const -> const T& { if (!p) throw std::out_of_range("generator::operator*"); return p->get(); } template <class T> generator<T>& generator<T>::operator++() { if (!p) throw std::out_of_range("generator::operator++"); if (!p->next()) p = {}; return *this; } template <class T> bool operator==(const generator<T>& a, const generator<T>& b) {return a.p == b.p;} template <class T> bool operator!=(const generator<T>& a, const generator<T>& b) {return !(a == b);} <|endoftext|>
<commit_before>/** * @file pot.cpp * * * @date May 25, 2015 * @author Tack */ #include <boost/lexical_cast.hpp> #include <math.h> #include "pot.h" #include "plugin_factory.h" #include "logger_factory.h" #include "level.h" #include "forecast_time.h" #include "regular_grid.h" #include "util.h" #include "matrix.h" using namespace std; using namespace himan::plugin; pot::pot() { itsClearTextFormula = "complex formula"; itsLogger = logger_factory::Instance()->GetLog("pot"); } void pot::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); /* * Set target parameter properties * - name PARM_NAME, this name is found from neons. For example: T-K * - univ_id UNIV_ID, newbase-id, ie code table 204 * - grib1 id must be in database * - grib2 descriptor X'Y'Z, http://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_table4-2.shtml * */ // param theRequestedParam(PARM_NAME, UNIV_ID, GRIB2DISCIPLINE, GRIB2CATEGORY, GRIB2NUMBER); param POT("POT-PRCNT", 12100, 0, 19, 2); // If this param is also used as a source param for other calculations // (like for example dewpoint, relative humidity), unit should also be // specified POT.Unit(kPrcnt); SetParams({POT}); Start(); } /* * Calculate() * * This function does the actual calculation. */ void pot::Calculate(info_t myTargetInfo, unsigned short threadIndex) { /* * Required source parameters */ const param CapeParam("CAPE-JKG"); const param RainParam("RRR-KGM2"); // ---- // Current time and level as given to this thread forecast_time forecastTime = myTargetInfo->Time(); level forecastLevel = myTargetInfo->Level(); forecast_type forecastType = myTargetInfo->ForecastType(); auto myThreadedLogger = logger_factory::Instance()->GetLog("pot_pluginThread #" + boost::lexical_cast<string> (threadIndex)); myThreadedLogger->Debug("Calculating time " + static_cast<string> (forecastTime.ValidDateTime()) + " level " + static_cast<string> (forecastLevel)); info_t CAPEInfo, RRInfo; CAPEInfo = Fetch(forecastTime, forecastLevel, CapeParam, forecastType, false); RRInfo = Fetch(forecastTime, forecastLevel, RainParam, forecastType, false); if (!(CAPEInfo && RRInfo)) { myThreadedLogger->Info("Skipping step " + boost::lexical_cast<string> (forecastTime.Step()) + ", level " + static_cast<string> (forecastLevel)); return; } // käytetään sadeparametrina mallin sateen alueellista keskiarvoa, jotta diskreettejä sadeolioita saadaan vähän levitettyä ympäristöön, tässä toimisi paremmin esim. 30 km säde. // Filter RR himan::matrix<double> filter_kernel(3,3,1,kFloatMissing); filter_kernel.Fill(1/9); himan::matrix<double> filtered_RR = util::Filter2D(RRInfo->Data(), filter_kernel); RRInfo->Grid()->Data(filtered_RR); string deviceType = "CPU"; LOCKSTEP(myTargetInfo, CAPEInfo, RRInfo) { double POT; double CAPE_ec = CAPEInfo->Value(); double RR = RRInfo->Value(); double LAT = myTargetInfo->LatLon().Y(); double PoLift_ec = 0; double PoThermoDyn_ec = 0; // Määritetään salamointi vs. CAPE riippuvuutta varten tarvitaan CAPEn ala- ja ylärajoille yhtälöt. Ala- ja ylärajat muuttuvat leveyspiirin funktiona. double lat_abs = abs(LAT); double cape_low = -25*lat_abs + 1225; double cape_high = -40*lat_abs + 2600; // Kiinnitetään cape_low ja high levespiirien 25...45 ulkopuolella vakioarvoihin. if (lat_abs <25) { cape_low = 600; cape_high = 1600; } if (lat_abs > 45) { cape_low = 100; cape_high = 800; } // CAPE-arvot skaalataan arvoihin 1....10. Ala- ja ylärajat muuttuvat leveyspiirin funktiona. double k = 9/(cape_high - cape_low); double scaled_cape = k*CAPE_ec + (1- k*cape_low); assert( scaled_cape > 0); // Leikataan skaalatun CAPEN arvot, jotka menevät yli 10 if (scaled_cape >10) scaled_cape = 10; //Ukkosta suosivan termodynamiikan todennäköisyys PoThermoDyn_ec = 0.4343 * log(scaled_cape); //salamoinnin todennäköisyys kasvaa logaritmisesti CAPE-arvojen kasvaessa. // Laukaisevan tekijän (Lift) todennäköisyys kasvaa ennustetun sateen intensiteetin funktiona. // Perustelu: Konvektioparametrisointi (eli malli saa nollasta poikkeavaa sademäärää) malleissa käynnistyy useimmiten alueilla, missä mallissa on konvergenssia tai liftiä tarjolla if (RR >= 0.05 && RR <= 5) { PoLift_ec = 0.217147241 * log(RR) + 0.650514998; // Funktio kasvaa nopeasti logaritmisesti nollasta ykköseen } if (RR > 5) { PoLift_ec = 1; } //POT on ainesosiensa todennäköisyyksien tulo POT = PoLift_ec * PoThermoDyn_ec * 100; //return result myTargetInfo->Value(POT); } myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string> (myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<string> (myTargetInfo->Data().Size())); } <commit_msg>fix bug log(0)<commit_after>/** * @file pot.cpp * * * @date May 25, 2015 * @author Tack */ #include <boost/lexical_cast.hpp> #include <math.h> #include "pot.h" #include "plugin_factory.h" #include "logger_factory.h" #include "level.h" #include "forecast_time.h" #include "regular_grid.h" #include "util.h" #include "matrix.h" using namespace std; using namespace himan::plugin; pot::pot() { itsClearTextFormula = "complex formula"; itsLogger = logger_factory::Instance()->GetLog("pot"); } void pot::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); /* * Set target parameter properties * - name PARM_NAME, this name is found from neons. For example: T-K * - univ_id UNIV_ID, newbase-id, ie code table 204 * - grib1 id must be in database * - grib2 descriptor X'Y'Z, http://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_table4-2.shtml * */ // param theRequestedParam(PARM_NAME, UNIV_ID, GRIB2DISCIPLINE, GRIB2CATEGORY, GRIB2NUMBER); param POT("POT-PRCNT", 12100, 0, 19, 2); // If this param is also used as a source param for other calculations // (like for example dewpoint, relative humidity), unit should also be // specified POT.Unit(kPrcnt); SetParams({POT}); Start(); } /* * Calculate() * * This function does the actual calculation. */ void pot::Calculate(info_t myTargetInfo, unsigned short threadIndex) { /* * Required source parameters */ const param CapeParam("CAPE-JKG"); const param RainParam("RRR-KGM2"); // ---- // Current time and level as given to this thread forecast_time forecastTime = myTargetInfo->Time(); level forecastLevel = myTargetInfo->Level(); forecast_type forecastType = myTargetInfo->ForecastType(); auto myThreadedLogger = logger_factory::Instance()->GetLog("pot_pluginThread #" + boost::lexical_cast<string> (threadIndex)); myThreadedLogger->Debug("Calculating time " + static_cast<string> (forecastTime.ValidDateTime()) + " level " + static_cast<string> (forecastLevel)); info_t CAPEInfo, RRInfo; CAPEInfo = Fetch(forecastTime, forecastLevel, CapeParam, forecastType, false); RRInfo = Fetch(forecastTime, forecastLevel, RainParam, forecastType, false); if (!(CAPEInfo && RRInfo)) { myThreadedLogger->Info("Skipping step " + boost::lexical_cast<string> (forecastTime.Step()) + ", level " + static_cast<string> (forecastLevel)); return; } // käytetään sadeparametrina mallin sateen alueellista keskiarvoa, jotta diskreettejä sadeolioita saadaan vähän levitettyä ympäristöön, tässä toimisi paremmin esim. 30 km säde. // Filter RR himan::matrix<double> filter_kernel(3,3,1,kFloatMissing); filter_kernel.Fill(1/9); himan::matrix<double> filtered_RR = util::Filter2D(RRInfo->Data(), filter_kernel); RRInfo->Grid()->Data(filtered_RR); string deviceType = "CPU"; LOCKSTEP(myTargetInfo, CAPEInfo, RRInfo) { double POT; double CAPE_ec = CAPEInfo->Value(); double RR = RRInfo->Value(); double LAT = myTargetInfo->LatLon().Y(); double PoLift_ec = 0; double PoThermoDyn_ec = 0; // Määritetään salamointi vs. CAPE riippuvuutta varten tarvitaan CAPEn ala- ja ylärajoille yhtälöt. Ala- ja ylärajat muuttuvat leveyspiirin funktiona. double lat_abs = abs(LAT); double cape_low = -25*lat_abs + 1225; double cape_high = -40*lat_abs + 3250; // Kiinnitetään cape_low ja high levespiirien 25...45 ulkopuolella vakioarvoihin. if (lat_abs <25) { cape_low = 600; cape_high = 2000; } if (lat_abs > 45) { cape_low = 100; cape_high = 1000; } // CAPE-arvot skaalataan arvoihin 1....10. Ala- ja ylärajat muuttuvat leveyspiirin funktiona. double k = 9/(cape_high - cape_low); double scaled_cape = 1; if (CAPE_ec >= cape_low) scaled_cape = k*CAPE_ec + (1- k*cape_low); assert( scaled_cape > 0); // Leikataan skaalatun CAPEN arvot, jotka menevät yli 10 if (scaled_cape >10) scaled_cape = 10; //Ukkosta suosivan termodynamiikan todennäköisyys PoThermoDyn_ec = 0.4343 * log(scaled_cape); //salamoinnin todennäköisyys kasvaa logaritmisesti CAPE-arvojen kasvaessa. // Laukaisevan tekijän (Lift) todennäköisyys kasvaa ennustetun sateen intensiteetin funktiona. // Perustelu: Konvektioparametrisointi (eli malli saa nollasta poikkeavaa sademäärää) malleissa käynnistyy useimmiten alueilla, missä mallissa on konvergenssia tai liftiä tarjolla if (RR >= 0.05 && RR <= 5) { PoLift_ec = 0.217147241 * log(RR) + 0.650514998; // Funktio kasvaa nopeasti logaritmisesti nollasta ykköseen } if (RR > 5) { PoLift_ec = 1; } //POT on ainesosiensa todennäköisyyksien tulo POT = PoLift_ec * PoThermoDyn_ec * 100; //return result myTargetInfo->Value(POT); } myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string> (myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<string> (myTargetInfo->Data().Size())); } <|endoftext|>
<commit_before>/* Module: getconfig_catena4610.cpp Function: Arduino-LMIC C++ HAL pinmaps for the Catena 4610 Copyright & License: See accompanying LICENSE file. Author: Terry Moore, MCCI November 2018 */ #if defined(ARDUINO_DISCO_L072CZ_LRWAN1) #include <arduino_lmic_hal_boards.h> #include <Arduino.h> #include "../lmic/oslmic.h" namespace Arduino_LMIC { class HalConfiguration_Disco_L072cz_Lrwan1_t : public HalConfiguration_t { public: enum DIGITAL_PINS : uint8_t { PIN_SX1276_NSS = 37, PIN_SX1276_NRESET = 33, PIN_SX1276_DIO0 = 38, PIN_SX1276_DIO1 = 39, PIN_SX1276_DIO2 = 40, PIN_SX1276_RXTX = 21, }; virtual bool queryUsingTcxo(void) override { return false; }; }; // save some typing by bringing the pin numbers into scope static HalConfiguration_Disco_L072cz_Lrwan1_t myConfig; static const HalPinmap_t myPinmap = { .nss = HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_NSS, .rxtx = HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_RXTX, .rst = HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_NRESET, .dio = {HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_DIO0, HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_DIO1, HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_DIO2, }, .rxtx_rx_active = 1, .rssi_cal = 10, .spi_freq = 8000000, /* 8MHz */ .pConfig = &myConfig }; const HalPinmap_t *GetPinmap_Disco_L072cz_Lrwan1(void) { return myPinmap; } }; // namespace Arduino_LMIC #endif /* defined(ARDUINO_DISCO_L072CZ_LRWAN1) */ <commit_msg>fix comments<commit_after>/* Module: getpinmap_disco_l072cz_lrwan1.cpp Function: Arduino-LMIC C++ HAL pinmaps for the Discovery L072CZ LRWAN1 Copyright & License: See accompanying LICENSE file. Author: Helium February 2020 */ #if defined(ARDUINO_DISCO_L072CZ_LRWAN1) #include <arduino_lmic_hal_boards.h> #include <Arduino.h> #include "../lmic/oslmic.h" namespace Arduino_LMIC { class HalConfiguration_Disco_L072cz_Lrwan1_t : public HalConfiguration_t { public: enum DIGITAL_PINS : uint8_t { PIN_SX1276_NSS = 37, PIN_SX1276_NRESET = 33, PIN_SX1276_DIO0 = 38, PIN_SX1276_DIO1 = 39, PIN_SX1276_DIO2 = 40, PIN_SX1276_RXTX = 21, }; virtual bool queryUsingTcxo(void) override { return false; }; }; // save some typing by bringing the pin numbers into scope static HalConfiguration_Disco_L072cz_Lrwan1_t myConfig; static const HalPinmap_t myPinmap = { .nss = HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_NSS, .rxtx = HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_RXTX, .rst = HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_NRESET, .dio = {HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_DIO0, HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_DIO1, HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_DIO2, }, .rxtx_rx_active = 1, .rssi_cal = 10, .spi_freq = 8000000, /* 8MHz */ .pConfig = &myConfig }; const HalPinmap_t *GetPinmap_Disco_L072cz_Lrwan1(void) { return myPinmap; } }; // namespace Arduino_LMIC #endif /* defined(ARDUINO_DISCO_L072CZ_LRWAN1) */ <|endoftext|>
<commit_before>/* This file is part of the clang-lazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com Author: Sérgio Martins <sergio.martins@kdab.com> Copyright (C) 2015 Sergio Martins <smartins@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "Utils.h" #include "StringUtils.h" #include "checkbase.h" #include "checkmanager.h" #include "clang/Frontend/FrontendPluginRegistry.h" #include "clang/AST/AST.h" #include "clang/AST/ASTConsumer.h" #include "clang/Frontend/CompilerInstance.h" #include "llvm/Support/raw_ostream.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Lex/Lexer.h" #include "clang/Rewrite/Frontend/FixItRewriter.h" #include "clang/AST/ParentMap.h" #include <stdio.h> #include <sstream> #include <iostream> using namespace clang; using namespace std; namespace { class MyFixItOptions : public FixItOptions { public: MyFixItOptions(bool inplace) { InPlace = inplace; FixWhatYouCan = true; FixOnlyWarnings = true; Silent = false; } std::string RewriteFilename(const std::string &filename, int &fd) override { fd = -1; return InPlace ? filename : filename + "_fixed.cpp"; } #if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 6 bool InPlace; #endif }; static void manuallyPopulateParentMap(ParentMap *map, Stmt *s) { if (!s) return; auto it = s->child_begin(); auto e = s->child_end(); for (; it != e; ++it) { llvm::errs() << "Patching " << (*it)->getStmtClassName() << "\n"; map->setParent(*it, s); manuallyPopulateParentMap(map, *it); } } class LazyASTConsumer : public ASTConsumer, public RecursiveASTVisitor<LazyASTConsumer> { public: LazyASTConsumer(CompilerInstance &ci, const vector<string> &requestedChecks, bool inplaceFixits) : m_ci(ci) , m_rewriter(nullptr) , m_parentMap(nullptr) , m_checkManager(CheckManager::instance()) { m_checkManager->setCompilerInstance(&m_ci); m_checkManager->createChecks(requestedChecks); if (m_checkManager->fixitsEnabled()) m_rewriter = new FixItRewriter(ci.getDiagnostics(), m_ci.getSourceManager(), m_ci.getLangOpts(), new MyFixItOptions(inplaceFixits)); } ~LazyASTConsumer() { if (m_rewriter != nullptr) { m_rewriter->WriteFixedFiles(); delete m_rewriter; } } void setParentMap(ParentMap *map) { delete m_parentMap; m_parentMap = map; auto &createdChecks = m_checkManager->createdChecks(); for (auto &check : createdChecks) check->setParentMap(map); } bool VisitDecl(Decl *decl) { auto &createdChecks = m_checkManager->createdChecks(); for (auto it = createdChecks.cbegin(), end = createdChecks.cend(); it != end; ++it) { (*it)->VisitDeclaration(decl); } return true; } bool VisitStmt(Stmt *stm) { static Stmt *lastStm = nullptr; // Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements. if (lastStm && isa<CXXCatchStmt>(lastStm) && m_parentMap && !m_parentMap->hasParent(stm)) { m_parentMap->setParent(stm, lastStm); manuallyPopulateParentMap(m_parentMap, stm); } lastStm = stm; // clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration // So re-set a parent map each time we go into a different hieararchy if (m_parentMap == nullptr || !m_parentMap->hasParent(stm)) { assert(stm != nullptr); setParentMap(new ParentMap(stm)); } auto &createdChecks = m_checkManager->createdChecks(); for (auto it = createdChecks.cbegin(), end = createdChecks.cend(); it != end; ++it) { (*it)->VisitStatement(stm); } return true; } void HandleTranslationUnit(ASTContext &ctx) override { TraverseDecl(ctx.getTranslationUnitDecl()); } CompilerInstance &m_ci; FixItRewriter *m_rewriter; ParentMap *m_parentMap; CheckManager *m_checkManager; }; //------------------------------------------------------------------------------ static bool parseArgument(const string &arg, vector<string> &args) { auto it = std::find(args.begin(), args.end(), arg); if (it != args.end()) { args.erase(it, it + 1); return true; } return false; } static int parseLevel(vector<std::string> &args) { static const vector<string> levels = { "level0", "level1", "level2", "level3", "level4" }; const int numLevels = levels.size(); for (int i = 0; i < numLevels; ++i) { if (parseArgument(levels.at(i), args)) { return i; } } return -1; } class LazyASTAction : public PluginASTAction { protected: std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(CompilerInstance &ci, llvm::StringRef) override { return llvm::make_unique<LazyASTConsumer>(ci, m_checks, m_inplaceFixits); } bool ParseArgs(const CompilerInstance &ci, const std::vector<std::string> &args_) override { std::vector<std::string> args = args_; if (parseArgument("help", args)) { llvm::errs() << "Help:\n"; PrintHelp(llvm::errs()); return false; } if (parseArgument("no-inplace-fixits", args)) { // Unit-tests don't use inplace fixits m_inplaceFixits = false; } auto checkManager = CheckManager::instance(); const int requestedLevel = parseLevel(/*by-ref*/args); if (requestedLevel != -1) { checkManager->setRequestedLevel(requestedLevel); } if (parseArgument("enable-all-fixits", args)) { // This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise. CheckManager::instance()->enableAllFixIts(); } if (args.empty()) { m_checks = CheckManager::instance()->requestedCheckNamesThroughEnv(); } if (args.size() > 1) { // Too many arguments. llvm::errs() << "Too many arguments: "; for (const std::string &a : args) llvm::errs() << a << " "; llvm::errs() << "\n"; PrintHelp(llvm::errs()); return false; } else if (args.size() == 1) { m_checks = CheckManager::instance()->checkNamesForCommaSeparatedString(args[0]); if (m_checks.empty()) { llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n"; PrintHelp(llvm::errs()); return false; } } return true; } void PrintHelp(llvm::raw_ostream &ros) { const vector<string> &names = CheckManager::instance()->availableCheckNames(false); ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n"; ros << "export CLAZY_CHECKS=\"reserve-candidates,qstring-uneeded-heap-allocations\"\n\n"; ros << "or pass as compiler arguments, for example:\n"; ros << "-Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-uneeded-heap-allocations\n"; ros << "\n"; ros << "To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\n"; ros << "export CLAZY_FIXIT=\"fix-qlatin1string-allocations\"\n\n"; ros << "FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\nSpecifying a list of different FixIts is not supported.\n\n"; ros << "Available checks and FixIts:\n\n"; for (uint i = 1; i < names.size(); ++i) { auto padded = names[i]; padded.insert(padded.end(), 39 - padded.size(), ' '); ros << names[i]; auto fixits = CheckManager::instance()->availableFixIts(names[i]); if (!fixits.empty()) { ros << " ("; bool isFirst = true; for (auto fixit : fixits) { if (isFirst) { isFirst = false; } else { ros << ","; } ros << fixit.name; } ros << ")"; } ros << "\n"; } exit(-2); } private: vector<string> m_checks; bool m_inplaceFixits = true; }; } static FrontendPluginRegistry::Add<LazyASTAction> X("clang-lazy", "clang lazy plugin"); <commit_msg>Simplify code<commit_after>/* This file is part of the clang-lazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com Author: Sérgio Martins <sergio.martins@kdab.com> Copyright (C) 2015 Sergio Martins <smartins@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "Utils.h" #include "StringUtils.h" #include "checkbase.h" #include "checkmanager.h" #include "clang/Frontend/FrontendPluginRegistry.h" #include "clang/AST/AST.h" #include "clang/AST/ASTConsumer.h" #include "clang/Frontend/CompilerInstance.h" #include "llvm/Support/raw_ostream.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Lex/Lexer.h" #include "clang/Rewrite/Frontend/FixItRewriter.h" #include "clang/AST/ParentMap.h" #include <stdio.h> #include <sstream> #include <iostream> using namespace clang; using namespace std; namespace { class MyFixItOptions : public FixItOptions { public: MyFixItOptions(bool inplace) { InPlace = inplace; FixWhatYouCan = true; FixOnlyWarnings = true; Silent = false; } std::string RewriteFilename(const std::string &filename, int &fd) override { fd = -1; return InPlace ? filename : filename + "_fixed.cpp"; } #if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 6 bool InPlace; #endif }; static void manuallyPopulateParentMap(ParentMap *map, Stmt *s) { if (!s) return; auto it = s->child_begin(); auto e = s->child_end(); for (; it != e; ++it) { llvm::errs() << "Patching " << (*it)->getStmtClassName() << "\n"; map->setParent(*it, s); manuallyPopulateParentMap(map, *it); } } class LazyASTConsumer : public ASTConsumer, public RecursiveASTVisitor<LazyASTConsumer> { public: LazyASTConsumer(CompilerInstance &ci, const vector<string> &requestedChecks, bool inplaceFixits) : m_ci(ci) , m_rewriter(nullptr) , m_parentMap(nullptr) , m_checkManager(CheckManager::instance()) { m_checkManager->setCompilerInstance(&m_ci); m_checkManager->createChecks(requestedChecks); if (m_checkManager->fixitsEnabled()) m_rewriter = new FixItRewriter(ci.getDiagnostics(), m_ci.getSourceManager(), m_ci.getLangOpts(), new MyFixItOptions(inplaceFixits)); } ~LazyASTConsumer() { if (m_rewriter != nullptr) { m_rewriter->WriteFixedFiles(); delete m_rewriter; } } void setParentMap(ParentMap *map) { delete m_parentMap; m_parentMap = map; auto &createdChecks = m_checkManager->createdChecks(); for (auto &check : createdChecks) check->setParentMap(map); } bool VisitDecl(Decl *decl) { auto &createdChecks = m_checkManager->createdChecks(); for (auto it = createdChecks.cbegin(), end = createdChecks.cend(); it != end; ++it) { (*it)->VisitDeclaration(decl); } return true; } bool VisitStmt(Stmt *stm) { static Stmt *lastStm = nullptr; // Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements. if (lastStm && isa<CXXCatchStmt>(lastStm) && m_parentMap && !m_parentMap->hasParent(stm)) { m_parentMap->setParent(stm, lastStm); manuallyPopulateParentMap(m_parentMap, stm); } lastStm = stm; // clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration // So re-set a parent map each time we go into a different hieararchy if (m_parentMap == nullptr || !m_parentMap->hasParent(stm)) { assert(stm != nullptr); setParentMap(new ParentMap(stm)); } auto &createdChecks = m_checkManager->createdChecks(); for (auto it = createdChecks.cbegin(), end = createdChecks.cend(); it != end; ++it) { (*it)->VisitStatement(stm); } return true; } void HandleTranslationUnit(ASTContext &ctx) override { TraverseDecl(ctx.getTranslationUnitDecl()); } CompilerInstance &m_ci; FixItRewriter *m_rewriter; ParentMap *m_parentMap; CheckManager *m_checkManager; }; //------------------------------------------------------------------------------ static bool parseArgument(const string &arg, vector<string> &args) { auto it = std::find(args.begin(), args.end(), arg); if (it != args.end()) { args.erase(it, it + 1); return true; } return false; } static int parseLevel(vector<std::string> &args) { static const vector<string> levels = { "level0", "level1", "level2", "level3", "level4" }; const int numLevels = levels.size(); for (int i = 0; i < numLevels; ++i) { if (parseArgument(levels.at(i), args)) { return i; } } return -1; } class LazyASTAction : public PluginASTAction { protected: std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(CompilerInstance &ci, llvm::StringRef) override { return llvm::make_unique<LazyASTConsumer>(ci, m_checks, m_inplaceFixits); } bool ParseArgs(const CompilerInstance &ci, const std::vector<std::string> &args_) override { std::vector<std::string> args = args_; if (parseArgument("help", args)) { llvm::errs() << "Help:\n"; PrintHelp(llvm::errs()); return false; } if (parseArgument("no-inplace-fixits", args)) { // Unit-tests don't use inplace fixits m_inplaceFixits = false; } auto checkManager = CheckManager::instance(); const int requestedLevel = parseLevel(/*by-ref*/args); if (requestedLevel != -1) { checkManager->setRequestedLevel(requestedLevel); } if (parseArgument("enable-all-fixits", args)) { // This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise. checkManager->enableAllFixIts(); } if (args.empty()) { m_checks = CheckManager::instance()->requestedCheckNamesThroughEnv(); } if (args.size() > 1) { // Too many arguments. llvm::errs() << "Too many arguments: "; for (const std::string &a : args) llvm::errs() << a << " "; llvm::errs() << "\n"; PrintHelp(llvm::errs()); return false; } else if (args.size() == 1) { m_checks = checkManager->checkNamesForCommaSeparatedString(args[0]); if (m_checks.empty()) { llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n"; PrintHelp(llvm::errs()); return false; } } return true; } void PrintHelp(llvm::raw_ostream &ros) { const vector<string> &names = CheckManager::instance()->availableCheckNames(false); ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n"; ros << "export CLAZY_CHECKS=\"reserve-candidates,qstring-uneeded-heap-allocations\"\n\n"; ros << "or pass as compiler arguments, for example:\n"; ros << "-Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-uneeded-heap-allocations\n"; ros << "\n"; ros << "To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\n"; ros << "export CLAZY_FIXIT=\"fix-qlatin1string-allocations\"\n\n"; ros << "FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\nSpecifying a list of different FixIts is not supported.\n\n"; ros << "Available checks and FixIts:\n\n"; for (uint i = 1; i < names.size(); ++i) { auto padded = names[i]; padded.insert(padded.end(), 39 - padded.size(), ' '); ros << names[i]; auto fixits = CheckManager::instance()->availableFixIts(names[i]); if (!fixits.empty()) { ros << " ("; bool isFirst = true; for (auto fixit : fixits) { if (isFirst) { isFirst = false; } else { ros << ","; } ros << fixit.name; } ros << ")"; } ros << "\n"; } exit(-2); } private: vector<string> m_checks; bool m_inplaceFixits = true; }; } static FrontendPluginRegistry::Add<LazyASTAction> X("clang-lazy", "clang lazy plugin"); <|endoftext|>
<commit_before>#include "word.h" #include <algorithm> #include <iterator> #include <stdexcept> #include <istream> #include <ostream> #include <cctype> #include <iostream> Word::Word(std::string const &input_string) { if(input_string.empty()) throw std::invalid_argument("given string is empty"); copy_if(input_string.cbegin(), input_string.cend(), std::back_inserter(data), [](char const character) { if (!std::isalpha(character)) throw std::invalid_argument("invalid characters"); return true; } ); } bool Word::operator==(Word const &other) const { return to_lower() == other.to_lower(); } bool Word::operator!=(Word const &other) const { return to_lower() != other.to_lower(); } bool Word::operator>(Word const &other) const { return to_lower() > other.to_lower(); } bool Word::operator<(Word const &other) const { return other > *this; } bool Word::operator>=(Word const &other) const { return to_lower() >= other.to_lower(); } bool Word::operator<=(Word const &other) const { return to_lower() <= other.to_lower(); } Word::operator std::string() const { return data; } std::string Word::to_lower() const { std::string lower {}; transform(data.cbegin(), data.cend(), std::back_inserter(lower), (int(*)(int))std::tolower); return lower; } bool Word::empty() const { return data.empty(); } std::istream& Word::read(std::istream &input_stream) { while(!std::isalpha(input_stream.peek()) && !input_stream.eof()) { input_stream.ignore(1); } if(!input_stream || input_stream.eof()) return input_stream; while(std::isalpha(input_stream.peek())) { data += input_stream.get(); } // if(!input_stream) input_stream.clear(std::ios_base::eofbit); return input_stream; } std::ostream& Word::print(std::ostream &output_stream) const { return (output_stream << data); } std::ostream& operator<<(std::ostream &output_stream, Word const &word) { return word.print(output_stream); } std::istream& operator>>(std::istream &input_stream, Word &word) { return word.read(input_stream); } <commit_msg>include <{i,o}stream> instead of <iostream><commit_after>#include "word.h" #include <algorithm> #include <iterator> #include <stdexcept> #include <istream> #include <ostream> #include <cctype> #include <istream> #include <ostream> Word::Word(std::string const &input_string) { if(input_string.empty()) throw std::invalid_argument("given string is empty"); copy_if(input_string.cbegin(), input_string.cend(), std::back_inserter(data), [](char const character) { if (!std::isalpha(character)) throw std::invalid_argument("invalid characters"); return true; } ); } bool Word::operator==(Word const &other) const { return to_lower() == other.to_lower(); } bool Word::operator!=(Word const &other) const { return to_lower() != other.to_lower(); } bool Word::operator>(Word const &other) const { return to_lower() > other.to_lower(); } bool Word::operator<(Word const &other) const { return other > *this; } bool Word::operator>=(Word const &other) const { return to_lower() >= other.to_lower(); } bool Word::operator<=(Word const &other) const { return to_lower() <= other.to_lower(); } Word::operator std::string() const { return data; } std::string Word::to_lower() const { std::string lower {}; transform(data.cbegin(), data.cend(), std::back_inserter(lower), (int(*)(int))std::tolower); return lower; } bool Word::empty() const { return data.empty(); } std::istream& Word::read(std::istream &input_stream) { while(!std::isalpha(input_stream.peek()) && !input_stream.eof()) { input_stream.ignore(1); } if(!input_stream || input_stream.eof()) return input_stream; while(std::isalpha(input_stream.peek())) { data += input_stream.get(); } // if(!input_stream) input_stream.clear(std::ios_base::eofbit); return input_stream; } std::ostream& Word::print(std::ostream &output_stream) const { return (output_stream << data); } std::ostream& operator<<(std::ostream &output_stream, Word const &word) { return word.print(output_stream); } std::istream& operator>>(std::istream &input_stream, Word &word) { return word.read(input_stream); } <|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 "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/extensions/feature_switch.h" #include "chrome/common/extensions/features/feature.h" #include "content/public/common/content_switches.h" namespace chrome { namespace { class TabCaptureApiTest : public ExtensionApiTest { public: TabCaptureApiTest() : current_channel_(VersionInfo::CHANNEL_UNKNOWN) {} private: extensions::Feature::ScopedCurrentChannel current_channel_; }; } // namespace IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTests) { extensions::FeatureSwitch::ScopedOverride tab_capture( extensions::FeatureSwitch::tab_capture(), true); ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental", "api_tests.html")) << message_; } #if defined(OS_WIN) // See http://crbug.com/174640 #define MAYBE_EndToEnd DISABLED_EndToEnd #else #define MAYBE_EndToEnd EndToEnd #endif IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_EndToEnd) { extensions::FeatureSwitch::ScopedOverride tab_capture( extensions::FeatureSwitch::tab_capture(), true); ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental", "end_to_end.html")) << message_; } IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, TabCapturePermissionsTestFlagOn) { extensions::FeatureSwitch::ScopedOverride tab_capture( extensions::FeatureSwitch::tab_capture(), true); ASSERT_TRUE(RunExtensionTest("tab_capture/permissions")) << message_; } IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, TabCapturePermissionsTestFlagOff) { extensions::FeatureSwitch::ScopedOverride tab_capture( extensions::FeatureSwitch::tab_capture(), false); ASSERT_TRUE(RunExtensionTest("tab_capture/permissions")) << message_; } } // namespace chrome <commit_msg>Disable TabCaptureApiTest.EndToEnd on OS X<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 "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/extensions/feature_switch.h" #include "chrome/common/extensions/features/feature.h" #include "content/public/common/content_switches.h" namespace chrome { namespace { class TabCaptureApiTest : public ExtensionApiTest { public: TabCaptureApiTest() : current_channel_(VersionInfo::CHANNEL_UNKNOWN) {} private: extensions::Feature::ScopedCurrentChannel current_channel_; }; } // namespace IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTests) { extensions::FeatureSwitch::ScopedOverride tab_capture( extensions::FeatureSwitch::tab_capture(), true); ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental", "api_tests.html")) << message_; } #if defined(OS_WIN) || defined(OS_MACOSX) // See http://crbug.com/174640 #define MAYBE_EndToEnd DISABLED_EndToEnd #else #define MAYBE_EndToEnd EndToEnd #endif IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_EndToEnd) { extensions::FeatureSwitch::ScopedOverride tab_capture( extensions::FeatureSwitch::tab_capture(), true); ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental", "end_to_end.html")) << message_; } IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, TabCapturePermissionsTestFlagOn) { extensions::FeatureSwitch::ScopedOverride tab_capture( extensions::FeatureSwitch::tab_capture(), true); ASSERT_TRUE(RunExtensionTest("tab_capture/permissions")) << message_; } IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, TabCapturePermissionsTestFlagOff) { extensions::FeatureSwitch::ScopedOverride tab_capture( extensions::FeatureSwitch::tab_capture(), false); ASSERT_TRUE(RunExtensionTest("tab_capture/permissions")) << message_; } } // namespace chrome <|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/command_line.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extension_install_dialog.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/webstore_inline_installer.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/content_notification_types.h" #include "googleurl/src/gurl.h" #include "net/base/host_port_pair.h" #include "net/base/mock_host_resolver.h" const char kWebstoreDomain[] = "cws.com"; const char kAppDomain[] = "app.com"; class WebstoreInlineInstallTest : public InProcessBrowserTest { public: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { EnableDOMAutomation(); // We start the test server now instead of in // SetUpInProcessBrowserTestFixture so that we can get its port number. ASSERT_TRUE(test_server()->Start()); InProcessBrowserTest::SetUpCommandLine(command_line); net::HostPortPair host_port = test_server()->host_port_pair(); test_gallery_url_ = base::StringPrintf( "http://%s:%d/files/extensions/api_test/webstore_inline_install", kWebstoreDomain, host_port.port()); command_line->AppendSwitchASCII( switches::kAppsGalleryURL, test_gallery_url_); GURL crx_url = GenerateTestServerUrl(kWebstoreDomain, "extension.crx"); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryUpdateURL, crx_url.spec()); command_line->AppendSwitch(switches::kEnableInlineWebstoreInstall); } virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { host_resolver()->AddRule(kWebstoreDomain, "127.0.0.1"); host_resolver()->AddRule(kAppDomain, "127.0.0.1"); } protected: GURL GenerateTestServerUrl(const std::string& domain, const std::string& page_filename) { GURL page_url = test_server()->GetURL( "files/extensions/api_test/webstore_inline_install/" + page_filename); GURL::Replacements replace_host; replace_host.SetHostStr(domain); return page_url.ReplaceComponents(replace_host); } std::string test_gallery_url_; }; IN_PROC_BROWSER_TEST_F(WebstoreInlineInstallTest, Install) { SetExtensionInstallDialogForManifestAutoConfirmForTests(true); ui_test_utils::WindowedNotificationObserver load_signal( chrome::NOTIFICATION_EXTENSION_LOADED, Source<Profile>(browser()->profile())); ui_test_utils::NavigateToURL( browser(), GenerateTestServerUrl(kAppDomain, "install.html")); bool result = false; std::string script = StringPrintf("runTest('%s')", test_gallery_url_.c_str()); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", UTF8ToWide(script), &result)); EXPECT_TRUE(result); load_signal.Wait(); const Extension* extension = browser()->profile()->GetExtensionService()-> GetExtensionById("ecglahbcnmdpdciemllbhojghbkagdje", false); EXPECT_TRUE(extension != NULL); } IN_PROC_BROWSER_TEST_F(WebstoreInlineInstallTest, FindLink) { ui_test_utils::NavigateToURL( browser(), GenerateTestServerUrl(kAppDomain, "find_link.html")); bool result = false; std::string script = StringPrintf("runTest('%s')", test_gallery_url_.c_str()); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", UTF8ToWide(script), &result)); EXPECT_TRUE(result); } <commit_msg>Disable flaky browser_test for WebstoreInlineInstallTest.FindLink on Linux.<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/command_line.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extension_install_dialog.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/webstore_inline_installer.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/content_notification_types.h" #include "googleurl/src/gurl.h" #include "net/base/host_port_pair.h" #include "net/base/mock_host_resolver.h" const char kWebstoreDomain[] = "cws.com"; const char kAppDomain[] = "app.com"; class WebstoreInlineInstallTest : public InProcessBrowserTest { public: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { EnableDOMAutomation(); // We start the test server now instead of in // SetUpInProcessBrowserTestFixture so that we can get its port number. ASSERT_TRUE(test_server()->Start()); InProcessBrowserTest::SetUpCommandLine(command_line); net::HostPortPair host_port = test_server()->host_port_pair(); test_gallery_url_ = base::StringPrintf( "http://%s:%d/files/extensions/api_test/webstore_inline_install", kWebstoreDomain, host_port.port()); command_line->AppendSwitchASCII( switches::kAppsGalleryURL, test_gallery_url_); GURL crx_url = GenerateTestServerUrl(kWebstoreDomain, "extension.crx"); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryUpdateURL, crx_url.spec()); command_line->AppendSwitch(switches::kEnableInlineWebstoreInstall); } virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { host_resolver()->AddRule(kWebstoreDomain, "127.0.0.1"); host_resolver()->AddRule(kAppDomain, "127.0.0.1"); } protected: GURL GenerateTestServerUrl(const std::string& domain, const std::string& page_filename) { GURL page_url = test_server()->GetURL( "files/extensions/api_test/webstore_inline_install/" + page_filename); GURL::Replacements replace_host; replace_host.SetHostStr(domain); return page_url.ReplaceComponents(replace_host); } std::string test_gallery_url_; }; IN_PROC_BROWSER_TEST_F(WebstoreInlineInstallTest, Install) { SetExtensionInstallDialogForManifestAutoConfirmForTests(true); ui_test_utils::WindowedNotificationObserver load_signal( chrome::NOTIFICATION_EXTENSION_LOADED, Source<Profile>(browser()->profile())); ui_test_utils::NavigateToURL( browser(), GenerateTestServerUrl(kAppDomain, "install.html")); bool result = false; std::string script = StringPrintf("runTest('%s')", test_gallery_url_.c_str()); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", UTF8ToWide(script), &result)); EXPECT_TRUE(result); load_signal.Wait(); const Extension* extension = browser()->profile()->GetExtensionService()-> GetExtensionById("ecglahbcnmdpdciemllbhojghbkagdje", false); EXPECT_TRUE(extension != NULL); } // Flakily fails on Linux. http://crbug.com/95280 #if defined(OS_LINUX) #define MAYBE_FindLink FLAKY_FindLink #else #define MAYBE_FindLink FindLink #endif IN_PROC_BROWSER_TEST_F(WebstoreInlineInstallTest, MAYBE_FindLink) { ui_test_utils::NavigateToURL( browser(), GenerateTestServerUrl(kAppDomain, "find_link.html")); bool result = false; std::string script = StringPrintf("runTest('%s')", test_gallery_url_.c_str()); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", UTF8ToWide(script), &result)); EXPECT_TRUE(result); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/url_request/url_request_unittest.h" class NotificationsPermissionTest : public UITest { public: NotificationsPermissionTest() { dom_automation_enabled_ = true; show_window_ = true; } }; TEST_F(NotificationsPermissionTest, FLAKY_TestUserGestureInfobar) { const wchar_t kDocRoot[] = L"chrome/test/data"; scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(server.get() != NULL); scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab(browser->GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(server->TestServerPageW( L"files/notifications/notifications_request_function.html"))); WaitUntilTabCount(1); // Request permission by calling request() while eval'ing an inline script; // That's considered a user gesture to webkit, and should produce an infobar. bool result; ASSERT_TRUE(tab->ExecuteAndExtractBool( L"", L"window.domAutomationController.send(request());", &result)); EXPECT_TRUE(result); EXPECT_TRUE(tab->WaitForInfoBarCount(1, action_max_timeout_ms())); } TEST_F(NotificationsPermissionTest, TestNoUserGestureInfobar) { const wchar_t kDocRoot[] = L"chrome/test/data"; scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(server.get() != NULL); scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab(browser->GetActiveTab()); ASSERT_TRUE(tab.get()); // Load a page which just does a request; no user gesture should result // in no infobar. ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(server->TestServerPageW( L"files/notifications/notifications_request_inline.html"))); WaitUntilTabCount(1); int info_bar_count; ASSERT_TRUE(tab->GetInfoBarCount(&info_bar_count)); EXPECT_EQ(0, info_bar_count); } <commit_msg>This test is no longer flaky now that it is run as an interactive UI test. Changing the name to match.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/url_request/url_request_unittest.h" class NotificationsPermissionTest : public UITest { public: NotificationsPermissionTest() { dom_automation_enabled_ = true; show_window_ = true; } }; TEST_F(NotificationsPermissionTest, TestUserGestureInfobar) { const wchar_t kDocRoot[] = L"chrome/test/data"; scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(server.get() != NULL); scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab(browser->GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(server->TestServerPageW( L"files/notifications/notifications_request_function.html"))); WaitUntilTabCount(1); // Request permission by calling request() while eval'ing an inline script; // That's considered a user gesture to webkit, and should produce an infobar. bool result; ASSERT_TRUE(tab->ExecuteAndExtractBool( L"", L"window.domAutomationController.send(request());", &result)); EXPECT_TRUE(result); EXPECT_TRUE(tab->WaitForInfoBarCount(1, action_max_timeout_ms())); } TEST_F(NotificationsPermissionTest, TestNoUserGestureInfobar) { const wchar_t kDocRoot[] = L"chrome/test/data"; scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(server.get() != NULL); scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab(browser->GetActiveTab()); ASSERT_TRUE(tab.get()); // Load a page which just does a request; no user gesture should result // in no infobar. ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(server->TestServerPageW( L"files/notifications/notifications_request_inline.html"))); WaitUntilTabCount(1); int info_bar_count; ASSERT_TRUE(tab->GetInfoBarCount(&info_bar_count)); EXPECT_EQ(0, info_bar_count); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE entry. #include "chrome/browser/sync/util/extensions_activity_monitor.h" #include "base/file_path.h" #include "base/string_util.h" #include "base/waitable_event.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/extensions/extension_bookmarks_module.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/notification_service.h" #include "testing/gtest/include/gtest/gtest.h" using browser_sync::ExtensionsActivityMonitor; namespace keys = extension_manifest_keys; namespace { static const char* kTestExtensionPath1 = "c:\\testextension1"; static const char* kTestExtensionPath2 = "c:\\testextension2"; static const char* kTestExtensionVersion = "1.0.0.0"; static const char* kTestExtensionName = "foo extension"; template <class FunctionType> class BookmarkAPIEventTask : public Task { public: BookmarkAPIEventTask(FunctionType* t, Extension* e, size_t repeats, base::WaitableEvent* done) : function_(t), extension_(e), repeats_(repeats), done_(done) {} virtual void Run() { for (size_t i = 0; i < repeats_; i++) { NotificationService::current()->Notify( NotificationType::EXTENSION_BOOKMARKS_API_INVOKED, Source<Extension>(extension_.get()), Details<const BookmarksFunction>(function_.get())); } done_->Signal(); } private: scoped_ptr<Extension> extension_; scoped_refptr<FunctionType> function_; size_t repeats_; base::WaitableEvent* done_; DISALLOW_COPY_AND_ASSIGN(BookmarkAPIEventTask); }; class BookmarkAPIEventGenerator { public: BookmarkAPIEventGenerator(MessageLoop* ui_loop) : ui_loop_(ui_loop) {} virtual ~BookmarkAPIEventGenerator() {} template <class T> void NewEvent(const std::string& extension_path, T* bookmarks_function, size_t repeats) { FilePath path(UTF8ToWide(extension_path)); Extension* extension = new Extension(path); std::string error; DictionaryValue input; input.SetString(keys::kVersion, kTestExtensionVersion); input.SetString(keys::kName, kTestExtensionName); extension->InitFromValue(input, false, &error); bookmarks_function->set_name(T::function_name()); base::WaitableEvent done_event(false, false); ui_loop_->PostTask(FROM_HERE, new BookmarkAPIEventTask<T>( bookmarks_function, extension, repeats, &done_event)); done_event.Wait(); } private: MessageLoop* ui_loop_; DISALLOW_COPY_AND_ASSIGN(BookmarkAPIEventGenerator); }; } // namespace class DoUIThreadSetupTask : public Task { public: DoUIThreadSetupTask(NotificationService** service, base::WaitableEvent* done) : service_(service), signal_when_done_(done) {} virtual ~DoUIThreadSetupTask() {} virtual void Run() { *service_ = new NotificationService(); signal_when_done_->Signal(); } private: NotificationService** service_; base::WaitableEvent* signal_when_done_; DISALLOW_COPY_AND_ASSIGN(DoUIThreadSetupTask); }; class ExtensionsActivityMonitorTest : public testing::Test { public: ExtensionsActivityMonitorTest() : service_(NULL), ui_thread_(ChromeThread::UI) { } virtual ~ExtensionsActivityMonitorTest() {} virtual void SetUp() { ui_thread_.Start(); base::WaitableEvent service_created(false, false); ui_thread_.message_loop()->PostTask(FROM_HERE, new DoUIThreadSetupTask(&service_, &service_created)); service_created.Wait(); } virtual void TearDown() { ui_thread_.message_loop()->DeleteSoon(FROM_HERE, service_); ui_thread_.Stop(); } MessageLoop* ui_loop() { return ui_thread_.message_loop(); } static std::string GetExtensionIdForPath(const std::string& extension_path) { std::string error; FilePath path(UTF8ToWide(extension_path)); Extension e(path); DictionaryValue input; input.SetString(keys::kVersion, kTestExtensionVersion); input.SetString(keys::kName, kTestExtensionName); e.InitFromValue(input, false, &error); EXPECT_EQ("", error); return e.id(); } private: NotificationService* service_; ChromeThread ui_thread_; }; TEST_F(ExtensionsActivityMonitorTest, Basic) { ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor(ui_loop()); BookmarkAPIEventGenerator generator(ui_loop()); generator.NewEvent<RemoveBookmarkFunction>(kTestExtensionPath1, new RemoveBookmarkFunction(), 1); generator.NewEvent<MoveBookmarkFunction>(kTestExtensionPath1, new MoveBookmarkFunction(), 1); generator.NewEvent<UpdateBookmarkFunction>(kTestExtensionPath1, new UpdateBookmarkFunction(), 2); generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1, new CreateBookmarkFunction(), 3); generator.NewEvent<SearchBookmarksFunction>(kTestExtensionPath1, new SearchBookmarksFunction(), 5); const int writes_by_extension1 = 1 + 1 + 2 + 3; generator.NewEvent<RemoveTreeBookmarkFunction>(kTestExtensionPath2, new RemoveTreeBookmarkFunction(), 8); generator.NewEvent<GetBookmarkTreeFunction>(kTestExtensionPath2, new GetBookmarkTreeFunction(), 13); generator.NewEvent<GetBookmarkChildrenFunction>(kTestExtensionPath2, new GetBookmarkChildrenFunction(), 21); generator.NewEvent<GetBookmarksFunction>(kTestExtensionPath2, new GetBookmarksFunction(), 33); const int writes_by_extension2 = 8; ExtensionsActivityMonitor::Records results; monitor->GetAndClearRecords(&results); std::string id1 = GetExtensionIdForPath(kTestExtensionPath1); std::string id2 = GetExtensionIdForPath(kTestExtensionPath2); EXPECT_EQ(2, results.size()); EXPECT_TRUE(results.end() != results.find(id1)); EXPECT_TRUE(results.end() != results.find(id2)); EXPECT_EQ(writes_by_extension1, results[id1].bookmark_write_count); EXPECT_EQ(writes_by_extension2, results[id2].bookmark_write_count); ui_loop()->DeleteSoon(FROM_HERE, monitor); } TEST_F(ExtensionsActivityMonitorTest, Put) { ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor(ui_loop()); BookmarkAPIEventGenerator generator(ui_loop()); std::string id1 = GetExtensionIdForPath(kTestExtensionPath1); std::string id2 = GetExtensionIdForPath(kTestExtensionPath2); generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1, new CreateBookmarkFunction(), 5); generator.NewEvent<MoveBookmarkFunction>(kTestExtensionPath2, new MoveBookmarkFunction(), 8); ExtensionsActivityMonitor::Records results; monitor->GetAndClearRecords(&results); EXPECT_EQ(2, results.size()); EXPECT_EQ(5, results[id1].bookmark_write_count); EXPECT_EQ(8, results[id2].bookmark_write_count); generator.NewEvent<GetBookmarksFunction>(kTestExtensionPath2, new GetBookmarksFunction(), 3); generator.NewEvent<UpdateBookmarkFunction>(kTestExtensionPath2, new UpdateBookmarkFunction(), 2); // Simulate a commit failure, which augments the active record set with the // refugee records. monitor->PutRecords(results); ExtensionsActivityMonitor::Records new_records; monitor->GetAndClearRecords(&new_records); EXPECT_EQ(2, results.size()); EXPECT_EQ(id1, new_records[id1].extension_id); EXPECT_EQ(id2, new_records[id2].extension_id); EXPECT_EQ(5, new_records[id1].bookmark_write_count); EXPECT_EQ(8 + 2, new_records[id2].bookmark_write_count); ui_loop()->DeleteSoon(FROM_HERE, monitor); } TEST_F(ExtensionsActivityMonitorTest, MultiGet) { ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor(ui_loop()); BookmarkAPIEventGenerator generator(ui_loop()); std::string id1 = GetExtensionIdForPath(kTestExtensionPath1); generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1, new CreateBookmarkFunction(), 5); ExtensionsActivityMonitor::Records results; monitor->GetAndClearRecords(&results); EXPECT_EQ(1, results.size()); EXPECT_EQ(5, results[id1].bookmark_write_count); monitor->GetAndClearRecords(&results); EXPECT_TRUE(results.empty()); generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1, new CreateBookmarkFunction(), 3); monitor->GetAndClearRecords(&results); EXPECT_EQ(1, results.size()); EXPECT_EQ(3, results[id1].bookmark_write_count); ui_loop()->DeleteSoon(FROM_HERE, monitor); }<commit_msg>Add newline to end of another file.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE entry. #include "chrome/browser/sync/util/extensions_activity_monitor.h" #include "base/file_path.h" #include "base/string_util.h" #include "base/waitable_event.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/extensions/extension_bookmarks_module.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/notification_service.h" #include "testing/gtest/include/gtest/gtest.h" using browser_sync::ExtensionsActivityMonitor; namespace keys = extension_manifest_keys; namespace { static const char* kTestExtensionPath1 = "c:\\testextension1"; static const char* kTestExtensionPath2 = "c:\\testextension2"; static const char* kTestExtensionVersion = "1.0.0.0"; static const char* kTestExtensionName = "foo extension"; template <class FunctionType> class BookmarkAPIEventTask : public Task { public: BookmarkAPIEventTask(FunctionType* t, Extension* e, size_t repeats, base::WaitableEvent* done) : function_(t), extension_(e), repeats_(repeats), done_(done) {} virtual void Run() { for (size_t i = 0; i < repeats_; i++) { NotificationService::current()->Notify( NotificationType::EXTENSION_BOOKMARKS_API_INVOKED, Source<Extension>(extension_.get()), Details<const BookmarksFunction>(function_.get())); } done_->Signal(); } private: scoped_ptr<Extension> extension_; scoped_refptr<FunctionType> function_; size_t repeats_; base::WaitableEvent* done_; DISALLOW_COPY_AND_ASSIGN(BookmarkAPIEventTask); }; class BookmarkAPIEventGenerator { public: BookmarkAPIEventGenerator(MessageLoop* ui_loop) : ui_loop_(ui_loop) {} virtual ~BookmarkAPIEventGenerator() {} template <class T> void NewEvent(const std::string& extension_path, T* bookmarks_function, size_t repeats) { FilePath path(UTF8ToWide(extension_path)); Extension* extension = new Extension(path); std::string error; DictionaryValue input; input.SetString(keys::kVersion, kTestExtensionVersion); input.SetString(keys::kName, kTestExtensionName); extension->InitFromValue(input, false, &error); bookmarks_function->set_name(T::function_name()); base::WaitableEvent done_event(false, false); ui_loop_->PostTask(FROM_HERE, new BookmarkAPIEventTask<T>( bookmarks_function, extension, repeats, &done_event)); done_event.Wait(); } private: MessageLoop* ui_loop_; DISALLOW_COPY_AND_ASSIGN(BookmarkAPIEventGenerator); }; } // namespace class DoUIThreadSetupTask : public Task { public: DoUIThreadSetupTask(NotificationService** service, base::WaitableEvent* done) : service_(service), signal_when_done_(done) {} virtual ~DoUIThreadSetupTask() {} virtual void Run() { *service_ = new NotificationService(); signal_when_done_->Signal(); } private: NotificationService** service_; base::WaitableEvent* signal_when_done_; DISALLOW_COPY_AND_ASSIGN(DoUIThreadSetupTask); }; class ExtensionsActivityMonitorTest : public testing::Test { public: ExtensionsActivityMonitorTest() : service_(NULL), ui_thread_(ChromeThread::UI) { } virtual ~ExtensionsActivityMonitorTest() {} virtual void SetUp() { ui_thread_.Start(); base::WaitableEvent service_created(false, false); ui_thread_.message_loop()->PostTask(FROM_HERE, new DoUIThreadSetupTask(&service_, &service_created)); service_created.Wait(); } virtual void TearDown() { ui_thread_.message_loop()->DeleteSoon(FROM_HERE, service_); ui_thread_.Stop(); } MessageLoop* ui_loop() { return ui_thread_.message_loop(); } static std::string GetExtensionIdForPath(const std::string& extension_path) { std::string error; FilePath path(UTF8ToWide(extension_path)); Extension e(path); DictionaryValue input; input.SetString(keys::kVersion, kTestExtensionVersion); input.SetString(keys::kName, kTestExtensionName); e.InitFromValue(input, false, &error); EXPECT_EQ("", error); return e.id(); } private: NotificationService* service_; ChromeThread ui_thread_; }; TEST_F(ExtensionsActivityMonitorTest, Basic) { ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor(ui_loop()); BookmarkAPIEventGenerator generator(ui_loop()); generator.NewEvent<RemoveBookmarkFunction>(kTestExtensionPath1, new RemoveBookmarkFunction(), 1); generator.NewEvent<MoveBookmarkFunction>(kTestExtensionPath1, new MoveBookmarkFunction(), 1); generator.NewEvent<UpdateBookmarkFunction>(kTestExtensionPath1, new UpdateBookmarkFunction(), 2); generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1, new CreateBookmarkFunction(), 3); generator.NewEvent<SearchBookmarksFunction>(kTestExtensionPath1, new SearchBookmarksFunction(), 5); const int writes_by_extension1 = 1 + 1 + 2 + 3; generator.NewEvent<RemoveTreeBookmarkFunction>(kTestExtensionPath2, new RemoveTreeBookmarkFunction(), 8); generator.NewEvent<GetBookmarkTreeFunction>(kTestExtensionPath2, new GetBookmarkTreeFunction(), 13); generator.NewEvent<GetBookmarkChildrenFunction>(kTestExtensionPath2, new GetBookmarkChildrenFunction(), 21); generator.NewEvent<GetBookmarksFunction>(kTestExtensionPath2, new GetBookmarksFunction(), 33); const int writes_by_extension2 = 8; ExtensionsActivityMonitor::Records results; monitor->GetAndClearRecords(&results); std::string id1 = GetExtensionIdForPath(kTestExtensionPath1); std::string id2 = GetExtensionIdForPath(kTestExtensionPath2); EXPECT_EQ(2, results.size()); EXPECT_TRUE(results.end() != results.find(id1)); EXPECT_TRUE(results.end() != results.find(id2)); EXPECT_EQ(writes_by_extension1, results[id1].bookmark_write_count); EXPECT_EQ(writes_by_extension2, results[id2].bookmark_write_count); ui_loop()->DeleteSoon(FROM_HERE, monitor); } TEST_F(ExtensionsActivityMonitorTest, Put) { ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor(ui_loop()); BookmarkAPIEventGenerator generator(ui_loop()); std::string id1 = GetExtensionIdForPath(kTestExtensionPath1); std::string id2 = GetExtensionIdForPath(kTestExtensionPath2); generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1, new CreateBookmarkFunction(), 5); generator.NewEvent<MoveBookmarkFunction>(kTestExtensionPath2, new MoveBookmarkFunction(), 8); ExtensionsActivityMonitor::Records results; monitor->GetAndClearRecords(&results); EXPECT_EQ(2, results.size()); EXPECT_EQ(5, results[id1].bookmark_write_count); EXPECT_EQ(8, results[id2].bookmark_write_count); generator.NewEvent<GetBookmarksFunction>(kTestExtensionPath2, new GetBookmarksFunction(), 3); generator.NewEvent<UpdateBookmarkFunction>(kTestExtensionPath2, new UpdateBookmarkFunction(), 2); // Simulate a commit failure, which augments the active record set with the // refugee records. monitor->PutRecords(results); ExtensionsActivityMonitor::Records new_records; monitor->GetAndClearRecords(&new_records); EXPECT_EQ(2, results.size()); EXPECT_EQ(id1, new_records[id1].extension_id); EXPECT_EQ(id2, new_records[id2].extension_id); EXPECT_EQ(5, new_records[id1].bookmark_write_count); EXPECT_EQ(8 + 2, new_records[id2].bookmark_write_count); ui_loop()->DeleteSoon(FROM_HERE, monitor); } TEST_F(ExtensionsActivityMonitorTest, MultiGet) { ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor(ui_loop()); BookmarkAPIEventGenerator generator(ui_loop()); std::string id1 = GetExtensionIdForPath(kTestExtensionPath1); generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1, new CreateBookmarkFunction(), 5); ExtensionsActivityMonitor::Records results; monitor->GetAndClearRecords(&results); EXPECT_EQ(1, results.size()); EXPECT_EQ(5, results[id1].bookmark_write_count); monitor->GetAndClearRecords(&results); EXPECT_TRUE(results.empty()); generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1, new CreateBookmarkFunction(), 3); monitor->GetAndClearRecords(&results); EXPECT_EQ(1, results.size()); EXPECT_EQ(3, results[id1].bookmark_write_count); ui_loop()->DeleteSoon(FROM_HERE, monitor); } <|endoftext|>
<commit_before> # include <Siv3D.hpp> class Block { public: // 引数のないコンストラクタも作っておくといろいろ便利. Block() {} Block(const RectF& region) : m_region(region), m_texture(L"Example/Brick.jpg") {} // 描画以外の操作をする関数 void update() { // 今回は何もない } // 点との当たり判定を取る関数 bool intersects(const Vec2 &shape) const { return m_region.intersects(shape); } // 描画をする関数(描画操作以外行わないこと.) void draw() { m_region(m_texture).draw(); } private: // ブロックの領域 RectF m_region; // ブロックのテキスチャ(画像) Texture m_texture; }; class Player { public: Player() : m_position(100, 200), m_texture(L"Example/Siv3D-kun.png"), m_isGrounded(false), m_jumpFrame(0) {} void checkGround(const Array<Block>& blocks) { m_isGrounded = false; for (size_t i = 0; i < blocks.size(); i++) { if (blocks[i].intersects(m_position)) { m_isGrounded = true; } } } // 描画以外の操作をする関数 void update() { if (m_isGrounded) { if (Input::KeySpace.clicked && m_jumpFrame <= 0) { m_jumpFrame = 30; } } else { m_position.y += 10.0; } if (m_jumpFrame > 0) { m_position.y -= 20.0; m_jumpFrame--; } if (Input::KeyRight.pressed) { m_position.x += 5.0; } if (Input::KeyLeft.pressed) { m_position.x -= 5.0; } } // 描画をする関数(描画操作以外行わないこと.) void draw() { RectF(m_position.x - 72.5, m_position.y - 200, 145, 200)(m_texture).draw(); } private: // プレイヤーの座標 Vec2 m_position; // プレイヤーのテクスチャ(画像) Texture m_texture; // 地面に接しているか否か bool m_isGrounded; // 残りのジャンプ時間 int m_jumpFrame; }; void Main() { Window::Resize(1280, 720); Texture background(L"Example/Windmill.png"); Player player; Array<Block> blocks; blocks.push_back(Block({-400, 400, 200, 200})); blocks.push_back(Block({-200, 400, 200, 200})); blocks.push_back(Block({0, 400, 200, 200})); blocks.push_back(Block({200, 400, 200, 200})); blocks.push_back(Block({200, 200, 200, 200})); blocks.push_back(Block({400, 400, 200, 200})); blocks.push_back(Block({800, 400, 200, 200})); blocks.push_back(Block({1000, 400, 200, 200})); blocks.push_back(Block({1300, 200, 400, 30})); while (System::Update()) { for (size_t i = 0; i < blocks.size(); i++) { blocks[i].update(); } player.checkGround(blocks); player.update(); // 本来ならリサイズしなくていいように画像を用意すべき. background.scale(1280.0 / 480.0).draw(); for (size_t i = 0; i < blocks.size(); i++) { blocks[i].draw(); } player.draw(); } } <commit_msg>Implement Scroll with Zero.<commit_after> # include <Siv3D.hpp> class Block { public: Block() {} Block(const RectF& region) : m_region(region), m_texture(L"Example/Brick.jpg") {} // プレイヤーの現在位置を更新する関数 void setPlayerPosition(const Vec2& pos) { m_playerPosition = pos; } // 描画以外の操作をする関数 void update() {} // 点との当たり判定を取る関数 bool intersects(const Vec2 &shape) const { return m_region.intersects(shape); } // 描画をする関数(描画操作以外行わないこと.) void draw() { m_region.movedBy(-m_playerPosition)(m_texture).draw(); } private: // ブロックの領域 RectF m_region; // ブロックのテキスチャ(画像) Texture m_texture; // プレイヤーの現在の位置 Vec2 m_playerPosition; }; class Player { public: Player() : m_position(100, 200), m_texture(L"Example/Siv3D-kun.png"), m_isGrounded(false), m_jumpFrame(0) {} Vec2 getPos() { return m_position; } // 地面に接しているかを更新する関数 void checkGround(const Array<Block>& blocks) { m_isGrounded = false; for (size_t i = 0; i < blocks.size(); i++) { if (blocks[i].intersects(m_position)) { m_isGrounded = true; } } } // 描画以外の操作をする関数 void update() { if (m_isGrounded) { if (Input::KeySpace.clicked && m_jumpFrame <= 0) { m_jumpFrame = 30; } } else { m_position.y += 10.0; } if (m_jumpFrame > 0) { m_position.y -= 20.0; m_jumpFrame--; } if (Input::KeyRight.pressed) { m_position.x += 5.0; } if (Input::KeyLeft.pressed) { m_position.x -= 5.0; } } // 描画をする関数(描画操作以外行わないこと.) void draw() { RectF(Vec2(-72.5, -200), 145, 200)(m_texture).draw(); } private: // プレイヤーの座標 Vec2 m_position; // プレイヤーのテクスチャ(画像) Texture m_texture; // 地面に接しているか否か bool m_isGrounded; // 残りのジャンプ時間 int m_jumpFrame; }; void Main() { Window::Resize(1280, 720); Texture background(L"Example/Windmill.png"); Player player; Array<Block> blocks; blocks.push_back(Block({-400, 400, 200, 200})); blocks.push_back(Block({-200, 400, 200, 200})); blocks.push_back(Block({0, 400, 200, 200})); blocks.push_back(Block({200, 400, 200, 200})); blocks.push_back(Block({200, 200, 200, 200})); blocks.push_back(Block({400, 400, 200, 200})); blocks.push_back(Block({800, 400, 200, 200})); blocks.push_back(Block({1000, 400, 200, 200})); blocks.push_back(Block({1300, 200, 400, 30})); while (System::Update()) { for (size_t i = 0; i < blocks.size(); i++) { blocks[i].setPlayerPosition(player.getPos()); blocks[i].update(); } player.checkGround(blocks); player.update(); background.scale(1280.0 / 480.0).draw(); for (size_t i = 0; i < blocks.size(); i++) { blocks[i].draw(); } player.draw(); } } <|endoftext|>
<commit_before>/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #include <libsoup/soup.h> #include "KmsHttpPost.h" #define OBJECT_NAME "HttpPost" #define MIME_MULTIPART_FORM_DATA "multipart/form-data" #define GST_CAT_DEFAULT kms_http_post_debug_category GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define KMS_HTTP_POST_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), KMS_TYPE_HTTP_POST, KmsHttpPostPrivate)) struct _KmsHttpPostPrivate { SoupMessage *msg; gchar *boundary; gulong handler_id; }; /* class initialization */ G_DEFINE_TYPE_WITH_CODE (KmsHttpPost, kms_http_post, G_TYPE_OBJECT, GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, OBJECT_NAME, 0, "debug category for " OBJECT_NAME " element") ) /* properties */ enum { PROP_0, PROP_MESSAGE, N_PROPERTIES }; #define KMS_HTTP_PORT_DEFAULT_MESSAGE NULL static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, }; /* signals */ enum { GOT_DATA, LAST_SIGNAL }; static guint obj_signals[LAST_SIGNAL] = { 0 }; static void got_chunk_cb (SoupMessage *msg, SoupBuffer *chunk, gpointer data) { GST_DEBUG ("TODO: Process data"); } static void kms_http_post_configure_msg (KmsHttpPost *self) { const gchar *content_type; GHashTable *params = NULL; content_type = soup_message_headers_get_content_type (self->priv->msg->request_headers, &params); if (content_type == NULL) { GST_WARNING ("Content-type header is not present in request"); soup_message_set_status (self->priv->msg, SOUP_STATUS_NOT_ACCEPTABLE); goto end; } if (g_strcmp0 (content_type, MIME_MULTIPART_FORM_DATA) == 0) { self->priv->boundary = g_strdup ( (gchar *) g_hash_table_lookup (params, "boundary") ); if (self->priv->boundary == NULL) { GST_WARNING ("Malformed multipart POST request"); soup_message_set_status (self->priv->msg, SOUP_STATUS_NOT_ACCEPTABLE); goto end; } } soup_message_set_status (self->priv->msg, SOUP_STATUS_OK); /* Get chunks without filling-in body's data field after */ /* the body is fully sent/received */ soup_message_body_set_accumulate (self->priv->msg->request_body, FALSE); self->priv->handler_id = g_signal_connect (self->priv->msg, "got-chunk", G_CALLBACK (got_chunk_cb), self); end: if (params != NULL) g_hash_table_destroy (params); } static void kms_http_post_set_property (GObject *obj, guint prop_id, const GValue *value, GParamSpec *pspec) { KmsHttpPost *self = KMS_HTTP_POST (obj); switch (prop_id) { case PROP_MESSAGE: if (self->priv->msg != NULL) g_object_unref (self->priv->msg); self->priv->msg = SOUP_MESSAGE (g_object_ref (g_value_get_object (value) ) ); kms_http_post_configure_msg (self); break; default: /* We don't have any other property... */ G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec); break; } } static void kms_http_post_get_property (GObject *obj, guint prop_id, GValue *value, GParamSpec *pspec) { KmsHttpPost *self = KMS_HTTP_POST (obj); switch (prop_id) { case PROP_MESSAGE: g_value_set_object (value, self->priv->msg); break; default: /* We don't have any other property... */ G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec); break; } } static void kms_http_post_dispose (GObject *obj) { KmsHttpPost *self = KMS_HTTP_POST (obj); if (self->priv->msg != NULL) { g_object_unref ( G_OBJECT (self->priv->msg) ); self->priv->msg = NULL; } /* Chain up to the parent class */ G_OBJECT_CLASS (kms_http_post_parent_class)->dispose (obj); } static void kms_http_post_finalize (GObject *obj) { KmsHttpPost *self = KMS_HTTP_POST (obj); if (self->priv->boundary != NULL) { g_free (self->priv->boundary); self->priv->boundary = NULL; } /* Chain up to the parent class */ G_OBJECT_CLASS (kms_http_post_parent_class)->finalize (obj); } static void kms_http_post_class_init (KmsHttpPostClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); gobject_class->set_property = kms_http_post_set_property; gobject_class->get_property = kms_http_post_get_property; gobject_class->dispose = kms_http_post_dispose; gobject_class->finalize = kms_http_post_finalize; obj_properties[PROP_MESSAGE] = g_param_spec_object ("soup-message", "Soup message object", "Message to get data from", SOUP_TYPE_MESSAGE, (GParamFlags) (G_PARAM_READWRITE) ); g_object_class_install_properties (gobject_class, N_PROPERTIES, obj_properties); obj_signals[GOT_DATA] = g_signal_new ("got-data", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (KmsHttpPostClass, got_data), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); /* Registers a private structure for an instantiatable type */ g_type_class_add_private (klass, sizeof (KmsHttpPostPrivate) ); } static void kms_http_post_init (KmsHttpPost *self) { self->priv = KMS_HTTP_POST_GET_PRIVATE (self); }<commit_msg>KmsHttpPost: Disconnect signal when message is removed<commit_after>/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #include <libsoup/soup.h> #include "KmsHttpPost.h" #define OBJECT_NAME "HttpPost" #define MIME_MULTIPART_FORM_DATA "multipart/form-data" #define GST_CAT_DEFAULT kms_http_post_debug_category GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define KMS_HTTP_POST_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), KMS_TYPE_HTTP_POST, KmsHttpPostPrivate)) struct _KmsHttpPostPrivate { SoupMessage *msg; gchar *boundary; gulong handler_id; }; /* class initialization */ G_DEFINE_TYPE_WITH_CODE (KmsHttpPost, kms_http_post, G_TYPE_OBJECT, GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, OBJECT_NAME, 0, "debug category for " OBJECT_NAME " element") ) /* properties */ enum { PROP_0, PROP_MESSAGE, N_PROPERTIES }; #define KMS_HTTP_PORT_DEFAULT_MESSAGE NULL static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, }; /* signals */ enum { GOT_DATA, LAST_SIGNAL }; static guint obj_signals[LAST_SIGNAL] = { 0 }; static void got_chunk_cb (SoupMessage *msg, SoupBuffer *chunk, gpointer data) { GST_DEBUG ("TODO: Process data"); } static void kms_http_post_configure_msg (KmsHttpPost *self) { const gchar *content_type; GHashTable *params = NULL; content_type = soup_message_headers_get_content_type (self->priv->msg->request_headers, &params); if (content_type == NULL) { GST_WARNING ("Content-type header is not present in request"); soup_message_set_status (self->priv->msg, SOUP_STATUS_NOT_ACCEPTABLE); goto end; } if (g_strcmp0 (content_type, MIME_MULTIPART_FORM_DATA) == 0) { self->priv->boundary = g_strdup ( (gchar *) g_hash_table_lookup (params, "boundary") ); if (self->priv->boundary == NULL) { GST_WARNING ("Malformed multipart POST request"); soup_message_set_status (self->priv->msg, SOUP_STATUS_NOT_ACCEPTABLE); goto end; } } soup_message_set_status (self->priv->msg, SOUP_STATUS_OK); /* Get chunks without filling-in body's data field after */ /* the body is fully sent/received */ soup_message_body_set_accumulate (self->priv->msg->request_body, FALSE); self->priv->handler_id = g_signal_connect (self->priv->msg, "got-chunk", G_CALLBACK (got_chunk_cb), self); end: if (params != NULL) g_hash_table_destroy (params); } static void kms_http_post_release_message (KmsHttpPost *self) { if (self->priv->msg == NULL) return; if (self->priv->handler_id != 0L) { g_signal_handler_disconnect (self->priv->msg, self->priv->handler_id); self->priv->handler_id = 0L; } g_object_unref (self->priv->msg); self->priv->msg = NULL; } static void kms_http_post_set_property (GObject *obj, guint prop_id, const GValue *value, GParamSpec *pspec) { KmsHttpPost *self = KMS_HTTP_POST (obj); switch (prop_id) { case PROP_MESSAGE: kms_http_post_release_message (self); if (self->priv->boundary != NULL) { g_free (self->priv->boundary); self->priv->boundary = NULL; } self->priv->msg = SOUP_MESSAGE (g_object_ref (g_value_get_object (value) ) ); kms_http_post_configure_msg (self); break; default: /* We don't have any other property... */ G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec); break; } } static void kms_http_post_get_property (GObject *obj, guint prop_id, GValue *value, GParamSpec *pspec) { KmsHttpPost *self = KMS_HTTP_POST (obj); switch (prop_id) { case PROP_MESSAGE: g_value_set_object (value, self->priv->msg); break; default: /* We don't have any other property... */ G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec); break; } } static void kms_http_post_dispose (GObject *obj) { KmsHttpPost *self = KMS_HTTP_POST (obj); kms_http_post_release_message (self); /* Chain up to the parent class */ G_OBJECT_CLASS (kms_http_post_parent_class)->dispose (obj); } static void kms_http_post_finalize (GObject *obj) { KmsHttpPost *self = KMS_HTTP_POST (obj); if (self->priv->boundary != NULL) { g_free (self->priv->boundary); self->priv->boundary = NULL; } /* Chain up to the parent class */ G_OBJECT_CLASS (kms_http_post_parent_class)->finalize (obj); } static void kms_http_post_class_init (KmsHttpPostClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); gobject_class->set_property = kms_http_post_set_property; gobject_class->get_property = kms_http_post_get_property; gobject_class->dispose = kms_http_post_dispose; gobject_class->finalize = kms_http_post_finalize; obj_properties[PROP_MESSAGE] = g_param_spec_object ("soup-message", "Soup message object", "Message to get data from", SOUP_TYPE_MESSAGE, (GParamFlags) (G_PARAM_READWRITE) ); g_object_class_install_properties (gobject_class, N_PROPERTIES, obj_properties); obj_signals[GOT_DATA] = g_signal_new ("got-data", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (KmsHttpPostClass, got_data), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); /* Registers a private structure for an instantiatable type */ g_type_class_add_private (klass, sizeof (KmsHttpPostPrivate) ); } static void kms_http_post_init (KmsHttpPost *self) { self->priv = KMS_HTTP_POST_GET_PRIVATE (self); self->priv->handler_id = 0L; }<|endoftext|>
<commit_before>// Native C++ Libraries #include <iostream> #include <string> // C++ Interpreter Libraries #include <Console.h> <commit_msg>Add the rest of the standard C++ code to main file.<commit_after>// Native C++ Libraries #include <iostream> #include <string> // C++ Interpreter Libraries #include <Console.h> using namespace std; int main() { } <|endoftext|>
<commit_before>#include <bcc/libbpf.h> #include <bpffeature.h> #include <cstddef> #include <cstdio> #include <fcntl.h> #include <fstream> #include <unistd.h> #include "btf.h" #include "list.h" #include "utils.h" namespace bpftrace { #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) static bool try_load(const char* name, enum libbpf::bpf_prog_type prog_type, struct bpf_insn* insns, size_t insns_cnt, int loglevel, char* logbuf, size_t logbuf_size) { int ret = 0; StderrSilencer silencer; silencer.silence(); for (int attempt = 0; attempt < 3; attempt++) { auto version = kernel_version(attempt); if (version == 0 && attempt > 0) { // Recent kernels don't check the version so we should try to call // bcc_prog_load during first iteration even if we failed to determine // the version. We should not do that in subsequent iterations to avoid // zeroing of log_buf on systems with older kernels. continue; } #ifdef HAVE_BCC_PROG_LOAD ret = bcc_prog_load( #else ret = bpf_prog_load( #endif static_cast<enum ::bpf_prog_type>(prog_type), name, insns, insns_cnt * sizeof(struct bpf_insn), "GPL", version, loglevel, logbuf, logbuf_size); if (ret >= 0) { close(ret); return true; } } return false; } static bool try_load(enum libbpf::bpf_prog_type prog_type, struct bpf_insn* insns, size_t len) { constexpr int log_size = 4096; char logbuf[log_size] = {}; // kfunc / kretfunc only for now. We can refactor if more attach types // get added to BPF_PROG_TYPE_TRACING if (prog_type == libbpf::BPF_PROG_TYPE_TRACING) { // List of available functions must be readable std::ifstream traceable_funcs(kprobe_path); // bcc checks the name (first arg) for the magic strings. If the bcc we // build against doesn't support kfunc then we will fail here. That's fine // because it still means kfunc doesn't work, only from a library side, not // a kernel side. return traceable_funcs.good() && try_load( "kfunc__strlen", prog_type, insns, len, 0, logbuf, log_size) && try_load( "kretfunc__strlen", prog_type, insns, len, 0, logbuf, log_size); } return try_load(nullptr, prog_type, insns, len, 0, logbuf, log_size); } bool BPFfeature::detect_helper(enum libbpf::bpf_func_id func_id, enum libbpf::bpf_prog_type prog_type) { // Stolen from libbpf's bpf_probe_helper char logbuf[4096] = {}; struct bpf_insn insns[] = { BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, func_id), BPF_EXIT_INSN(), }; if (try_load(nullptr, prog_type, insns, ARRAY_SIZE(insns), 1, logbuf, 4096)) return true; if (errno == EPERM || logbuf[0] == 0) return false; return (strstr(logbuf, "invalid func ") == nullptr) && (strstr(logbuf, "unknown func ") == nullptr); } bool BPFfeature::detect_prog_type(enum libbpf::bpf_prog_type prog_type) { struct bpf_insn insns[] = { BPF_MOV64_IMM(BPF_REG_0, 0), BPF_EXIT_INSN() }; return try_load(prog_type, insns, ARRAY_SIZE(insns)); } bool BPFfeature::detect_map(enum libbpf::bpf_map_type map_type) { int key_size = 4; int value_size = 4; int max_entries = 1; int flags = 0; int map_fd = 0; switch (map_type) { case libbpf::BPF_MAP_TYPE_STACK_TRACE: value_size = 8; break; default: break; } #ifdef HAVE_BCC_CREATE_MAP map_fd = bcc_create_map( #else map_fd = bpf_create_map( #endif static_cast<enum ::bpf_map_type>(map_type), nullptr, key_size, value_size, max_entries, flags); if (map_fd >= 0) close(map_fd); return map_fd >= 0; } bool BPFfeature::has_loop(void) { if (has_loop_.has_value()) return *has_loop_; struct bpf_insn insns[] = { BPF_MOV64_IMM(BPF_REG_0, 0), BPF_ALU64_IMM(BPF_ADD, BPF_REG_0, 1), BPF_JMP_IMM(BPF_JLT, BPF_REG_0, 4, -2), BPF_EXIT_INSN(), }; has_loop_ = std::make_optional<bool>( try_load(libbpf::BPF_PROG_TYPE_TRACEPOINT, insns, ARRAY_SIZE(insns))); return has_loop(); } bool BPFfeature::has_btf(void) { BTF btf; return btf.has_data(); } int BPFfeature::instruction_limit(void) { if (insns_limit_.has_value()) return *insns_limit_; struct bpf_insn insns[] = { BPF_LD_IMM64(BPF_REG_0, 0), BPF_EXIT_INSN(), }; constexpr int logsize = 4096; char logbuf[logsize] = {}; bool res = try_load(nullptr, libbpf::BPF_PROG_TYPE_KPROBE, insns, ARRAY_SIZE(insns), 1, logbuf, logsize); if (!res) insns_limit_ = std::make_optional<int>(-1); // Extract limit from the verifier log: // processed 2 insns (limit 131072), stack depth 0 std::string log(logbuf, logsize); std::size_t line_start = log.find("processed 2 insns"); if (line_start == std::string::npos) { insns_limit_ = std::make_optional<int>(-1); return *insns_limit_; } // Old kernels don't have the instruction limit in the verifier output auto begin = log.find("limit", line_start); if (begin == std::string::npos) { insns_limit_ = std::make_optional<int>(-1); return *insns_limit_; } begin += 6; /* "limit " = 6*/ std::size_t end = log.find(")", begin); std::string cnt = log.substr(begin, end - begin); insns_limit_ = std::make_optional<int>(std::stoi(cnt)); return *insns_limit_; } std::string BPFfeature::report(void) { std::stringstream buf; auto to_str = [](bool f) -> auto { return f ? "yes\n" : "no\n"; }; buf << "Kernel helpers" << std::endl << " probe_read: " << to_str(has_helper_probe_read()) << " probe_read_str: " << to_str(has_helper_probe_read_str()) << " probe_read_user: " << to_str(has_helper_probe_read_user()) << " probe_read_user_str: " << to_str(has_helper_probe_read_user_str()) << " probe_read_kernel: " << to_str(has_helper_probe_read_kernel()) << " probe_read_kernel_str: " << to_str(has_helper_probe_read_kernel_str()) << " get_current_cgroup_id: " << to_str(has_helper_get_current_cgroup_id()) << " send_signal: " << to_str(has_helper_send_signal()) << " override_return: " << to_str(has_helper_override_return()) << std::endl; buf << "Kernel features" << std::endl << " Instruction limit: " << instruction_limit() << std::endl << " Loop support: " << to_str(has_loop()) << " btf (depends on Build:libbpf): " << to_str(has_btf()) << std::endl; buf << "Map types" << std::endl << " hash: " << to_str(has_map_hash()) << " percpu hash: " << to_str(has_map_percpu_hash()) << " array: " << to_str(has_map_array()) << " percpu array: " << to_str(has_map_percpu_array()) << " stack_trace: " << to_str(has_map_stack_trace()) << " perf_event_array: " << to_str(has_map_perf_event_array()) << std::endl; buf << "Probe types" << std::endl << " kprobe: " << to_str(has_prog_kprobe()) << " tracepoint: " << to_str(has_prog_tracepoint()) << " perf_event: " << to_str(has_prog_perf_event()) << " kfunc: " << to_str(has_prog_kfunc()) << std::endl; return buf.str(); } } // namespace bpftrace <commit_msg>bpffeature: fix helper detection for older kernels<commit_after>#include <bcc/libbpf.h> #include <bpffeature.h> #include <cstddef> #include <cstdio> #include <fcntl.h> #include <fstream> #include <unistd.h> #include "btf.h" #include "list.h" #include "utils.h" namespace bpftrace { #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) static bool try_load(const char* name, enum libbpf::bpf_prog_type prog_type, struct bpf_insn* insns, size_t insns_cnt, int loglevel, char* logbuf, size_t logbuf_size) { int ret = 0; StderrSilencer silencer; silencer.silence(); for (int attempt = 0; attempt < 3; attempt++) { auto version = kernel_version(attempt); if (version == 0 && attempt > 0) { // Recent kernels don't check the version so we should try to call // bcc_prog_load during first iteration even if we failed to determine // the version. We should not do that in subsequent iterations to avoid // zeroing of log_buf on systems with older kernels. continue; } #ifdef HAVE_BCC_PROG_LOAD ret = bcc_prog_load( #else ret = bpf_prog_load( #endif static_cast<enum ::bpf_prog_type>(prog_type), name, insns, insns_cnt * sizeof(struct bpf_insn), "GPL", version, loglevel, logbuf, logbuf_size); if (ret >= 0) { close(ret); return true; } } return false; } static bool try_load(enum libbpf::bpf_prog_type prog_type, struct bpf_insn* insns, size_t len) { constexpr int log_size = 4096; char logbuf[log_size] = {}; // kfunc / kretfunc only for now. We can refactor if more attach types // get added to BPF_PROG_TYPE_TRACING if (prog_type == libbpf::BPF_PROG_TYPE_TRACING) { // List of available functions must be readable std::ifstream traceable_funcs(kprobe_path); // bcc checks the name (first arg) for the magic strings. If the bcc we // build against doesn't support kfunc then we will fail here. That's fine // because it still means kfunc doesn't work, only from a library side, not // a kernel side. return traceable_funcs.good() && try_load( "kfunc__strlen", prog_type, insns, len, 0, logbuf, log_size) && try_load( "kretfunc__strlen", prog_type, insns, len, 0, logbuf, log_size); } return try_load(nullptr, prog_type, insns, len, 0, logbuf, log_size); } bool BPFfeature::detect_helper(enum libbpf::bpf_func_id func_id, enum libbpf::bpf_prog_type prog_type) { // Stolen from libbpf's bpf_probe_helper char logbuf[4096] = {}; char* buf = logbuf; struct bpf_insn insns[] = { BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, func_id), BPF_EXIT_INSN(), }; if (try_load(nullptr, prog_type, insns, ARRAY_SIZE(insns), 1, logbuf, 4096)) return true; if (errno == EPERM) return false; // On older kernels the first byte can be zero, skip leading 0 bytes // $2 = "\000: (85) call 4\nR1 type=ctx expected=fp\n", '\000' <repeats 4056 // times> // ^^ for (int i = 0; i < 8 && *buf == 0; i++, buf++) ; if (*buf == 0) return false; return (strstr(buf, "invalid func ") == nullptr) && (strstr(buf, "unknown func ") == nullptr); } bool BPFfeature::detect_prog_type(enum libbpf::bpf_prog_type prog_type) { struct bpf_insn insns[] = { BPF_MOV64_IMM(BPF_REG_0, 0), BPF_EXIT_INSN() }; return try_load(prog_type, insns, ARRAY_SIZE(insns)); } bool BPFfeature::detect_map(enum libbpf::bpf_map_type map_type) { int key_size = 4; int value_size = 4; int max_entries = 1; int flags = 0; int map_fd = 0; switch (map_type) { case libbpf::BPF_MAP_TYPE_STACK_TRACE: value_size = 8; break; default: break; } #ifdef HAVE_BCC_CREATE_MAP map_fd = bcc_create_map( #else map_fd = bpf_create_map( #endif static_cast<enum ::bpf_map_type>(map_type), nullptr, key_size, value_size, max_entries, flags); if (map_fd >= 0) close(map_fd); return map_fd >= 0; } bool BPFfeature::has_loop(void) { if (has_loop_.has_value()) return *has_loop_; struct bpf_insn insns[] = { BPF_MOV64_IMM(BPF_REG_0, 0), BPF_ALU64_IMM(BPF_ADD, BPF_REG_0, 1), BPF_JMP_IMM(BPF_JLT, BPF_REG_0, 4, -2), BPF_EXIT_INSN(), }; has_loop_ = std::make_optional<bool>( try_load(libbpf::BPF_PROG_TYPE_TRACEPOINT, insns, ARRAY_SIZE(insns))); return has_loop(); } bool BPFfeature::has_btf(void) { BTF btf; return btf.has_data(); } int BPFfeature::instruction_limit(void) { if (insns_limit_.has_value()) return *insns_limit_; struct bpf_insn insns[] = { BPF_LD_IMM64(BPF_REG_0, 0), BPF_EXIT_INSN(), }; constexpr int logsize = 4096; char logbuf[logsize] = {}; bool res = try_load(nullptr, libbpf::BPF_PROG_TYPE_KPROBE, insns, ARRAY_SIZE(insns), 1, logbuf, logsize); if (!res) insns_limit_ = std::make_optional<int>(-1); // Extract limit from the verifier log: // processed 2 insns (limit 131072), stack depth 0 std::string log(logbuf, logsize); std::size_t line_start = log.find("processed 2 insns"); if (line_start == std::string::npos) { insns_limit_ = std::make_optional<int>(-1); return *insns_limit_; } // Old kernels don't have the instruction limit in the verifier output auto begin = log.find("limit", line_start); if (begin == std::string::npos) { insns_limit_ = std::make_optional<int>(-1); return *insns_limit_; } begin += 6; /* "limit " = 6*/ std::size_t end = log.find(")", begin); std::string cnt = log.substr(begin, end - begin); insns_limit_ = std::make_optional<int>(std::stoi(cnt)); return *insns_limit_; } std::string BPFfeature::report(void) { std::stringstream buf; auto to_str = [](bool f) -> auto { return f ? "yes\n" : "no\n"; }; buf << "Kernel helpers" << std::endl << " probe_read: " << to_str(has_helper_probe_read()) << " probe_read_str: " << to_str(has_helper_probe_read_str()) << " probe_read_user: " << to_str(has_helper_probe_read_user()) << " probe_read_user_str: " << to_str(has_helper_probe_read_user_str()) << " probe_read_kernel: " << to_str(has_helper_probe_read_kernel()) << " probe_read_kernel_str: " << to_str(has_helper_probe_read_kernel_str()) << " get_current_cgroup_id: " << to_str(has_helper_get_current_cgroup_id()) << " send_signal: " << to_str(has_helper_send_signal()) << " override_return: " << to_str(has_helper_override_return()) << std::endl; buf << "Kernel features" << std::endl << " Instruction limit: " << instruction_limit() << std::endl << " Loop support: " << to_str(has_loop()) << " btf (depends on Build:libbpf): " << to_str(has_btf()) << std::endl; buf << "Map types" << std::endl << " hash: " << to_str(has_map_hash()) << " percpu hash: " << to_str(has_map_percpu_hash()) << " array: " << to_str(has_map_array()) << " percpu array: " << to_str(has_map_percpu_array()) << " stack_trace: " << to_str(has_map_stack_trace()) << " perf_event_array: " << to_str(has_map_perf_event_array()) << std::endl; buf << "Probe types" << std::endl << " kprobe: " << to_str(has_prog_kprobe()) << " tracepoint: " << to_str(has_prog_tracepoint()) << " perf_event: " << to_str(has_prog_perf_event()) << " kfunc: " << to_str(has_prog_kfunc()) << std::endl; return buf.str(); } } // namespace bpftrace <|endoftext|>
<commit_before>#ifndef ALGORITHM_HUFFMAN_H_ #define ALGORITHM_HUFFMAN_H_ 1 #include <fstream> #include <vector> #include <array> #include <limits> #include <string> #include <cstring> namespace algorithm { /** \breif Modified Huffman coding Huffman coding method with Run Length Encoding. Combines the variable length codes of Huffman coding with the coding of repetitive data in Run Length Encoding. */ class Huffman { public: typedef size_t SizeType; typedef std::ifstream FileStreamInType; typedef std::ofstream FileStreamOutType; typedef std::string StringType; typedef uint8_t ByteType; /** One byte */ typedef uint32_t CodewordType; /** Codeword, consists of 4 bytes */ typedef std::pair<ByteType, SizeType> MetaSymbolType; /** Constants */ static const ByteType zerobit = 0; static const ByteType nonzerobit = 1; static const SizeType ascii_max = std::numeric_limits<ByteType>::max(); static const SizeType byte_size = 8; /**< 8 bits, bit size of ByteType */ static const SizeType buffer_size = byte_size * 4; /**< Bit size of CodewordType */ /** Class for each node in Huffman tree, and used in RLE */ struct Run { /** MetaSymbol, paired with MetaSymbolType */ ByteType symbol; /**< ASCII character */ SizeType run_len; /**< Run-length, used in RLE */ /** For Heap, and Huffman coding */ SizeType freq; /**< Frequency of the MetaSymbol */ /** For Huffman Tree */ Run * left; /**< Left child node */ Run * right; /**< Right child node */ CodewordType codeword; /**< Huffman codeword */ SizeType codeword_len; /**< Length of member `codeword' */ /** For ArrayList */ Run * next; /** Contructors */ Run(const ByteType & symbol, const SizeType & run_len, const SizeType & freq = 0) : symbol (symbol) , run_len (run_len) , freq (freq) , left (nullptr) , right (nullptr) , codeword (0) , codeword_len (0) , next (nullptr) { } Run(const MetaSymbolType & meta_symbol, const SizeType & freq = 0) : symbol (meta_symbol.first) , run_len (meta_symbol.second) , freq (freq) , left (nullptr) , right (nullptr) , codeword (0) , codeword_len (0) , next (nullptr) { } Run(const Run & run) : symbol (run.symbol) , run_len (run.run_len) , freq (run.freq) , left (run.left) , right (run.right) , codeword (run.codeword) , codeword_len (run.codeword_len) , next (run.next) { } Run(Run * left, Run * right) : symbol (0) , run_len (0) , freq (left->freq + right->freq) , left (left) , right (right) , codeword (0) , codeword_len (0) , next (nullptr) { } /** Operators */ inline Run & operator=(Run run) { this->symbol = run.symbol; this->run_len = run.run_len; this->freq = run.freq; this->left = run.left; this->right = run.right; this->codeword = run.codeword; this->codeword_len = run.codeword_len; this->next = run.next; return *this; } inline bool operator==(const Run & rhs) const { return symbol == rhs.symbol && run_len == rhs.run_len; } inline bool operator!=(const Run & rhs) const { return ! (*this == rhs); } inline Run & operator++(void) { ++freq; return *this; } inline Run operator++(int) { Run temp(*this); operator++(); return temp; } inline Run & operator--(void) { --freq; return *this; } inline Run operator--(int) { Run temp(*this); operator--(); return temp; } inline bool operator<(const Run & rhs) const { return (this->freq < rhs.freq); } inline bool operator>(const Run & rhs) const { return (this->freq > rhs.freq); } inline bool operator<=(const Run & rhs) const { return ! operator>(rhs); } inline bool operator>=(const Run & rhs) const { return ! operator<(rhs); } }; typedef Run RunType; typedef std::vector<RunType> RunArrayType; typedef RunType * HuffmanTreeType; typedef std::array<RunType *, ascii_max + 1> RunListType; private: /** Member data */ RunArrayType runs_; /** Set of runs */ RunListType list_; /** ArrayList of runs, for symbol searching efficiency */ HuffmanTreeType root_; /** Root node of the Huffman tree */ /** Member functions */ template<typename T = CodewordType> void WriteToFile(FileStreamOutType & fout, T src, const bool & rm_trailing_zerobit = false) { /** Do not use defualt buffer_size (which is 32) */ const SizeType buffer_size = 4; unsigned char buffer[buffer_size] = { 0, }; for(int i = buffer_size - 1; i >= 0; --i) { buffer[i] = src % (0x1 << 8); src >>= 8; } SizeType last_pos = buffer_size - 1; if(rm_trailing_zerobit == true) for(; last_pos > 0 && buffer[last_pos] == 0x0; --last_pos); fout.write((char *)&buffer, sizeof(unsigned char) * (last_pos + 1)); } template<typename T = CodewordType> void ReadFromFile(FileStreamInType & fin, T & dest) { const SizeType byte_size = 8; const SizeType char_size = sizeof(unsigned char) * byte_size; const SizeType type_size = sizeof(T) * byte_size; const SizeType buffer_size = (type_size / char_size) + ((type_size % char_size == 0) ? 0 : 1); unsigned char buffer[buffer_size] = { 0, }; fin.read((char *)&buffer, sizeof(unsigned char) * buffer_size); for(int i = 0; i < buffer_size; ++i) { dest <<= byte_size; dest += buffer[i]; } } template<typename T = ByteType> void PrintBinary(FILE * fout, T src, const size_t & buffer_size = buffer_size) { while(src != 0) { ByteType buffer[buffer_size] = { 0, }; for(int bpos = buffer_size - 1; bpos >= 0; --bpos) { buffer[bpos] = ((src % 2 == 0) ? zerobit : nonzerobit); src = src >> 1; } for(int i = 0; i < buffer_size; ++i) { if(i != 0 && i % 4 == 0) fprintf(fout, " "); fprintf(fout, "%d", buffer[i]); } fprintf(fout, " "); } } void CollectRuns(FileStreamInType &); void CreateHuffmanTree(void); void AssignCodeword(RunType *, const CodewordType & = 0, const SizeType & = 0); void CreateRunList(RunType *); SizeType GetCodeword(CodewordType &, const ByteType &, const SizeType &); void WriteHeader(FileStreamInType &, FileStreamOutType &); void WriteEncode(FileStreamInType &, FileStreamOutType &); void WriteDecode(FileStreamInType &, FileStreamOutType &); void PrintHuffmanTree(FILE *, const RunType *, const SizeType &); SizeType ReadHeader(FileStreamInType &); public: void CompressFile(FileStreamInType &, const StringType &, const StringType &); void DecompressFile(FileStreamInType &, const StringType &, const StringType &); void PrintAllRuns(FILE * = stdout); inline void PrintHuffmanTree(FILE * fout = stdout) { PrintHuffmanTree(fout, root_, 0); } }; } /** ns: algorithm */ #endif /** ! ALGORITHM_HUFFMAN_H_ */ <commit_msg>Fix the misspelled word<commit_after>#ifndef ALGORITHM_HUFFMAN_H_ #define ALGORITHM_HUFFMAN_H_ 1 #include <fstream> #include <vector> #include <array> #include <limits> #include <string> #include <cstring> namespace algorithm { /** \brief Modified Huffman coding Huffman coding method with Run Length Encoding. Combines the variable length codes of Huffman coding with the coding of repetitive data in Run Length Encoding. */ class Huffman { public: typedef size_t SizeType; typedef std::ifstream FileStreamInType; typedef std::ofstream FileStreamOutType; typedef std::string StringType; typedef uint8_t ByteType; /** One byte */ typedef uint32_t CodewordType; /** Codeword, consists of 4 bytes */ typedef std::pair<ByteType, SizeType> MetaSymbolType; /** Constants */ static const ByteType zerobit = 0; static const ByteType nonzerobit = 1; static const SizeType ascii_max = std::numeric_limits<ByteType>::max(); static const SizeType byte_size = 8; /**< 8 bits, bit size of ByteType */ static const SizeType buffer_size = byte_size * 4; /**< Bit size of CodewordType */ /** Class for each node in Huffman tree, and used in RLE */ struct Run { /** MetaSymbol, paired with MetaSymbolType */ ByteType symbol; /**< ASCII character */ SizeType run_len; /**< Run-length, used in RLE */ /** For Heap, and Huffman coding */ SizeType freq; /**< Frequency of the MetaSymbol */ /** For Huffman Tree */ Run * left; /**< Left child node */ Run * right; /**< Right child node */ CodewordType codeword; /**< Huffman codeword */ SizeType codeword_len; /**< Length of member `codeword' */ /** For ArrayList */ Run * next; /** Contructors */ Run(const ByteType & symbol, const SizeType & run_len, const SizeType & freq = 0) : symbol (symbol) , run_len (run_len) , freq (freq) , left (nullptr) , right (nullptr) , codeword (0) , codeword_len (0) , next (nullptr) { } Run(const MetaSymbolType & meta_symbol, const SizeType & freq = 0) : symbol (meta_symbol.first) , run_len (meta_symbol.second) , freq (freq) , left (nullptr) , right (nullptr) , codeword (0) , codeword_len (0) , next (nullptr) { } Run(const Run & run) : symbol (run.symbol) , run_len (run.run_len) , freq (run.freq) , left (run.left) , right (run.right) , codeword (run.codeword) , codeword_len (run.codeword_len) , next (run.next) { } Run(Run * left, Run * right) : symbol (0) , run_len (0) , freq (left->freq + right->freq) , left (left) , right (right) , codeword (0) , codeword_len (0) , next (nullptr) { } /** Operators */ inline Run & operator=(Run run) { this->symbol = run.symbol; this->run_len = run.run_len; this->freq = run.freq; this->left = run.left; this->right = run.right; this->codeword = run.codeword; this->codeword_len = run.codeword_len; this->next = run.next; return *this; } inline bool operator==(const Run & rhs) const { return symbol == rhs.symbol && run_len == rhs.run_len; } inline bool operator!=(const Run & rhs) const { return ! (*this == rhs); } inline Run & operator++(void) { ++freq; return *this; } inline Run operator++(int) { Run temp(*this); operator++(); return temp; } inline Run & operator--(void) { --freq; return *this; } inline Run operator--(int) { Run temp(*this); operator--(); return temp; } inline bool operator<(const Run & rhs) const { return (this->freq < rhs.freq); } inline bool operator>(const Run & rhs) const { return (this->freq > rhs.freq); } inline bool operator<=(const Run & rhs) const { return ! operator>(rhs); } inline bool operator>=(const Run & rhs) const { return ! operator<(rhs); } }; typedef Run RunType; typedef std::vector<RunType> RunArrayType; typedef RunType * HuffmanTreeType; typedef std::array<RunType *, ascii_max + 1> RunListType; private: /** Member data */ RunArrayType runs_; /** Set of runs */ RunListType list_; /** ArrayList of runs, for symbol searching efficiency */ HuffmanTreeType root_; /** Root node of the Huffman tree */ /** Member functions */ template<typename T = CodewordType> void WriteToFile(FileStreamOutType & fout, T src, const bool & rm_trailing_zerobit = false) { /** Do not use defualt buffer_size (which is 32) */ const SizeType buffer_size = 4; unsigned char buffer[buffer_size] = { 0, }; for(int i = buffer_size - 1; i >= 0; --i) { buffer[i] = src % (0x1 << 8); src >>= 8; } SizeType last_pos = buffer_size - 1; if(rm_trailing_zerobit == true) for(; last_pos > 0 && buffer[last_pos] == 0x0; --last_pos); fout.write((char *)&buffer, sizeof(unsigned char) * (last_pos + 1)); } template<typename T = CodewordType> void ReadFromFile(FileStreamInType & fin, T & dest) { const SizeType byte_size = 8; const SizeType char_size = sizeof(unsigned char) * byte_size; const SizeType type_size = sizeof(T) * byte_size; const SizeType buffer_size = (type_size / char_size) + ((type_size % char_size == 0) ? 0 : 1); unsigned char buffer[buffer_size] = { 0, }; fin.read((char *)&buffer, sizeof(unsigned char) * buffer_size); for(int i = 0; i < buffer_size; ++i) { dest <<= byte_size; dest += buffer[i]; } } template<typename T = ByteType> void PrintBinary(FILE * fout, T src, const size_t & buffer_size = buffer_size) { while(src != 0) { ByteType buffer[buffer_size] = { 0, }; for(int bpos = buffer_size - 1; bpos >= 0; --bpos) { buffer[bpos] = ((src % 2 == 0) ? zerobit : nonzerobit); src = src >> 1; } for(int i = 0; i < buffer_size; ++i) { if(i != 0 && i % 4 == 0) fprintf(fout, " "); fprintf(fout, "%d", buffer[i]); } fprintf(fout, " "); } } void CollectRuns(FileStreamInType &); void CreateHuffmanTree(void); void AssignCodeword(RunType *, const CodewordType & = 0, const SizeType & = 0); void CreateRunList(RunType *); SizeType GetCodeword(CodewordType &, const ByteType &, const SizeType &); void WriteHeader(FileStreamInType &, FileStreamOutType &); void WriteEncode(FileStreamInType &, FileStreamOutType &); void WriteDecode(FileStreamInType &, FileStreamOutType &); void PrintHuffmanTree(FILE *, const RunType *, const SizeType &); SizeType ReadHeader(FileStreamInType &); public: void CompressFile(FileStreamInType &, const StringType &, const StringType &); void DecompressFile(FileStreamInType &, const StringType &, const StringType &); void PrintAllRuns(FILE * = stdout); inline void PrintHuffmanTree(FILE * fout = stdout) { PrintHuffmanTree(fout, root_, 0); } }; } /** ns: algorithm */ #endif /** ! ALGORITHM_HUFFMAN_H_ */ <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_i18npool.hxx" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sal/main.h> #include <sal/types.h> #include <rtl/strbuf.hxx> #include <rtl/ustring.hxx> using namespace ::rtl; /* Main Procedure */ SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv) { FILE *sfp, *cfp; if (argc < 3) exit(-1); sfp = fopen(argv[1], "rb"); // open the source file for read; if (sfp == NULL) { printf("Open the dictionary source file failed."); return -1; } // create the C source file to write cfp = fopen(argv[2], "wb"); if (cfp == NULL) { fclose(sfp); printf("Can't create the C source file."); return -1; } fprintf(cfp, "/*\n"); fprintf(cfp, " * Copyright(c) 1999 - 2000, Sun Microsystems, Inc.\n"); fprintf(cfp, " * All Rights Reserved.\n"); fprintf(cfp, " */\n\n"); fprintf(cfp, "/* !!!The file is generated automatically. DONOT edit the file manually!!! */\n\n"); fprintf(cfp, "#include <sal/types.h>\n\n"); fprintf(cfp, "extern \"C\" {\n"); sal_Int32 count, i, j; sal_Int32 lenArrayCurr = 0, lenArrayCount = 0, lenArrayLen = 0, *lenArray = NULL, charArray[0x10000]; sal_Bool exist[0x10000]; for (i = 0; i < 0x10000; i++) { exist[i] = sal_False; charArray[i] = 0; } // generate main dict. data array fprintf(cfp, "static const sal_Unicode dataArea[] = {"); sal_Char str[1024]; sal_Unicode current = 0; count = 0; while (fgets(str, 1024, sfp)) { // input file is in UTF-8 encoding // don't convert last new line character to Ostr. OUString Ostr((const sal_Char *)str, strlen(str) - 1, RTL_TEXTENCODING_UTF8); const sal_Unicode *u = Ostr.getStr(); sal_Int32 len = Ostr.getLength(); i=0; Ostr.iterateCodePoints(&i, 1); if (len == i) continue; // skip one character word if (*u != current) { if (*u < current) printf("u %x, current %x, count %d, lenArrayCount %d\n", *u, current, sal::static_int_cast<int>(count), sal::static_int_cast<int>(lenArrayCount)); current = *u; charArray[current] = lenArrayCount; } if (lenArrayLen <= lenArrayCount+1) lenArray = (sal_Int32*) realloc(lenArray, (lenArrayLen += 1000) * sizeof(sal_Int32)); lenArray[lenArrayCount++] = lenArrayCurr; exist[u[0]] = sal_True; for (i = 1; i < len; i++) { // start from second character, exist[u[i]] = sal_True; // since the first character is captured in charArray. lenArrayCurr++; if ((count++) % 0x10 == 0) fprintf(cfp, "\n\t"); fprintf(cfp, "0x%04x, ", u[i]); } } lenArray[lenArrayCount++] = lenArrayCurr; // store last ending pointer charArray[current+1] = lenArrayCount; fprintf(cfp, "\n};\n"); // generate lenArray fprintf(cfp, "static const sal_Int32 lenArray[] = {\n\t"); count = 1; fprintf(cfp, "0x%x, ", 0); // insert one slat for skipping 0 in index2 array. for (i = 0; i < lenArrayCount; i++) { fprintf(cfp, "0x%lx, ", static_cast<long unsigned int>(lenArray[i])); if (count == 0xf) { count = 0; fprintf(cfp, "\n\t"); } else count++; } fprintf(cfp, "\n};\n"); free(lenArray); // generate index1 array fprintf (cfp, "static const sal_Int16 index1[] = {\n\t"); sal_Int16 set[0x100]; count = 0; for (i = 0; i < 0x100; i++) { for (j = 0; j < 0x100; j++) if (charArray[(i*0x100) + j] != 0) break; fprintf(cfp, "0x%02x, ", set[i] = (j < 0x100 ? sal::static_int_cast<sal_Int16>(count++) : 0xff)); if ((i+1) % 0x10 == 0) fprintf (cfp, "\n\t"); } fprintf (cfp, "};\n"); // generate index2 array fprintf (cfp, "static const sal_Int32 index2[] = {\n\t"); sal_Int32 prev = 0; for (i = 0; i < 0x100; i++) { if (set[i] != 0xff) { for (j = 0; j < 0x100; j++) { sal_Int32 k = (i*0x100) + j; if (prev != 0 && charArray[k] == 0) { for (k++; k < 0x10000; k++) if (charArray[k] != 0) break; } prev = charArray[(i*0x100) + j]; fprintf( cfp, "0x%lx, ", sal::static_int_cast< unsigned long >( k < 0x10000 ? charArray[k] + 1 : 0)); if ((j+1) % 0x10 == 0) fprintf (cfp, "\n\t"); } fprintf (cfp, "\n\t"); } } fprintf (cfp, "\n};\n"); // generate existMark array count = 0; fprintf (cfp, "static const sal_uInt8 existMark[] = {\n\t"); for (i = 0; i < 0x1FFF; i++) { sal_uInt8 bit = 0; for (j = 0; j < 8; j++) if (exist[i * 8 + j]) bit |= 1 << j; fprintf(cfp, "0x%02x, ", bit); if (count == 0xf) { count = 0; fprintf(cfp, "\n\t"); } else count++; } fprintf (cfp, "\n};\n"); // create function to return arrays fprintf (cfp, "\tconst sal_uInt8* getExistMark() { return existMark; }\n"); fprintf (cfp, "\tconst sal_Int16* getIndex1() { return index1; }\n"); fprintf (cfp, "\tconst sal_Int32* getIndex2() { return index2; }\n"); fprintf (cfp, "\tconst sal_Int32* getLenArray() { return lenArray; }\n"); fprintf (cfp, "\tconst sal_Unicode* getDataArea() { return dataArea; }\n"); fprintf (cfp, "}\n"); fclose(sfp); fclose(cfp); return 0; } // End of main /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>cpp cleanliness: fixed some memleaks<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_i18npool.hxx" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sal/main.h> #include <sal/types.h> #include <rtl/strbuf.hxx> #include <rtl/ustring.hxx> #include <vector> using std::vector; using namespace ::rtl; /* Main Procedure */ SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv) { FILE *sfp, *cfp; if (argc < 3) exit(-1); sfp = fopen(argv[1], "rb"); // open the source file for read; if (sfp == NULL) { printf("Open the dictionary source file failed."); return -1; } // create the C source file to write cfp = fopen(argv[2], "wb"); if (cfp == NULL) { fclose(sfp); printf("Can't create the C source file."); return -1; } fprintf(cfp, "/*\n"); fprintf(cfp, " * Copyright(c) 1999 - 2000, Sun Microsystems, Inc.\n"); fprintf(cfp, " * All Rights Reserved.\n"); fprintf(cfp, " */\n\n"); fprintf(cfp, "/* !!!The file is generated automatically. DONOT edit the file manually!!! */\n\n"); fprintf(cfp, "#include <sal/types.h>\n\n"); fprintf(cfp, "extern \"C\" {\n"); sal_Int32 count, i, j; sal_Int32 lenArrayCurr = 0, charArray[0x10000]; vector<sal_Int32> lenArray; sal_Bool exist[0x10000]; for (i = 0; i < 0x10000; i++) { exist[i] = sal_False; charArray[i] = 0; } // generate main dict. data array fprintf(cfp, "static const sal_Unicode dataArea[] = {"); sal_Char str[1024]; sal_Unicode current = 0; count = 0; while (fgets(str, 1024, sfp)) { // input file is in UTF-8 encoding // don't convert last new line character to Ostr. OUString Ostr((const sal_Char *)str, strlen(str) - 1, RTL_TEXTENCODING_UTF8); const sal_Unicode *u = Ostr.getStr(); sal_Int32 len = Ostr.getLength(); i=0; Ostr.iterateCodePoints(&i, 1); if (len == i) continue; // skip one character word if (*u != current) { if (*u < current) printf("u %x, current %x, count %d, lenArray.size() %d\n", *u, current, sal::static_int_cast<int>(count), sal::static_int_cast<int>(lenArray.size())); current = *u; charArray[current] = lenArray.size(); } lenArray.push_back(lenArrayCurr); exist[u[0]] = sal_True; for (i = 1; i < len; i++) { // start from second character, exist[u[i]] = sal_True; // since the first character is captured in charArray. lenArrayCurr++; if ((count++) % 0x10 == 0) fprintf(cfp, "\n\t"); fprintf(cfp, "0x%04x, ", u[i]); } } lenArray.push_back( lenArrayCurr ); // store last ending pointer charArray[current+1] = lenArray.size(); fprintf(cfp, "\n};\n"); // generate lenArray fprintf(cfp, "static const sal_Int32 lenArray[] = {\n\t"); count = 1; fprintf(cfp, "0x%x, ", 0); // insert one slat for skipping 0 in index2 array. for (i = 0; i < lenArray.size(); i++) { fprintf(cfp, "0x%lx, ", static_cast<long unsigned int>(lenArray[i])); if (count == 0xf) { count = 0; fprintf(cfp, "\n\t"); } else count++; } fprintf(cfp, "\n};\n"); // generate index1 array fprintf (cfp, "static const sal_Int16 index1[] = {\n\t"); sal_Int16 set[0x100]; count = 0; for (i = 0; i < 0x100; i++) { for (j = 0; j < 0x100; j++) if (charArray[(i*0x100) + j] != 0) break; fprintf(cfp, "0x%02x, ", set[i] = (j < 0x100 ? sal::static_int_cast<sal_Int16>(count++) : 0xff)); if ((i+1) % 0x10 == 0) fprintf (cfp, "\n\t"); } fprintf (cfp, "};\n"); // generate index2 array fprintf (cfp, "static const sal_Int32 index2[] = {\n\t"); sal_Int32 prev = 0; for (i = 0; i < 0x100; i++) { if (set[i] != 0xff) { for (j = 0; j < 0x100; j++) { sal_Int32 k = (i*0x100) + j; if (prev != 0 && charArray[k] == 0) { for (k++; k < 0x10000; k++) if (charArray[k] != 0) break; } prev = charArray[(i*0x100) + j]; fprintf( cfp, "0x%lx, ", sal::static_int_cast< unsigned long >( k < 0x10000 ? charArray[k] + 1 : 0)); if ((j+1) % 0x10 == 0) fprintf (cfp, "\n\t"); } fprintf (cfp, "\n\t"); } } fprintf (cfp, "\n};\n"); // generate existMark array count = 0; fprintf (cfp, "static const sal_uInt8 existMark[] = {\n\t"); for (i = 0; i < 0x1FFF; i++) { sal_uInt8 bit = 0; for (j = 0; j < 8; j++) if (exist[i * 8 + j]) bit |= 1 << j; fprintf(cfp, "0x%02x, ", bit); if (count == 0xf) { count = 0; fprintf(cfp, "\n\t"); } else count++; } fprintf (cfp, "\n};\n"); // create function to return arrays fprintf (cfp, "\tconst sal_uInt8* getExistMark() { return existMark; }\n"); fprintf (cfp, "\tconst sal_Int16* getIndex1() { return index1; }\n"); fprintf (cfp, "\tconst sal_Int32* getIndex2() { return index2; }\n"); fprintf (cfp, "\tconst sal_Int32* getLenArray() { return lenArray; }\n"); fprintf (cfp, "\tconst sal_Unicode* getDataArea() { return dataArea; }\n"); fprintf (cfp, "}\n"); fclose(sfp); fclose(cfp); return 0; } // End of main /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: LocaleNode.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2005-03-15 13:42:47 $ * * 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 _LOCALE_NODE_ #define _LOCALE_NODE_ #include <com/sun/star/xml/sax/XParser.hpp> #include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp> #include <vector> #include <com/sun/star/registry/XImplementationRegistration.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/xml/sax/SAXParseException.hpp> #include <com/sun/star/xml/sax/XParser.hpp> #include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp> #include <com/sun/star/io/XOutputStream.hpp> #include <com/sun/star/io/XActiveDataSource.hpp> #include <cppuhelper/servicefactory.hxx> #include <cppuhelper/implbase1.hxx> #include <cppuhelper/implbase3.hxx> using namespace ::rtl; using namespace ::std; using namespace ::com::sun::star::xml::sax; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::registry; using namespace ::com::sun::star::xml::sax; using namespace ::com::sun::star::io; class OFileWriter { public: OFileWriter(const char *pcFile, const char *locale ); virtual ~OFileWriter(); virtual void writeStringCharacters(const ::rtl::OUString& str) const; virtual void writeAsciiString(const char *str)const ; virtual void writeInt(sal_Int16 nb) const; virtual void writeFunction(const char *func, const char *count, const char *array) const; virtual void writeRefFunction(const char *func, const ::rtl::OUString& useLocale) const; virtual void writeFunction(const char *func, const char *count, const char *array, const char *from, const char *to) const; virtual void writeRefFunction(const char *func, const ::rtl::OUString& useLocale, const char *to) const; virtual void writeFunction2(const char *func, const char *style, const char* attr, const char *array) const; virtual void writeRefFunction2(const char *func, const ::rtl::OUString& useLocale) const; virtual void writeFunction3(const char *func, const char *style, const char* levels, const char* attr, const char *array) const; virtual void writeRefFunction3(const char *func, const ::rtl::OUString& useLocale) const; virtual void writeIntParameter(const sal_Char* pAsciiStr, const sal_Int16 count, sal_Int16 val) const; virtual void writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str, sal_Int16 count) const; virtual void writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str) const; virtual void writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const; virtual void writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count) const; virtual void writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const; virtual void writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, const sal_Int16 count) const; virtual void writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const; virtual void writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const; virtual void flush(void) const ; virtual void closeOutput(void) const; private: char m_pcFile[1024]; char theLocale[50]; FILE *m_f; }; class Attr { Sequence <OUString> name; Sequence <OUString> value; public: Attr (const Reference< XAttributeList > & attr); const OUString& getValueByName (const sal_Char *str) const; sal_Int32 getLength() const; const OUString& getTypeByIndex (sal_Int32 idx) const; const OUString& getValueByIndex (sal_Int32 idx) const ; }; class LocaleNode { OUString aName; OUString aValue; Attr * xAttribs; LocaleNode * parent; LocaleNode* * children; sal_Int32 nChildren; sal_Int32 childArrSize; void setParent ( LocaleNode* node); protected: mutable int nError; public: LocaleNode (const OUString& name, const Reference< XAttributeList > & attr); inline void setValue(const OUString &oValue) { aValue += oValue; }; inline const OUString& getName() const { return aName; }; inline const OUString& getValue() const { return aValue; }; inline const Attr* getAttr() const { return xAttribs; }; inline const sal_Int32 getNumberOfChildren () const { return nChildren; }; inline LocaleNode * getChildAt (sal_Int32 idx) const { return children[idx] ; }; const LocaleNode * findNode ( const sal_Char *name) const; void print () const; void printR () const; virtual ~LocaleNode(); void addChild ( LocaleNode * node); int getError() const; virtual void generateCode (const OFileWriter &of) const; static LocaleNode* createNode (const OUString& name,const Reference< XAttributeList > & attr); }; class LCInfoNode : public LocaleNode { public: inline LCInfoNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCCTYPENode : public LocaleNode { public: inline LCCTYPENode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCFormatNode : public LocaleNode { public: inline LCFormatNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCCollationNode : public LocaleNode { public: inline LCCollationNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCIndexNode : public LocaleNode { public: inline LCIndexNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCSearchNode : public LocaleNode { public: inline LCSearchNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCCalendarNode : public LocaleNode { public: inline LCCalendarNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCCurrencyNode : public LocaleNode { public: inline LCCurrencyNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCTransliterationNode : public LocaleNode { public: inline LCTransliterationNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCMiscNode : public LocaleNode { public: inline LCMiscNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCNumberingLevelNode : public LocaleNode { public: inline LCNumberingLevelNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCOutlineNumberingLevelNode : public LocaleNode { public: inline LCOutlineNumberingLevelNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; #endif <commit_msg>INTEGRATION: CWS localedata4 (1.8.4); FILE MERGED 2005/04/25 16:19:06 er 1.8.4.1: #i45077# very basic build time checks for locale data<commit_after>/************************************************************************* * * $RCSfile: LocaleNode.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2005-06-09 14:34:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _LOCALE_NODE_ #define _LOCALE_NODE_ #include <com/sun/star/xml/sax/XParser.hpp> #include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp> #include <vector> #include <com/sun/star/registry/XImplementationRegistration.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/xml/sax/SAXParseException.hpp> #include <com/sun/star/xml/sax/XParser.hpp> #include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp> #include <com/sun/star/io/XOutputStream.hpp> #include <com/sun/star/io/XActiveDataSource.hpp> #include <cppuhelper/servicefactory.hxx> #include <cppuhelper/implbase1.hxx> #include <cppuhelper/implbase3.hxx> using namespace ::rtl; using namespace ::std; using namespace ::com::sun::star::xml::sax; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::registry; using namespace ::com::sun::star::xml::sax; using namespace ::com::sun::star::io; class OFileWriter { public: OFileWriter(const char *pcFile, const char *locale ); virtual ~OFileWriter(); virtual void writeStringCharacters(const ::rtl::OUString& str) const; virtual void writeAsciiString(const char *str)const ; virtual void writeInt(sal_Int16 nb) const; virtual void writeFunction(const char *func, const char *count, const char *array) const; virtual void writeRefFunction(const char *func, const ::rtl::OUString& useLocale) const; virtual void writeFunction(const char *func, const char *count, const char *array, const char *from, const char *to) const; virtual void writeRefFunction(const char *func, const ::rtl::OUString& useLocale, const char *to) const; virtual void writeFunction2(const char *func, const char *style, const char* attr, const char *array) const; virtual void writeRefFunction2(const char *func, const ::rtl::OUString& useLocale) const; virtual void writeFunction3(const char *func, const char *style, const char* levels, const char* attr, const char *array) const; virtual void writeRefFunction3(const char *func, const ::rtl::OUString& useLocale) const; virtual void writeIntParameter(const sal_Char* pAsciiStr, const sal_Int16 count, sal_Int16 val) const; virtual void writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str, sal_Int16 count) const; virtual void writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str) const; virtual void writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const; virtual void writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count) const; virtual void writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const; virtual void writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, const sal_Int16 count) const; virtual void writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const; virtual void writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const; virtual void flush(void) const ; virtual void closeOutput(void) const; private: char m_pcFile[1024]; char theLocale[50]; FILE *m_f; }; class Attr { Sequence <OUString> name; Sequence <OUString> value; public: Attr (const Reference< XAttributeList > & attr); const OUString& getValueByName (const sal_Char *str) const; sal_Int32 getLength() const; const OUString& getTypeByIndex (sal_Int32 idx) const; const OUString& getValueByIndex (sal_Int32 idx) const ; }; class LocaleNode { OUString aName; OUString aValue; Attr * xAttribs; LocaleNode * parent; LocaleNode* * children; sal_Int32 nChildren; sal_Int32 childArrSize; void setParent ( LocaleNode* node); protected: mutable int nError; public: LocaleNode (const OUString& name, const Reference< XAttributeList > & attr); inline void setValue(const OUString &oValue) { aValue += oValue; }; inline const OUString& getName() const { return aName; }; inline const OUString& getValue() const { return aValue; }; inline const Attr* getAttr() const { return xAttribs; }; inline const sal_Int32 getNumberOfChildren () const { return nChildren; }; inline LocaleNode * getChildAt (sal_Int32 idx) const { return children[idx] ; }; const LocaleNode * findNode ( const sal_Char *name) const; void print () const; void printR () const; virtual ~LocaleNode(); void addChild ( LocaleNode * node); const LocaleNode* getParent() const { return parent; }; const LocaleNode* getRoot() const; int getError() const; virtual void generateCode (const OFileWriter &of) const; // MUST >= nMinLen // nMinLen <= 0 : no error // nMinLen > 0 : error if less than nMinLen characters // SHOULD NOT > nMaxLen // nMaxLen < 0 : any length // nMaxLen >= 0 : warning if more than nMaxLen characters OUString writeParameterCheckLen( const OFileWriter &of, const char* pNodeName, const char* pParameterName, sal_Int32 nMinLen, sal_Int32 nMaxLen ) const; // ++nError with output to stderr void incError( const char* pStr ) const; static LocaleNode* createNode (const OUString& name,const Reference< XAttributeList > & attr); }; class LCInfoNode : public LocaleNode { public: inline LCInfoNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCCTYPENode : public LocaleNode { public: inline LCCTYPENode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCFormatNode : public LocaleNode { public: inline LCFormatNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCCollationNode : public LocaleNode { public: inline LCCollationNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCIndexNode : public LocaleNode { public: inline LCIndexNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCSearchNode : public LocaleNode { public: inline LCSearchNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCCalendarNode : public LocaleNode { public: inline LCCalendarNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCCurrencyNode : public LocaleNode { public: inline LCCurrencyNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCTransliterationNode : public LocaleNode { public: inline LCTransliterationNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCMiscNode : public LocaleNode { public: inline LCMiscNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCNumberingLevelNode : public LocaleNode { public: inline LCNumberingLevelNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; class LCOutlineNumberingLevelNode : public LocaleNode { public: inline LCOutlineNumberingLevelNode (const OUString& name, const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; }; virtual void generateCode (const OFileWriter &of) const; }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: astoperation.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-02-04 13:23: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 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 _IDLC_ASTOPERATION_HXX_ #include <idlc/astoperation.hxx> #endif #ifndef _IDLC_ASTTYPE_HXX_ #include <idlc/asttype.hxx> #endif #ifndef _IDLC_ASTBASETYPE_HXX_ #include <idlc/astbasetype.hxx> #endif #ifndef _IDLC_ASTPARAMETER_HXX_ #include <idlc/astparameter.hxx> #endif #ifndef _IDLC_ERRORHANDLER_HXX_ #include <idlc/errorhandler.hxx> #endif using namespace ::rtl; void AstOperation::addExceptions(StringList* pExceptions) { if ( isOneway() ) { idlc()->error()->error1(EIDL_ONEWAY_RAISE_CONFLICT, this); } StringList::iterator iter = pExceptions->begin(); StringList::iterator end = pExceptions->end(); AstDeclaration* pDecl = NULL; while ( iter != end) { pDecl = lookupByName(*iter); if ( !pDecl ) { idlc()->error()->lookupError(*iter); return; } if ( (pDecl->getNodeType() == NT_exception) ) { m_exceptions.push_back(pDecl); } else { idlc()->error()->error1(EIDL_ILLEGAL_RAISES, this); } ++iter; } } sal_Bool AstOperation::isVoid() { if ( m_pReturnType && (m_pReturnType->getNodeType() == NT_predefined) ) { if ( ((AstBaseType*)m_pReturnType)->getExprType() == ET_void ) return sal_True; } return sal_False; } sal_Bool AstOperation::dumpBlob(RegistryTypeWriter& rBlob, sal_uInt16 index) { sal_uInt16 nParam = getNodeCount(NT_parameter); sal_uInt16 nExcep = nExceptions(); RTMethodMode methodMode = RT_MODE_TWOWAY; if ( isOneway() ) methodMode = RT_MODE_ONEWAY; rBlob.setMethodData(index, OStringToOUString(getLocalName(), RTL_TEXTENCODING_UTF8), OStringToOUString(getReturnType()->getRelativName(), RTL_TEXTENCODING_UTF8), methodMode, nParam, nExcep, getDocumentation()); if ( nParam ) { DeclList::iterator iter = getIteratorBegin(); DeclList::iterator end = getIteratorEnd(); AstDeclaration* pDecl = NULL; AstParameter* pParam = NULL; RTParamMode paramMode; sal_uInt16 paramIndex = 0; while ( iter != end ) { pDecl = *iter; if ( pDecl->getNodeType() == NT_parameter ) { AstParameter* pParam = (AstParameter*)pDecl; switch (pParam->getDirection()) { case DIR_IN : paramMode = RT_PARAM_IN; break; case DIR_OUT : paramMode = RT_PARAM_OUT; break; case DIR_INOUT : paramMode = RT_PARAM_INOUT; break; default: paramMode = RT_PARAM_INVALID; break; } rBlob.setParamData(index, paramIndex++, OStringToOUString(pParam->getType()->getRelativName(), RTL_TEXTENCODING_UTF8), OStringToOUString(pDecl->getLocalName(), RTL_TEXTENCODING_UTF8), paramMode); } ++iter; } } if ( nExcep ) { DeclList::iterator iter = m_exceptions.begin(); DeclList::iterator end = m_exceptions.end(); sal_uInt16 exceptIndex = 0; while ( iter != end ) { rBlob.setExcData(index, exceptIndex++, OStringToOUString((*iter)->getRelativName(), RTL_TEXTENCODING_UTF8) ); ++iter; } } return sal_True; } AstDeclaration* AstOperation::addDeclaration(AstDeclaration* pDecl) { if ( pDecl->getNodeType() == NT_parameter ) { AstParameter* pParam = (AstParameter*)pDecl; if ( isOneway() && (pParam->getDirection() == DIR_OUT || pParam->getDirection() == DIR_INOUT) ) { idlc()->error()->error2(EIDL_ONEWAY_CONFLICT, pDecl, this); return NULL; } } return AstScope::addDeclaration(pDecl); } <commit_msg>INTEGRATION: CWS sb14 (1.3.4); FILE MERGED 2004/03/15 09:53:56 sb 1.3.4.4: #i21150# Adapted to new extensible type writer interface; added support for bound interface attributes. 2004/03/12 14:30:29 sb 1.3.4.3: #i21150# Added support for extended attributes (still need to fix TODO in AstAttribute::dumpBlob. 2004/03/05 08:35:19 sb 1.3.4.2: #i21150# Support for rest parameters; clean up. 2004/03/01 12:59:23 sb 1.3.4.1: #i21150# Added optional interface inheritance; added -stdin switch; do not warn about bad member names of com.sun.star.uno.Uik; some general clean up and added const qualifiers.<commit_after>/************************************************************************* * * $RCSfile: astoperation.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2004-03-30 16:45:40 $ * * 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 _IDLC_ASTOPERATION_HXX_ #include <idlc/astoperation.hxx> #endif #ifndef _IDLC_ASTTYPE_HXX_ #include <idlc/asttype.hxx> #endif #ifndef _IDLC_ASTBASETYPE_HXX_ #include <idlc/astbasetype.hxx> #endif #ifndef _IDLC_ASTPARAMETER_HXX_ #include <idlc/astparameter.hxx> #endif #ifndef _IDLC_ERRORHANDLER_HXX_ #include <idlc/errorhandler.hxx> #endif #include "registry/writer.hxx" using namespace ::rtl; void AstOperation::setExceptions(DeclList const * pExceptions) { if (pExceptions != 0) { if (isOneway()) { idlc()->error()->error1(EIDL_ONEWAY_RAISE_CONFLICT, this); } m_exceptions = *pExceptions; } } sal_Bool AstOperation::isVoid() { if ( m_pReturnType && (m_pReturnType->getNodeType() == NT_predefined) ) { if ( ((AstBaseType*)m_pReturnType)->getExprType() == ET_void ) return sal_True; } return sal_False; } bool AstOperation::isVariadic() const { DeclList::const_iterator i(getIteratorEnd()); return i != getIteratorBegin() && static_cast< AstParameter const * >(*(--i))->isRest(); } sal_Bool AstOperation::dumpBlob(typereg::Writer & rBlob, sal_uInt16 index) { sal_uInt16 nParam = getNodeCount(NT_parameter); sal_uInt16 nExcep = nExceptions(); RTMethodMode methodMode = RT_MODE_TWOWAY; if ( isOneway() ) methodMode = RT_MODE_ONEWAY; rtl::OUString returnTypeName; if (m_pReturnType == 0) { returnTypeName = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("void")); } else { returnTypeName = rtl::OStringToOUString( m_pReturnType->getRelativName(), RTL_TEXTENCODING_UTF8); } rBlob.setMethodData( index, getDocumentation(), methodMode, OStringToOUString(getLocalName(), RTL_TEXTENCODING_UTF8), returnTypeName, nParam, nExcep); if ( nParam ) { DeclList::const_iterator iter = getIteratorBegin(); DeclList::const_iterator end = getIteratorEnd(); AstDeclaration* pDecl = NULL; AstParameter* pParam = NULL; RTParamMode paramMode; sal_uInt16 paramIndex = 0; while ( iter != end ) { pDecl = *iter; if ( pDecl->getNodeType() == NT_parameter ) { AstParameter* pParam = (AstParameter*)pDecl; switch (pParam->getDirection()) { case DIR_IN : paramMode = RT_PARAM_IN; break; case DIR_OUT : paramMode = RT_PARAM_OUT; break; case DIR_INOUT : paramMode = RT_PARAM_INOUT; break; default: paramMode = RT_PARAM_INVALID; break; } if (pParam->isRest()) { paramMode = static_cast< RTParamMode >( paramMode | RT_PARAM_REST); } rBlob.setMethodParameterData( index, paramIndex++, paramMode, OStringToOUString( pDecl->getLocalName(), RTL_TEXTENCODING_UTF8), OStringToOUString( pParam->getType()->getRelativName(), RTL_TEXTENCODING_UTF8)); } ++iter; } } if ( nExcep ) { DeclList::iterator iter = m_exceptions.begin(); DeclList::iterator end = m_exceptions.end(); sal_uInt16 exceptIndex = 0; while ( iter != end ) { rBlob.setMethodExceptionTypeName( index, exceptIndex++, OStringToOUString( (*iter)->getRelativName(), RTL_TEXTENCODING_UTF8)); ++iter; } } return sal_True; } AstDeclaration* AstOperation::addDeclaration(AstDeclaration* pDecl) { if ( pDecl->getNodeType() == NT_parameter ) { AstParameter* pParam = (AstParameter*)pDecl; if ( isOneway() && (pParam->getDirection() == DIR_OUT || pParam->getDirection() == DIR_INOUT) ) { idlc()->error()->error2(EIDL_ONEWAY_CONFLICT, pDecl, this); return NULL; } } return AstScope::addDeclaration(pDecl); } <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <visionaray/gl/util.h> #include <visionaray/math/math.h> #include "../util.h" namespace gl = visionaray::gl; namespace visionaray { std::string gl::last_error() { GLenum err = glGetError(); if (err != GL_NO_ERROR) { return std::string(reinterpret_cast<char const*>(glewGetErrorString(err))); } return ""; } void gl::alloc_texture(pixel_format_info info, GLsizei w, GLsizei h) { if (glTexStorage2D) { glTexStorage2D(GL_TEXTURE_2D, 1, info.internal_format, w, h); } else { glTexImage2D(GL_TEXTURE_2D, 0, info.internal_format, w, h, 0, info.format, info.type, 0); } } void gl::update_texture( pixel_format_info info, GLsizei x, GLsizei y, GLsizei w, GLsizei h, GLvoid const* pixels ) { glTexSubImage2D( GL_TEXTURE_2D, 0, // TODO x, y, w, h, info.format, info.type, pixels ); } void gl::update_texture( pixel_format_info info, GLsizei w, GLsizei h, GLvoid const* pixels ) { glTexSubImage2D( GL_TEXTURE_2D, 0, // TODO 0, 0, w, h, info.format, info.type, pixels ); } void gl::draw_full_screen_quad() { glPushAttrib(GL_TEXTURE_BIT | GL_TRANSFORM_BIT); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glActiveTexture(GL_TEXTURE0); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f); glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f, 1.0f); glEnd(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glPopAttrib(); } void gl::blend_texture(GLuint texture, GLenum sfactor, GLenum dfactor) { glPushAttrib(GL_ALL_ATTRIB_BITS); glActiveTexture(GL_TEXTURE0); glEnable(GL_BLEND); glBlendFunc(sfactor, dfactor); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture); glDepthMask(GL_FALSE); glDisable(GL_LIGHTING); draw_full_screen_quad(); glPopAttrib(); } #if defined(VSNRAY_OPENGL_LEGACY) void gl::blend_pixels(GLsizei w, GLsizei h, GLenum format, GLenum type, GLvoid const* pixels, GLenum sfactor, GLenum dfactor) { glPushAttrib(GL_ALL_ATTRIB_BITS); recti vp = gl::viewport(); glWindowPos2i(vp[0], vp[1]); GLfloat scalex = vp[2] / static_cast<GLfloat>(w); GLfloat scaley = vp[3] / static_cast<GLfloat>(h); glPixelZoom(scalex, scaley); glEnable(GL_BLEND); glBlendFunc(sfactor, dfactor); glDrawPixels(w, h, format, type, pixels); glPopAttrib(); } #endif recti gl::viewport() { GLint vp[4]; glGetIntegerv(GL_VIEWPORT, &vp[0]); return recti(vp[0], vp[1], vp[2], vp[3]); } } // visionaray <commit_msg>Don't use GLEW with OpenGLES<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <visionaray/gl/util.h> #include <visionaray/math/math.h> #include "../util.h" namespace gl = visionaray::gl; namespace visionaray { std::string gl::last_error() { GLenum err = glGetError(); if (err != GL_NO_ERROR) { #if VSNRAY_HAVE_GLEW return std::string(reinterpret_cast<char const*>(glewGetErrorString(err))); #endif } return ""; } void gl::alloc_texture(pixel_format_info info, GLsizei w, GLsizei h) { if (glTexStorage2D) { glTexStorage2D(GL_TEXTURE_2D, 1, info.internal_format, w, h); } else { glTexImage2D(GL_TEXTURE_2D, 0, info.internal_format, w, h, 0, info.format, info.type, 0); } } void gl::update_texture( pixel_format_info info, GLsizei x, GLsizei y, GLsizei w, GLsizei h, GLvoid const* pixels ) { glTexSubImage2D( GL_TEXTURE_2D, 0, // TODO x, y, w, h, info.format, info.type, pixels ); } void gl::update_texture( pixel_format_info info, GLsizei w, GLsizei h, GLvoid const* pixels ) { glTexSubImage2D( GL_TEXTURE_2D, 0, // TODO 0, 0, w, h, info.format, info.type, pixels ); } void gl::draw_full_screen_quad() { glPushAttrib(GL_TEXTURE_BIT | GL_TRANSFORM_BIT); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glActiveTexture(GL_TEXTURE0); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f); glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f, 1.0f); glEnd(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glPopAttrib(); } void gl::blend_texture(GLuint texture, GLenum sfactor, GLenum dfactor) { glPushAttrib(GL_ALL_ATTRIB_BITS); glActiveTexture(GL_TEXTURE0); glEnable(GL_BLEND); glBlendFunc(sfactor, dfactor); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture); glDepthMask(GL_FALSE); glDisable(GL_LIGHTING); draw_full_screen_quad(); glPopAttrib(); } #if defined(VSNRAY_OPENGL_LEGACY) void gl::blend_pixels(GLsizei w, GLsizei h, GLenum format, GLenum type, GLvoid const* pixels, GLenum sfactor, GLenum dfactor) { glPushAttrib(GL_ALL_ATTRIB_BITS); recti vp = gl::viewport(); glWindowPos2i(vp[0], vp[1]); GLfloat scalex = vp[2] / static_cast<GLfloat>(w); GLfloat scaley = vp[3] / static_cast<GLfloat>(h); glPixelZoom(scalex, scaley); glEnable(GL_BLEND); glBlendFunc(sfactor, dfactor); glDrawPixels(w, h, format, type, pixels); glPopAttrib(); } #endif recti gl::viewport() { GLint vp[4]; glGetIntegerv(GL_VIEWPORT, &vp[0]); return recti(vp[0], vp[1], vp[2], vp[3]); } } // visionaray <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/chaincoin-config.h> #endif #include <chainparams.h> #include <clientversion.h> #include <compat.h> #include <fs.h> #include <rpc/server.h> #include <init.h> #include <noui.h> #include <util.h> #include <masternodeconfig.h> #include <httpserver.h> #include <httprpc.h> #include <utilstrencodings.h> #include <walletinitinterface.h> #include <boost/thread.hpp> #include <stdio.h> /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * * This is the developer documentation of the reference client for an experimental new digital currency called Chaincoin (https://www.chaincoin.org/), * which enables instant payments to anyone, anywhere in the world. Chaincoin uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ void WaitForShutdown() { bool fShutdown = ShutdownRequested(); // Tell the main threads to shutdown. while (!fShutdown) { MilliSleep(200); fShutdown = ShutdownRequested(); } Interrupt(); } ////////////////////////////////////////////////////////////////////////////// // // Start // bool AppInit(int argc, char* argv[]) { bool fRet = false; // // Parameters // // If Qt is used, parameters/chaincoin.conf are parsed in qt/chaincoin.cpp's main() gArgs.ParseParameters(argc, argv); // Process help and version before taking care about datadir if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) { std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n"; if (gArgs.IsArgSet("-version")) { strUsage += FormatParagraph(LicenseInfo()); } else { strUsage += "\n" + _("Usage:") + "\n" + " chaincoind [options] " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n"; strUsage += "\n" + HelpMessage(HelpMessageMode::BITCOIND); } fprintf(stdout, "%s", strUsage.c_str()); return true; } try { if (!fs::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); return false; } try { gArgs.ReadConfigFile(gArgs.GetArg("-conf", CHAINCOIN_CONF_FILENAME)); } catch (const std::exception& e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(gArgs.GetChainName()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return false; } // parse masternode.conf std::string strErr; if(!masternodeConfig.read(strErr)) { fprintf(stderr,"Error reading masternode configuration file: %s\n", strErr.c_str()); return false; } // Error out when loose non-argument tokens are encountered on command line for (int i = 1; i < argc; i++) { if (!IsSwitchChar(argv[i][0])) { fprintf(stderr, "Error: Command line contains unexpected token '%s', see bitcoind -h for a list of options.\n", argv[i]); return false; } } // -server defaults to true for chaincoind but not for the GUI so do this here gArgs.SoftSetBoolArg("-server", true); // Set this early so that parameter interactions go to console InitLogging(); InitParameterInteraction(); if (!AppInitBasicSetup()) { // InitError will have been called with detailed error, which ends up on console return false; } if (!AppInitParameterInteraction()) { // InitError will have been called with detailed error, which ends up on console return false; } if (!AppInitSanityChecks()) { // InitError will have been called with detailed error, which ends up on console return false; } if (gArgs.GetBoolArg("-daemon", false)) { #if HAVE_DECL_DAEMON fprintf(stdout, "Chaincoin server starting\n"); // Daemonize if (daemon(1, 0)) { // don't chdir (1), do close FDs (0) fprintf(stderr, "Error: daemon() failed: %s\n", strerror(errno)); return false; } #else fprintf(stderr, "Error: -daemon is not supported on this operating system\n"); return false; #endif // HAVE_DECL_DAEMON } // Lock data directory after daemonization if (!AppInitLockDataDirectory()) { // If locking the data directory failed, exit immediately return false; } fRet = AppInitMain(); } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(nullptr, "AppInit()"); } if (!fRet) { Interrupt(); } else { WaitForShutdown(); } Shutdown(); return fRet; } int main(int argc, char* argv[]) { SetupEnvironment(); // Connect chaincoind signal handlers noui_connect(); return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE); } <commit_msg>Ignore macOS daemon() depracation warning<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/chaincoin-config.h> #endif #include <chainparams.h> #include <clientversion.h> #include <compat.h> #include <fs.h> #include <rpc/server.h> #include <init.h> #include <noui.h> #include <util.h> #include <masternodeconfig.h> #include <httpserver.h> #include <httprpc.h> #include <utilstrencodings.h> #include <walletinitinterface.h> #include <boost/thread.hpp> #include <stdio.h> /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * * This is the developer documentation of the reference client for an experimental new digital currency called Chaincoin (https://www.chaincoin.org/), * which enables instant payments to anyone, anywhere in the world. Chaincoin uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ void WaitForShutdown() { bool fShutdown = ShutdownRequested(); // Tell the main threads to shutdown. while (!fShutdown) { MilliSleep(200); fShutdown = ShutdownRequested(); } Interrupt(); } ////////////////////////////////////////////////////////////////////////////// // // Start // bool AppInit(int argc, char* argv[]) { bool fRet = false; // // Parameters // // If Qt is used, parameters/chaincoin.conf are parsed in qt/chaincoin.cpp's main() gArgs.ParseParameters(argc, argv); // Process help and version before taking care about datadir if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) { std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n"; if (gArgs.IsArgSet("-version")) { strUsage += FormatParagraph(LicenseInfo()); } else { strUsage += "\n" + _("Usage:") + "\n" + " chaincoind [options] " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n"; strUsage += "\n" + HelpMessage(HelpMessageMode::BITCOIND); } fprintf(stdout, "%s", strUsage.c_str()); return true; } try { if (!fs::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); return false; } try { gArgs.ReadConfigFile(gArgs.GetArg("-conf", CHAINCOIN_CONF_FILENAME)); } catch (const std::exception& e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(gArgs.GetChainName()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return false; } // parse masternode.conf std::string strErr; if(!masternodeConfig.read(strErr)) { fprintf(stderr,"Error reading masternode configuration file: %s\n", strErr.c_str()); return false; } // Error out when loose non-argument tokens are encountered on command line for (int i = 1; i < argc; i++) { if (!IsSwitchChar(argv[i][0])) { fprintf(stderr, "Error: Command line contains unexpected token '%s', see bitcoind -h for a list of options.\n", argv[i]); return false; } } // -server defaults to true for chaincoind but not for the GUI so do this here gArgs.SoftSetBoolArg("-server", true); // Set this early so that parameter interactions go to console InitLogging(); InitParameterInteraction(); if (!AppInitBasicSetup()) { // InitError will have been called with detailed error, which ends up on console return false; } if (!AppInitParameterInteraction()) { // InitError will have been called with detailed error, which ends up on console return false; } if (!AppInitSanityChecks()) { // InitError will have been called with detailed error, which ends up on console return false; } if (gArgs.GetBoolArg("-daemon", false)) { #if HAVE_DECL_DAEMON #if defined(MAC_OSX) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif fprintf(stdout, "Chaincoin server starting\n"); // Daemonize if (daemon(1, 0)) { // don't chdir (1), do close FDs (0) fprintf(stderr, "Error: daemon() failed: %s\n", strerror(errno)); return false; } #if defined(MAC_OSX) #pragma GCC diagnostic pop #endif #else fprintf(stderr, "Error: -daemon is not supported on this operating system\n"); return false; #endif // HAVE_DECL_DAEMON } // Lock data directory after daemonization if (!AppInitLockDataDirectory()) { // If locking the data directory failed, exit immediately return false; } fRet = AppInitMain(); } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(nullptr, "AppInit()"); } if (!fRet) { Interrupt(); } else { WaitForShutdown(); } Shutdown(); return fRet; } int main(int argc, char* argv[]) { SetupEnvironment(); // Connect chaincoind signal handlers noui_connect(); return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE); } <|endoftext|>
<commit_before>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkImage.h" #include "SkRandom.h" #include "SkSurface.h" static sk_sp<SkImage> make_image() { const SkImageInfo info = SkImageInfo::MakeN32Premul(319, 52); auto surface(SkSurface::MakeRaster(info)); SkCanvas* canvas = surface->getCanvas(); canvas->drawColor(sk_tool_utils::color_to_565(0xFFF8F8F8)); SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); for (int i = 0; i < 20; ++i) { canvas->drawCircle(-4, 25, 20, paint); canvas->translate(25, 0); } return surface->makeImageSnapshot(); } DEF_SIMPLE_GM(mipmap, canvas, 400, 200) { sk_sp<SkImage> img(make_image());//SkImage::NewFromEncoded(data)); SkPaint paint; const SkRect dst = SkRect::MakeWH(177, 15); paint.setTextSize(30); SkString str; str.printf("scale %g %g", dst.width() / img->width(), dst.height() / img->height()); // canvas->drawText(str.c_str(), str.size(), 300, 100, paint); canvas->translate(20, 20); for (int i = 0; i < 4; ++i) { paint.setFilterQuality(SkFilterQuality(i)); canvas->drawImageRect(img.get(), dst, &paint); canvas->translate(0, 20); } canvas->drawImage(img.get(), 20, 20, nullptr); } /////////////////////////////////////////////////////////////////////////////////////////////////// // create a circle image computed raw, so we can wrap it as a linear or srgb image static sk_sp<SkImage> make(sk_sp<SkColorSpace> cs) { const int N = 100; SkImageInfo info = SkImageInfo::Make(N, N, kN32_SkColorType, kPremul_SkAlphaType, cs); SkBitmap bm; bm.allocPixels(info); for (int y = 0; y < N; ++y) { for (int x = 0; x < N; ++x) { *bm.getAddr32(x, y) = (x ^ y) & 1 ? 0xFFFFFFFF : 0xFF000000; } } bm.setImmutable(); return SkImage::MakeFromBitmap(bm); } static void show_mips(SkCanvas* canvas, SkImage* img) { SkPaint paint; paint.setFilterQuality(kMedium_SkFilterQuality); SkRect dst = SkRect::MakeIWH(img->width(), img->height()); while (dst.width() > 5) { canvas->drawImageRect(img, dst, &paint); dst.offset(dst.width() + 10, 0); dst.fRight = dst.fLeft + SkScalarHalf(dst.width()); dst.fBottom = dst.fTop + SkScalarHalf(dst.height()); } } /* * Ensure that in L32 drawing mode, both images/mips look the same as each other, and * their mips are darker than the original (since the mips should ignore the gamma in L32). * * Ensure that in S32 drawing mode, all images/mips look the same, and look correct (i.e. * the mip levels match the original in brightness). */ DEF_SIMPLE_GM(mipmap_srgb, canvas, 260, 230) { sk_sp<SkImage> limg = make(nullptr); sk_sp<SkImage> simg = make(SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named)); canvas->translate(10, 10); show_mips(canvas, limg.get()); canvas->translate(0, limg->height() + 10.0f); show_mips(canvas, simg.get()); } <commit_msg>tweak mipmap_srgb gm to use integer coordinates<commit_after>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkImage.h" #include "SkRandom.h" #include "SkSurface.h" static sk_sp<SkImage> make_image() { const SkImageInfo info = SkImageInfo::MakeN32Premul(319, 52); auto surface(SkSurface::MakeRaster(info)); SkCanvas* canvas = surface->getCanvas(); canvas->drawColor(sk_tool_utils::color_to_565(0xFFF8F8F8)); SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); for (int i = 0; i < 20; ++i) { canvas->drawCircle(-4, 25, 20, paint); canvas->translate(25, 0); } return surface->makeImageSnapshot(); } DEF_SIMPLE_GM(mipmap, canvas, 400, 200) { sk_sp<SkImage> img(make_image());//SkImage::NewFromEncoded(data)); SkPaint paint; const SkRect dst = SkRect::MakeWH(177, 15); paint.setTextSize(30); SkString str; str.printf("scale %g %g", dst.width() / img->width(), dst.height() / img->height()); // canvas->drawText(str.c_str(), str.size(), 300, 100, paint); canvas->translate(20, 20); for (int i = 0; i < 4; ++i) { paint.setFilterQuality(SkFilterQuality(i)); canvas->drawImageRect(img.get(), dst, &paint); canvas->translate(0, 20); } canvas->drawImage(img.get(), 20, 20, nullptr); } /////////////////////////////////////////////////////////////////////////////////////////////////// // create a circle image computed raw, so we can wrap it as a linear or srgb image static sk_sp<SkImage> make(sk_sp<SkColorSpace> cs) { const int N = 100; SkImageInfo info = SkImageInfo::Make(N, N, kN32_SkColorType, kPremul_SkAlphaType, cs); SkBitmap bm; bm.allocPixels(info); for (int y = 0; y < N; ++y) { for (int x = 0; x < N; ++x) { *bm.getAddr32(x, y) = (x ^ y) & 1 ? 0xFFFFFFFF : 0xFF000000; } } bm.setImmutable(); return SkImage::MakeFromBitmap(bm); } static void show_mips(SkCanvas* canvas, SkImage* img) { SkPaint paint; paint.setFilterQuality(kMedium_SkFilterQuality); // Want to ensure we never draw fractional pixels, so we use an IRect SkIRect dst = SkIRect::MakeWH(img->width(), img->height()); while (dst.width() > 5) { canvas->drawImageRect(img, SkRect::Make(dst), &paint); dst.offset(dst.width() + 10, 0); dst.fRight = dst.fLeft + dst.width()/2; dst.fBottom = dst.fTop + dst.height()/2; } } /* * Ensure that in L32 drawing mode, both images/mips look the same as each other, and * their mips are darker than the original (since the mips should ignore the gamma in L32). * * Ensure that in S32 drawing mode, all images/mips look the same, and look correct (i.e. * the mip levels match the original in brightness). */ DEF_SIMPLE_GM(mipmap_srgb, canvas, 260, 230) { sk_sp<SkImage> limg = make(nullptr); sk_sp<SkImage> simg = make(SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named)); canvas->translate(10, 10); show_mips(canvas, limg.get()); canvas->translate(0, limg->height() + 10.0f); show_mips(canvas, simg.get()); } <|endoftext|>
<commit_before>/* * Copyright (C) 2018 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <seastar/core/sleep.hh> #include <seastar/util/noncopyable_function.hh> #include "seastarx.hh" inline void eventually(noncopyable_function<void ()> f, size_t max_attempts = 17) { size_t attempts = 0; while (true) { try { f(); break; } catch (...) { if (++attempts < max_attempts) { sleep(std::chrono::milliseconds(1 << attempts)).get0(); } else { throw; } } } } inline bool eventually_true(noncopyable_function<bool ()> f) { const unsigned max_attempts = 15; unsigned attempts = 0; while (true) { if (f()) { return true; } if (++attempts < max_attempts) { seastar::sleep(std::chrono::milliseconds(1 << attempts)).get0(); } else { return false; } } return false; } #define REQUIRE_EVENTUALLY_EQUAL(a, b) BOOST_REQUIRE(eventually_true([&] { return a == b; })) <commit_msg>test: add CHECK_EVENTUALLY_EQUAL utility macro<commit_after>/* * Copyright (C) 2018 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <seastar/core/sleep.hh> #include <seastar/util/noncopyable_function.hh> #include "seastarx.hh" inline void eventually(noncopyable_function<void ()> f, size_t max_attempts = 17) { size_t attempts = 0; while (true) { try { f(); break; } catch (...) { if (++attempts < max_attempts) { sleep(std::chrono::milliseconds(1 << attempts)).get0(); } else { throw; } } } } inline bool eventually_true(noncopyable_function<bool ()> f) { const unsigned max_attempts = 15; unsigned attempts = 0; while (true) { if (f()) { return true; } if (++attempts < max_attempts) { seastar::sleep(std::chrono::milliseconds(1 << attempts)).get0(); } else { return false; } } return false; } #define REQUIRE_EVENTUALLY_EQUAL(a, b) BOOST_REQUIRE(eventually_true([&] { return a == b; })) #define CHECK_EVENTUALLY_EQUAL(a, b) BOOST_CHECK(eventually_true([&] { return a == b; })) <|endoftext|>
<commit_before>// // main.cpp // GLEngineExample1 // // Created by Asger Nyman Christiansen on 18/12/2016. // Copyright © 2016 Asger Nyman Christiansen. All rights reserved. // #include "GLCamera.h" #include "MeshCreator.h" #include "materials/GLFlatMaterial.h" #include "materials/GLStandardMaterial.h" #include "gtx/rotate_vector.hpp" #define GLFW_INCLUDE_NONE #include "glfw3.h" using namespace std; using namespace glm; using namespace gle; using namespace mesh; GLFWwindow* gWindow = NULL; shared_ptr<mat4> cube_rotation = make_shared<mat4>(1.); void on_error(int errorCode, const char* msg) { throw std::runtime_error(msg); } void print_fps(double elapsedTime) { static int draws = 0; draws++; static float seconds = 0.; seconds += elapsedTime; if(seconds > 5) { std::cout << "FPS: " << ((float)draws)/seconds << std::endl; seconds = 0.; draws = 0; } } void update() { static float last_time = glfwGetTime(); float time = glfwGetTime(); float elapsed_time = time - last_time; print_fps(elapsed_time); *cube_rotation = rotate(rotate(*cube_rotation, elapsed_time, vec3(0., 1., 0.)), elapsed_time, vec3(1., 0., 0.)); last_time = time; } void create_cubes(GLNode& root) { auto rotation_node = std::make_shared<GLTransformationNode>(cube_rotation); root.add_child(rotation_node); { auto translation_node = std::make_shared<GLTransformationNode>(translate(vec3(-1., 0., 1.))); rotation_node->add_child(translation_node); auto geometry = MeshCreator::create_box(false); auto material = shared_ptr<GLMaterial>(new GLFlatMaterial({0.5, 0.5, 0.5}, {0., 0.5, 0.}, {0.5, 0., 0.}, 1.)); translation_node->add_leaf(geometry, material); } { auto translation_node = std::make_shared<GLTransformationNode>(translate(vec3(1., 0., -1.))); rotation_node->add_child(translation_node); auto geometry = MeshCreator::create_box(false); auto material = shared_ptr<GLMaterial>(new GLStandardMaterial(geometry->normal(), {0.5, 0.5, 0.5}, {0., 0.5, 0.}, {0.5, 0., 0.}, 1.)); translation_node->add_leaf(geometry, material); } } int main(int argc, const char * argv[]) { int WIN_SIZE_X = 1200; int WIN_SIZE_Y = 700; // initialise GLFW glfwSetErrorCallback(on_error); if(!glfwInit()) throw std::runtime_error("glfwInit failed"); // Open a window with GLFW glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); gWindow = glfwCreateWindow(WIN_SIZE_X, WIN_SIZE_Y, "GLEngine example 1", NULL, NULL); if(!gWindow) throw std::runtime_error("glfwCreateWindow failed. Can your hardware handle OpenGL 3.2?"); // GLFW settings glfwSetInputMode(gWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPos(gWindow, 0, 0); glfwMakeContextCurrent(gWindow); glfwGetFramebufferSize(gWindow, &WIN_SIZE_X, &WIN_SIZE_Y); // Create camera auto camera = GLCamera(WIN_SIZE_X, WIN_SIZE_Y); camera.set_view(vec3(5.,0.,5.), vec3(-1., 0., -1.)); // Create scene auto scene = GLScene(); // Create object create_cubes(scene); // run while the window is open while(!glfwWindowShouldClose(gWindow)) { // process pending events glfwPollEvents(); // update the scene based on the time elapsed since last update update(); // draw one frame GLCamera::clear_screen(); camera.draw(scene); glfwSwapBuffers(gWindow); //exit program if escape key is pressed if(glfwGetKey(gWindow, GLFW_KEY_ESCAPE)) glfwSetWindowShouldClose(gWindow, GL_TRUE); } // clean up and exit glfwTerminate(); return 0; } <commit_msg>Updated example to use deferred shading.<commit_after>// // main.cpp // GLEngineExample1 // // Created by Asger Nyman Christiansen on 18/12/2016. // Copyright © 2016 Asger Nyman Christiansen. All rights reserved. // #include "GLCamera.h" #include "MeshCreator.h" #include "materials/GLFlatMaterial.h" #include "materials/GLStandardMaterial.h" #include "materials/GLColorMaterial.h" #include "gtx/rotate_vector.hpp" #define GLFW_INCLUDE_NONE #include "glfw3.h" using namespace std; using namespace glm; using namespace gle; using namespace mesh; GLFWwindow* gWindow = NULL; shared_ptr<mat4> cube_rotation = make_shared<mat4>(1.); void on_error(int errorCode, const char* msg) { throw std::runtime_error(msg); } void print_fps(double elapsedTime) { static int draws = 0; draws++; static float seconds = 0.; seconds += elapsedTime; if(seconds > 5) { std::cout << "FPS: " << ((float)draws)/seconds << std::endl; seconds = 0.; draws = 0; } } void update() { static float last_time = glfwGetTime(); float time = glfwGetTime(); float elapsed_time = time - last_time; print_fps(elapsed_time); *cube_rotation = rotate(rotate(*cube_rotation, elapsed_time, vec3(0., 1., 0.)), elapsed_time, vec3(1., 0., 0.)); last_time = time; } void create_cubes(GLScene& root) { root.add_light(std::make_shared<GLDirectionalLight>(glm::vec3(1., -1., -1.))); auto rotation_node = std::make_shared<GLTransformationNode>(cube_rotation); root.add_child(rotation_node); { auto translation_node = std::make_shared<GLTransformationNode>(translate(vec3(-1., 0., 1.))); rotation_node->add_child(translation_node); auto geometry = MeshCreator::create_box(false); auto material = make_shared<GLFlatMaterial>(vec3(0.1, 0.5, 0.5)); translation_node->add_leaf(geometry, material); } { auto translation_node = std::make_shared<GLTransformationNode>(translate(vec3(1., 0., -1.))); rotation_node->add_child(translation_node); auto geometry = MeshCreator::create_box(false); auto material = make_shared<GLColorMaterial>(vec3(0.5, 0.1, 0.7)); translation_node->add_leaf(geometry, material); } } int main(int argc, const char * argv[]) { int WIN_SIZE_X = 1200; int WIN_SIZE_Y = 700; // initialise GLFW glfwSetErrorCallback(on_error); if(!glfwInit()) throw std::runtime_error("glfwInit failed"); // Open a window with GLFW glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); gWindow = glfwCreateWindow(WIN_SIZE_X, WIN_SIZE_Y, "GLEngine example 1", NULL, NULL); if(!gWindow) throw std::runtime_error("glfwCreateWindow failed. Can your hardware handle OpenGL 3.2?"); // GLFW settings glfwSetInputMode(gWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPos(gWindow, 0, 0); glfwMakeContextCurrent(gWindow); glfwGetFramebufferSize(gWindow, &WIN_SIZE_X, &WIN_SIZE_Y); // Create camera auto camera = GLCamera(WIN_SIZE_X, WIN_SIZE_Y); camera.set_view(vec3(5.,0.,5.), vec3(-1., 0., -1.)); // Create scene auto scene = GLScene(); // Create object create_cubes(scene); // run while the window is open while(!glfwWindowShouldClose(gWindow)) { // process pending events glfwPollEvents(); // update the scene based on the time elapsed since last update update(); // draw one frame GLCamera::clear_screen(); camera.draw_deferred(scene); glfwSwapBuffers(gWindow); //exit program if escape key is pressed if(glfwGetKey(gWindow, GLFW_KEY_ESCAPE)) glfwSetWindowShouldClose(gWindow, GL_TRUE); } // clean up and exit glfwTerminate(); return 0; } <|endoftext|>
<commit_before>#include "gpio.hpp" #include "engine.hpp" #include <string> #include <math.h> #include <ros/ros.h> #include <geometry_msgs/Twist.h> using namespace ros; using namespace std; GPIO gpio; // enable direction speed Engine driveLeft(&gpio, GPIO::P9_31, GPIO::P9_21, GPIO::P9_14); Engine driveRight(&gpio, GPIO::P8_10, GPIO::P8_12, GPIO::P8_13); Engine rotatorLeft(&gpio, GPIO::P9_26, GPIO::P9_24, GPIO::P9_16); Engine rotatorRight(&gpio, GPIO::P8_17, GPIO::P8_15, GPIO::P8_19); void velocityCallback(const geometry_msgs::Twist& msg) { //ROS_INFO("%f", msg.linear.x); // ================ // Car-like steering (rotate around inner wheel) //double leftSpd = max(0.0, min(1.0, msg.linear.x * (1.0 + msg.angular.x))); //double rightSpd = max(0.0, min(1.0, msg.linear.x * (1.0 - msg.angular.x))); // ================ // ================ // Tank-like steering (rotate around vehicle center) // First, set linear back/forward speed double leftSpd = msg.linear.x; double rightSpd = msg.linear.x; // Second, add left/right speeds so that turning on the spot is possible // if(msg.linear.x >= 0) { leftSpd -= msg.angular.z; rightSpd += msg.angular.z; // } else { // leftSpd += msg.angular.z; // rightSpd -= msg.angular.z; // } // Determine rotation directions Engine::Direction leftDir = leftSpd > 0 ? Engine::BACKWARD : Engine::FORWARD; Engine::Direction rightDir = rightSpd > 0 ? Engine::FORWARD : Engine::BACKWARD; // Normalize leftSpd = leftSpd < 0 ? leftSpd * -1.0 : leftSpd; rightSpd = rightSpd < 0 ? rightSpd * -1.0 : rightSpd; leftSpd = min(1.0, max(0.0, leftSpd)); rightSpd = min(1.0, max(0.0, rightSpd)); // Apply! driveLeft.setDirection(leftDir); driveLeft.setSpeed(leftSpd); driveRight.setDirection(rightDir); driveRight.setSpeed(rightSpd); // ================ // Wheel disc rotation double leftRotSpd = msg.angular.y; double rightRotSpd = msg.angular.y; Engine::Direction leftRotDir = leftRotSpd > 0 ? Engine::BACKWARD : Engine::FORWARD; Engine::Direction rightRotDir = rightRotSpd > 0 ? Engine::FORWARD : Engine::BACKWARD; leftRotSpd = leftRotSpd < 0 ? leftRotSpd * -1.0 : leftRotSpd; rightRotSpd = rightRotSpd < 0 ? rightRotSpd * -1.0 : rightRotSpd; leftRotSpd = min(1.0, max(0.0, leftRotSpd)); rightRotSpd = min(1.0, max(0.0, rightRotSpd)); rotatorLeft.setDirection(leftRotDir); rotatorLeft.setSpeed(leftRotSpd); rotatorRight.setDirection(rightRotDir); rotatorRight.setSpeed(leftRotSpd); } int main(int argc, char **argv) { // init ros init(argc, argv, "enginecontrol"); NodeHandle n; // This is correct - we're borrowing the turtle's topics Subscriber sub = n.subscribe("turtle1/cmd_vel", 1, velocityCallback); ROS_INFO("enginecontrol up and running."); // enter ros loop and wait for callbacks spin(); return 0; } <commit_msg>Adapt pin mappings to hardware reality<commit_after>#include "gpio.hpp" #include "engine.hpp" #include <string> #include <math.h> #include <ros/ros.h> #include <geometry_msgs/Twist.h> using namespace ros; using namespace std; GPIO gpio; // enable direction speed Engine driveLeft(&gpio, GPIO::P9_31, GPIO::P9_21, GPIO::P9_14); Engine driveRight(&gpio, GPIO::P8_10, GPIO::P8_12, GPIO::P8_13); Engine rotatorLeft(&gpio, GPIO::P9_24, GPIO::P9_26, GPIO::P9_16); Engine rotatorRight(&gpio, GPIO::P8_17, GPIO::P8_15, GPIO::P8_19); void velocityCallback(const geometry_msgs::Twist& msg) { //ROS_INFO("%f", msg.linear.x); // ================ // Car-like steering (rotate around inner wheel) //double leftSpd = max(0.0, min(1.0, msg.linear.x * (1.0 + msg.angular.x))); //double rightSpd = max(0.0, min(1.0, msg.linear.x * (1.0 - msg.angular.x))); // ================ // ================ // Tank-like steering (rotate around vehicle center) // First, set linear back/forward speed double leftSpd = msg.linear.x; double rightSpd = msg.linear.x; // Second, add left/right speeds so that turning on the spot is possible // if(msg.linear.x >= 0) { leftSpd -= msg.angular.z; rightSpd += msg.angular.z; // } else { // leftSpd += msg.angular.z; // rightSpd -= msg.angular.z; // } // Determine rotation directions Engine::Direction leftDir = leftSpd > 0 ? Engine::BACKWARD : Engine::FORWARD; Engine::Direction rightDir = rightSpd > 0 ? Engine::FORWARD : Engine::BACKWARD; // Normalize leftSpd = leftSpd < 0 ? leftSpd * -1.0 : leftSpd; rightSpd = rightSpd < 0 ? rightSpd * -1.0 : rightSpd; leftSpd = min(1.0, max(0.0, leftSpd)); rightSpd = min(1.0, max(0.0, rightSpd)); // Apply! driveLeft.setDirection(leftDir); driveLeft.setSpeed(leftSpd); driveRight.setDirection(rightDir); driveRight.setSpeed(rightSpd); // ================ // Wheel disc rotation double leftRotSpd = msg.angular.y; double rightRotSpd = msg.angular.y; Engine::Direction leftRotDir = leftRotSpd > 0 ? Engine::BACKWARD : Engine::FORWARD; Engine::Direction rightRotDir = rightRotSpd > 0 ? Engine::FORWARD : Engine::BACKWARD; leftRotSpd = leftRotSpd < 0 ? leftRotSpd * -1.0 : leftRotSpd; rightRotSpd = rightRotSpd < 0 ? rightRotSpd * -1.0 : rightRotSpd; leftRotSpd = min(1.0, max(0.0, leftRotSpd)); rightRotSpd = min(1.0, max(0.0, rightRotSpd)); rotatorLeft.setDirection(leftRotDir); rotatorLeft.setSpeed(leftRotSpd); rotatorRight.setDirection(rightRotDir); rotatorRight.setSpeed(leftRotSpd); } int main(int argc, char **argv) { // init ros init(argc, argv, "enginecontrol"); NodeHandle n; // This is correct - we're borrowing the turtle's topics Subscriber sub = n.subscribe("turtle1/cmd_vel", 1, velocityCallback); ROS_INFO("enginecontrol up and running."); // enter ros loop and wait for callbacks spin(); return 0; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <string> #include "pcre2++/pcre2pp.h" TEST(MatchResults, basic) { pcre2::smatch m; EXPECT_FALSE(m.ready()); EXPECT_TRUE(m.empty()); EXPECT_EQ(0, m.size()); EXPECT_EQ(m.begin(), m.end()); EXPECT_EQ(m.cbegin(), m.cend()); } /** * @see http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html#tag_20_116_13_03 */ TEST(MatchResults, format_sed) { std::string email("Something <someone@example.com> anything"); pcre2::regex re("<([^@]++)@([^>]++)>"); pcre2::smatch m; bool f = pcre2::regex_search(email, m, re); EXPECT_TRUE(f); EXPECT_EQ(std::string("someone"), m[1].str()); EXPECT_EQ(std::string("example.com"), m[2].str()); std::string actual; // An <ampersand> ( '&' ) appearing in the replacement shall be replaced by the string matching the BRE. actual = m.format("!&!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!<someone@example.com>!"), actual); // The special meaning of '&' in this context can be suppressed by preceding it by a <backslash>. actual = m.format("!&\\&!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!<someone@example.com>&!"), actual); // The characters "\n", where n is a digit, shall be replaced by the text matched by the corresponding back-reference expression. actual = m.format("!\\1 \\2!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!someone example.com!"), actual); // If the corresponding back-reference expression does not match, then the characters "\n" shall be replaced by the empty string. actual = m.format("!\\3!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!!"), actual); // The special meaning of "\n" where n is a digit in this context, can be suppressed by preceding it by a <backslash>. actual = m.format("!\\\\1 \\2!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!\\1 example.com!"), actual); /* */ actual = m.format("!\\x \\2!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!\\x example.com!"), actual); /* Corner case - backslash is the last character */ actual = m.format("\\1 \\", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("someone \\"), actual); } TEST(MatchResults, format_default) { { // http://en.cppreference.com/w/cpp/regex/match_results/format std::string s = "for a good time, call 867-5309"; pcre2::regex phone_regex("\\d{3}-\\d{4}"); pcre2::smatch phone_match; bool f = pcre2::regex_search(s, phone_match, phone_regex); EXPECT_TRUE(f); std::string actual = phone_match.format( "<$`>" // $` means characters before the match "[$&]" // $& means the matched characters "<$'>" // $' means characters following the match ); EXPECT_EQ(std::string("<for a good time, call >[867-5309]<>"), actual); } { std::string s = "IP: 127.0.0.1 localhost"; pcre2::regex re("([0-9]++)\\.([0-9]++)\\.([0-9]++)\\.([0-9]++)"); pcre2::smatch m; std::string actual; bool f = pcre2::regex_search(s, m, re); EXPECT_TRUE(f); actual = m.format("$`"); EXPECT_EQ(std::string("IP: "), actual); actual = m.format("$'"); EXPECT_EQ(std::string(" localhost"), actual); actual = m.format("$&"); EXPECT_EQ(std::string("127.0.0.1"), actual); actual = m.format("$0"); EXPECT_EQ(std::string("127.0.0.1"), actual); actual = m.format("$00"); EXPECT_EQ(std::string("127.0.0.1"), actual); actual = m.format("$x $$ $1 $5 $4 $"); EXPECT_EQ(std::string("$x $ 127 1 $"), actual); } } <commit_msg>Cover more branches<commit_after>#include <gtest/gtest.h> #include <string> #include "pcre2++/pcre2pp.h" TEST(MatchResults, basic) { pcre2::smatch m; EXPECT_FALSE(m.ready()); EXPECT_TRUE(m.empty()); EXPECT_EQ(0, m.size()); EXPECT_EQ(m.begin(), m.end()); EXPECT_EQ(m.cbegin(), m.cend()); } /** * @see http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html#tag_20_116_13_03 */ TEST(MatchResults, format_sed) { std::string email("Something <someone@example.com> anything"); pcre2::regex re("<([^@]++)@([^>]++)>"); pcre2::smatch m; bool f = pcre2::regex_search(email, m, re); EXPECT_TRUE(f); EXPECT_EQ(std::string("someone"), m[1].str()); EXPECT_EQ(std::string("example.com"), m[2].str()); std::string actual; // An <ampersand> ( '&' ) appearing in the replacement shall be replaced by the string matching the BRE. actual = m.format("!&!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!<someone@example.com>!"), actual); // The special meaning of '&' in this context can be suppressed by preceding it by a <backslash>. actual = m.format("!&\\&!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!<someone@example.com>&!"), actual); // The characters "\n", where n is a digit, shall be replaced by the text matched by the corresponding back-reference expression. actual = m.format("!\\1 \\2!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!someone example.com!"), actual); // If the corresponding back-reference expression does not match, then the characters "\n" shall be replaced by the empty string. actual = m.format("!\\3!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!!"), actual); // The special meaning of "\n" where n is a digit in this context, can be suppressed by preceding it by a <backslash>. actual = m.format("!\\\\1 \\2!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!\\1 example.com!"), actual); /* */ actual = m.format("!\\x \\2!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!\\x example.com!"), actual); /* Corner case - backslash is the last character */ actual = m.format("\\1 \\", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("someone \\"), actual); } TEST(MatchResults, format_default) { { // http://en.cppreference.com/w/cpp/regex/match_results/format std::string s = "for a good time, call 867-5309"; pcre2::regex phone_regex("\\d{3}-\\d{4}"); pcre2::smatch phone_match; bool f = pcre2::regex_search(s, phone_match, phone_regex); EXPECT_TRUE(f); std::string actual = phone_match.format( "<$`>" // $` means characters before the match "[$&]" // $& means the matched characters "<$'>" // $' means characters following the match ); EXPECT_EQ(std::string("<for a good time, call >[867-5309]<>"), actual); } { std::string s = "867-5309 is the phone to call"; pcre2::regex phone_regex("\\d{3}-\\d{4}"); pcre2::smatch phone_match; bool f = pcre2::regex_search(s, phone_match, phone_regex); EXPECT_TRUE(f); std::string actual = phone_match.format( "<$`>" // $` means characters before the match "[$&]" // $& means the matched characters "<$'>" // $' means characters following the match ); EXPECT_EQ(std::string("<>[867-5309]< is the phone to call>"), actual); } { std::string s = "IP: 127.0.0.1 localhost"; pcre2::regex re("([0-9]++)\\.([0-9]++)\\.([0-9]++)\\.([0-9]++)"); pcre2::smatch m; std::string actual; bool f = pcre2::regex_search(s, m, re); EXPECT_TRUE(f); actual = m.format("$`"); EXPECT_EQ(std::string("IP: "), actual); actual = m.format("$'"); EXPECT_EQ(std::string(" localhost"), actual); actual = m.format("$&"); EXPECT_EQ(std::string("127.0.0.1"), actual); actual = m.format("$0"); EXPECT_EQ(std::string("127.0.0.1"), actual); actual = m.format("$00"); EXPECT_EQ(std::string("127.0.0.1"), actual); actual = m.format("$x $$ $1 $5 $4 $"); EXPECT_EQ(std::string("$x $ 127 1 $"), actual); } } <|endoftext|>
<commit_before>/** * @file csv.cpp * * @date Nov 27, 2012 * @author: partio */ #include "csv.h" #include "logger_factory.h" #include <fstream> #include "regular_grid.h" #include "irregular_grid.h" #include <boost/foreach.hpp> #include "csv_v3.h" #include <boost/filesystem.hpp> using namespace std; using namespace himan::plugin; typedef tuple< int, // station id string, // station name double, // longitude double, // latitude string, // origintime as timestamp string, // forecasttime as timestamp string, // level name double, // level value string, // parameter name double> // value record; typedef io::CSVReader< 10, // column count io::trim_chars<' ', '\t'>, io::no_quote_escape<','>, io::throw_on_overflow, io::no_comment > csv_reader; bool GetLine(csv_reader& in, record& line) { int station_id; string station_name; double longitude; double latitude; string origintime; string forecasttime; string level_name; double level_value; string parameter_name; double value; if (in.read_row(station_id, station_name, longitude, latitude, origintime, forecasttime, level_name, level_value, parameter_name, value)) { line = make_tuple(station_id, station_name, longitude, latitude, origintime, forecasttime, level_name, level_value, parameter_name, value); return true; } return false; } csv::csv() { itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("csv")); } bool csv::ToFile(info& theInfo, string& theOutputFile, HPFileWriteOption fileWriteOption) { if (theInfo.Grid()->Type() != kIrregularGrid) { itsLogger->Error("Only irregular grids can be written to CSV"); return false; } auto aTimer = timer_factory::Instance()->GetTimer(); aTimer->Start(); ofstream out(theOutputFile); assert(out.is_open()); out << "station_id,station_name,longitude,latitude,origintime,forecasttime,level_name,level_value,parameter_name,value" << endl; for (theInfo.ResetTime(); theInfo.NextTime();) { forecast_time time = theInfo.Time(); for (theInfo.ResetLevel(); theInfo.NextLevel();) { level lev = theInfo.Level(); for (theInfo.ResetParam(); theInfo.NextParam();) { param par = theInfo.Param(); for (theInfo.ResetLocation(); theInfo.NextLocation();) { station s = theInfo.Station(); out << s.Id() << "," << s.Name() << "," << s.X() << "," << s.Y() << "," << time.OriginDateTime().String() << "," << time.ValidDateTime().String() << "," << HPLevelTypeToString.at(lev.Type()) << "," << lev.Value() << "," << par.Name() << "," << theInfo.Value() << endl; } out.flush(); } } } aTimer->Stop(); double duration = static_cast<double> (aTimer->GetTime()); double bytes = static_cast<double> (boost::filesystem::file_size(theOutputFile)); double speed = floor((bytes / 1024. / 1024.) / (duration / 1000.)); itsLogger->Info("Wrote file '" + theOutputFile + "' (" + boost::lexical_cast<string> (speed) + " MB/s)"); return true; } shared_ptr<himan::info> csv::FromFile(const string& inputFile, search_options& options) { info_t ret = make_shared<info> (); csv_reader in(inputFile); in.read_header(io::ignore_no_column, "station_id", "station_name","longitude","latitude","origintime","forecasttime","level_name","level_value","parameter_name","value"); if (!in.has_column("station_id")) { itsLogger->Error("CSV file does not have column station_id"); throw kFileDataNotFound; } record line; vector<forecast_time> times; vector<param> params; vector<level> levels; // First create descriptors while (GetLine(in, line)) { /* Validate time */ forecast_time f(get<4>(line), get<5>(line)); if (f != options.time) { itsLogger->Debug("Time does not match"); itsLogger->Debug("Origin time " + static_cast<string> (options.time.OriginDateTime()) + " vs " + static_cast<string> (f.OriginDateTime())); itsLogger->Debug("Forecast time: " + static_cast<string> (options.time.ValidDateTime()) + " vs " + static_cast<string> (f.ValidDateTime())); continue; } string level_name = get<6>(line); boost::algorithm::to_lower(level_name); /* Validate level */ level l(HPStringToLevelType.at(level_name), get<7>(line)); if (l != options.level) { itsLogger->Debug("Level does not match"); itsLogger->Debug(static_cast<string> (options.level) + " vs " + static_cast<string> (l)); continue; } /* Validate param */ param p(get<8>(line)); if (p != options.param) { itsLogger->Debug("PAram does not match"); itsLogger->Debug(options.param.Name() + " vs " + p.Name()); continue; } bool found = false; /* Prevent duplicates */ BOOST_FOREACH(const forecast_time& t, times) { if (f == t) { found = true; break; } } if (!found) times.push_back(f); found = false; BOOST_FOREACH(const level& t, levels) { if (l == t) { found = true; break; } } if (!found) levels.push_back(l); found = false; BOOST_FOREACH(const param& t, params) { if (p == t) { found = true; break; } } if (!found) params.push_back(p); } if (times.size() == 0 || params.size() == 0 || levels.size() == 0) { itsLogger->Error("Did not find valid data from file '" + inputFile + "'"); throw kFileDataNotFound; } assert(times.size()); assert(params.size()); assert(levels.size()); ret->Times(times); ret->Params(params); ret->Levels(levels); auto base = unique_ptr<grid> (new irregular_grid()); // placeholder base->Projection(kLatLonProjection); ret->Create(base.get()); itsLogger->Debug("Read " + boost::lexical_cast<string> (times.size()) + " times, " + boost::lexical_cast<string> (levels.size()) + " levels and " + boost::lexical_cast<string> (params.size()) + " params from file '" + inputFile + "'"); // Then set grids // The csv library used is sub-standard in that it doesn't allow rewinding of the // file. It does provide functions to set and get file line number, but that doesn't // affect the reading of the file! csv_reader in2(inputFile); in2.read_header(io::ignore_no_column, "station_id", "station_name","longitude","latitude","origintime","forecasttime","level_name","level_value","parameter_name","value"); int counter = 0; while (GetLine(in2, line)) { forecast_time f(get<4>(line), get<5>(line)); string level_name = get<6>(line); boost::algorithm::to_lower(level_name); level l(HPStringToLevelType.at(level_name), get<7>(line)); param p(get<8>(line)); station s (get<0>(line), get<1>(line), get<2>(line), get<3>(line)); if (!ret->Param(p)) continue; if (!ret->Time(f)) continue; if (!ret->Level(l)) continue; // Add new station auto stats = dynamic_cast<irregular_grid*> (ret->Grid())->Stations(); stats.push_back(s); dynamic_cast<irregular_grid*> (ret->Grid())->Stations(stats); // Add the data point ret->Grid()->Value(stats.size()-1, get<9> (line)); counter++; } itsLogger->Debug("Read " + boost::lexical_cast<string> (counter) + " lines of data"); return ret; } <commit_msg>fix reading of csv<commit_after>/** * @file csv.cpp * * @date Nov 27, 2012 * @author: partio */ #include "csv.h" #include "logger_factory.h" #include <fstream> #include "regular_grid.h" #include "irregular_grid.h" #include <boost/foreach.hpp> #include "csv_v3.h" #include <boost/filesystem.hpp> using namespace std; using namespace himan::plugin; typedef tuple< int, // station id string, // station name double, // longitude double, // latitude string, // origintime as timestamp string, // forecasttime as timestamp string, // level name double, // level value string, // parameter name double> // value record; typedef io::CSVReader< 10, // column count io::trim_chars<' ', '\t'>, io::no_quote_escape<','>, io::throw_on_overflow, io::no_comment > csv_reader; bool GetLine(csv_reader& in, record& line) { int station_id; string station_name; double longitude; double latitude; string origintime; string forecasttime; string level_name; double level_value; string parameter_name; double value; if (in.read_row(station_id, station_name, longitude, latitude, origintime, forecasttime, level_name, level_value, parameter_name, value)) { line = make_tuple(station_id, station_name, longitude, latitude, origintime, forecasttime, level_name, level_value, parameter_name, value); return true; } return false; } csv::csv() { itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("csv")); } bool csv::ToFile(info& theInfo, string& theOutputFile, HPFileWriteOption fileWriteOption) { if (theInfo.Grid()->Type() != kIrregularGrid) { itsLogger->Error("Only irregular grids can be written to CSV"); return false; } auto aTimer = timer_factory::Instance()->GetTimer(); aTimer->Start(); ofstream out(theOutputFile); assert(out.is_open()); out << "station_id,station_name,longitude,latitude,origintime,forecasttime,level_name,level_value,parameter_name,value" << endl; for (theInfo.ResetTime(); theInfo.NextTime();) { forecast_time time = theInfo.Time(); for (theInfo.ResetLevel(); theInfo.NextLevel();) { level lev = theInfo.Level(); for (theInfo.ResetParam(); theInfo.NextParam();) { param par = theInfo.Param(); for (theInfo.ResetLocation(); theInfo.NextLocation();) { station s = theInfo.Station(); out << s.Id() << "," << s.Name() << "," << s.X() << "," << s.Y() << "," << time.OriginDateTime().String() << "," << time.ValidDateTime().String() << "," << HPLevelTypeToString.at(lev.Type()) << "," << lev.Value() << "," << par.Name() << "," << theInfo.Value() << endl; } out.flush(); } } } aTimer->Stop(); double duration = static_cast<double> (aTimer->GetTime()); double bytes = static_cast<double> (boost::filesystem::file_size(theOutputFile)); double speed = floor((bytes / 1024. / 1024.) / (duration / 1000.)); itsLogger->Info("Wrote file '" + theOutputFile + "' (" + boost::lexical_cast<string> (speed) + " MB/s)"); return true; } shared_ptr<himan::info> csv::FromFile(const string& inputFile, search_options& options) { info_t ret = make_shared<info> (); csv_reader in(inputFile); in.read_header(io::ignore_no_column, "station_id", "station_name","longitude","latitude","origintime","forecasttime","level_name","level_value","parameter_name","value"); if (!in.has_column("station_id")) { itsLogger->Error("CSV file does not have column station_id"); throw kFileDataNotFound; } record line; vector<forecast_time> times; vector<param> params; vector<level> levels; vector<station> stats; // First create descriptors while (GetLine(in, line)) { /* Validate time */ forecast_time f(get<4>(line), get<5>(line)); if (f != options.time) { itsLogger->Debug("Time does not match"); itsLogger->Debug("Origin time " + static_cast<string> (options.time.OriginDateTime()) + " vs " + static_cast<string> (f.OriginDateTime())); itsLogger->Debug("Forecast time: " + static_cast<string> (options.time.ValidDateTime()) + " vs " + static_cast<string> (f.ValidDateTime())); continue; } string level_name = get<6>(line); boost::algorithm::to_lower(level_name); /* Validate level */ level l(HPStringToLevelType.at(level_name), get<7>(line)); if (l != options.level) { itsLogger->Debug("Level does not match"); itsLogger->Debug(static_cast<string> (options.level) + " vs " + static_cast<string> (l)); continue; } /* Validate param */ param p(get<8>(line)); if (p != options.param) { itsLogger->Debug("Param does not match"); itsLogger->Debug(options.param.Name() + " vs " + p.Name()); continue; } bool found = false; /* Prevent duplicates */ BOOST_FOREACH(const forecast_time& t, times) { if (f == t) { found = true; break; } } if (!found) times.push_back(f); found = false; BOOST_FOREACH(const level& t, levels) { if (l == t) { found = true; break; } } if (!found) levels.push_back(l); found = false; BOOST_FOREACH(const param& t, params) { if (p == t) { found = true; break; } } if (!found) params.push_back(p); // Add location information station s (get<0>(line), get<1>(line), get<2>(line), get<3>(line)); found = false; BOOST_FOREACH(const station& stat, stats) { if (stat == s) { found = true; break; } } if (!found) stats.push_back(s); } if (times.size() == 0 || params.size() == 0 || levels.size() == 0) { itsLogger->Error("Did not find valid data from file '" + inputFile + "'"); throw kFileDataNotFound; } assert(times.size()); assert(params.size()); assert(levels.size()); ret->Times(times); ret->Params(params); ret->Levels(levels); auto base = unique_ptr<grid> (new irregular_grid()); // placeholder base->Projection(kLatLonProjection); ret->Create(base.get()); dynamic_cast<irregular_grid*> (ret->Grid())->Stations(stats); itsLogger->Debug("Read " + boost::lexical_cast<string> (times.size()) + " times, " + boost::lexical_cast<string> (levels.size()) + " levels and " + boost::lexical_cast<string> (params.size()) + " params from file '" + inputFile + "'"); // Then set grids // The csv library used is sub-standard in that it doesn't allow rewinding of the // file. It does provide functions to set and get file line number, but that doesn't // affect the reading of the file! csv_reader in2(inputFile); in2.read_header(io::ignore_no_column, "station_id", "station_name","longitude","latitude","origintime","forecasttime","level_name","level_value","parameter_name","value"); int counter = 0; while (GetLine(in2, line)) { forecast_time f(get<4>(line), get<5>(line)); string level_name = get<6>(line); boost::algorithm::to_lower(level_name); level l(HPStringToLevelType.at(level_name), get<7>(line)); param p(get<8>(line)); station s (get<0>(line), get<1>(line), get<2>(line), get<3>(line)); if (!ret->Param(p)) continue; if (!ret->Time(f)) continue; if (!ret->Level(l)) continue; for (size_t i = 0; i < stats.size(); i++) { if (s == stats[i]) { // Add the data point ret->Grid()->Value(i, get<9> (line)); counter++; } } } itsLogger->Debug("Read " + boost::lexical_cast<string> (counter) + " lines of data"); return ret; } <|endoftext|>
<commit_before>#include <vector> #include <openssl/sha.h> #include <openssl/hmac.h> #include <mimetic/mimetic.h> #include <opkele/util.h> #include <opkele/exception.h> #include <opkele/server.h> #include <opkele/data.h> namespace opkele { using namespace std; void server_t::associate(const params_t& pin,params_t& pout) { util::dh_t dh; util::bignum_t c_pub; unsigned char key_sha1[SHA_DIGEST_LENGTH]; enum { sess_cleartext, sess_dh_sha1 } st = sess_cleartext; if( pin.has_param("openid.session_type") && pin.get_param("openid.session_type")=="DH-SHA1" ) { /* TODO: fallback to cleartext in case of exceptions here? */ if(!(dh = DH_new())) throw exception_openssl(OPKELE_CP_ "failed to DH_new()"); c_pub = util::base64_to_bignum(pin.get_param("openid.dh_consumer_public")); if(pin.has_param("openid.dh_modulus")) dh->p = util::base64_to_bignum(pin.get_param("openid.dh_modulus")); else dh->p = util::dec_to_bignum(data::_default_p); if(pin.has_param("openid.dh_gen")) dh->g = util::base64_to_bignum(pin.get_param("openid.dh_gen")); else dh->g = util::dec_to_bignum(data::_default_g); if(!DH_generate_key(dh)) throw exception_openssl(OPKELE_CP_ "failed to DH_generate_key()"); vector<unsigned char> ck(DH_size(dh)); int cklen = DH_compute_key(&(ck.front()),c_pub,dh); if(cklen<0) throw exception_openssl(OPKELE_CP_ "failed to DH_compute_key()"); ck.resize(cklen); // OpenID algorithm requires extra zero in case of set bit here if(ck[0]&0x80) ck.insert(ck.begin(),1,0); SHA1(&(ck.front()),ck.size(),key_sha1); st = sess_dh_sha1; } assoc_t assoc = alloc_assoc(mode_associate); time_t now = time(0); pout.clear(); pout["assoc_type"] = assoc->assoc_type(); pout["assoc_handle"] = assoc->handle(); /* TODO: eventually remove deprecated stuff */ pout["issued"] = util::time_to_w3c(now); pout["expiry"] = util::time_to_w3c(now+assoc->expires_in()); pout["expires_in"] = util::long_to_string(assoc->expires_in()); secret_t secret = assoc->secret(); switch(st) { case sess_dh_sha1: pout["session_type"] = "DH-SHA1"; pout["dh_server_public"] = util::bignum_to_base64(dh->pub_key); secret.enxor_to_base64(key_sha1,pout["enc_mac_key"]); break; default: secret.to_base64(pout["mac_key"]); break; } } void server_t::checkid_immediate(const params_t& pin,string& return_to,params_t& pout) { checkid_(mode_checkid_immediate,pin,return_to,pout); } void server_t::checkid_setup(const params_t& pin,string& return_to,params_t& pout) { checkid_(mode_checkid_setup,pin,return_to,pout); } void server_t::checkid_(mode_t mode,const params_t& pin,string& return_to,params_t& pout) { if(mode!=mode_checkid_immediate && mode!=mode_checkid_setup) throw bad_input(OPKELE_CP_ "invalid checkid_* mode"); assoc_t assoc; try { assoc = retrieve_assoc(pin.get_param("openid.assoc_handle")); }catch(failed_lookup& fl) { // no handle specified or no valid handle found, going dumb assoc = alloc_assoc(mode_checkid_setup); } string trust_root; try { trust_root = pin.get_param("openid.trust_root"); }catch(failed_lookup& fl) { } string identity = pin.get_param("openid.identity"); return_to = pin.get_param("openid.return_to"); validate(*assoc,pin,identity,trust_root); pout.clear(); pout["mode"] = "id_res"; pout["assoc_handle"] = assoc->handle(); if(pin.has_param("openid.assoc_handle") && assoc->stateless()) pout["invalidate_handle"] = pin.get_param("openid.assoc_handle"); pout["identity"] = identity; pout["return_to"] = return_to; /* TODO: eventually remove deprecated stuff */ time_t now = time(0); pout["issued"] = util::time_to_w3c(now); pout["valid_to"] = util::time_to_w3c(now+120); pout["exipres_in"] = "120"; pout.sign(assoc->secret(),pout["sig"],pout["signed"]="mode,identity,return_to"); } void server_t::check_authentication(const params_t& pin,params_t& pout) { vector<unsigned char> sig; mimetic::Base64::Decoder b; const string& sigenc = pin.get_param("openid.sig"); mimetic::decode( sigenc.begin(),sigenc.end(), b, back_insert_iterator<vector<unsigned char> >(sig)); assoc_t assoc; try { assoc = retrieve_assoc(pin.get_param("openid.assoc_handle")); }catch(failed_lookup& fl) { throw failed_assertion(OPKELE_CP_ "invalid handle or handle not specified"); } if(!assoc->stateless()) throw stateful_handle(OPKELE_CP_ "will not do check_authentication on a stateful handle"); const string& slist = pin.get_param("openid.signed"); string kv; string::size_type p =0; while(true) { string::size_type co = slist.find(',',p); string f = (co==string::npos)?slist.substr(p):slist.substr(p,co-p); kv += f; kv += ':'; if(f=="mode") kv += "id_res"; else { f.insert(0,"openid."); kv += pin.get_param(f); } kv += '\n'; if(co==string::npos) break; p = co+1; } secret_t secret = assoc->secret(); unsigned int md_len = 0; unsigned char *md = HMAC( EVP_sha1(), &(secret.front()),secret.size(), (const unsigned char *)kv.data(),kv.length(), 0,&md_len); pout.clear(); if(sig.size()==md_len && !memcmp(&(sig.front()),md,md_len)) { pout["is_valid"]="true"; pout["lifetime"]="60"; /* TODO: eventually remove deprecated stuff */ }else{ pout["is_valid"]="false"; pout["lifetime"]="0"; /* TODO: eventually remove deprecated stuff */ } if(pin.has_param("openid.invalidate_handle")) { string h = pin.get_param("openid.invalidate_handle"); try { assoc_t assoc = retrieve_assoc(h); }catch(invalid_handle& ih) { pout["invalidate_handle"] = h; }catch(failed_lookup& fl) { } } } } <commit_msg>invalidate invalid handles.<commit_after>#include <vector> #include <openssl/sha.h> #include <openssl/hmac.h> #include <mimetic/mimetic.h> #include <opkele/util.h> #include <opkele/exception.h> #include <opkele/server.h> #include <opkele/data.h> namespace opkele { using namespace std; void server_t::associate(const params_t& pin,params_t& pout) { util::dh_t dh; util::bignum_t c_pub; unsigned char key_sha1[SHA_DIGEST_LENGTH]; enum { sess_cleartext, sess_dh_sha1 } st = sess_cleartext; if( pin.has_param("openid.session_type") && pin.get_param("openid.session_type")=="DH-SHA1" ) { /* TODO: fallback to cleartext in case of exceptions here? */ if(!(dh = DH_new())) throw exception_openssl(OPKELE_CP_ "failed to DH_new()"); c_pub = util::base64_to_bignum(pin.get_param("openid.dh_consumer_public")); if(pin.has_param("openid.dh_modulus")) dh->p = util::base64_to_bignum(pin.get_param("openid.dh_modulus")); else dh->p = util::dec_to_bignum(data::_default_p); if(pin.has_param("openid.dh_gen")) dh->g = util::base64_to_bignum(pin.get_param("openid.dh_gen")); else dh->g = util::dec_to_bignum(data::_default_g); if(!DH_generate_key(dh)) throw exception_openssl(OPKELE_CP_ "failed to DH_generate_key()"); vector<unsigned char> ck(DH_size(dh)); int cklen = DH_compute_key(&(ck.front()),c_pub,dh); if(cklen<0) throw exception_openssl(OPKELE_CP_ "failed to DH_compute_key()"); ck.resize(cklen); // OpenID algorithm requires extra zero in case of set bit here if(ck[0]&0x80) ck.insert(ck.begin(),1,0); SHA1(&(ck.front()),ck.size(),key_sha1); st = sess_dh_sha1; } assoc_t assoc = alloc_assoc(mode_associate); time_t now = time(0); pout.clear(); pout["assoc_type"] = assoc->assoc_type(); pout["assoc_handle"] = assoc->handle(); /* TODO: eventually remove deprecated stuff */ pout["issued"] = util::time_to_w3c(now); pout["expiry"] = util::time_to_w3c(now+assoc->expires_in()); pout["expires_in"] = util::long_to_string(assoc->expires_in()); secret_t secret = assoc->secret(); switch(st) { case sess_dh_sha1: pout["session_type"] = "DH-SHA1"; pout["dh_server_public"] = util::bignum_to_base64(dh->pub_key); secret.enxor_to_base64(key_sha1,pout["enc_mac_key"]); break; default: secret.to_base64(pout["mac_key"]); break; } } void server_t::checkid_immediate(const params_t& pin,string& return_to,params_t& pout) { checkid_(mode_checkid_immediate,pin,return_to,pout); } void server_t::checkid_setup(const params_t& pin,string& return_to,params_t& pout) { checkid_(mode_checkid_setup,pin,return_to,pout); } void server_t::checkid_(mode_t mode,const params_t& pin,string& return_to,params_t& pout) { if(mode!=mode_checkid_immediate && mode!=mode_checkid_setup) throw bad_input(OPKELE_CP_ "invalid checkid_* mode"); pout.clear(); assoc_t assoc; try { assoc = retrieve_assoc(pin.get_param("openid.assoc_handle")); }catch(failed_lookup& fl) { // no handle specified or no valid handle found, going dumb assoc = alloc_assoc(mode_checkid_setup); if(pin.has_param("openid.assoc_handle")) pout["invalidate_handle"]=pin.get_param("openid.assoc_handle"); } string trust_root; try { trust_root = pin.get_param("openid.trust_root"); }catch(failed_lookup& fl) { } string identity = pin.get_param("openid.identity"); return_to = pin.get_param("openid.return_to"); validate(*assoc,pin,identity,trust_root); pout["mode"] = "id_res"; pout["assoc_handle"] = assoc->handle(); if(pin.has_param("openid.assoc_handle") && assoc->stateless()) pout["invalidate_handle"] = pin.get_param("openid.assoc_handle"); pout["identity"] = identity; pout["return_to"] = return_to; /* TODO: eventually remove deprecated stuff */ time_t now = time(0); pout["issued"] = util::time_to_w3c(now); pout["valid_to"] = util::time_to_w3c(now+120); pout["exipres_in"] = "120"; pout.sign(assoc->secret(),pout["sig"],pout["signed"]="mode,identity,return_to"); } void server_t::check_authentication(const params_t& pin,params_t& pout) { vector<unsigned char> sig; mimetic::Base64::Decoder b; const string& sigenc = pin.get_param("openid.sig"); mimetic::decode( sigenc.begin(),sigenc.end(), b, back_insert_iterator<vector<unsigned char> >(sig)); assoc_t assoc; try { assoc = retrieve_assoc(pin.get_param("openid.assoc_handle")); }catch(failed_lookup& fl) { throw failed_assertion(OPKELE_CP_ "invalid handle or handle not specified"); } if(!assoc->stateless()) throw stateful_handle(OPKELE_CP_ "will not do check_authentication on a stateful handle"); const string& slist = pin.get_param("openid.signed"); string kv; string::size_type p =0; while(true) { string::size_type co = slist.find(',',p); string f = (co==string::npos)?slist.substr(p):slist.substr(p,co-p); kv += f; kv += ':'; if(f=="mode") kv += "id_res"; else { f.insert(0,"openid."); kv += pin.get_param(f); } kv += '\n'; if(co==string::npos) break; p = co+1; } secret_t secret = assoc->secret(); unsigned int md_len = 0; unsigned char *md = HMAC( EVP_sha1(), &(secret.front()),secret.size(), (const unsigned char *)kv.data(),kv.length(), 0,&md_len); pout.clear(); if(sig.size()==md_len && !memcmp(&(sig.front()),md,md_len)) { pout["is_valid"]="true"; pout["lifetime"]="60"; /* TODO: eventually remove deprecated stuff */ }else{ pout["is_valid"]="false"; pout["lifetime"]="0"; /* TODO: eventually remove deprecated stuff */ } if(pin.has_param("openid.invalidate_handle")) { string h = pin.get_param("openid.invalidate_handle"); try { assoc_t assoc = retrieve_assoc(h); }catch(invalid_handle& ih) { pout["invalidate_handle"] = h; }catch(failed_lookup& fl) { } } } } <|endoftext|>
<commit_before>#include <stdio.h> #include <cmath> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <assert.h> #include "common/util.h" #include "common/swaglog.h" #include "common/visionimg.h" #include "ui.hpp" #include "paint.hpp" int write_param_float(float param, const char* param_name, bool persistent_param) { char s[16]; int size = snprintf(s, sizeof(s), "%f", param); return Params(persistent_param).write_db_value(param_name, s, size < sizeof(s) ? size : sizeof(s)); } static void ui_init_vision(UIState *s) { // Invisible until we receive a calibration message. s->scene.world_objects_visible = false; for (int i = 0; i < s->vipc_client->num_buffers; i++) { s->texture[i].reset(new EGLImageTexture(&s->vipc_client->buffers[i])); glBindTexture(GL_TEXTURE_2D, s->texture[i]->frame_tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // BGR glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED); } assert(glGetError() == GL_NO_ERROR); } void ui_init(UIState *s) { s->sm = new SubMaster({"modelV2", "controlsState", "uiLayoutState", "liveCalibration", "radarState", "thermal", "frame", "health", "carParams", "driverState", "dMonitoringState", "sensorEvents"}); s->started = false; s->status = STATUS_OFFROAD; s->fb = framebuffer_init("ui", 0, true, &s->fb_w, &s->fb_h); assert(s->fb); ui_nvg_init(s); s->last_frame = nullptr; s->vipc_client_rear = new VisionIpcClient("camerad", VISION_STREAM_RGB_BACK, true); s->vipc_client_front = new VisionIpcClient("camerad", VISION_STREAM_RGB_FRONT, true); s->vipc_client = s->vipc_client_rear; } template <class T> static void update_line_data(const UIState *s, const cereal::ModelDataV2::XYZTData::Reader &line, float y_off, float z_off, T *pvd, float max_distance) { const auto line_x = line.getX(), line_y = line.getY(), line_z = line.getZ(); int max_idx = -1; vertex_data *v = &pvd->v[0]; const float margin = 500.0f; for (int i = 0; ((i < TRAJECTORY_SIZE) and (line_x[i] < fmax(MIN_DRAW_DISTANCE, max_distance))); i++) { v += car_space_to_full_frame(s, line_x[i], -line_y[i] - y_off, -line_z[i] + z_off, v, margin); max_idx = i; } for (int i = max_idx; i >= 0; i--) { v += car_space_to_full_frame(s, line_x[i], -line_y[i] + y_off, -line_z[i] + z_off, v, margin); } pvd->cnt = v - pvd->v; assert(pvd->cnt < std::size(pvd->v)); } static void update_model(UIState *s, const cereal::ModelDataV2::Reader &model) { UIScene &scene = s->scene; const float max_distance = fmin(model.getPosition().getX()[TRAJECTORY_SIZE - 1], MAX_DRAW_DISTANCE); // update lane lines const auto lane_lines = model.getLaneLines(); const auto lane_line_probs = model.getLaneLineProbs(); for (int i = 0; i < std::size(scene.lane_line_vertices); i++) { scene.lane_line_probs[i] = lane_line_probs[i]; update_line_data(s, lane_lines[i], 0.025 * scene.lane_line_probs[i], 1.22, &scene.lane_line_vertices[i], max_distance); } // update road edges const auto road_edges = model.getRoadEdges(); const auto road_edge_stds = model.getRoadEdgeStds(); for (int i = 0; i < std::size(scene.road_edge_vertices); i++) { scene.road_edge_stds[i] = road_edge_stds[i]; update_line_data(s, road_edges[i], 0.025, 1.22, &scene.road_edge_vertices[i], max_distance); } // update path const float lead_d = scene.lead_data[0].getStatus() ? scene.lead_data[0].getDRel() * 2. : MAX_DRAW_DISTANCE; float path_length = (lead_d > 0.) ? lead_d - fmin(lead_d * 0.35, 10.) : MAX_DRAW_DISTANCE; path_length = fmin(path_length, max_distance); update_line_data(s, model.getPosition(), 0.5, 0, &scene.track_vertices, path_length); } static void update_sockets(UIState *s) { UIScene &scene = s->scene; SubMaster &sm = *(s->sm); if (sm.update(0) == 0){ return; } if (s->started && sm.updated("controlsState")) { scene.controls_state = sm["controlsState"].getControlsState(); } if (sm.updated("radarState")) { auto data = sm["radarState"].getRadarState(); scene.lead_data[0] = data.getLeadOne(); scene.lead_data[1] = data.getLeadTwo(); } if (sm.updated("liveCalibration")) { scene.world_objects_visible = true; auto extrinsicl = sm["liveCalibration"].getLiveCalibration().getExtrinsicMatrix(); for (int i = 0; i < 3 * 4; i++) { scene.extrinsic_matrix.v[i] = extrinsicl[i]; } } if (sm.updated("modelV2")) { update_model(s, sm["modelV2"].getModelV2()); } if (sm.updated("uiLayoutState")) { auto data = sm["uiLayoutState"].getUiLayoutState(); s->active_app = data.getActiveApp(); scene.sidebar_collapsed = data.getSidebarCollapsed(); } if (sm.updated("thermal")) { scene.thermal = sm["thermal"].getThermal(); } if (sm.updated("health")) { auto health = sm["health"].getHealth(); scene.hwType = health.getHwType(); s->ignition = health.getIgnitionLine() || health.getIgnitionCan(); } else if ((s->sm->frame - s->sm->rcv_frame("health")) > 5*UI_FREQ) { scene.hwType = cereal::HealthData::HwType::UNKNOWN; } if (sm.updated("carParams")) { s->longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl(); } if (sm.updated("driverState")) { scene.driver_state = sm["driverState"].getDriverState(); } if (sm.updated("dMonitoringState")) { scene.dmonitoring_state = sm["dMonitoringState"].getDMonitoringState(); scene.is_rhd = scene.dmonitoring_state.getIsRHD(); scene.frontview = scene.dmonitoring_state.getIsPreview(); } else if (scene.frontview && (sm.frame - sm.rcv_frame("dMonitoringState")) > UI_FREQ/2) { scene.frontview = false; } if (sm.updated("sensorEvents")) { for (auto sensor : sm["sensorEvents"].getSensorEvents()) { if (sensor.which() == cereal::SensorEventData::LIGHT) { s->light_sensor = sensor.getLight(); } else if (!s->started && sensor.which() == cereal::SensorEventData::ACCELERATION) { s->accel_sensor = sensor.getAcceleration().getV()[2]; } else if (!s->started && sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) { s->gyro_sensor = sensor.getGyroUncalibrated().getV()[1]; } } } s->started = scene.thermal.getStarted() || scene.frontview; } static void update_alert(UIState *s) { if (!s->started || s->scene.frontview) return; UIScene &scene = s->scene; if (s->sm->updated("controlsState")) { auto alert_sound = scene.controls_state.getAlertSound(); if (scene.alert_type.compare(scene.controls_state.getAlertType()) != 0) { if (alert_sound == AudibleAlert::NONE) { s->sound->stop(); } else { s->sound->play(alert_sound); } } scene.alert_text1 = scene.controls_state.getAlertText1(); scene.alert_text2 = scene.controls_state.getAlertText2(); scene.alert_size = scene.controls_state.getAlertSize(); scene.alert_type = scene.controls_state.getAlertType(); scene.alert_blinking_rate = scene.controls_state.getAlertBlinkingRate(); auto alert_status = scene.controls_state.getAlertStatus(); if (alert_status == cereal::ControlsState::AlertStatus::USER_PROMPT) { s->status = STATUS_WARNING; } else if (alert_status == cereal::ControlsState::AlertStatus::CRITICAL) { s->status = STATUS_ALERT; } else { s->status = scene.controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED; } } // Handle controls timeout if ((s->sm->frame - s->started_frame) > 10 * UI_FREQ) { const uint64_t cs_frame = s->sm->rcv_frame("controlsState"); if (cs_frame < s->started_frame) { // car is started, but controlsState hasn't been seen at all s->scene.alert_text1 = "openpilot Unavailable"; s->scene.alert_text2 = "Waiting for controls to start"; s->scene.alert_size = cereal::ControlsState::AlertSize::MID; } else if ((s->sm->frame - cs_frame) > 5 * UI_FREQ) { // car is started, but controls is lagging or died if (s->scene.alert_text2 != "Controls Unresponsive") { s->sound->play(AudibleAlert::CHIME_WARNING_REPEAT); LOGE("Controls unresponsive"); } s->scene.alert_text1 = "TAKE CONTROL IMMEDIATELY"; s->scene.alert_text2 = "Controls Unresponsive"; s->scene.alert_size = cereal::ControlsState::AlertSize::FULL; s->status = STATUS_ALERT; } } } static void update_params(UIState *s) { const uint64_t frame = s->sm->frame; if (frame % (5*UI_FREQ) == 0) { read_param(&s->is_metric, "IsMetric"); } else if (frame % (6*UI_FREQ) == 0) { s->scene.athenaStatus = NET_DISCONNECTED; uint64_t last_ping = 0; if (read_param(&last_ping, "LastAthenaPingTime") == 0) { s->scene.athenaStatus = nanos_since_boot() - last_ping < 70e9 ? NET_CONNECTED : NET_ERROR; } } } static void update_vision(UIState *s) { if (!s->vipc_client->connected && s->started) { s->vipc_client = s->scene.frontview ? s->vipc_client_front : s->vipc_client_rear; if (s->vipc_client->connect(false)){ ui_init_vision(s); } } if (s->vipc_client->connected){ VisionBuf * buf = s->vipc_client->recv(); if (buf != nullptr){ s->last_frame = buf; } } } void ui_update(UIState *s) { update_params(s); update_sockets(s); update_alert(s); update_vision(s); // Handle onroad/offroad transition if (!s->started && s->status != STATUS_OFFROAD) { s->status = STATUS_OFFROAD; s->active_app = cereal::UiLayoutState::App::HOME; s->scene.sidebar_collapsed = false; s->sound->stop(); s->vipc_client->connected = false; } else if (s->started && s->status == STATUS_OFFROAD) { s->status = STATUS_DISENGAGED; s->started_frame = s->sm->frame; s->active_app = cereal::UiLayoutState::App::NONE; s->scene.sidebar_collapsed = true; s->scene.alert_size = cereal::ControlsState::AlertSize::NONE; } } <commit_msg>fix qt UI after #19762<commit_after>#include <stdio.h> #include <cmath> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <assert.h> #include "common/util.h" #include "common/swaglog.h" #include "common/visionimg.h" #include "ui.hpp" #include "paint.hpp" int write_param_float(float param, const char* param_name, bool persistent_param) { char s[16]; int size = snprintf(s, sizeof(s), "%f", param); return Params(persistent_param).write_db_value(param_name, s, size < sizeof(s) ? size : sizeof(s)); } static void ui_init_vision(UIState *s) { // Invisible until we receive a calibration message. s->scene.world_objects_visible = false; for (int i = 0; i < s->vipc_client->num_buffers; i++) { s->texture[i].reset(new EGLImageTexture(&s->vipc_client->buffers[i])); glBindTexture(GL_TEXTURE_2D, s->texture[i]->frame_tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // BGR glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED); } assert(glGetError() == GL_NO_ERROR); } void ui_init(UIState *s) { s->sm = new SubMaster({"modelV2", "controlsState", "uiLayoutState", "liveCalibration", "radarState", "thermal", "frame", "health", "carParams", "driverState", "dMonitoringState", "sensorEvents"}); s->started = false; s->status = STATUS_OFFROAD; s->fb = framebuffer_init("ui", 0, true, &s->fb_w, &s->fb_h); assert(s->fb); ui_nvg_init(s); s->last_frame = nullptr; s->vipc_client_rear = new VisionIpcClient("camerad", VISION_STREAM_RGB_BACK, true); s->vipc_client_front = new VisionIpcClient("camerad", VISION_STREAM_RGB_FRONT, true); s->vipc_client = s->vipc_client_rear; } template <class T> static void update_line_data(const UIState *s, const cereal::ModelDataV2::XYZTData::Reader &line, float y_off, float z_off, T *pvd, float max_distance) { const auto line_x = line.getX(), line_y = line.getY(), line_z = line.getZ(); int max_idx = -1; vertex_data *v = &pvd->v[0]; const float margin = 500.0f; for (int i = 0; ((i < TRAJECTORY_SIZE) and (line_x[i] < fmax(MIN_DRAW_DISTANCE, max_distance))); i++) { v += car_space_to_full_frame(s, line_x[i], -line_y[i] - y_off, -line_z[i] + z_off, v, margin); max_idx = i; } for (int i = max_idx; i >= 0; i--) { v += car_space_to_full_frame(s, line_x[i], -line_y[i] + y_off, -line_z[i] + z_off, v, margin); } pvd->cnt = v - pvd->v; assert(pvd->cnt < std::size(pvd->v)); } static void update_model(UIState *s, const cereal::ModelDataV2::Reader &model) { UIScene &scene = s->scene; const float max_distance = fmin(model.getPosition().getX()[TRAJECTORY_SIZE - 1], MAX_DRAW_DISTANCE); // update lane lines const auto lane_lines = model.getLaneLines(); const auto lane_line_probs = model.getLaneLineProbs(); for (int i = 0; i < std::size(scene.lane_line_vertices); i++) { scene.lane_line_probs[i] = lane_line_probs[i]; update_line_data(s, lane_lines[i], 0.025 * scene.lane_line_probs[i], 1.22, &scene.lane_line_vertices[i], max_distance); } // update road edges const auto road_edges = model.getRoadEdges(); const auto road_edge_stds = model.getRoadEdgeStds(); for (int i = 0; i < std::size(scene.road_edge_vertices); i++) { scene.road_edge_stds[i] = road_edge_stds[i]; update_line_data(s, road_edges[i], 0.025, 1.22, &scene.road_edge_vertices[i], max_distance); } // update path const float lead_d = scene.lead_data[0].getStatus() ? scene.lead_data[0].getDRel() * 2. : MAX_DRAW_DISTANCE; float path_length = (lead_d > 0.) ? lead_d - fmin(lead_d * 0.35, 10.) : MAX_DRAW_DISTANCE; path_length = fmin(path_length, max_distance); update_line_data(s, model.getPosition(), 0.5, 0, &scene.track_vertices, path_length); } static void update_sockets(UIState *s) { UIScene &scene = s->scene; SubMaster &sm = *(s->sm); if (sm.update(0) == 0){ return; } if (s->started && sm.updated("controlsState")) { scene.controls_state = sm["controlsState"].getControlsState(); } if (sm.updated("radarState")) { auto data = sm["radarState"].getRadarState(); scene.lead_data[0] = data.getLeadOne(); scene.lead_data[1] = data.getLeadTwo(); } if (sm.updated("liveCalibration")) { scene.world_objects_visible = true; auto extrinsicl = sm["liveCalibration"].getLiveCalibration().getExtrinsicMatrix(); for (int i = 0; i < 3 * 4; i++) { scene.extrinsic_matrix.v[i] = extrinsicl[i]; } } if (sm.updated("modelV2")) { update_model(s, sm["modelV2"].getModelV2()); } if (sm.updated("uiLayoutState")) { auto data = sm["uiLayoutState"].getUiLayoutState(); s->active_app = data.getActiveApp(); scene.sidebar_collapsed = data.getSidebarCollapsed(); } if (sm.updated("thermal")) { scene.thermal = sm["thermal"].getThermal(); } if (sm.updated("health")) { auto health = sm["health"].getHealth(); scene.hwType = health.getHwType(); s->ignition = health.getIgnitionLine() || health.getIgnitionCan(); } else if ((s->sm->frame - s->sm->rcv_frame("health")) > 5*UI_FREQ) { scene.hwType = cereal::HealthData::HwType::UNKNOWN; } if (sm.updated("carParams")) { s->longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl(); } if (sm.updated("driverState")) { scene.driver_state = sm["driverState"].getDriverState(); } if (sm.updated("dMonitoringState")) { scene.dmonitoring_state = sm["dMonitoringState"].getDMonitoringState(); scene.is_rhd = scene.dmonitoring_state.getIsRHD(); scene.frontview = scene.dmonitoring_state.getIsPreview(); } else if (scene.frontview && (sm.frame - sm.rcv_frame("dMonitoringState")) > UI_FREQ/2) { scene.frontview = false; } if (sm.updated("sensorEvents")) { for (auto sensor : sm["sensorEvents"].getSensorEvents()) { if (sensor.which() == cereal::SensorEventData::LIGHT) { s->light_sensor = sensor.getLight(); } else if (!s->started && sensor.which() == cereal::SensorEventData::ACCELERATION) { s->accel_sensor = sensor.getAcceleration().getV()[2]; } else if (!s->started && sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) { s->gyro_sensor = sensor.getGyroUncalibrated().getV()[1]; } } } } static void update_alert(UIState *s) { if (!s->started || s->scene.frontview) return; UIScene &scene = s->scene; if (s->sm->updated("controlsState")) { auto alert_sound = scene.controls_state.getAlertSound(); if (scene.alert_type.compare(scene.controls_state.getAlertType()) != 0) { if (alert_sound == AudibleAlert::NONE) { s->sound->stop(); } else { s->sound->play(alert_sound); } } scene.alert_text1 = scene.controls_state.getAlertText1(); scene.alert_text2 = scene.controls_state.getAlertText2(); scene.alert_size = scene.controls_state.getAlertSize(); scene.alert_type = scene.controls_state.getAlertType(); scene.alert_blinking_rate = scene.controls_state.getAlertBlinkingRate(); auto alert_status = scene.controls_state.getAlertStatus(); if (alert_status == cereal::ControlsState::AlertStatus::USER_PROMPT) { s->status = STATUS_WARNING; } else if (alert_status == cereal::ControlsState::AlertStatus::CRITICAL) { s->status = STATUS_ALERT; } else { s->status = scene.controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED; } } // Handle controls timeout if ((s->sm->frame - s->started_frame) > 10 * UI_FREQ) { const uint64_t cs_frame = s->sm->rcv_frame("controlsState"); if (cs_frame < s->started_frame) { // car is started, but controlsState hasn't been seen at all s->scene.alert_text1 = "openpilot Unavailable"; s->scene.alert_text2 = "Waiting for controls to start"; s->scene.alert_size = cereal::ControlsState::AlertSize::MID; } else if ((s->sm->frame - cs_frame) > 5 * UI_FREQ) { // car is started, but controls is lagging or died if (s->scene.alert_text2 != "Controls Unresponsive") { s->sound->play(AudibleAlert::CHIME_WARNING_REPEAT); LOGE("Controls unresponsive"); } s->scene.alert_text1 = "TAKE CONTROL IMMEDIATELY"; s->scene.alert_text2 = "Controls Unresponsive"; s->scene.alert_size = cereal::ControlsState::AlertSize::FULL; s->status = STATUS_ALERT; } } } static void update_params(UIState *s) { const uint64_t frame = s->sm->frame; if (frame % (5*UI_FREQ) == 0) { read_param(&s->is_metric, "IsMetric"); } else if (frame % (6*UI_FREQ) == 0) { s->scene.athenaStatus = NET_DISCONNECTED; uint64_t last_ping = 0; if (read_param(&last_ping, "LastAthenaPingTime") == 0) { s->scene.athenaStatus = nanos_since_boot() - last_ping < 70e9 ? NET_CONNECTED : NET_ERROR; } } } static void update_vision(UIState *s) { if (!s->vipc_client->connected && s->started) { s->vipc_client = s->scene.frontview ? s->vipc_client_front : s->vipc_client_rear; if (s->vipc_client->connect(false)){ ui_init_vision(s); } } if (s->vipc_client->connected){ VisionBuf * buf = s->vipc_client->recv(); if (buf != nullptr){ s->last_frame = buf; } } } void ui_update(UIState *s) { update_params(s); update_sockets(s); update_alert(s); s->started = s->scene.thermal.getStarted() || s->scene.frontview; update_vision(s); // Handle onroad/offroad transition if (!s->started && s->status != STATUS_OFFROAD) { s->status = STATUS_OFFROAD; s->active_app = cereal::UiLayoutState::App::HOME; s->scene.sidebar_collapsed = false; s->sound->stop(); s->vipc_client->connected = false; } else if (s->started && s->status == STATUS_OFFROAD) { s->status = STATUS_DISENGAGED; s->started_frame = s->sm->frame; s->active_app = cereal::UiLayoutState::App::NONE; s->scene.sidebar_collapsed = true; s->scene.alert_size = cereal::ControlsState::AlertSize::NONE; } } <|endoftext|>
<commit_before>#include "cinder/app/App.h" #include "cinder/ImageIo.h" #if defined( CINDER_COCOA ) #include "cinder/cocoa/CinderCocoa.h" #include <CoreGraphics/CoreGraphics.h> #elif defined( CINDER_MSW ) #include "cinder/msw/CinderMswGdiplus.h" #endif #include "Resources.h" using namespace ci; using namespace ci::app; using namespace std; class Renderer2dApp : public App { public: void setup(); void draw(); #if defined( CINDER_COCOA ) CGImageRef mImage; #elif defined( CINDER_MSW ) Gdiplus::Bitmap *mImage; Surface8u mImageSurface; #endif }; void Renderer2dApp::setup() { #if defined( CINDER_COCOA ) mImage = cocoa::createCgImage( loadImage( loadResource( RES_CINDER_LOGO ) ) ); #elif defined( CINDER_MSW ) mImageSurface = Surface( loadImage( loadResource( RES_CINDER_LOGO ) ), SurfaceConstraintsGdiPlus() ); // because this only wraps the Surface, we need to keep it around mImage = msw::createGdiplusBitmap( mImageSurface ); #endif } void Renderer2dApp::draw() { // Render using CoreGraphics on the mac #if defined( CINDER_COCOA ) CGContextRef context = cocoa::getWindowContext(); CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB(); CGFloat colors[8] = { 0, 0, 0, 1, 0.866, 0.866, 0.866, 1 }; CGGradientRef gradient = CGGradientCreateWithColorComponents( baseSpace, colors, NULL, 2 ); ::CGColorSpaceRelease( baseSpace ), baseSpace = NULL; ::CGContextDrawLinearGradient( context, gradient, CGPointMake( 0, 0 ), CGPointMake( 0, getWindowHeight() ), 0 ); ::CGGradientRelease(gradient), gradient = NULL; // CoreGraphics is "upside down" by default; setup CTM to flip and center it ivec2 imgSize( ::CGImageGetWidth( mImage ), ::CGImageGetHeight( mImage ) ); ivec2 centerMargin( ( getWindowWidth() - imgSize.x ) / 2, ( getWindowHeight() - imgSize.y ) / 2 ); ::CGContextTranslateCTM( context, centerMargin.x, imgSize.y + centerMargin.y ); ::CGContextScaleCTM( context, 1.0, -1.0 ); ::CGContextDrawImage( context, CGRectMake( 0, 0, imgSize.x, imgSize.y ), mImage ); #elif defined( CINDER_MSW ) // Render using GDI+ on Windows Gdiplus::Graphics graphics( getWindow()->getDc() ); Gdiplus::LinearGradientBrush brush( Gdiplus::Rect( 0, 0, getWindowWidth(), getWindowHeight() ), Gdiplus::Color( 0, 0, 0 ), Gdiplus::Color( 220, 220, 220 ), Gdiplus::LinearGradientModeVertical ); graphics.FillRectangle( &brush, 0, 0, getWindowWidth(), getWindowHeight() ); graphics.DrawImage( mImage, ( getWindowWidth() - mImageSurface.getWidth() ) / 2, ( getWindowHeight() - mImageSurface.getHeight() ) / 2, mImageSurface.getWidth(), mImageSurface.getHeight() ); #endif } CINDER_APP( Renderer2dApp, Renderer2d ) <commit_msg>use override directives in sample<commit_after>#include "cinder/app/App.h" #include "cinder/ImageIo.h" #if defined( CINDER_COCOA ) #include "cinder/cocoa/CinderCocoa.h" #include <CoreGraphics/CoreGraphics.h> #elif defined( CINDER_MSW ) #include "cinder/msw/CinderMswGdiplus.h" #endif #include "Resources.h" using namespace ci; using namespace ci::app; using namespace std; class Renderer2dApp : public App { public: void setup() override; void draw() override; #if defined( CINDER_COCOA ) CGImageRef mImage; #elif defined( CINDER_MSW ) Gdiplus::Bitmap *mImage; Surface8u mImageSurface; #endif }; void Renderer2dApp::setup() { #if defined( CINDER_COCOA ) mImage = cocoa::createCgImage( loadImage( loadResource( RES_CINDER_LOGO ) ) ); #elif defined( CINDER_MSW ) mImageSurface = Surface( loadImage( loadResource( RES_CINDER_LOGO ) ), SurfaceConstraintsGdiPlus() ); // because this only wraps the Surface, we need to keep it around mImage = msw::createGdiplusBitmap( mImageSurface ); #endif } void Renderer2dApp::draw() { // Render using CoreGraphics on the mac #if defined( CINDER_COCOA ) CGContextRef context = cocoa::getWindowContext(); CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB(); CGFloat colors[8] = { 0, 0, 0, 1, 0.866, 0.866, 0.866, 1 }; CGGradientRef gradient = CGGradientCreateWithColorComponents( baseSpace, colors, NULL, 2 ); ::CGColorSpaceRelease( baseSpace ), baseSpace = NULL; ::CGContextDrawLinearGradient( context, gradient, CGPointMake( 0, 0 ), CGPointMake( 0, getWindowHeight() ), 0 ); ::CGGradientRelease(gradient), gradient = NULL; // CoreGraphics is "upside down" by default; setup CTM to flip and center it ivec2 imgSize( ::CGImageGetWidth( mImage ), ::CGImageGetHeight( mImage ) ); ivec2 centerMargin( ( getWindowWidth() - imgSize.x ) / 2, ( getWindowHeight() - imgSize.y ) / 2 ); ::CGContextTranslateCTM( context, centerMargin.x, imgSize.y + centerMargin.y ); ::CGContextScaleCTM( context, 1.0, -1.0 ); ::CGContextDrawImage( context, CGRectMake( 0, 0, imgSize.x, imgSize.y ), mImage ); #elif defined( CINDER_MSW ) // Render using GDI+ on Windows Gdiplus::Graphics graphics( getWindow()->getDc() ); Gdiplus::LinearGradientBrush brush( Gdiplus::Rect( 0, 0, getWindowWidth(), getWindowHeight() ), Gdiplus::Color( 0, 0, 0 ), Gdiplus::Color( 220, 220, 220 ), Gdiplus::LinearGradientModeVertical ); graphics.FillRectangle( &brush, 0, 0, getWindowWidth(), getWindowHeight() ); graphics.DrawImage( mImage, ( getWindowWidth() - mImageSurface.getWidth() ) / 2, ( getWindowHeight() - mImageSurface.getHeight() ) / 2, mImageSurface.getWidth(), mImageSurface.getHeight() ); #endif } CINDER_APP( Renderer2dApp, Renderer2d ) <|endoftext|>
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <ctime> #include <ArgumentList.hpp> #include <Exceptions.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <utils.hpp> #include <Shifts.hpp> #include <Dedispersion.hpp> typedef float dataType; std::string typeName("float"); int main(int argc, char *argv[]) { bool localMem = false; bool print = false; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int nrSamplesPerBlock = 0; unsigned int nrDMsPerBlock = 0; unsigned int nrSamplesPerThread = 0; unsigned int nrDMsPerThread = 0; long long unsigned int wrongSamples = 0; AstroData::Observation< dataType > observation("DedispersionTest", typeName); try { isa::utils::ArgumentList args(argc, argv); print = args.getSwitch("-print"); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); localMem = args.getSwitch("-local"); nrSamplesPerBlock = args.getSwitchArgument< unsigned int >("-sb"); nrDMsPerBlock = args.getSwitchArgument< unsigned int >("-db"); nrSamplesPerThread = args.getSwitchArgument< unsigned int >("-st"); nrDMsPerThread = args.getSwitchArgument< unsigned int >("-dt"); observation.setMinFreq(args.getSwitchArgument< float >("-min_freq")); observation.setChannelBandwidth(args.getSwitchArgument< float >("-channel_bandwidth")); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); observation.setNrChannels(args.getSwitchArgument< unsigned int >("-channels")); observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms")); observation.setFirstDM(args.getSwitchArgument< float >("-dm_first")); observation.setDMStep(args.getSwitchArgument< float >("-dm_step")); observation.setMaxFreq(observation.getMinFreq() + (observation.getChannelBandwidth() * (observation.getNrChannels() - 1))); } catch ( isa::Exceptions::SwitchNotFound &err ) { std::cerr << err.what() << std::endl; return 1; }catch ( std::exception &err ) { std::cerr << "Usage: " << argv[0] << " [-print] -opencl_platform ... -opencl_device ... -padding ... [-local] -sb ... -db ... -st ... -dt ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl; return 1; } // Initialize OpenCL cl::Context * clContext = new cl::Context(); std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); std::vector< unsigned int > * shifts = PulsarSearch::getShifts(observation); observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + (*shifts)[((observation.getNrDMs() - 1) * observation.getNrPaddedChannels())]); // Allocate memory cl::Buffer shifts_d; std::vector< dataType > dispersedData = std::vector< dataType >(observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel()); cl::Buffer dispersedData_d; std::vector< dataType > dedispersedData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); cl::Buffer dedispersedData_d; std::vector< dataType > controlData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); try { shifts_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(unsigned int), NULL, NULL); dispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, dispersedData.size() * sizeof(dataType), NULL, NULL); dedispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, dedispersedData.size() * sizeof(dataType), NULL, NULL); } catch ( cl::Error &err ) { std::cerr << "OpenCL error allocating memory: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } srand(time(NULL)); for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { for ( unsigned int sample = 0; sample < observation.getNrSamplesPerDispersedChannel(); sample++ ) { dispersedData[(channel * observation.getNrSamplesPerDispersedChannel()) + sample] = static_cast< dataType >(rand() % 10); } } // Copy data structures to device try { clQueues->at(clDeviceID)[0].enqueueWriteBuffer(shifts_d, CL_FALSE, 0, shifts->size() * sizeof(unsigned int), reinterpret_cast< void * >(shifts->data()), NULL, NULL); clQueues->at(clDeviceID)[0].enqueueWriteBuffer(dispersedData_d, CL_FALSE, 0, dispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dispersedData.data()), NULL, NULL); } catch ( cl::Error &err ) { std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } // Generate kernel std::string * code = PulsarSearch::getDedispersionOpenCL< dataType >(localMem, nrSamplesPerBlock, nrDMsPerBlock, nrSamplesPerThread, nrDMsPerThread, typeName, observation, *shifts); cl::Kernel * kernel; if ( print ) { std::cout << *code << std::endl; } try { kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID)); } catch ( isa::Exceptions::OpenCLError &err ) { std::cerr << err.what() << std::endl; return 1; } // Run OpenCL kernel and CPU control try { cl::NDRange global(observation.getNrSamplesPerPaddedSecond() / nrSamplesPerThread, observation.getNrDMs() / nrDMsPerThread); cl::NDRange local(nrSamplesPerBlock, nrDMsPerBlock); kernel->setArg(0, dispersedData_d); kernel->setArg(1, dedispersedData_d); kernel->setArg(2, shifts_d); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local); PulsarSearch::dedispersion< dataType >(observation, dispersedData, controlData, *shifts); clQueues->at(clDeviceID)[0].enqueueReadBuffer(dedispersedData_d, CL_TRUE, 0, dedispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dedispersedData.data())); } catch ( cl::Error &err ) { std::cerr << "OpenCL error kernel execution: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) { if ( !isa::utils::same(controlData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample], dedispersedData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample]) ) { wrongSamples++; } } } if ( wrongSamples > 0 ) { std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond()) << "%)." << std::endl; } else { std::cout << "TEST PASSED." << std::endl; } return 0; } <commit_msg>Using the new exceptions.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <ctime> #include <ArgumentList.hpp> #include <Exceptions.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <utils.hpp> #include <Shifts.hpp> #include <Dedispersion.hpp> typedef float dataType; std::string typeName("float"); int main(int argc, char *argv[]) { bool localMem = false; bool print = false; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int nrSamplesPerBlock = 0; unsigned int nrDMsPerBlock = 0; unsigned int nrSamplesPerThread = 0; unsigned int nrDMsPerThread = 0; long long unsigned int wrongSamples = 0; AstroData::Observation< dataType > observation("DedispersionTest", typeName); try { isa::utils::ArgumentList args(argc, argv); print = args.getSwitch("-print"); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); localMem = args.getSwitch("-local"); nrSamplesPerBlock = args.getSwitchArgument< unsigned int >("-sb"); nrDMsPerBlock = args.getSwitchArgument< unsigned int >("-db"); nrSamplesPerThread = args.getSwitchArgument< unsigned int >("-st"); nrDMsPerThread = args.getSwitchArgument< unsigned int >("-dt"); observation.setMinFreq(args.getSwitchArgument< float >("-min_freq")); observation.setChannelBandwidth(args.getSwitchArgument< float >("-channel_bandwidth")); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); observation.setNrChannels(args.getSwitchArgument< unsigned int >("-channels")); observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms")); observation.setFirstDM(args.getSwitchArgument< float >("-dm_first")); observation.setDMStep(args.getSwitchArgument< float >("-dm_step")); observation.setMaxFreq(observation.getMinFreq() + (observation.getChannelBandwidth() * (observation.getNrChannels() - 1))); } catch ( isa::utils::SwitchNotFound &err ) { std::cerr << err.what() << std::endl; return 1; }catch ( std::exception &err ) { std::cerr << "Usage: " << argv[0] << " [-print] -opencl_platform ... -opencl_device ... -padding ... [-local] -sb ... -db ... -st ... -dt ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl; return 1; } // Initialize OpenCL cl::Context * clContext = new cl::Context(); std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); std::vector< unsigned int > * shifts = PulsarSearch::getShifts(observation); observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + (*shifts)[((observation.getNrDMs() - 1) * observation.getNrPaddedChannels())]); // Allocate memory cl::Buffer shifts_d; std::vector< dataType > dispersedData = std::vector< dataType >(observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel()); cl::Buffer dispersedData_d; std::vector< dataType > dedispersedData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); cl::Buffer dedispersedData_d; std::vector< dataType > controlData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); try { shifts_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(unsigned int), NULL, NULL); dispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, dispersedData.size() * sizeof(dataType), NULL, NULL); dedispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, dedispersedData.size() * sizeof(dataType), NULL, NULL); } catch ( cl::Error &err ) { std::cerr << "OpenCL error allocating memory: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } srand(time(NULL)); for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { for ( unsigned int sample = 0; sample < observation.getNrSamplesPerDispersedChannel(); sample++ ) { dispersedData[(channel * observation.getNrSamplesPerDispersedChannel()) + sample] = static_cast< dataType >(rand() % 10); } } // Copy data structures to device try { clQueues->at(clDeviceID)[0].enqueueWriteBuffer(shifts_d, CL_FALSE, 0, shifts->size() * sizeof(unsigned int), reinterpret_cast< void * >(shifts->data()), NULL, NULL); clQueues->at(clDeviceID)[0].enqueueWriteBuffer(dispersedData_d, CL_FALSE, 0, dispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dispersedData.data()), NULL, NULL); } catch ( cl::Error &err ) { std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } // Generate kernel std::string * code = PulsarSearch::getDedispersionOpenCL< dataType >(localMem, nrSamplesPerBlock, nrDMsPerBlock, nrSamplesPerThread, nrDMsPerThread, typeName, observation, *shifts); cl::Kernel * kernel; if ( print ) { std::cout << *code << std::endl; } try { kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError &err ) { std::cerr << err.what() << std::endl; return 1; } // Run OpenCL kernel and CPU control try { cl::NDRange global(observation.getNrSamplesPerPaddedSecond() / nrSamplesPerThread, observation.getNrDMs() / nrDMsPerThread); cl::NDRange local(nrSamplesPerBlock, nrDMsPerBlock); kernel->setArg(0, dispersedData_d); kernel->setArg(1, dedispersedData_d); kernel->setArg(2, shifts_d); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local); PulsarSearch::dedispersion< dataType >(observation, dispersedData, controlData, *shifts); clQueues->at(clDeviceID)[0].enqueueReadBuffer(dedispersedData_d, CL_TRUE, 0, dedispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dedispersedData.data())); } catch ( cl::Error &err ) { std::cerr << "OpenCL error kernel execution: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) { if ( !isa::utils::same(controlData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample], dedispersedData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample]) ) { wrongSamples++; } } } if ( wrongSamples > 0 ) { std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond()) << "%)." << std::endl; } else { std::cout << "TEST PASSED." << std::endl; } return 0; } <|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/chromeos/login/update_screen.h" #include "base/logging.h" #include "chrome/browser/chromeos/login/screen_observer.h" #include "chrome/browser/chromeos/login/update_view.h" namespace { // Update window should appear for at least kMinimalUpdateTime seconds. const int kMinimalUpdateTime = 3; // Progress bar increment step. const int kUpdateCheckProgressIncrement = 20; const int kUpdateCompleteProgressIncrement = 75; } // anonymous namespace namespace chromeos { UpdateScreen::UpdateScreen(WizardScreenDelegate* delegate) : DefaultViewScreen<chromeos::UpdateView>(delegate), update_result_(UPGRADE_STARTED), update_error_(GOOGLE_UPDATE_NO_ERROR), checking_for_update_(true) { } UpdateScreen::~UpdateScreen() { // Remove pointer to this object from view. if (view()) view()->set_controller(NULL); // Google Updater is holding a pointer to us until it reports status, // so we need to remove it in case we were still listening. if (google_updater_.get()) google_updater_->set_status_listener(NULL); } void UpdateScreen::OnReportResults(GoogleUpdateUpgradeResult result, GoogleUpdateErrorCode error_code, const std::wstring& version) { // Drop the last reference to the object so that it gets cleaned up here. google_updater_ = NULL; // Depending on the result decide what to do next. update_result_ = result; update_error_ = error_code; LOG(INFO) << "Update result: " << update_error_; switch (update_result_) { case UPGRADE_IS_AVAILABLE: checking_for_update_ = false; // Advance view progress bar. view()->AddProgress(kUpdateCheckProgressIncrement); // Create new Google Updater instance and install the update. google_updater_ = CreateGoogleUpdate(); google_updater_->CheckForUpdate(true, NULL); LOG(INFO) << "Installing an update"; break; case UPGRADE_SUCCESSFUL: view()->AddProgress(kUpdateCompleteProgressIncrement); // Fall through. case UPGRADE_ALREADY_UP_TO_DATE: checking_for_update_ = false; view()->AddProgress(kUpdateCheckProgressIncrement); // Fall through. case UPGRADE_ERROR: if (MinimalUpdateTimeElapsed()) { ExitUpdate(); } break; default: NOTREACHED(); } } void UpdateScreen::StartUpdate() { // Reset view. view()->Reset(); view()->set_controller(this); // Start the minimal update time timer. minimal_update_time_timer_.Start( base::TimeDelta::FromSeconds(kMinimalUpdateTime), this, &UpdateScreen::OnMinimalUpdateTimeElapsed); // Create Google Updater object and check if there is an update available. checking_for_update_ = true; google_updater_ = CreateGoogleUpdate(); google_updater_->CheckForUpdate(false, NULL); LOG(INFO) << "Checking for update"; } void UpdateScreen::CancelUpdate() { #if !defined(OFFICIAL_BUILD) update_result_ = UPGRADE_ALREADY_UP_TO_DATE; update_error_ = GOOGLE_UPDATE_NO_ERROR; ExitUpdate(); #endif } void UpdateScreen::ExitUpdate() { google_updater_->set_status_listener(NULL); google_updater_ = NULL; minimal_update_time_timer_.Stop(); ScreenObserver* observer = delegate()->GetObserver(this); if (observer) { switch (update_result_) { case UPGRADE_ALREADY_UP_TO_DATE: observer->OnExit(ScreenObserver::UPDATE_NOUPDATE); break; case UPGRADE_SUCCESSFUL: observer->OnExit(ScreenObserver::UPDATE_INSTALLED); break; case UPGRADE_ERROR: if (checking_for_update_) { observer->OnExit(ScreenObserver::UPDATE_ERROR_CHECKING_FOR_UPDATE); } else { observer->OnExit(ScreenObserver::UPDATE_ERROR_UPDATING); } break; default: NOTREACHED(); } } } bool UpdateScreen::MinimalUpdateTimeElapsed() { return !minimal_update_time_timer_.IsRunning(); } GoogleUpdate* UpdateScreen::CreateGoogleUpdate() { GoogleUpdate* updater = new GoogleUpdate(); updater->set_status_listener(this); return updater; } void UpdateScreen::OnMinimalUpdateTimeElapsed() { if (update_result_ == UPGRADE_SUCCESSFUL || update_result_ == UPGRADE_ALREADY_UP_TO_DATE || update_result_ == UPGRADE_ERROR) { ExitUpdate(); } } } // namespace chromeos <commit_msg>Fix crash on update screen. Introduced in CL http://codereview.chromium.org/2842024<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/chromeos/login/update_screen.h" #include "base/logging.h" #include "chrome/browser/chromeos/login/screen_observer.h" #include "chrome/browser/chromeos/login/update_view.h" namespace { // Update window should appear for at least kMinimalUpdateTime seconds. const int kMinimalUpdateTime = 3; // Progress bar increment step. const int kUpdateCheckProgressIncrement = 20; const int kUpdateCompleteProgressIncrement = 75; } // anonymous namespace namespace chromeos { UpdateScreen::UpdateScreen(WizardScreenDelegate* delegate) : DefaultViewScreen<chromeos::UpdateView>(delegate), update_result_(UPGRADE_STARTED), update_error_(GOOGLE_UPDATE_NO_ERROR), checking_for_update_(true) { } UpdateScreen::~UpdateScreen() { // Remove pointer to this object from view. if (view()) view()->set_controller(NULL); // Google Updater is holding a pointer to us until it reports status, // so we need to remove it in case we were still listening. if (google_updater_.get()) google_updater_->set_status_listener(NULL); } void UpdateScreen::OnReportResults(GoogleUpdateUpgradeResult result, GoogleUpdateErrorCode error_code, const std::wstring& version) { // Drop the last reference to the object so that it gets cleaned up here. if (google_updater_.get()) { google_updater_->set_status_listener(NULL); google_updater_ = NULL; } // Depending on the result decide what to do next. update_result_ = result; update_error_ = error_code; LOG(INFO) << "Update result: " << update_error_; switch (update_result_) { case UPGRADE_IS_AVAILABLE: checking_for_update_ = false; // Advance view progress bar. view()->AddProgress(kUpdateCheckProgressIncrement); // Create new Google Updater instance and install the update. google_updater_ = CreateGoogleUpdate(); google_updater_->CheckForUpdate(true, NULL); LOG(INFO) << "Installing an update"; break; case UPGRADE_SUCCESSFUL: view()->AddProgress(kUpdateCompleteProgressIncrement); // Fall through. case UPGRADE_ALREADY_UP_TO_DATE: checking_for_update_ = false; view()->AddProgress(kUpdateCheckProgressIncrement); // Fall through. case UPGRADE_ERROR: if (MinimalUpdateTimeElapsed()) { ExitUpdate(); } break; default: NOTREACHED(); } } void UpdateScreen::StartUpdate() { // Reset view. view()->Reset(); view()->set_controller(this); // Start the minimal update time timer. minimal_update_time_timer_.Start( base::TimeDelta::FromSeconds(kMinimalUpdateTime), this, &UpdateScreen::OnMinimalUpdateTimeElapsed); // Create Google Updater object and check if there is an update available. checking_for_update_ = true; google_updater_ = CreateGoogleUpdate(); google_updater_->CheckForUpdate(false, NULL); LOG(INFO) << "Checking for update"; } void UpdateScreen::CancelUpdate() { #if !defined(OFFICIAL_BUILD) update_result_ = UPGRADE_ALREADY_UP_TO_DATE; update_error_ = GOOGLE_UPDATE_NO_ERROR; ExitUpdate(); #endif } void UpdateScreen::ExitUpdate() { if (google_updater_.get()) { google_updater_->set_status_listener(NULL); google_updater_ = NULL; } minimal_update_time_timer_.Stop(); ScreenObserver* observer = delegate()->GetObserver(this); if (observer) { switch (update_result_) { case UPGRADE_ALREADY_UP_TO_DATE: observer->OnExit(ScreenObserver::UPDATE_NOUPDATE); break; case UPGRADE_SUCCESSFUL: observer->OnExit(ScreenObserver::UPDATE_INSTALLED); break; case UPGRADE_ERROR: if (checking_for_update_) { observer->OnExit(ScreenObserver::UPDATE_ERROR_CHECKING_FOR_UPDATE); } else { observer->OnExit(ScreenObserver::UPDATE_ERROR_UPDATING); } break; default: NOTREACHED(); } } } bool UpdateScreen::MinimalUpdateTimeElapsed() { return !minimal_update_time_timer_.IsRunning(); } GoogleUpdate* UpdateScreen::CreateGoogleUpdate() { GoogleUpdate* updater = new GoogleUpdate(); updater->set_status_listener(this); return updater; } void UpdateScreen::OnMinimalUpdateTimeElapsed() { if (update_result_ == UPGRADE_SUCCESSFUL || update_result_ == UPGRADE_ALREADY_UP_TO_DATE || update_result_ == UPGRADE_ERROR) { ExitUpdate(); } } } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) 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/greasemonkey_master.h" #include <fstream> #include "base/file_path.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/common/notification_service.h" #include "testing/gtest/include/gtest/gtest.h" // Test bringing up a master on a specific directory, putting a script in there, etc. class GreasemonkeyMasterTest : public testing::Test, public NotificationObserver { public: GreasemonkeyMasterTest() : shared_memory_(NULL) {} virtual void SetUp() { // Name a subdirectory of the temp directory. std::wstring path_str; ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &path_str)); script_dir_ = FilePath(path_str).Append( FILE_PATH_LITERAL("GreasemonkeyTest")); // Create a fresh, empty copy of this directory. file_util::Delete(script_dir_.value(), true); file_util::CreateDirectory(script_dir_.value()); // Register for all user script notifications. NotificationService::current()->AddObserver(this, NOTIFY_NEW_USER_SCRIPTS, NotificationService::AllSources()); } virtual void TearDown() { NotificationService::current()->RemoveObserver(this, NOTIFY_NEW_USER_SCRIPTS, NotificationService::AllSources()); // Clean up test directory. ASSERT_TRUE(file_util::Delete(script_dir_.value(), true)); ASSERT_FALSE(file_util::PathExists(script_dir_.value())); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NOTIFY_NEW_USER_SCRIPTS); shared_memory_.reset(Details<SharedMemory>(details).ptr()); if (MessageLoop::current() == &message_loop_) MessageLoop::current()->Quit(); } // MessageLoop used in tests. MessageLoop message_loop_; // Directory containing user scripts. FilePath script_dir_; // Updated to the script shared memory when we get notified. scoped_ptr<SharedMemory> shared_memory_; }; // Test that we *don't* get spurious notifications. TEST_F(GreasemonkeyMasterTest, NoScripts) { // Set shared_memory_ to something non-NULL, so we can check it became NULL. shared_memory_.reset(reinterpret_cast<SharedMemory*>(1)); scoped_refptr<GreasemonkeyMaster> master( new GreasemonkeyMaster(MessageLoop::current(), script_dir_)); message_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask); message_loop_.Run(); // There were no scripts in the script dir, so we shouldn't have gotten // a notification. ASSERT_EQ(NULL, shared_memory_.get()); } // Test that we get notified about new scripts after they're added. TEST_F(GreasemonkeyMasterTest, NewScripts) { scoped_refptr<GreasemonkeyMaster> master( new GreasemonkeyMaster(MessageLoop::current(), script_dir_)); FilePath path = script_dir_.Append(FILE_PATH_LITERAL("script.user.js")); std::ofstream file; file.open(WideToUTF8(path.value()).c_str()); file << "some content"; file.close(); message_loop_.Run(); ASSERT_TRUE(shared_memory_ != NULL); } // Test that we get notified about scripts if they're already in the test dir. TEST_F(GreasemonkeyMasterTest, ExistingScripts) { FilePath path = script_dir_.Append(FILE_PATH_LITERAL("script.user.js")); std::ofstream file; file.open(WideToUTF8(path.value()).c_str()); file << "some content"; file.close(); scoped_refptr<GreasemonkeyMaster> master( new GreasemonkeyMaster(MessageLoop::current(), script_dir_)); message_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask); message_loop_.Run(); ASSERT_TRUE(shared_memory_ != NULL); }<commit_msg>The SharedMemory is owned by the GreasemonkeyMaster, not the unit test. My previous attempt at fixing the purify problem was overzealous; I just needed to fix the uninitialized boolean that my previous "fix" did. This change halfway-reverts to before that state.<commit_after>// Copyright (c) 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/greasemonkey_master.h" #include <fstream> #include "base/file_path.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/common/notification_service.h" #include "testing/gtest/include/gtest/gtest.h" // Test bringing up a master on a specific directory, putting a script in there, etc. class GreasemonkeyMasterTest : public testing::Test, public NotificationObserver { public: GreasemonkeyMasterTest() : shared_memory_(NULL) {} virtual void SetUp() { // Name a subdirectory of the temp directory. std::wstring path_str; ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &path_str)); script_dir_ = FilePath(path_str).Append( FILE_PATH_LITERAL("GreasemonkeyTest")); // Create a fresh, empty copy of this directory. file_util::Delete(script_dir_.value(), true); file_util::CreateDirectory(script_dir_.value()); // Register for all user script notifications. NotificationService::current()->AddObserver(this, NOTIFY_NEW_USER_SCRIPTS, NotificationService::AllSources()); } virtual void TearDown() { NotificationService::current()->RemoveObserver(this, NOTIFY_NEW_USER_SCRIPTS, NotificationService::AllSources()); // Clean up test directory. ASSERT_TRUE(file_util::Delete(script_dir_.value(), true)); ASSERT_FALSE(file_util::PathExists(script_dir_.value())); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NOTIFY_NEW_USER_SCRIPTS); shared_memory_ = Details<SharedMemory>(details).ptr(); if (MessageLoop::current() == &message_loop_) MessageLoop::current()->Quit(); } // MessageLoop used in tests. MessageLoop message_loop_; // Directory containing user scripts. FilePath script_dir_; // Updated to the script shared memory when we get notified. SharedMemory* shared_memory_; }; // Test that we *don't* get spurious notifications. TEST_F(GreasemonkeyMasterTest, NoScripts) { // Set shared_memory_ to something non-NULL, so we can check it became NULL. shared_memory_ = reinterpret_cast<SharedMemory*>(1); scoped_refptr<GreasemonkeyMaster> master( new GreasemonkeyMaster(MessageLoop::current(), script_dir_)); message_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask); message_loop_.Run(); // There were no scripts in the script dir, so we shouldn't have gotten // a notification. ASSERT_EQ(NULL, shared_memory_); } // Test that we get notified about new scripts after they're added. TEST_F(GreasemonkeyMasterTest, NewScripts) { scoped_refptr<GreasemonkeyMaster> master( new GreasemonkeyMaster(MessageLoop::current(), script_dir_)); FilePath path = script_dir_.Append(FILE_PATH_LITERAL("script.user.js")); std::ofstream file; file.open(WideToUTF8(path.value()).c_str()); file << "some content"; file.close(); message_loop_.Run(); ASSERT_TRUE(shared_memory_ != NULL); } // Test that we get notified about scripts if they're already in the test dir. TEST_F(GreasemonkeyMasterTest, ExistingScripts) { FilePath path = script_dir_.Append(FILE_PATH_LITERAL("script.user.js")); std::ofstream file; file.open(WideToUTF8(path.value()).c_str()); file << "some content"; file.close(); scoped_refptr<GreasemonkeyMaster> master( new GreasemonkeyMaster(MessageLoop::current(), script_dir_)); message_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask); message_loop_.Run(); ASSERT_TRUE(shared_memory_ != NULL); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/tab_contents_drag_source.h" #include <string> #include "app/gfx/gtk_util.h" #include "app/gtk_dnd_util.h" #include "base/file_util.h" #include "base/mime_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/download/drag_download_file.h" #include "chrome/browser/download/drag_download_util.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_view_host_delegate.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "net/base/file_stream.h" #include "net/base/net_util.h" #include "webkit/glue/webdropdata.h" using WebKit::WebDragOperation; using WebKit::WebDragOperationNone; TabContentsDragSource::TabContentsDragSource( TabContentsView* tab_contents_view) : tab_contents_view_(tab_contents_view), drag_failed_(false), drag_widget_(NULL) { drag_widget_ = gtk_invisible_new(); g_signal_connect(drag_widget_, "drag-failed", G_CALLBACK(OnDragFailedThunk), this); g_signal_connect(drag_widget_, "drag-begin", G_CALLBACK(OnDragBeginThunk), this); g_signal_connect(drag_widget_, "drag-end", G_CALLBACK(OnDragEndThunk), this); g_signal_connect(drag_widget_, "drag-data-get", G_CALLBACK(OnDragDataGetThunk), this); g_object_ref_sink(drag_widget_); } TabContentsDragSource::~TabContentsDragSource() { g_signal_handlers_disconnect_by_func(drag_widget_, reinterpret_cast<gpointer>(OnDragFailedThunk), this); g_signal_handlers_disconnect_by_func(drag_widget_, reinterpret_cast<gpointer>(OnDragBeginThunk), this); g_signal_handlers_disconnect_by_func(drag_widget_, reinterpret_cast<gpointer>(OnDragEndThunk), this); g_signal_handlers_disconnect_by_func(drag_widget_, reinterpret_cast<gpointer>(OnDragDataGetThunk), this); // Break the current drag, if any. if (drop_data_.get()) { gtk_grab_add(drag_widget_); gtk_grab_remove(drag_widget_); MessageLoopForUI::current()->RemoveObserver(this); drop_data_.reset(); } gtk_widget_destroy(drag_widget_); g_object_unref(drag_widget_); drag_widget_ = NULL; } TabContents* TabContentsDragSource::tab_contents() const { return tab_contents_view_->tab_contents(); } void TabContentsDragSource::StartDragging(const WebDropData& drop_data, GdkEventButton* last_mouse_down, const SkBitmap& image, const gfx::Point& image_offset) { int targets_mask = 0; if (!drop_data.plain_text.empty()) targets_mask |= gtk_dnd_util::TEXT_PLAIN; if (drop_data.url.is_valid()) { targets_mask |= gtk_dnd_util::TEXT_URI_LIST; targets_mask |= gtk_dnd_util::CHROME_NAMED_URL; targets_mask |= gtk_dnd_util::NETSCAPE_URL; } if (!drop_data.text_html.empty()) targets_mask |= gtk_dnd_util::TEXT_HTML; if (!drop_data.file_contents.empty()) targets_mask |= gtk_dnd_util::CHROME_WEBDROP_FILE_CONTENTS; if (!drop_data.download_metadata.empty() && drag_download_util::ParseDownloadMetadata(drop_data.download_metadata, &wide_download_mime_type_, &download_file_name_, &download_url_)) { targets_mask |= gtk_dnd_util::DIRECT_SAVE_FILE; } if (targets_mask == 0) { NOTIMPLEMENTED(); if (tab_contents()->render_view_host()) tab_contents()->render_view_host()->DragSourceSystemDragEnded(); } drop_data_.reset(new WebDropData(drop_data)); drag_image_ = image; image_offset_ = image_offset; GtkTargetList* list = gtk_dnd_util::GetTargetListFromCodeMask(targets_mask); if (targets_mask & gtk_dnd_util::CHROME_WEBDROP_FILE_CONTENTS) { drag_file_mime_type_ = gdk_atom_intern( mime_util::GetDataMimeType(drop_data.file_contents).c_str(), FALSE); gtk_target_list_add(list, drag_file_mime_type_, 0, gtk_dnd_util::CHROME_WEBDROP_FILE_CONTENTS); } drag_failed_ = false; // If we don't pass an event, GDK won't know what event time to start grabbing // mouse events. Technically it's the mouse motion event and not the mouse // down event that causes the drag, but there's no reliable way to know // *which* motion event initiated the drag, so this will have to do. // TODO(estade): This can sometimes be very far off, e.g. if the user clicks // and holds and doesn't start dragging for a long time. I doubt it matters // much, but we should probably look into the possibility of getting the // initiating event from webkit. GdkDragContext* context = gtk_drag_begin( drag_widget_, list, static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_LINK), 1, // Drags are always initiated by the left button. reinterpret_cast<GdkEvent*>(last_mouse_down)); // The drag adds a ref; let it own the list. gtk_target_list_unref(list); // Sometimes the drag fails to start; |context| will be NULL and we won't // get a drag-end signal. if (!context) { drop_data_.reset(); if (tab_contents()->render_view_host()) tab_contents()->render_view_host()->DragSourceSystemDragEnded(); return; } MessageLoopForUI::current()->AddObserver(this); } void TabContentsDragSource::WillProcessEvent(GdkEvent* event) { // No-op. } void TabContentsDragSource::DidProcessEvent(GdkEvent* event) { if (event->type != GDK_MOTION_NOTIFY) return; GdkEventMotion* event_motion = reinterpret_cast<GdkEventMotion*>(event); gfx::Point client = gtk_util::ClientPoint(GetContentNativeView()); if (tab_contents()->render_view_host()) { tab_contents()->render_view_host()->DragSourceMovedTo( client.x(), client.y(), static_cast<int>(event_motion->x_root), static_cast<int>(event_motion->y_root)); } } void TabContentsDragSource::OnDragDataGet( GdkDragContext* context, GtkSelectionData* selection_data, guint target_type, guint time) { const int kBitsPerByte = 8; switch (target_type) { case gtk_dnd_util::TEXT_PLAIN: { std::string utf8_text = UTF16ToUTF8(drop_data_->plain_text); gtk_selection_data_set_text(selection_data, utf8_text.c_str(), utf8_text.length()); break; } case gtk_dnd_util::TEXT_HTML: { // TODO(estade): change relative links to be absolute using // |html_base_url|. std::string utf8_text = UTF16ToUTF8(drop_data_->text_html); gtk_selection_data_set(selection_data, gtk_dnd_util::GetAtomForTarget( gtk_dnd_util::TEXT_HTML), kBitsPerByte, reinterpret_cast<const guchar*>(utf8_text.c_str()), utf8_text.length()); break; } case gtk_dnd_util::TEXT_URI_LIST: case gtk_dnd_util::CHROME_NAMED_URL: case gtk_dnd_util::NETSCAPE_URL: { gtk_dnd_util::WriteURLWithName(selection_data, drop_data_->url, drop_data_->url_title, target_type); break; } case gtk_dnd_util::CHROME_WEBDROP_FILE_CONTENTS: { gtk_selection_data_set( selection_data, drag_file_mime_type_, kBitsPerByte, reinterpret_cast<const guchar*>(drop_data_->file_contents.data()), drop_data_->file_contents.length()); break; } case gtk_dnd_util::DIRECT_SAVE_FILE: { char status_code = 'E'; // Retrieves the full file path (in file URL format) provided by the // drop target by reading from the source window's XdndDirectSave0 // property. gint file_url_len = 0; guchar* file_url_value = NULL; if (gdk_property_get(context->source_window, gtk_dnd_util::GetAtomForTarget( gtk_dnd_util::DIRECT_SAVE_FILE), gtk_dnd_util::GetAtomForTarget( gtk_dnd_util::TEXT_PLAIN_NO_CHARSET), 0, 1024, FALSE, NULL, NULL, &file_url_len, &file_url_value) && file_url_value) { // Convert from the file url to the file path. GURL file_url(std::string(reinterpret_cast<char*>(file_url_value), file_url_len)); FilePath file_path; if (net::FileURLToFilePath(file_url, &file_path)) { // Open the file as a stream. net::FileStream* file_stream = drag_download_util::CreateFileStreamForDrop(&file_path); if (file_stream) { // Start downloading the file to the stream. TabContents* tab_contents = tab_contents_view_->tab_contents(); scoped_refptr<DragDownloadFile> drag_file_downloader = new DragDownloadFile(file_path, linked_ptr<net::FileStream>(file_stream), download_url_, tab_contents->GetURL(), tab_contents->encoding(), tab_contents); drag_file_downloader->Start( new drag_download_util::PromiseFileFinalizer( drag_file_downloader)); // Set the status code to success. status_code = 'S'; } } // Return the status code to the file manager. gtk_selection_data_set(selection_data, selection_data->target, 8, reinterpret_cast<guchar*>(&status_code), 1); } break; } default: NOTREACHED(); } } gboolean TabContentsDragSource::OnDragFailed() { drag_failed_ = true; gfx::Point root = gtk_util::ScreenPoint(GetContentNativeView()); gfx::Point client = gtk_util::ClientPoint(GetContentNativeView()); if (tab_contents()->render_view_host()) { tab_contents()->render_view_host()->DragSourceEndedAt( client.x(), client.y(), root.x(), root.y(), WebDragOperationNone); } // Let the native failure animation run. return FALSE; } void TabContentsDragSource::OnDragBegin(GdkDragContext* drag_context) { if (!download_url_.is_empty()) { // Generate the file name based on both mime type and proposed file name. std::string download_mime_type = UTF16ToUTF8(wide_download_mime_type_); std::string content_disposition("attachment; filename="); content_disposition += download_file_name_.value(); FilePath generated_download_file_name; DownloadManager::GenerateFileName(download_url_, content_disposition, std::string(), download_mime_type, &generated_download_file_name); // Pass the file name to the drop target by setting the source window's // XdndDirectSave0 property. gdk_property_change(drag_context->source_window, gtk_dnd_util::GetAtomForTarget( gtk_dnd_util::DIRECT_SAVE_FILE), gtk_dnd_util::GetAtomForTarget( gtk_dnd_util::TEXT_PLAIN_NO_CHARSET), 8, GDK_PROP_MODE_REPLACE, reinterpret_cast<const guchar*>( generated_download_file_name.value().c_str()), generated_download_file_name.value().length()); } if (!drag_image_.isNull()) { GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&drag_image_); gtk_drag_set_icon_pixbuf(drag_context, pixbuf, image_offset_.x(), image_offset_.y()); // Let the drag take ownership. g_object_unref(pixbuf); } } void TabContentsDragSource::OnDragEnd(GdkDragContext* drag_context, WebDragOperation operation) { MessageLoopForUI::current()->RemoveObserver(this); if (!download_url_.is_empty()) { gdk_property_delete(drag_context->source_window, gtk_dnd_util::GetAtomForTarget( gtk_dnd_util::DIRECT_SAVE_FILE)); } if (!drag_failed_) { gfx::Point root = gtk_util::ScreenPoint(GetContentNativeView()); gfx::Point client = gtk_util::ClientPoint(GetContentNativeView()); if (tab_contents()->render_view_host()) { tab_contents()->render_view_host()->DragSourceEndedAt( client.x(), client.y(), root.x(), root.y(), operation); } } if (tab_contents()->render_view_host()) tab_contents()->render_view_host()->DragSourceSystemDragEnded(); drop_data_.reset(); } gfx::NativeView TabContentsDragSource::GetContentNativeView() const { return tab_contents_view_->GetContentNativeView(); } <commit_msg>fixing bustage... file was moved<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/tab_contents_drag_source.h" #include <string> #include "app/gtk_dnd_util.h" #include "base/file_util.h" #include "base/mime_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/download/drag_download_file.h" #include "chrome/browser/download/drag_download_util.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_view_host_delegate.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "gfx/gtk_util.h" #include "net/base/file_stream.h" #include "net/base/net_util.h" #include "webkit/glue/webdropdata.h" using WebKit::WebDragOperation; using WebKit::WebDragOperationNone; TabContentsDragSource::TabContentsDragSource( TabContentsView* tab_contents_view) : tab_contents_view_(tab_contents_view), drag_failed_(false), drag_widget_(NULL) { drag_widget_ = gtk_invisible_new(); g_signal_connect(drag_widget_, "drag-failed", G_CALLBACK(OnDragFailedThunk), this); g_signal_connect(drag_widget_, "drag-begin", G_CALLBACK(OnDragBeginThunk), this); g_signal_connect(drag_widget_, "drag-end", G_CALLBACK(OnDragEndThunk), this); g_signal_connect(drag_widget_, "drag-data-get", G_CALLBACK(OnDragDataGetThunk), this); g_object_ref_sink(drag_widget_); } TabContentsDragSource::~TabContentsDragSource() { g_signal_handlers_disconnect_by_func(drag_widget_, reinterpret_cast<gpointer>(OnDragFailedThunk), this); g_signal_handlers_disconnect_by_func(drag_widget_, reinterpret_cast<gpointer>(OnDragBeginThunk), this); g_signal_handlers_disconnect_by_func(drag_widget_, reinterpret_cast<gpointer>(OnDragEndThunk), this); g_signal_handlers_disconnect_by_func(drag_widget_, reinterpret_cast<gpointer>(OnDragDataGetThunk), this); // Break the current drag, if any. if (drop_data_.get()) { gtk_grab_add(drag_widget_); gtk_grab_remove(drag_widget_); MessageLoopForUI::current()->RemoveObserver(this); drop_data_.reset(); } gtk_widget_destroy(drag_widget_); g_object_unref(drag_widget_); drag_widget_ = NULL; } TabContents* TabContentsDragSource::tab_contents() const { return tab_contents_view_->tab_contents(); } void TabContentsDragSource::StartDragging(const WebDropData& drop_data, GdkEventButton* last_mouse_down, const SkBitmap& image, const gfx::Point& image_offset) { int targets_mask = 0; if (!drop_data.plain_text.empty()) targets_mask |= gtk_dnd_util::TEXT_PLAIN; if (drop_data.url.is_valid()) { targets_mask |= gtk_dnd_util::TEXT_URI_LIST; targets_mask |= gtk_dnd_util::CHROME_NAMED_URL; targets_mask |= gtk_dnd_util::NETSCAPE_URL; } if (!drop_data.text_html.empty()) targets_mask |= gtk_dnd_util::TEXT_HTML; if (!drop_data.file_contents.empty()) targets_mask |= gtk_dnd_util::CHROME_WEBDROP_FILE_CONTENTS; if (!drop_data.download_metadata.empty() && drag_download_util::ParseDownloadMetadata(drop_data.download_metadata, &wide_download_mime_type_, &download_file_name_, &download_url_)) { targets_mask |= gtk_dnd_util::DIRECT_SAVE_FILE; } if (targets_mask == 0) { NOTIMPLEMENTED(); if (tab_contents()->render_view_host()) tab_contents()->render_view_host()->DragSourceSystemDragEnded(); } drop_data_.reset(new WebDropData(drop_data)); drag_image_ = image; image_offset_ = image_offset; GtkTargetList* list = gtk_dnd_util::GetTargetListFromCodeMask(targets_mask); if (targets_mask & gtk_dnd_util::CHROME_WEBDROP_FILE_CONTENTS) { drag_file_mime_type_ = gdk_atom_intern( mime_util::GetDataMimeType(drop_data.file_contents).c_str(), FALSE); gtk_target_list_add(list, drag_file_mime_type_, 0, gtk_dnd_util::CHROME_WEBDROP_FILE_CONTENTS); } drag_failed_ = false; // If we don't pass an event, GDK won't know what event time to start grabbing // mouse events. Technically it's the mouse motion event and not the mouse // down event that causes the drag, but there's no reliable way to know // *which* motion event initiated the drag, so this will have to do. // TODO(estade): This can sometimes be very far off, e.g. if the user clicks // and holds and doesn't start dragging for a long time. I doubt it matters // much, but we should probably look into the possibility of getting the // initiating event from webkit. GdkDragContext* context = gtk_drag_begin( drag_widget_, list, static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_LINK), 1, // Drags are always initiated by the left button. reinterpret_cast<GdkEvent*>(last_mouse_down)); // The drag adds a ref; let it own the list. gtk_target_list_unref(list); // Sometimes the drag fails to start; |context| will be NULL and we won't // get a drag-end signal. if (!context) { drop_data_.reset(); if (tab_contents()->render_view_host()) tab_contents()->render_view_host()->DragSourceSystemDragEnded(); return; } MessageLoopForUI::current()->AddObserver(this); } void TabContentsDragSource::WillProcessEvent(GdkEvent* event) { // No-op. } void TabContentsDragSource::DidProcessEvent(GdkEvent* event) { if (event->type != GDK_MOTION_NOTIFY) return; GdkEventMotion* event_motion = reinterpret_cast<GdkEventMotion*>(event); gfx::Point client = gtk_util::ClientPoint(GetContentNativeView()); if (tab_contents()->render_view_host()) { tab_contents()->render_view_host()->DragSourceMovedTo( client.x(), client.y(), static_cast<int>(event_motion->x_root), static_cast<int>(event_motion->y_root)); } } void TabContentsDragSource::OnDragDataGet( GdkDragContext* context, GtkSelectionData* selection_data, guint target_type, guint time) { const int kBitsPerByte = 8; switch (target_type) { case gtk_dnd_util::TEXT_PLAIN: { std::string utf8_text = UTF16ToUTF8(drop_data_->plain_text); gtk_selection_data_set_text(selection_data, utf8_text.c_str(), utf8_text.length()); break; } case gtk_dnd_util::TEXT_HTML: { // TODO(estade): change relative links to be absolute using // |html_base_url|. std::string utf8_text = UTF16ToUTF8(drop_data_->text_html); gtk_selection_data_set(selection_data, gtk_dnd_util::GetAtomForTarget( gtk_dnd_util::TEXT_HTML), kBitsPerByte, reinterpret_cast<const guchar*>(utf8_text.c_str()), utf8_text.length()); break; } case gtk_dnd_util::TEXT_URI_LIST: case gtk_dnd_util::CHROME_NAMED_URL: case gtk_dnd_util::NETSCAPE_URL: { gtk_dnd_util::WriteURLWithName(selection_data, drop_data_->url, drop_data_->url_title, target_type); break; } case gtk_dnd_util::CHROME_WEBDROP_FILE_CONTENTS: { gtk_selection_data_set( selection_data, drag_file_mime_type_, kBitsPerByte, reinterpret_cast<const guchar*>(drop_data_->file_contents.data()), drop_data_->file_contents.length()); break; } case gtk_dnd_util::DIRECT_SAVE_FILE: { char status_code = 'E'; // Retrieves the full file path (in file URL format) provided by the // drop target by reading from the source window's XdndDirectSave0 // property. gint file_url_len = 0; guchar* file_url_value = NULL; if (gdk_property_get(context->source_window, gtk_dnd_util::GetAtomForTarget( gtk_dnd_util::DIRECT_SAVE_FILE), gtk_dnd_util::GetAtomForTarget( gtk_dnd_util::TEXT_PLAIN_NO_CHARSET), 0, 1024, FALSE, NULL, NULL, &file_url_len, &file_url_value) && file_url_value) { // Convert from the file url to the file path. GURL file_url(std::string(reinterpret_cast<char*>(file_url_value), file_url_len)); FilePath file_path; if (net::FileURLToFilePath(file_url, &file_path)) { // Open the file as a stream. net::FileStream* file_stream = drag_download_util::CreateFileStreamForDrop(&file_path); if (file_stream) { // Start downloading the file to the stream. TabContents* tab_contents = tab_contents_view_->tab_contents(); scoped_refptr<DragDownloadFile> drag_file_downloader = new DragDownloadFile(file_path, linked_ptr<net::FileStream>(file_stream), download_url_, tab_contents->GetURL(), tab_contents->encoding(), tab_contents); drag_file_downloader->Start( new drag_download_util::PromiseFileFinalizer( drag_file_downloader)); // Set the status code to success. status_code = 'S'; } } // Return the status code to the file manager. gtk_selection_data_set(selection_data, selection_data->target, 8, reinterpret_cast<guchar*>(&status_code), 1); } break; } default: NOTREACHED(); } } gboolean TabContentsDragSource::OnDragFailed() { drag_failed_ = true; gfx::Point root = gtk_util::ScreenPoint(GetContentNativeView()); gfx::Point client = gtk_util::ClientPoint(GetContentNativeView()); if (tab_contents()->render_view_host()) { tab_contents()->render_view_host()->DragSourceEndedAt( client.x(), client.y(), root.x(), root.y(), WebDragOperationNone); } // Let the native failure animation run. return FALSE; } void TabContentsDragSource::OnDragBegin(GdkDragContext* drag_context) { if (!download_url_.is_empty()) { // Generate the file name based on both mime type and proposed file name. std::string download_mime_type = UTF16ToUTF8(wide_download_mime_type_); std::string content_disposition("attachment; filename="); content_disposition += download_file_name_.value(); FilePath generated_download_file_name; DownloadManager::GenerateFileName(download_url_, content_disposition, std::string(), download_mime_type, &generated_download_file_name); // Pass the file name to the drop target by setting the source window's // XdndDirectSave0 property. gdk_property_change(drag_context->source_window, gtk_dnd_util::GetAtomForTarget( gtk_dnd_util::DIRECT_SAVE_FILE), gtk_dnd_util::GetAtomForTarget( gtk_dnd_util::TEXT_PLAIN_NO_CHARSET), 8, GDK_PROP_MODE_REPLACE, reinterpret_cast<const guchar*>( generated_download_file_name.value().c_str()), generated_download_file_name.value().length()); } if (!drag_image_.isNull()) { GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&drag_image_); gtk_drag_set_icon_pixbuf(drag_context, pixbuf, image_offset_.x(), image_offset_.y()); // Let the drag take ownership. g_object_unref(pixbuf); } } void TabContentsDragSource::OnDragEnd(GdkDragContext* drag_context, WebDragOperation operation) { MessageLoopForUI::current()->RemoveObserver(this); if (!download_url_.is_empty()) { gdk_property_delete(drag_context->source_window, gtk_dnd_util::GetAtomForTarget( gtk_dnd_util::DIRECT_SAVE_FILE)); } if (!drag_failed_) { gfx::Point root = gtk_util::ScreenPoint(GetContentNativeView()); gfx::Point client = gtk_util::ClientPoint(GetContentNativeView()); if (tab_contents()->render_view_host()) { tab_contents()->render_view_host()->DragSourceEndedAt( client.x(), client.y(), root.x(), root.y(), operation); } } if (tab_contents()->render_view_host()) tab_contents()->render_view_host()->DragSourceSystemDragEnded(); drop_data_.reset(); } gfx::NativeView TabContentsDragSource::GetContentNativeView() const { return tab_contents_view_->GetContentNativeView(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2018 the MRtrix3 contributors. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/ * * MRtrix3 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * For more details, see http://www.mrtrix.org/ */ #include "connectome/lut.h" #include <fstream> #include "mrtrix.h" // For strip() namespace MR { namespace Connectome { LUT::LUT (const std::string& path) : exclusive (true) { load (path); } void LUT::load (const std::string& path) { file_format format = LUT_NONE; try { format = guess_file_format (path); } catch (Exception& e) { throw e; } std::ifstream in_lut (path, std::ios_base::in); if (!in_lut) throw Exception ("Unable to open lookup table file"); std::string line; while (std::getline (in_lut, line)) { if (line.size() > 1 && line[0] != '#') { switch (format) { case LUT_BASIC: parse_line_basic (line); break; case LUT_FREESURFER: parse_line_freesurfer (line); break; case LUT_AAL: parse_line_aal (line); break; case LUT_ITKSNAP: parse_line_itksnap (line); break; case LUT_MRTRIX: parse_line_mrtrix (line); break; default: assert (0); } } line.clear(); } } LUT::file_format LUT::guess_file_format (const std::string& path) { class Column { NOMEMALIGN public: Column () : numeric (true), integer (true), min (std::numeric_limits<default_type>::infinity()), max (-std::numeric_limits<default_type>::infinity()), sum_lengths (0), count (0) { } void operator() (const std::string& entry) { try { const default_type value = to<default_type> (entry); min = std::min (min, value); max = std::max (max, value); } catch (...) { numeric = integer = false; } if (entry.find ('.') != std::string::npos) integer = false; sum_lengths += entry.size(); ++count; } default_type mean_length() const { return sum_lengths / default_type(count); } bool is_numeric() const { return numeric; } bool is_integer() const { return integer; } bool is_unary_range_float() const { return is_numeric() && min >= 0.0 && max <= 1.0; } bool is_8bit() const { return is_integer() && min >= 0 && max <= 255; } operator std::string() const { if (!is_numeric()) return "text"; if (is_integer()) { if (is_8bit()) return "8bit_integer"; else return "integer"; } if (is_unary_range_float()) return "unary_float"; else return "float"; assert (0); } private: bool numeric, integer; default_type min, max; size_t sum_lengths, count; }; std::ifstream in_lut (path, std::ios_base::in); if (!in_lut) throw Exception ("Unable to open lookup table file"); vector<Column> columns; std::string line; size_t line_counter = 0; while (std::getline (in_lut, line)) { ++line_counter; if (line.size() > 1 && line[0] != '#') { // Before splitting by whitespace, need to capture any strings that are // encased within quotation marks auto split_by_quotes = split (line, "\"\'", false); if (!(split_by_quotes.size()%2)) throw Exception ("Line " + str(line_counter) + " of LUT file \"" + Path::basename (path) + "\" contains an odd number of quotation marks, and hence cannot be properly split up according to quotation marks"); decltype(split_by_quotes) entries; for (size_t i = 0; i != split_by_quotes.size(); ++i) { // Every second line must be encased in quotation marks, and is // therefore preserved without splitting if (i % 2) { entries.push_back (split_by_quotes[i]); } else { const auto block_split = split(split_by_quotes[i], "\t ,", true); entries.insert (entries.end(), block_split.begin(), block_split.end()); } } for (decltype(entries)::iterator i = entries.begin(); i != entries.end();) { if (!i->size() || (i->size() == 1 && std::isspace ((*i)[0]))) i = entries.erase (i); else ++i; } if (entries.size()) { if (columns.size() && entries.size() != columns.size()) { Exception E ("Inconsistent number of columns in LUT file \"" + Path::basename (path) + "\""); E.push_back ("Initial file contents contain " + str(columns.size()) + " columns, but line " + str(line_counter) + " contains " + str(entries.size()) + " entries:"); E.push_back ("\"" + line + "\""); throw E; } if (columns.empty()) columns.resize (entries.size()); for (size_t c = 0; c != columns.size(); ++c) columns[c] (entries[c]); } } } // Make an assessment of the LUT format if (columns.size() == 2 && columns[0].is_integer() && !columns[1].is_numeric()) { DEBUG ("LUT file \"" + Path::basename (path) + "\" contains 1 integer, 1 string per line: Basic format"); return LUT_BASIC; } if (columns.size() == 6 && columns[0].is_integer() && !columns[1].is_numeric() && columns[2].is_8bit() && columns[3].is_8bit() && columns[4].is_8bit() && columns[5].is_8bit()) { DEBUG ("LUT file \"" + Path::basename (path) + "\" contains 1 integer, 1 string, then 4 8-bit integers per line: Freesurfer format"); return LUT_FREESURFER; } if (columns.size() == 3 && !columns[0].is_numeric() && !columns[1].is_numeric() && columns[0].mean_length() < columns[1].mean_length() && columns[2].is_integer()) { DEBUG ("LUT file \"" + Path::basename (path) + "\" contains 2 strings (shorter first), then an integer per line: AAL format"); return LUT_AAL; } if (columns.size() == 8 && columns[0].is_integer() && columns[1].is_8bit() && columns[2].is_8bit() && columns[3].is_8bit() && columns[4].is_unary_range_float() && columns[5].is_integer() && columns[6].is_integer() && !columns[7].is_numeric()) { DEBUG ("LUT file \"" + Path::basename (path) + "\" contains an integer, 3 8-bit integers, a float, two integers, and a string per line: ITKSNAP format"); return LUT_ITKSNAP; } if (columns.size() == 7 && columns[0].is_integer() && !columns[1].is_numeric() && !columns[2].is_numeric() && columns[1].mean_length() < columns[2].mean_length() && columns[3].is_8bit() && columns[4].is_8bit() && columns[5].is_8bit() && columns[6].is_8bit()) { DEBUG ("LUT file \"" + Path::basename (path) + "\" contains 1 integer, 2 strings (shortest first), then 4 8-bit integers per line: MRtrix format"); return LUT_MRTRIX; } std::string format_string; format_string += "[ "; for (auto c : columns) format_string += std::string (c) + " "; format_string += "]"; Exception e ("LUT file \"" + Path::basename (path) + "\" in unrecognized format:"); e.push_back (format_string); throw e; return LUT_NONE; } void LUT::parse_line_basic (const std::string& line) { node_t index = std::numeric_limits<node_t>::max(); char name [80]; sscanf (line.c_str(), "%u%*[ ,]%s", &index, name); if (index != std::numeric_limits<node_t>::max()) { const std::string strname (strip(name, " \t\n\"")); check_and_insert (index, LUT_node (strname)); } } void LUT::parse_line_freesurfer (const std::string& line) { node_t index = std::numeric_limits<node_t>::max(); node_t r = 256, g = 256, b = 256, a = 255; char name [80]; sscanf (line.c_str(), "%u%*[ ,]%s%*[ ,]%u%*[ ,]%u%*[ ,]%u%*[ ,]%u", &index, name, &r, &g, &b, &a); if (index != std::numeric_limits<node_t>::max()) { const std::string strname (strip(name, " \t\n\"")); check_and_insert (index, LUT_node (strname, r, g, b, a)); } } void LUT::parse_line_aal (const std::string& line) { node_t index = std::numeric_limits<node_t>::max(); char short_name[20], name [80]; sscanf (line.c_str(), "%s%*[ ,]%s%*[ ,]%u", short_name, name, &index); if (index != std::numeric_limits<node_t>::max()) { const std::string strshortname (strip(short_name, " \t\n\"")); const std::string strname (strip(name, " \t\n\"")); check_and_insert (index, LUT_node (strname, strshortname)); } } void LUT::parse_line_itksnap (const std::string& line) { node_t index = std::numeric_limits<node_t>::max(); node_t r = 256, g = 256, b = 256; float a = 1.0; unsigned int label_vis = 0, mesh_vis = 0; char name [80]; sscanf (line.c_str(), "%u%*[ ,]%u%*[ ,]%u%*[ ,]%u%*[ ,]%f%*[ ,]%u%*[ ,]%u%*[ ,]%s", &index, &r, &g, &b, &a, &label_vis, &mesh_vis, name); if (index != std::numeric_limits<node_t>::max()) { std::string strname (strip(name, " \t\n\"")); check_and_insert (index, LUT_node (strname, r, g, b, uint8_t(a*255.0))); } } void LUT::parse_line_mrtrix (const std::string& line) { node_t index = std::numeric_limits<node_t>::max(); node_t r = 256, g = 256, b = 256, a = 255; char short_name[20], name[80]; sscanf (line.c_str(), "%u%*[ ,]%s%*[ ,]%s%*[ ,]%u%*[ ,]%u%*[ ,]%u%*[ ,]%u", &index, short_name, name, &r, &g, &b, &a); if (index != std::numeric_limits<node_t>::max()) { const std::string strshortname (strip(short_name, " \t\n\"")); const std::string strname (strip(name, " \t\n\"")); check_and_insert (index, LUT_node (strname, strshortname, r, g, b, a)); } } void LUT::check_and_insert (const node_t index, const LUT_node& data) { if (find (index) != end()) exclusive = false; insert (std::make_pair (index, data)); } vector<node_t> get_lut_mapping (const LUT& in, const LUT& out) { if (in.empty()) return vector<node_t>(); vector<node_t> map (in.rbegin()->first + 1, 0); for (const auto& node_in : in) { node_t target = 0; for (const auto& node_out : out) { if (node_out.second.get_name() == node_in.second.get_name()) { if (target) { throw Exception ("Cannot perform LUT conversion: Node " + str(node_in.first) + " (" + node_in.second.get_name() + ") has multiple possible targets"); return vector<node_t> (); } target = node_out.first; break; } } if (target) map[node_in.first] = target; } return map; } } } <commit_msg>Connectome LUT: Remove attempted support for comma delimiters<commit_after>/* * Copyright (c) 2008-2018 the MRtrix3 contributors. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/ * * MRtrix3 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * For more details, see http://www.mrtrix.org/ */ #include "connectome/lut.h" #include <fstream> #include "mrtrix.h" // For strip() namespace MR { namespace Connectome { LUT::LUT (const std::string& path) : exclusive (true) { load (path); } void LUT::load (const std::string& path) { file_format format = LUT_NONE; try { format = guess_file_format (path); } catch (Exception& e) { throw e; } std::ifstream in_lut (path, std::ios_base::in); if (!in_lut) throw Exception ("Unable to open lookup table file"); std::string line; while (std::getline (in_lut, line)) { if (line.size() > 1 && line[0] != '#') { switch (format) { case LUT_BASIC: parse_line_basic (line); break; case LUT_FREESURFER: parse_line_freesurfer (line); break; case LUT_AAL: parse_line_aal (line); break; case LUT_ITKSNAP: parse_line_itksnap (line); break; case LUT_MRTRIX: parse_line_mrtrix (line); break; default: assert (0); } } line.clear(); } } LUT::file_format LUT::guess_file_format (const std::string& path) { class Column { NOMEMALIGN public: Column () : numeric (true), integer (true), min (std::numeric_limits<default_type>::infinity()), max (-std::numeric_limits<default_type>::infinity()), sum_lengths (0), count (0) { } void operator() (const std::string& entry) { try { const default_type value = to<default_type> (entry); min = std::min (min, value); max = std::max (max, value); } catch (...) { numeric = integer = false; } if (entry.find ('.') != std::string::npos) integer = false; sum_lengths += entry.size(); ++count; } default_type mean_length() const { return sum_lengths / default_type(count); } bool is_numeric() const { return numeric; } bool is_integer() const { return integer; } bool is_unary_range_float() const { return is_numeric() && min >= 0.0 && max <= 1.0; } bool is_8bit() const { return is_integer() && min >= 0 && max <= 255; } operator std::string() const { if (!is_numeric()) return "text"; if (is_integer()) { if (is_8bit()) return "8bit_integer"; else return "integer"; } if (is_unary_range_float()) return "unary_float"; else return "float"; assert (0); } private: bool numeric, integer; default_type min, max; size_t sum_lengths, count; }; std::ifstream in_lut (path, std::ios_base::in); if (!in_lut) throw Exception ("Unable to open lookup table file"); vector<Column> columns; std::string line; size_t line_counter = 0; while (std::getline (in_lut, line)) { ++line_counter; if (line.size() > 1 && line[0] != '#') { // Before splitting by whitespace, need to capture any strings that are // encased within quotation marks auto split_by_quotes = split (line, "\"\'", false); if (!(split_by_quotes.size()%2)) throw Exception ("Line " + str(line_counter) + " of LUT file \"" + Path::basename (path) + "\" contains an odd number of quotation marks, and hence cannot be properly split up according to quotation marks"); decltype(split_by_quotes) entries; for (size_t i = 0; i != split_by_quotes.size(); ++i) { // Every second line must be encased in quotation marks, and is // therefore preserved without splitting if (i % 2) { entries.push_back (split_by_quotes[i]); } else { const auto block_split = split(split_by_quotes[i], "\t ", true); entries.insert (entries.end(), block_split.begin(), block_split.end()); } } for (decltype(entries)::iterator i = entries.begin(); i != entries.end();) { if (!i->size() || (i->size() == 1 && std::isspace ((*i)[0]))) i = entries.erase (i); else ++i; } if (entries.size()) { if (columns.size() && entries.size() != columns.size()) { Exception E ("Inconsistent number of columns in LUT file \"" + Path::basename (path) + "\""); E.push_back ("Initial file contents contain " + str(columns.size()) + " columns, but line " + str(line_counter) + " contains " + str(entries.size()) + " entries:"); E.push_back ("\"" + line + "\""); throw E; } if (columns.empty()) columns.resize (entries.size()); for (size_t c = 0; c != columns.size(); ++c) columns[c] (entries[c]); } } } // Make an assessment of the LUT format if (columns.size() == 2 && columns[0].is_integer() && !columns[1].is_numeric()) { DEBUG ("LUT file \"" + Path::basename (path) + "\" contains 1 integer, 1 string per line: Basic format"); return LUT_BASIC; } if (columns.size() == 6 && columns[0].is_integer() && !columns[1].is_numeric() && columns[2].is_8bit() && columns[3].is_8bit() && columns[4].is_8bit() && columns[5].is_8bit()) { DEBUG ("LUT file \"" + Path::basename (path) + "\" contains 1 integer, 1 string, then 4 8-bit integers per line: Freesurfer format"); return LUT_FREESURFER; } if (columns.size() == 3 && !columns[0].is_numeric() && !columns[1].is_numeric() && columns[0].mean_length() < columns[1].mean_length() && columns[2].is_integer()) { DEBUG ("LUT file \"" + Path::basename (path) + "\" contains 2 strings (shorter first), then an integer per line: AAL format"); return LUT_AAL; } if (columns.size() == 8 && columns[0].is_integer() && columns[1].is_8bit() && columns[2].is_8bit() && columns[3].is_8bit() && columns[4].is_unary_range_float() && columns[5].is_integer() && columns[6].is_integer() && !columns[7].is_numeric()) { DEBUG ("LUT file \"" + Path::basename (path) + "\" contains an integer, 3 8-bit integers, a float, two integers, and a string per line: ITKSNAP format"); return LUT_ITKSNAP; } if (columns.size() == 7 && columns[0].is_integer() && !columns[1].is_numeric() && !columns[2].is_numeric() && columns[1].mean_length() < columns[2].mean_length() && columns[3].is_8bit() && columns[4].is_8bit() && columns[5].is_8bit() && columns[6].is_8bit()) { DEBUG ("LUT file \"" + Path::basename (path) + "\" contains 1 integer, 2 strings (shortest first), then 4 8-bit integers per line: MRtrix format"); return LUT_MRTRIX; } std::string format_string; format_string += "[ "; for (auto c : columns) format_string += std::string (c) + " "; format_string += "]"; Exception e ("LUT file \"" + Path::basename (path) + "\" in unrecognized format:"); e.push_back (format_string); throw e; return LUT_NONE; } void LUT::parse_line_basic (const std::string& line) { node_t index = std::numeric_limits<node_t>::max(); char name [80]; sscanf (line.c_str(), "%u %s", &index, name); if (index != std::numeric_limits<node_t>::max()) { const std::string strname (strip(name, " \t\n\"")); check_and_insert (index, LUT_node (strname)); } } void LUT::parse_line_freesurfer (const std::string& line) { node_t index = std::numeric_limits<node_t>::max(); node_t r = 256, g = 256, b = 256, a = 255; char name [80]; sscanf (line.c_str(), "%u %s %u %u %u %u", &index, name, &r, &g, &b, &a); if (index != std::numeric_limits<node_t>::max()) { const std::string strname (strip(name, " \t\n\"")); check_and_insert (index, LUT_node (strname, r, g, b, a)); } } void LUT::parse_line_aal (const std::string& line) { node_t index = std::numeric_limits<node_t>::max(); char short_name[20], name [80]; sscanf (line.c_str(), "%s %s %u", short_name, name, &index); if (index != std::numeric_limits<node_t>::max()) { const std::string strshortname (strip(short_name, " \t\n\"")); const std::string strname (strip(name, " \t\n\"")); check_and_insert (index, LUT_node (strname, strshortname)); } } void LUT::parse_line_itksnap (const std::string& line) { node_t index = std::numeric_limits<node_t>::max(); node_t r = 256, g = 256, b = 256; float a = 1.0; unsigned int label_vis = 0, mesh_vis = 0; char name [80]; sscanf (line.c_str(), "%u %u %u %u %f %u %u %s", &index, &r, &g, &b, &a, &label_vis, &mesh_vis, name); if (index != std::numeric_limits<node_t>::max()) { std::string strname (strip(name, " \t\n\"")); check_and_insert (index, LUT_node (strname, r, g, b, uint8_t(a*255.0))); } } void LUT::parse_line_mrtrix (const std::string& line) { node_t index = std::numeric_limits<node_t>::max(); node_t r = 256, g = 256, b = 256, a = 255; char short_name[20], name[80]; sscanf (line.c_str(), "%u %s %s %u %u %u %u", &index, short_name, name, &r, &g, &b, &a); if (index != std::numeric_limits<node_t>::max()) { const std::string strshortname (strip(short_name, " \t\n\"")); const std::string strname (strip(name, " \t\n\"")); check_and_insert (index, LUT_node (strname, strshortname, r, g, b, a)); } } void LUT::check_and_insert (const node_t index, const LUT_node& data) { if (find (index) != end()) exclusive = false; insert (std::make_pair (index, data)); } vector<node_t> get_lut_mapping (const LUT& in, const LUT& out) { if (in.empty()) return vector<node_t>(); vector<node_t> map (in.rbegin()->first + 1, 0); for (const auto& node_in : in) { node_t target = 0; for (const auto& node_out : out) { if (node_out.second.get_name() == node_in.second.get_name()) { if (target) { throw Exception ("Cannot perform LUT conversion: Node " + str(node_in.first) + " (" + node_in.second.get_name() + ") has multiple possible targets"); return vector<node_t> (); } target = node_out.first; break; } } if (target) map[node_in.first] = target; } return map; } } } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #define N 70 int main(int argc, char *argv[]){ int primo[N]; int primo_siguiente = 1; // Indica el numero de celda en el //que guardar el siguiente primo. primo[0] = 2; /** * Mientras no tenga 70 primos * Cojo un candidato_a_primo * Mientras no encuentre un divisor para el candidato a primo * sigo diviendo haste el 2 (en la celda 0) * * Si he llegado hasta el dos y ninguno lo ha dividido * entonces lo añado como primo_siguiente */ /* * +---+---+---+ * | 2 | 3 | 5 | * +---+---+---+ * 0 1 2 * * primo_siguiente => 3 */ for(int candidato = 3; primo_siguiente < N; candidato++){ bool puede_ser_primo = true; for (int posicion_primo=0; puede_ser_primo && posicion_primo < primo_siguiente; posicion_primo++) if (candidato % primo[posicion_primo] == 0) puede_ser_primo = false; if (puede_ser_primo) primo[primo_siguiente++] = candidato; } for(int i=0; i<N; i++) printf("%i ", primo[i]); printf("\n"); return EXIT_SUCCESS; } <commit_msg>Delete primes.cpp<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/print_web_view_helper.h" #include "base/file_descriptor_posix.h" #include "base/logging.h" #include "chrome/common/render_messages.h" #include "printing/native_metafile.h" #include "printing/units.h" #include "skia/ext/vector_canvas.h" #include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/WebKit/chromium/public/WebSize.h" using printing::NativeMetafile; using WebKit::WebFrame; using WebKit::WebSize; static void FillDefaultPrintParams(ViewMsg_Print_Params* params) { // TODO(myhuang): Get printing parameters via IPC // using the print_web_view_helper.cc version of Print. // For testing purpose, we hard-coded printing parameters here. // The paper size is US Letter (8.5 in. by 11 in.). double page_width_in_pixel = 8.5 * printing::kPixelsPerInch; double page_height_in_pixel = 11.0 * printing::kPixelsPerInch; params->page_size = gfx::Size( static_cast<int>(page_width_in_pixel), static_cast<int>(page_height_in_pixel)); params->printable_size = gfx::Size( static_cast<int>( page_width_in_pixel - (NativeMetafile::kLeftMarginInInch + NativeMetafile::kRightMarginInInch) * printing::kPixelsPerInch), static_cast<int>( page_height_in_pixel - (NativeMetafile::kTopMarginInInch + NativeMetafile::kBottomMarginInInch) * printing::kPixelsPerInch)); params->margin_top = static_cast<int>( NativeMetafile::kTopMarginInInch * printing::kPixelsPerInch); params->margin_left = static_cast<int>( NativeMetafile::kLeftMarginInInch * printing::kPixelsPerInch); params->dpi = printing::kPixelsPerInch; } void PrintWebViewHelper::Print(WebFrame* frame, bool script_initiated) { // If still not finished with earlier print request simply ignore. if (IsPrinting()) return; ViewMsg_Print_Params default_settings; FillDefaultPrintParams(&default_settings); double content_width, content_height; GetPageSizeAndMarginsInPoints(frame, 0, default_settings, &content_width, &content_height, NULL, NULL, NULL, NULL); default_settings.dpi = printing::kPointsPerInch; default_settings.min_shrink = 1.25; default_settings.max_shrink = 2.0; default_settings.desired_dpi = printing::kPointsPerInch; default_settings.document_cookie = 0; default_settings.selection_only = false; default_settings.printable_size = gfx::Size( static_cast<int>(content_width), static_cast<int>(content_height)); ViewMsg_PrintPages_Params print_settings; print_settings.params = default_settings; PrintPages(print_settings, frame); } void PrintWebViewHelper::PrintPages(const ViewMsg_PrintPages_Params& params, WebFrame* frame) { PrepareFrameAndViewForPrint prep_frame_view(params.params, frame, frame->view()); int page_count = prep_frame_view.GetExpectedPageCount(); // TODO(myhuang): Send ViewHostMsg_DidGetPrintedPagesCount. if (page_count == 0) return; // We only can use PDF in the renderer because Cairo needs to create a // temporary file for a PostScript surface. printing::NativeMetafile metafile(printing::NativeMetafile::PDF); metafile.Init(); ViewMsg_PrintPage_Params print_page_params; print_page_params.params = params.params; const gfx::Size& canvas_size = prep_frame_view.GetPrintCanvasSize(); if (params.pages.empty()) { for (int i = 0; i < page_count; ++i) { print_page_params.page_number = i; PrintPage(print_page_params, canvas_size, frame, &metafile); } } else { for (size_t i = 0; i < params.pages.size(); ++i) { print_page_params.page_number = params.pages[i]; PrintPage(print_page_params, canvas_size, frame, &metafile); } } metafile.Close(); // Get the size of the resulting metafile. uint32 buf_size = metafile.GetDataSize(); DCHECK_GT(buf_size, 0u); base::FileDescriptor fd; int fd_in_browser = -1; // Ask the browser to open a file for us. if (!Send(new ViewHostMsg_AllocateTempFileForPrinting(&fd, &fd_in_browser))) { return; } if (!metafile.SaveTo(fd)) return; // Tell the browser we've finished writing the file. Send(new ViewHostMsg_TempFileForPrintingWritten(fd_in_browser)); } void PrintWebViewHelper::PrintPage(const ViewMsg_PrintPage_Params& params, const gfx::Size& canvas_size, WebFrame* frame, printing::NativeMetafile* metafile) { ViewMsg_Print_Params default_params; FillDefaultPrintParams(&default_params); double content_width_in_points; double content_height_in_points; double margin_top_in_points; double margin_right_in_points; double margin_bottom_in_points; double margin_left_in_points; GetPageSizeAndMarginsInPoints(frame, params.page_number, default_params, &content_width_in_points, &content_height_in_points, &margin_top_in_points, &margin_right_in_points, &margin_bottom_in_points, &margin_left_in_points); cairo_t* cairo_context = metafile->StartPage(content_width_in_points, content_height_in_points, margin_top_in_points, margin_right_in_points, margin_bottom_in_points, margin_left_in_points); if (!cairo_context) return; skia::VectorCanvas canvas(cairo_context, canvas_size.width(), canvas_size.height()); frame->printPage(params.page_number, &canvas); // TODO(myhuang): We should handle transformation for paper margins. // TODO(myhuang): We should render the header and the footer. // Done printing. Close the device context to retrieve the compiled metafile. if (!metafile->FinishPage()) NOTREACHED() << "metafile failed"; } <commit_msg>Linux fix for Issue 50340: @page rules inside @media print rules are not properly handled<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/print_web_view_helper.h" #include "base/file_descriptor_posix.h" #include "base/logging.h" #include "chrome/common/render_messages.h" #include "printing/native_metafile.h" #include "printing/units.h" #include "skia/ext/vector_canvas.h" #include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/WebKit/chromium/public/WebSize.h" using printing::NativeMetafile; using WebKit::WebFrame; using WebKit::WebSize; static void FillDefaultPrintParams(ViewMsg_Print_Params* params) { // TODO(myhuang): Get printing parameters via IPC // using the print_web_view_helper.cc version of Print. // For testing purpose, we hard-coded printing parameters here. // The paper size is US Letter (8.5 in. by 11 in.). double page_width_in_pixel = 8.5 * printing::kPixelsPerInch; double page_height_in_pixel = 11.0 * printing::kPixelsPerInch; params->page_size = gfx::Size( static_cast<int>(page_width_in_pixel), static_cast<int>(page_height_in_pixel)); params->printable_size = gfx::Size( static_cast<int>( page_width_in_pixel - (NativeMetafile::kLeftMarginInInch + NativeMetafile::kRightMarginInInch) * printing::kPixelsPerInch), static_cast<int>( page_height_in_pixel - (NativeMetafile::kTopMarginInInch + NativeMetafile::kBottomMarginInInch) * printing::kPixelsPerInch)); params->margin_top = static_cast<int>( NativeMetafile::kTopMarginInInch * printing::kPixelsPerInch); params->margin_left = static_cast<int>( NativeMetafile::kLeftMarginInInch * printing::kPixelsPerInch); params->dpi = printing::kPixelsPerInch; params->desired_dpi = params->dpi; } void PrintWebViewHelper::Print(WebFrame* frame, bool script_initiated) { // If still not finished with earlier print request simply ignore. if (IsPrinting()) return; ViewMsg_Print_Params default_settings; FillDefaultPrintParams(&default_settings); double content_width, content_height; { // PrepareFrameAndViewForPrint instance must be destructed before calling // PrintPages where another instance is created. PrepareFrameAndViewForPrint prepare(default_settings, frame, frame->view()); GetPageSizeAndMarginsInPoints(frame, 0, default_settings, &content_width, &content_height, NULL, NULL, NULL, NULL); } default_settings.dpi = printing::kPointsPerInch; default_settings.min_shrink = 1.25; default_settings.max_shrink = 2.0; default_settings.desired_dpi = printing::kPointsPerInch; default_settings.document_cookie = 0; default_settings.selection_only = false; default_settings.printable_size = gfx::Size( static_cast<int>(content_width), static_cast<int>(content_height)); ViewMsg_PrintPages_Params print_settings; print_settings.params = default_settings; PrintPages(print_settings, frame); } void PrintWebViewHelper::PrintPages(const ViewMsg_PrintPages_Params& params, WebFrame* frame) { PrepareFrameAndViewForPrint prep_frame_view(params.params, frame, frame->view()); int page_count = prep_frame_view.GetExpectedPageCount(); // TODO(myhuang): Send ViewHostMsg_DidGetPrintedPagesCount. if (page_count == 0) return; // We only can use PDF in the renderer because Cairo needs to create a // temporary file for a PostScript surface. printing::NativeMetafile metafile(printing::NativeMetafile::PDF); metafile.Init(); ViewMsg_PrintPage_Params print_page_params; print_page_params.params = params.params; const gfx::Size& canvas_size = prep_frame_view.GetPrintCanvasSize(); if (params.pages.empty()) { for (int i = 0; i < page_count; ++i) { print_page_params.page_number = i; PrintPage(print_page_params, canvas_size, frame, &metafile); } } else { for (size_t i = 0; i < params.pages.size(); ++i) { print_page_params.page_number = params.pages[i]; PrintPage(print_page_params, canvas_size, frame, &metafile); } } metafile.Close(); // Get the size of the resulting metafile. uint32 buf_size = metafile.GetDataSize(); DCHECK_GT(buf_size, 0u); base::FileDescriptor fd; int fd_in_browser = -1; // Ask the browser to open a file for us. if (!Send(new ViewHostMsg_AllocateTempFileForPrinting(&fd, &fd_in_browser))) { return; } if (!metafile.SaveTo(fd)) return; // Tell the browser we've finished writing the file. Send(new ViewHostMsg_TempFileForPrintingWritten(fd_in_browser)); } void PrintWebViewHelper::PrintPage(const ViewMsg_PrintPage_Params& params, const gfx::Size& canvas_size, WebFrame* frame, printing::NativeMetafile* metafile) { ViewMsg_Print_Params default_params; FillDefaultPrintParams(&default_params); double content_width_in_points; double content_height_in_points; double margin_top_in_points; double margin_right_in_points; double margin_bottom_in_points; double margin_left_in_points; GetPageSizeAndMarginsInPoints(frame, params.page_number, default_params, &content_width_in_points, &content_height_in_points, &margin_top_in_points, &margin_right_in_points, &margin_bottom_in_points, &margin_left_in_points); cairo_t* cairo_context = metafile->StartPage(content_width_in_points, content_height_in_points, margin_top_in_points, margin_right_in_points, margin_bottom_in_points, margin_left_in_points); if (!cairo_context) return; skia::VectorCanvas canvas(cairo_context, canvas_size.width(), canvas_size.height()); frame->printPage(params.page_number, &canvas); // TODO(myhuang): We should handle transformation for paper margins. // TODO(myhuang): We should render the header and the footer. // Done printing. Close the device context to retrieve the compiled metafile. if (!metafile->FinishPage()) NOTREACHED() << "metafile failed"; } <|endoftext|>
<commit_before>#include "Engine.h" #include <iostream> #include "Supernova.h" #include "lua.h" #include "lualib.h" #include "lauxlib.h" #include "Scene.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include "Events.h" #include "math/Rect.h" #include "platform/Log.h" #include "LuaBind.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "Mesh.h" #include "InputCode.h" #include "audio/SoundManager.h" using namespace Supernova; Scene *Engine::mainScene; int Engine::screenWidth; int Engine::screenHeight; int Engine::canvasWidth; int Engine::canvasHeight; int Engine::preferedCanvasWidth; int Engine::preferedCanvasHeight; Rect Engine::viewRect; int Engine::renderAPI; bool Engine::mouseAsTouch; bool Engine::useDegrees; int Engine::scalingMode; bool Engine::nearestScaleTexture; unsigned long Engine::lastTime = 0; unsigned int Engine::updateTimeCount = 0; unsigned int Engine::frametime = 0; float Engine::deltatime = 0; float Engine::framerate = 0; unsigned int Engine::updateTime = 20; Engine::Engine() { } Engine::~Engine() { } void Engine::setScene(Scene *mainScene){ Engine::mainScene = mainScene; } Scene* Engine::getScene(){ return mainScene; } int Engine::getScreenWidth(){ return Engine::screenWidth; } int Engine::getScreenHeight(){ return Engine::screenHeight; } void Engine::setScreenSize(int screenWidth, int screenHeight){ Engine::screenWidth = screenWidth; Engine::screenHeight = screenHeight; if ((Engine::preferedCanvasWidth != 0) && (Engine::preferedCanvasHeight != 0)){ setCanvasSize(preferedCanvasWidth, preferedCanvasHeight); } } int Engine::getCanvasWidth(){ return Engine::canvasWidth; } int Engine::getCanvasHeight(){ return Engine::canvasHeight; } void Engine::setCanvasSize(int canvasWidth, int canvasHeight){ Engine::canvasWidth = canvasWidth; Engine::canvasHeight = canvasHeight; if ((Engine::screenWidth == 0) || (Engine::screenHeight == 0)){ setScreenSize(canvasWidth, canvasHeight); } //When canvas size is changed if (scalingMode == S_SCALING_FITWIDTH){ Engine::canvasWidth = canvasWidth; Engine::canvasHeight = screenHeight * canvasWidth / screenWidth; } if (scalingMode == S_SCALING_FITHEIGHT){ Engine::canvasHeight = canvasHeight; Engine::canvasWidth = screenWidth * canvasHeight / screenHeight; } if ((Engine::preferedCanvasWidth == 0) && (Engine::preferedCanvasHeight == 0)){ setPreferedCanvasSize(canvasWidth, canvasHeight); } } int Engine::getPreferedCanvasWidth(){ return Engine::preferedCanvasWidth; } int Engine::getPreferedCanvasHeight(){ return Engine::preferedCanvasHeight; } void Engine::setPreferedCanvasSize(int preferedCanvasWidth, int preferedCanvasHeight){ if ((Engine::preferedCanvasWidth == 0) && (Engine::preferedCanvasHeight == 0)){ Engine::preferedCanvasWidth = preferedCanvasWidth; Engine::preferedCanvasHeight = preferedCanvasHeight; } } Rect* Engine::getViewRect(){ return &viewRect; } void Engine::setRenderAPI(int renderAPI){ Engine::renderAPI = renderAPI; } int Engine::getRenderAPI(){ return renderAPI; } void Engine::setScalingMode(int scalingMode){ Engine::scalingMode = scalingMode; } int Engine::getScalingMode(){ return scalingMode; } void Engine::setMouseAsTouch(bool mouseAsTouch){ Engine::mouseAsTouch = mouseAsTouch; } bool Engine::isMouseAsTouch(){ return Engine::mouseAsTouch; } void Engine::setUseDegrees(bool useDegrees){ Engine::useDegrees = useDegrees; } bool Engine::isUseDegrees(){ return Engine::useDegrees; } void Engine::setNearestScaleTexture(bool nearestScaleTexture){ Engine::nearestScaleTexture = nearestScaleTexture; } bool Engine::isNearestScaleTexture(){ return nearestScaleTexture; } void Engine::setUpdateTime(unsigned int updateTime){ Engine::updateTime = updateTime; } unsigned int Engine::getUpdateTime(){ return Engine::updateTime; } int Engine::getPlatform(){ #ifdef SUPERNOVA_IOS return S_IOS; #endif #ifdef SUPERNOVA_ANDROID return S_ANDROID; #endif #ifdef SUPERNOVA_WEB return S_WEB; #endif return 0; } float Engine::getFramerate(){ return framerate; } float Engine::getDeltatime(){ return deltatime; } unsigned int Engine::getFrametime(){ return frametime; } void Engine::onStart(){ onStart(0, 0); } void Engine::onStart(int width, int height){ Engine::setScreenSize(width, height); Engine::setMouseAsTouch(true); Engine::setUseDegrees(true); Engine::setRenderAPI(S_GLES2); Engine::setScalingMode(S_SCALING_FITWIDTH); Engine::setNearestScaleTexture(false); LuaBind::createLuaState(); LuaBind::bind(); auto now = std::chrono::steady_clock::now(); lastTime = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count(); init(); } void Engine::onSurfaceCreated(){ if (Engine::getScene() != NULL){ (Engine::getScene())->load(); } } void Engine::onSurfaceChanged(int width, int height) { Engine::setScreenSize(width, height); int viewX = 0; int viewY = 0; int viewWidth = Engine::getScreenWidth(); int viewHeight = Engine::getScreenHeight(); float screenAspect = (float)Engine::getScreenWidth() / (float)Engine::getScreenHeight(); float canvasAspect = (float)Engine::getPreferedCanvasWidth() / (float)Engine::getPreferedCanvasHeight(); //When canvas size is not changed if (Engine::getScalingMode() == S_SCALING_LETTERBOX){ if (screenAspect < canvasAspect){ float aspect = (float)Engine::getScreenWidth() / (float)Engine::getPreferedCanvasWidth(); int newHeight = (int)((float)Engine::getPreferedCanvasHeight() * aspect); int dif = Engine::getScreenHeight() - newHeight; viewY = (dif/2); viewHeight = Engine::getScreenHeight()-dif; }else{ float aspect = (float)Engine::getScreenHeight() / (float)Engine::getPreferedCanvasHeight(); int newWidth = (int)((float)Engine::getPreferedCanvasWidth() * aspect); int dif = Engine::getScreenWidth() - newWidth; viewX = (dif/2); viewWidth = Engine::getScreenWidth()-dif; } } if (Engine::getScalingMode() == S_SCALING_CROP){ if (screenAspect > canvasAspect){ float aspect = (float)Engine::getScreenWidth() / (float)Engine::getPreferedCanvasWidth(); int newHeight = (int)((float)Engine::getPreferedCanvasHeight() * aspect); int dif = Engine::getScreenHeight() - newHeight; viewY = (dif/2); viewHeight = Engine::getScreenHeight()-dif; }else{ float aspect = (float)Engine::getScreenHeight() / (float)Engine::getPreferedCanvasHeight(); int newWidth = (int)((float)Engine::getPreferedCanvasWidth() * aspect); int dif = Engine::getScreenWidth() - newWidth; viewX = (dif/2); viewWidth = Engine::getScreenWidth()-dif; } } // S_SCALING_STRETCH do not need nothing viewRect.setRect(viewX, viewY, viewWidth, viewHeight); if (Engine::getScene() != NULL){ (Engine::getScene())->updateViewSize(); } } void Engine::onDraw() { if (Engine::getScene() != NULL){ (Engine::getScene())->draw(); } auto now = std::chrono::steady_clock::now(); unsigned long newTime = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count(); frametime = (unsigned int)(newTime - lastTime); lastTime = newTime; deltatime = (float)frametime / updateTime; float frameTimeSeconds = (float)frametime / 1000; framerate = 1 / frameTimeSeconds; updateTimeCount += frametime; if (updateTimeCount > updateTime){ unsigned int updateCallCount = floor((float)updateTimeCount / updateTime); for (int i = 0; i < updateCallCount; i++){ Events::call_onUpdate(); } updateTimeCount -= (updateTime * updateCallCount); } Events::call_onDraw(); SoundManager::checkActive(); } void Engine::onPause(){ SoundManager::pauseAll(); } void Engine::onResume(){ SoundManager::resumeAll(); } bool Engine::transformCoordPos(float& x, float& y){ x = (x * (float)screenWidth / viewRect.getWidth()); y = (y * (float)screenHeight / viewRect.getHeight()); x = ((float)Engine::getCanvasWidth() * (x+1)) / 2; y = ((float)Engine::getCanvasHeight() * (y+1)) / 2; return ((x >= 0) && (x <= Engine::getCanvasWidth()) && (y >= 0) && (y <= Engine::getCanvasHeight())); } void Engine::onTouchPress(float x, float y){ if (transformCoordPos(x, y)){ Events::call_onTouchPress(x, y); } } void Engine::onTouchUp(float x, float y){ if (transformCoordPos(x, y)){ Events::call_onTouchUp(x, y); } } void Engine::onTouchDrag(float x, float y){ if (transformCoordPos(x, y)){ Events::call_onTouchDrag(x, y); } } void Engine::onMousePress(int button, float x, float y){ if (transformCoordPos(x, y)){ Events::call_onMousePress(button, x, y); if ((Engine::isMouseAsTouch()) && (button == S_MOUSE_BUTTON_LEFT)){ Events::call_onTouchPress(x, y); } } } void Engine::onMouseUp(int button, float x, float y){ if (transformCoordPos(x, y)){ Events::call_onMouseUp(button, x, y); if ((Engine::isMouseAsTouch()) && (button == S_MOUSE_BUTTON_LEFT)){ Events::call_onTouchUp(x, y); } } } void Engine::onMouseDrag(int button, float x, float y){ if (transformCoordPos(x, y)){ Events::call_onMouseDrag(button, x, y); if ((Engine::isMouseAsTouch()) && (button == S_MOUSE_BUTTON_LEFT)){ Events::call_onTouchDrag(x, y); } } } void Engine::onMouseMove(float x, float y){ if (transformCoordPos(x, y)){ Events::call_onMouseMove(x, y); } } void Engine::onKeyPress(int inputKey){ Events::call_onKeyPress(inputKey); //printf("keypress %i\n", inputKey); } void Engine::onKeyUp(int inputKey){ Events::call_onKeyUp(inputKey); //printf("keyup %i\n", inputKey); } void Engine::onTextInput(const char* text){ //printf("textinput %s\n", text); Log::Verbose(LOG_TAG,"textinput %s\n", text); } <commit_msg>Fixed screen view rect for letterbox and crop<commit_after>#include "Engine.h" #include <iostream> #include "Supernova.h" #include "lua.h" #include "lualib.h" #include "lauxlib.h" #include "Scene.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include "Events.h" #include "math/Rect.h" #include "platform/Log.h" #include "LuaBind.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "Mesh.h" #include "InputCode.h" #include "audio/SoundManager.h" using namespace Supernova; Scene *Engine::mainScene; int Engine::screenWidth; int Engine::screenHeight; int Engine::canvasWidth; int Engine::canvasHeight; int Engine::preferedCanvasWidth; int Engine::preferedCanvasHeight; Rect Engine::viewRect; int Engine::renderAPI; bool Engine::mouseAsTouch; bool Engine::useDegrees; int Engine::scalingMode; bool Engine::nearestScaleTexture; unsigned long Engine::lastTime = 0; unsigned int Engine::updateTimeCount = 0; unsigned int Engine::frametime = 0; float Engine::deltatime = 0; float Engine::framerate = 0; unsigned int Engine::updateTime = 20; Engine::Engine() { } Engine::~Engine() { } void Engine::setScene(Scene *mainScene){ Engine::mainScene = mainScene; } Scene* Engine::getScene(){ return mainScene; } int Engine::getScreenWidth(){ return Engine::screenWidth; } int Engine::getScreenHeight(){ return Engine::screenHeight; } void Engine::setScreenSize(int screenWidth, int screenHeight){ Engine::screenWidth = screenWidth; Engine::screenHeight = screenHeight; if ((Engine::preferedCanvasWidth != 0) && (Engine::preferedCanvasHeight != 0)){ setCanvasSize(preferedCanvasWidth, preferedCanvasHeight); } } int Engine::getCanvasWidth(){ return Engine::canvasWidth; } int Engine::getCanvasHeight(){ return Engine::canvasHeight; } void Engine::setCanvasSize(int canvasWidth, int canvasHeight){ Engine::canvasWidth = canvasWidth; Engine::canvasHeight = canvasHeight; if ((Engine::screenWidth == 0) || (Engine::screenHeight == 0)){ setScreenSize(canvasWidth, canvasHeight); } //When canvas size is changed if (scalingMode == S_SCALING_FITWIDTH){ Engine::canvasWidth = canvasWidth; Engine::canvasHeight = screenHeight * canvasWidth / screenWidth; } if (scalingMode == S_SCALING_FITHEIGHT){ Engine::canvasHeight = canvasHeight; Engine::canvasWidth = screenWidth * canvasHeight / screenHeight; } if ((Engine::preferedCanvasWidth == 0) && (Engine::preferedCanvasHeight == 0)){ setPreferedCanvasSize(canvasWidth, canvasHeight); } } int Engine::getPreferedCanvasWidth(){ return Engine::preferedCanvasWidth; } int Engine::getPreferedCanvasHeight(){ return Engine::preferedCanvasHeight; } void Engine::setPreferedCanvasSize(int preferedCanvasWidth, int preferedCanvasHeight){ if ((Engine::preferedCanvasWidth == 0) && (Engine::preferedCanvasHeight == 0)){ Engine::preferedCanvasWidth = preferedCanvasWidth; Engine::preferedCanvasHeight = preferedCanvasHeight; } } Rect* Engine::getViewRect(){ return &viewRect; } void Engine::setRenderAPI(int renderAPI){ Engine::renderAPI = renderAPI; } int Engine::getRenderAPI(){ return renderAPI; } void Engine::setScalingMode(int scalingMode){ Engine::scalingMode = scalingMode; } int Engine::getScalingMode(){ return scalingMode; } void Engine::setMouseAsTouch(bool mouseAsTouch){ Engine::mouseAsTouch = mouseAsTouch; } bool Engine::isMouseAsTouch(){ return Engine::mouseAsTouch; } void Engine::setUseDegrees(bool useDegrees){ Engine::useDegrees = useDegrees; } bool Engine::isUseDegrees(){ return Engine::useDegrees; } void Engine::setNearestScaleTexture(bool nearestScaleTexture){ Engine::nearestScaleTexture = nearestScaleTexture; } bool Engine::isNearestScaleTexture(){ return nearestScaleTexture; } void Engine::setUpdateTime(unsigned int updateTime){ Engine::updateTime = updateTime; } unsigned int Engine::getUpdateTime(){ return Engine::updateTime; } int Engine::getPlatform(){ #ifdef SUPERNOVA_IOS return S_IOS; #endif #ifdef SUPERNOVA_ANDROID return S_ANDROID; #endif #ifdef SUPERNOVA_WEB return S_WEB; #endif return 0; } float Engine::getFramerate(){ return framerate; } float Engine::getDeltatime(){ return deltatime; } unsigned int Engine::getFrametime(){ return frametime; } void Engine::onStart(){ onStart(0, 0); } void Engine::onStart(int width, int height){ Engine::setScreenSize(width, height); Engine::setMouseAsTouch(true); Engine::setUseDegrees(true); Engine::setRenderAPI(S_GLES2); Engine::setScalingMode(S_SCALING_FITWIDTH); Engine::setNearestScaleTexture(false); LuaBind::createLuaState(); LuaBind::bind(); auto now = std::chrono::steady_clock::now(); lastTime = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count(); init(); } void Engine::onSurfaceCreated(){ if (Engine::getScene() != NULL){ (Engine::getScene())->load(); } } void Engine::onSurfaceChanged(int width, int height) { Engine::setScreenSize(width, height); int viewX = 0; int viewY = 0; int viewWidth = Engine::getScreenWidth(); int viewHeight = Engine::getScreenHeight(); float screenAspect = (float)Engine::getScreenWidth() / (float)Engine::getScreenHeight(); float canvasAspect = (float)Engine::getPreferedCanvasWidth() / (float)Engine::getPreferedCanvasHeight(); //When canvas size is not changed if (Engine::getScalingMode() == S_SCALING_LETTERBOX){ if (screenAspect < canvasAspect){ float aspect = (float)Engine::getScreenWidth() / (float)Engine::getPreferedCanvasWidth(); int newHeight = (int)((float)Engine::getPreferedCanvasHeight() * aspect); int dif = Engine::getScreenHeight() - newHeight; viewY = (dif/2); viewHeight = Engine::getScreenHeight()-(viewY*2); //diff could be odd, for this use view*2 }else{ float aspect = (float)Engine::getScreenHeight() / (float)Engine::getPreferedCanvasHeight(); int newWidth = (int)((float)Engine::getPreferedCanvasWidth() * aspect); int dif = Engine::getScreenWidth() - newWidth; viewX = (dif/2); viewWidth = Engine::getScreenWidth()-(viewX*2); } } if (Engine::getScalingMode() == S_SCALING_CROP){ if (screenAspect > canvasAspect){ float aspect = (float)Engine::getScreenWidth() / (float)Engine::getPreferedCanvasWidth(); int newHeight = (int)((float)Engine::getPreferedCanvasHeight() * aspect); int dif = Engine::getScreenHeight() - newHeight; viewY = (dif/2); viewHeight = Engine::getScreenHeight()-(viewY*2); }else{ float aspect = (float)Engine::getScreenHeight() / (float)Engine::getPreferedCanvasHeight(); int newWidth = (int)((float)Engine::getPreferedCanvasWidth() * aspect); int dif = Engine::getScreenWidth() - newWidth; viewX = (dif/2); viewWidth = Engine::getScreenWidth()-(viewX*2); } } // S_SCALING_STRETCH do not need nothing viewRect.setRect(viewX, viewY, viewWidth, viewHeight); if (Engine::getScene() != NULL){ (Engine::getScene())->updateViewSize(); } } void Engine::onDraw() { if (Engine::getScene() != NULL){ (Engine::getScene())->draw(); } auto now = std::chrono::steady_clock::now(); unsigned long newTime = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count(); frametime = (unsigned int)(newTime - lastTime); lastTime = newTime; deltatime = (float)frametime / updateTime; float frameTimeSeconds = (float)frametime / 1000; framerate = 1 / frameTimeSeconds; updateTimeCount += frametime; if (updateTimeCount > updateTime){ unsigned int updateCallCount = floor((float)updateTimeCount / updateTime); for (int i = 0; i < updateCallCount; i++){ Events::call_onUpdate(); } updateTimeCount -= (updateTime * updateCallCount); } Events::call_onDraw(); SoundManager::checkActive(); } void Engine::onPause(){ SoundManager::pauseAll(); } void Engine::onResume(){ SoundManager::resumeAll(); } bool Engine::transformCoordPos(float& x, float& y){ x = (x * (float)screenWidth / viewRect.getWidth()); y = (y * (float)screenHeight / viewRect.getHeight()); x = ((float)Engine::getCanvasWidth() * (x+1)) / 2; y = ((float)Engine::getCanvasHeight() * (y+1)) / 2; return ((x >= 0) && (x <= Engine::getCanvasWidth()) && (y >= 0) && (y <= Engine::getCanvasHeight())); } void Engine::onTouchPress(float x, float y){ if (transformCoordPos(x, y)){ Events::call_onTouchPress(x, y); } } void Engine::onTouchUp(float x, float y){ if (transformCoordPos(x, y)){ Events::call_onTouchUp(x, y); } } void Engine::onTouchDrag(float x, float y){ if (transformCoordPos(x, y)){ Events::call_onTouchDrag(x, y); } } void Engine::onMousePress(int button, float x, float y){ if (transformCoordPos(x, y)){ Events::call_onMousePress(button, x, y); if ((Engine::isMouseAsTouch()) && (button == S_MOUSE_BUTTON_LEFT)){ Events::call_onTouchPress(x, y); } } } void Engine::onMouseUp(int button, float x, float y){ if (transformCoordPos(x, y)){ Events::call_onMouseUp(button, x, y); if ((Engine::isMouseAsTouch()) && (button == S_MOUSE_BUTTON_LEFT)){ Events::call_onTouchUp(x, y); } } } void Engine::onMouseDrag(int button, float x, float y){ if (transformCoordPos(x, y)){ Events::call_onMouseDrag(button, x, y); if ((Engine::isMouseAsTouch()) && (button == S_MOUSE_BUTTON_LEFT)){ Events::call_onTouchDrag(x, y); } } } void Engine::onMouseMove(float x, float y){ if (transformCoordPos(x, y)){ Events::call_onMouseMove(x, y); } } void Engine::onKeyPress(int inputKey){ Events::call_onKeyPress(inputKey); //printf("keypress %i\n", inputKey); } void Engine::onKeyUp(int inputKey){ Events::call_onKeyUp(inputKey); //printf("keyup %i\n", inputKey); } void Engine::onTextInput(const char* text){ //printf("textinput %s\n", text); Log::Verbose(LOG_TAG,"textinput %s\n", text); } <|endoftext|>
<commit_before>// Ouzel by Elviss Strazdins #ifndef OUZEL_FORMATS_INI_HPP #define OUZEL_FORMATS_INI_HPP #include <algorithm> #include <array> #include <cstdint> #include <functional> #include <map> #include <stdexcept> #include <string> #include <string_view> namespace ouzel::ini { class ParseError final: public std::logic_error { public: using std::logic_error::logic_error; }; class RangeError final: public std::range_error { public: using std::range_error::range_error; }; inline namespace detail { constexpr std::array<std::uint8_t, 3> utf8ByteOrderMark = {0xEF, 0xBB, 0xBF}; template <class Iterator> [[nodiscard]] bool hasByteOrderMark(const Iterator begin, const Iterator end) noexcept { auto i = begin; for (const auto b : utf8ByteOrderMark) if (i == end || static_cast<std::uint8_t>(*i++) != b) return false; return true; } [[nodiscard]] constexpr bool isWhiteSpace(const char c) noexcept { return c == ' ' || c == '\t'; } inline std::string& leftTrim(std::string& s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](char c) noexcept {return !isWhiteSpace(c);})); return s; } inline std::string& rightTrim(std::string& s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](char c) noexcept {return !isWhiteSpace(c);}).base(), s.end()); return s; } inline std::string& trim(std::string& s) { return leftTrim(rightTrim(s)); } } using Values = std::map<std::string, std::string, std::less<>>; class Section final { public: Section() = default; explicit Section(const std::string& initName): name{initName} { } auto begin() noexcept { return values.begin(); } auto end() noexcept { return values.end(); } auto begin() const noexcept { return values.begin(); } auto end() const noexcept { return values.end(); } const std::string& getName() const noexcept { return name; } void setName(const std::string& newName) { name = newName; } const Values& getValues() const noexcept { return values; } bool hasValue(const std::string_view key) const { return values.find(key) != values.end(); } std::string& operator[](const std::string_view key) { if (const auto iterator = values.find(key); iterator != values.end()) return iterator->second; else { const auto& [newIterator, success] = values.insert(std::make_pair(std::string{key}, std::string{})); (void)success; return newIterator->second; } } const std::string& operator[](const std::string_view key) const { if (const auto iterator = values.find(key); iterator != values.end()) return iterator->second; else throw RangeError{"Value does not exist"}; } const std::string& getValue(const std::string_view key, const std::string& defaultValue = {}) const { if (const auto iterator = values.find(key); iterator != values.end()) return iterator->second; return defaultValue; } void deleteValue(const std::string_view key) { if (const auto iterator = values.find(key); iterator != values.end()) values.erase(iterator); } std::size_t getSize() const noexcept { return values.size(); } private: std::string name; Values values; }; class Data final { public: using Sections = std::map<std::string, Section, std::less<>>; Data() = default; const Sections& getSections() const noexcept { return sections; } auto begin() noexcept { return sections.begin(); } auto end() noexcept { return sections.end(); } auto begin() const noexcept { return sections.begin(); } auto end() const noexcept { return sections.end(); } bool hasSection(const std::string_view name) const { return sections.find(name) != sections.end(); } Section& operator[](const std::string_view name) { if (const auto sectionIterator = sections.find(name); sectionIterator != sections.end()) return sectionIterator->second; else { const auto& [newIterator, success] = sections.insert(std::make_pair(std::string{name}, Section{})); (void)success; return newIterator->second; } } const Section& operator[](const std::string_view name) const { if (const auto sectionIterator = sections.find(name); sectionIterator != sections.end()) return sectionIterator->second; else throw RangeError{"Section does not exist"}; } void eraseSection(const std::string_view name) { if (const auto sectionIterator = sections.find(name); sectionIterator != sections.end()) sections.erase(sectionIterator); } std::size_t getSize() const noexcept { return sections.size(); } private: Sections sections; }; template <class Iterator> Data parse(Iterator begin, Iterator end) { class Parser final { public: static Data parse(Iterator begin, Iterator end) { Data result; std::string section; for (auto iterator = hasByteOrderMark(begin, end) ? begin + 3 : begin; iterator != end;) { if (isWhiteSpace(static_cast<char>(*iterator)) || static_cast<char>(*iterator) == '\n' || static_cast<char>(*iterator) == '\r') // line starts with a white space ++iterator; // skip the white space else if (static_cast<char>(*iterator) == '[') // section { ++iterator; // skip the left bracket bool parsedSection = false; for (;;) { if (iterator == end || static_cast<char>(*iterator) == '\n' || static_cast<char>(*iterator) == '\r') { if (!parsedSection) throw ParseError{"Unexpected end of section"}; ++iterator; // skip the newline break; } else if (static_cast<char>(*iterator) == ';') { ++iterator; // skip the semicolon if (!parsedSection) throw ParseError{"Unexpected comment"}; while (iterator != end) { if (static_cast<char>(*iterator) == '\n' || static_cast<char>(*iterator) == '\r') { ++iterator; // skip the newline break; } ++iterator; } break; } else if (static_cast<char>(*iterator) == ']') parsedSection = true; else if (static_cast<char>(*iterator) != ' ' && static_cast<char>(*iterator) != '\t') { if (parsedSection) throw ParseError{"Unexpected character after section"}; } if (!parsedSection) section.push_back(static_cast<char>(*iterator)); ++iterator; } trim(section); if (section.empty()) throw ParseError{"Invalid section name"}; result[section] = Section{}; } else if (static_cast<char>(*iterator) == ';') // comment { while (++iterator != end) { if (static_cast<char>(*iterator) == '\r' || static_cast<char>(*iterator) == '\n') { ++iterator; // skip the newline break; } } } else // key, value pair { std::string key; std::string value; bool parsedKey = false; while (iterator != end) { if (static_cast<char>(*iterator) == '\r' || static_cast<char>(*iterator) == '\n') { ++iterator; // skip the newline break; } else if (static_cast<char>(*iterator) == '=') { if (!parsedKey) parsedKey = true; else throw ParseError{"Unexpected character"}; } else if (static_cast<char>(*iterator) == ';') { ++iterator; // skip the semicolon while (iterator != end) { if (static_cast<char>(*iterator) == '\r' || static_cast<char>(*iterator) == '\n') { ++iterator; // skip the newline break; } ++iterator; } break; } else { if (!parsedKey) key.push_back(static_cast<char>(*iterator)); else value.push_back(static_cast<char>(*iterator)); } ++iterator; } if (key.empty()) throw ParseError{"Invalid key name"}; trim(key); trim(value); result[section][key] = value; } } return result; } }; return Parser::parse(begin, end); } inline Data parse(const char* data) { auto end = data; while (*end) ++end; return parse(data, end); } template <class T> Data parse(const T& data) { using std::begin, std::end; // add std::begin and std::end to lookup return parse(begin(data), end(data)); } inline std::string encode(const Data& data, bool byteOrderMark = false) { std::string result; if (byteOrderMark) result.assign(utf8ByteOrderMark.begin(), utf8ByteOrderMark.end()); for (const auto& [name, section] : data) { if (!name.empty()) { result.push_back('['); result.insert(result.end(), name.begin(), name.end()); result.push_back(']'); result.push_back('\n'); } for (const auto& [key, value] : section) { result.insert(result.end(), key.begin(), key.end()); result.push_back('='); result.insert(result.end(), value.begin(), value.end()); result.push_back('\n'); } } return result; } } #endif // OUZEL_FORMATS_INI_HPP <commit_msg>Use string_view and try_emplace<commit_after>// Ouzel by Elviss Strazdins #ifndef OUZEL_FORMATS_INI_HPP #define OUZEL_FORMATS_INI_HPP #include <algorithm> #include <array> #include <cstdint> #include <functional> #include <map> #include <stdexcept> #include <string> #include <string_view> namespace ouzel::ini { class ParseError final: public std::logic_error { public: using std::logic_error::logic_error; }; class RangeError final: public std::range_error { public: using std::range_error::range_error; }; inline namespace detail { constexpr std::array<std::uint8_t, 3> utf8ByteOrderMark = {0xEF, 0xBB, 0xBF}; template <class Iterator> [[nodiscard]] bool hasByteOrderMark(const Iterator begin, const Iterator end) noexcept { auto i = begin; for (const auto b : utf8ByteOrderMark) if (i == end || static_cast<std::uint8_t>(*i++) != b) return false; return true; } [[nodiscard]] constexpr bool isWhiteSpace(const char c) noexcept { return c == ' ' || c == '\t'; } inline std::string& leftTrim(std::string& s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](char c) noexcept {return !isWhiteSpace(c);})); return s; } inline std::string& rightTrim(std::string& s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](char c) noexcept {return !isWhiteSpace(c);}).base(), s.end()); return s; } inline std::string& trim(std::string& s) { return leftTrim(rightTrim(s)); } } using Values = std::map<std::string, std::string, std::less<>>; class Section final { public: Section() = default; explicit Section(const std::string& initName): name{initName} { } auto begin() noexcept { return values.begin(); } auto end() noexcept { return values.end(); } auto begin() const noexcept { return values.begin(); } auto end() const noexcept { return values.end(); } const std::string& getName() const noexcept { return name; } void setName(const std::string_view newName) { name = newName; } const Values& getValues() const noexcept { return values; } bool hasValue(const std::string_view key) const { return values.find(key) != values.end(); } std::string& operator[](const std::string_view key) { if (const auto iterator = values.find(key); iterator != values.end()) return iterator->second; else { const auto& [newIterator, success] = values.try_emplace(std::string{key}, std::string{}); (void)success; return newIterator->second; } } const std::string& operator[](const std::string_view key) const { if (const auto iterator = values.find(key); iterator != values.end()) return iterator->second; else throw RangeError{"Value does not exist"}; } const std::string& getValue(const std::string_view key, const std::string& defaultValue = {}) const { if (const auto iterator = values.find(key); iterator != values.end()) return iterator->second; return defaultValue; } void deleteValue(const std::string_view key) { if (const auto iterator = values.find(key); iterator != values.end()) values.erase(iterator); } std::size_t getSize() const noexcept { return values.size(); } private: std::string name; Values values; }; class Data final { public: using Sections = std::map<std::string, Section, std::less<>>; Data() = default; const Sections& getSections() const noexcept { return sections; } auto begin() noexcept { return sections.begin(); } auto end() noexcept { return sections.end(); } auto begin() const noexcept { return sections.begin(); } auto end() const noexcept { return sections.end(); } bool hasSection(const std::string_view name) const { return sections.find(name) != sections.end(); } Section& operator[](const std::string_view name) { if (const auto sectionIterator = sections.find(name); sectionIterator != sections.end()) return sectionIterator->second; else { const auto& [newIterator, success] = sections.try_emplace(std::string{name}, Section{}); (void)success; return newIterator->second; } } const Section& operator[](const std::string_view name) const { if (const auto sectionIterator = sections.find(name); sectionIterator != sections.end()) return sectionIterator->second; else throw RangeError{"Section does not exist"}; } void eraseSection(const std::string_view name) { if (const auto sectionIterator = sections.find(name); sectionIterator != sections.end()) sections.erase(sectionIterator); } std::size_t getSize() const noexcept { return sections.size(); } private: Sections sections; }; template <class Iterator> Data parse(Iterator begin, Iterator end) { class Parser final { public: static Data parse(Iterator begin, Iterator end) { Data result; std::string section; for (auto iterator = hasByteOrderMark(begin, end) ? begin + 3 : begin; iterator != end;) { if (isWhiteSpace(static_cast<char>(*iterator)) || static_cast<char>(*iterator) == '\n' || static_cast<char>(*iterator) == '\r') // line starts with a white space ++iterator; // skip the white space else if (static_cast<char>(*iterator) == '[') // section { ++iterator; // skip the left bracket bool parsedSection = false; for (;;) { if (iterator == end || static_cast<char>(*iterator) == '\n' || static_cast<char>(*iterator) == '\r') { if (!parsedSection) throw ParseError{"Unexpected end of section"}; ++iterator; // skip the newline break; } else if (static_cast<char>(*iterator) == ';') { ++iterator; // skip the semicolon if (!parsedSection) throw ParseError{"Unexpected comment"}; while (iterator != end) { if (static_cast<char>(*iterator) == '\n' || static_cast<char>(*iterator) == '\r') { ++iterator; // skip the newline break; } ++iterator; } break; } else if (static_cast<char>(*iterator) == ']') parsedSection = true; else if (static_cast<char>(*iterator) != ' ' && static_cast<char>(*iterator) != '\t') { if (parsedSection) throw ParseError{"Unexpected character after section"}; } if (!parsedSection) section.push_back(static_cast<char>(*iterator)); ++iterator; } trim(section); if (section.empty()) throw ParseError{"Invalid section name"}; result[section] = Section{}; } else if (static_cast<char>(*iterator) == ';') // comment { while (++iterator != end) { if (static_cast<char>(*iterator) == '\r' || static_cast<char>(*iterator) == '\n') { ++iterator; // skip the newline break; } } } else // key, value pair { std::string key; std::string value; bool parsedKey = false; while (iterator != end) { if (static_cast<char>(*iterator) == '\r' || static_cast<char>(*iterator) == '\n') { ++iterator; // skip the newline break; } else if (static_cast<char>(*iterator) == '=') { if (!parsedKey) parsedKey = true; else throw ParseError{"Unexpected character"}; } else if (static_cast<char>(*iterator) == ';') { ++iterator; // skip the semicolon while (iterator != end) { if (static_cast<char>(*iterator) == '\r' || static_cast<char>(*iterator) == '\n') { ++iterator; // skip the newline break; } ++iterator; } break; } else { if (!parsedKey) key.push_back(static_cast<char>(*iterator)); else value.push_back(static_cast<char>(*iterator)); } ++iterator; } if (key.empty()) throw ParseError{"Invalid key name"}; trim(key); trim(value); result[section][key] = value; } } return result; } }; return Parser::parse(begin, end); } inline Data parse(const char* data) { auto end = data; while (*end) ++end; return parse(data, end); } template <class T> Data parse(const T& data) { using std::begin, std::end; // add std::begin and std::end to lookup return parse(begin(data), end(data)); } inline std::string encode(const Data& data, bool byteOrderMark = false) { std::string result; if (byteOrderMark) result.assign(utf8ByteOrderMark.begin(), utf8ByteOrderMark.end()); for (const auto& [name, section] : data) { if (!name.empty()) { result.push_back('['); result.insert(result.end(), name.begin(), name.end()); result.push_back(']'); result.push_back('\n'); } for (const auto& [key, value] : section) { result.insert(result.end(), key.begin(), key.end()); result.push_back('='); result.insert(result.end(), value.begin(), value.end()); result.push_back('\n'); } } return result; } } #endif // OUZEL_FORMATS_INI_HPP <|endoftext|>
<commit_before>//===- IRBindings.cpp - Additional bindings for ir ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines additional C bindings for the ir component. // //===----------------------------------------------------------------------===// #include "IRBindings.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/DebugLoc.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" using namespace llvm; void LLVMAddFunctionAttr2(LLVMValueRef Fn, uint64_t PA) { Function *Func = unwrap<Function>(Fn); const AttributeSet PAL = Func->getAttributes(); AttrBuilder B(PA); const AttributeSet PALnew = PAL.addAttributes(Func->getContext(), AttributeSet::FunctionIndex, AttributeSet::get(Func->getContext(), AttributeSet::FunctionIndex, B)); Func->setAttributes(PALnew); } uint64_t LLVMGetFunctionAttr2(LLVMValueRef Fn) { Function *Func = unwrap<Function>(Fn); const AttributeSet PAL = Func->getAttributes(); return PAL.Raw(AttributeSet::FunctionIndex); } void LLVMRemoveFunctionAttr2(LLVMValueRef Fn, uint64_t PA) { Function *Func = unwrap<Function>(Fn); const AttributeSet PAL = Func->getAttributes(); AttrBuilder B(PA); const AttributeSet PALnew = PAL.removeAttributes(Func->getContext(), AttributeSet::FunctionIndex, AttributeSet::get(Func->getContext(), AttributeSet::FunctionIndex, B)); Func->setAttributes(PALnew); } LLVMMetadataRef LLVMConstantAsMetadata(LLVMValueRef C) { return wrap(ConstantAsMetadata::get(unwrap<Constant>(C))); } LLVMMetadataRef LLVMMDString2(LLVMContextRef C, const char *Str, unsigned SLen) { return wrap(MDString::get(*unwrap(C), StringRef(Str, SLen))); } LLVMMetadataRef LLVMMDNode2(LLVMContextRef C, LLVMMetadataRef *MDs, unsigned Count) { return wrap( MDNode::get(*unwrap(C), ArrayRef<Metadata *>(unwrap(MDs), Count))); } LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef C, LLVMMetadataRef *MDs, unsigned Count) { return wrap(MDTuple::getTemporary(*unwrap(C), ArrayRef<Metadata *>(unwrap(MDs), Count)) .release()); } void LLVMAddNamedMetadataOperand2(LLVMModuleRef M, const char *name, LLVMMetadataRef Val) { NamedMDNode *N = unwrap(M)->getOrInsertNamedMetadata(name); if (!N) return; if (!Val) return; N->addOperand(unwrap<MDNode>(Val)); } void LLVMSetMetadata2(LLVMValueRef Inst, unsigned KindID, LLVMMetadataRef MD) { MDNode *N = MD ? unwrap<MDNode>(MD) : nullptr; unwrap<Instruction>(Inst)->setMetadata(KindID, N); } void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef MD, LLVMMetadataRef New) { auto *Node = unwrap<MDTuple>(MD); assert(Node->isTemporary() && "Expected temporary node"); Node->replaceAllUsesWith(unwrap<MDNode>(New)); MDNode::deleteTemporary(Node); } void LLVMSetCurrentDebugLocation2(LLVMBuilderRef Bref, unsigned Line, unsigned Col, LLVMMetadataRef Scope, LLVMMetadataRef InlinedAt) { unwrap(Bref)->SetCurrentDebugLocation( DebugLoc::get(Line, Col, Scope ? unwrap<MDNode>(Scope) : nullptr, InlinedAt ? unwrap<MDNode>(InlinedAt) : nullptr)); } <commit_msg>Go bindings: use MDNode::replaceAllUsesWith instead of MDTuple::replaceAllUsesWith.<commit_after>//===- IRBindings.cpp - Additional bindings for ir ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines additional C bindings for the ir component. // //===----------------------------------------------------------------------===// #include "IRBindings.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/DebugLoc.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" using namespace llvm; void LLVMAddFunctionAttr2(LLVMValueRef Fn, uint64_t PA) { Function *Func = unwrap<Function>(Fn); const AttributeSet PAL = Func->getAttributes(); AttrBuilder B(PA); const AttributeSet PALnew = PAL.addAttributes(Func->getContext(), AttributeSet::FunctionIndex, AttributeSet::get(Func->getContext(), AttributeSet::FunctionIndex, B)); Func->setAttributes(PALnew); } uint64_t LLVMGetFunctionAttr2(LLVMValueRef Fn) { Function *Func = unwrap<Function>(Fn); const AttributeSet PAL = Func->getAttributes(); return PAL.Raw(AttributeSet::FunctionIndex); } void LLVMRemoveFunctionAttr2(LLVMValueRef Fn, uint64_t PA) { Function *Func = unwrap<Function>(Fn); const AttributeSet PAL = Func->getAttributes(); AttrBuilder B(PA); const AttributeSet PALnew = PAL.removeAttributes(Func->getContext(), AttributeSet::FunctionIndex, AttributeSet::get(Func->getContext(), AttributeSet::FunctionIndex, B)); Func->setAttributes(PALnew); } LLVMMetadataRef LLVMConstantAsMetadata(LLVMValueRef C) { return wrap(ConstantAsMetadata::get(unwrap<Constant>(C))); } LLVMMetadataRef LLVMMDString2(LLVMContextRef C, const char *Str, unsigned SLen) { return wrap(MDString::get(*unwrap(C), StringRef(Str, SLen))); } LLVMMetadataRef LLVMMDNode2(LLVMContextRef C, LLVMMetadataRef *MDs, unsigned Count) { return wrap( MDNode::get(*unwrap(C), ArrayRef<Metadata *>(unwrap(MDs), Count))); } LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef C, LLVMMetadataRef *MDs, unsigned Count) { return wrap(MDTuple::getTemporary(*unwrap(C), ArrayRef<Metadata *>(unwrap(MDs), Count)) .release()); } void LLVMAddNamedMetadataOperand2(LLVMModuleRef M, const char *name, LLVMMetadataRef Val) { NamedMDNode *N = unwrap(M)->getOrInsertNamedMetadata(name); if (!N) return; if (!Val) return; N->addOperand(unwrap<MDNode>(Val)); } void LLVMSetMetadata2(LLVMValueRef Inst, unsigned KindID, LLVMMetadataRef MD) { MDNode *N = MD ? unwrap<MDNode>(MD) : nullptr; unwrap<Instruction>(Inst)->setMetadata(KindID, N); } void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef MD, LLVMMetadataRef New) { auto *Node = unwrap<MDNode>(MD); Node->replaceAllUsesWith(unwrap<Metadata>(New)); MDNode::deleteTemporary(Node); } void LLVMSetCurrentDebugLocation2(LLVMBuilderRef Bref, unsigned Line, unsigned Col, LLVMMetadataRef Scope, LLVMMetadataRef InlinedAt) { unwrap(Bref)->SetCurrentDebugLocation( DebugLoc::get(Line, Col, Scope ? unwrap<MDNode>(Scope) : nullptr, InlinedAt ? unwrap<MDNode>(InlinedAt) : nullptr)); } <|endoftext|>
<commit_before>#include "parser.h" #include "in_uncod_android_bypass_Bypass.h" namespace boost { void throw_exception(std::exception const&) {} } jobject recurseElement(Bypass::Element element) { } JNIEXPORT jobject JNICALL Java_in_uncod_android_bypass_Bypass_processMarkdown (JNIEnv *env, jobject o, jstring markdown) { const char* str; str = env->GetStringUTFChars(markdown, NULL); Bypass::Parser parser; Bypass::Document document = parser.parse(str); env->ReleaseStringUTFChars(markdown, str); jclass java_document_class = env->FindClass("in/uncod/android/bypass/Document"); jmethodID java_document_init = env->GetMethodID(java_document_class, "<init>", "([Lin/uncod/android/bypass/Element;)V"); jclass java_element_class = env->FindClass("in/uncod/android/bypass/Element"); jmethodID java_element_init = env->GetMethodID(java_element_class, "<init>", "(Ljava/lang/String;I[Lin/uncod/android/bypass/Element;)V"); jobjectArray elements = (jobjectArray) env->NewObjectArray(document.size(), java_element_class, 0); for (int i=0; i<document.size(); i++) { jobject jelement = recurseElement(document[i]); env->SetObjectArrayElement(elements, i, jelement); } jobject jdocument = env->NewObject(java_document_class, java_document_init, elements); return jdocument; } <commit_msg>Convert c++ objects to java objects<commit_after>#include "parser.h" #include "in_uncod_android_bypass_Bypass.h" namespace boost { void throw_exception(std::exception const&) {} } jclass java_element_class; jmethodID java_element_init; jobject recurseElement(JNIEnv *env, Bypass::Element element) { jobjectArray elements = (jobjectArray) env->NewObjectArray(element.size(), java_element_class, 0); for (int i=0; i<element.size(); i++) { jobject jelement = recurseElement(env, element[i]); env->SetObjectArrayElement(elements, i, jelement); } jstring text = env->NewStringUTF(element.getText().c_str()); jobject jelement = env->NewObject(java_element_class, java_element_init, text, element.getType(), elements); return jelement; } JNIEXPORT jobject JNICALL Java_in_uncod_android_bypass_Bypass_processMarkdown (JNIEnv *env, jobject o, jstring markdown) { const char* str; str = env->GetStringUTFChars(markdown, NULL); Bypass::Parser parser; Bypass::Document document = parser.parse(str); env->ReleaseStringUTFChars(markdown, str); jclass java_document_class = env->FindClass("in/uncod/android/bypass/Document"); jmethodID java_document_init = env->GetMethodID(java_document_class, "<init>", "([Lin/uncod/android/bypass/Element;)V"); java_element_class = env->FindClass("in/uncod/android/bypass/Element"); java_element_init = env->GetMethodID(java_element_class, "<init>", "(Ljava/lang/String;I[Lin/uncod/android/bypass/Element;)V"); jobjectArray elements = (jobjectArray) env->NewObjectArray(document.size(), java_element_class, 0); for (int i=0; i<document.size(); i++) { jobject jelement = recurseElement(env, document[i]); env->SetObjectArrayElement(elements, i, jelement); } jobject jdocument = env->NewObject(java_document_class, java_document_init, elements); return jdocument; } <|endoftext|>
<commit_before>/* Copyright (c) 2003 - 2006, Arvid Norberg Copyright (c) 2007, Arvid Norberg, Un Shyam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_BT_PEER_CONNECTION_HPP_INCLUDED #define TORRENT_BT_PEER_CONNECTION_HPP_INCLUDED #include <ctime> #include <algorithm> #include <vector> #include <deque> #include <string> #include "libtorrent/debug.hpp" #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/smart_ptr.hpp> #include <boost/noncopyable.hpp> #include <boost/array.hpp> #include <boost/optional.hpp> #include <boost/cstdint.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/buffer.hpp" #include "libtorrent/peer_connection.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/peer_id.hpp" #include "libtorrent/storage.hpp" #include "libtorrent/stat.hpp" #include "libtorrent/alert.hpp" #include "libtorrent/torrent_handle.hpp" #include "libtorrent/torrent.hpp" #include "libtorrent/peer_request.hpp" #include "libtorrent/piece_block_progress.hpp" #include "libtorrent/config.hpp" #include "libtorrent/pe_crypto.hpp" namespace libtorrent { class torrent; namespace detail { struct session_impl; } class TORRENT_EXPORT bt_peer_connection : public peer_connection { friend class invariant_access; public: // this is the constructor where the we are the active part. // The peer_conenction should handshake and verify that the // other end has the correct id bt_peer_connection( aux::session_impl& ses , boost::weak_ptr<torrent> t , boost::shared_ptr<socket_type> s , tcp::endpoint const& remote , policy::peer* peerinfo); // with this constructor we have been contacted and we still don't // know which torrent the connection belongs to bt_peer_connection( aux::session_impl& ses , boost::shared_ptr<socket_type> s , tcp::endpoint const& remote , policy::peer* peerinfo); void start(); ~bt_peer_connection(); #ifndef TORRENT_DISABLE_ENCRYPTION bool supports_encryption() const { return m_encrypted; } #endif enum message_type { // standard messages msg_choke = 0, msg_unchoke, msg_interested, msg_not_interested, msg_have, msg_bitfield, msg_request, msg_piece, msg_cancel, // DHT extension msg_dht_port, // FAST extension msg_suggest_piece = 0xd, msg_have_all, msg_have_none, msg_reject_request, msg_allowed_fast, // extension protocol message msg_extended = 20, num_supported_messages }; // called from the main loop when this connection has any // work to do. void on_sent(error_code const& error , std::size_t bytes_transferred); void on_receive(error_code const& error , std::size_t bytes_transferred); virtual void get_specific_peer_info(peer_info& p) const; virtual bool in_handshake() const; #ifndef TORRENT_DISABLE_EXTENSIONS bool support_extensions() const { return m_supports_extensions; } template <class T> T* supports_extension() const { for (extension_list_t::const_iterator i = m_extensions.begin() , end(m_extensions.end()); i != end; ++i) { T* ret = dynamic_cast<T*>(i->get()); if (ret) return ret; } return 0; } #endif // the message handlers are called // each time a recv() returns some new // data, the last time it will be called // is when the entire packet has been // received, then it will no longer // be called. i.e. most handlers need // to check how much of the packet they // have received before any processing void on_keepalive(); void on_choke(int received); void on_unchoke(int received); void on_interested(int received); void on_not_interested(int received); void on_have(int received); void on_bitfield(int received); void on_request(int received); void on_piece(int received); void on_cancel(int received); // DHT extension void on_dht_port(int received); // FAST extension void on_suggest_piece(int received); void on_have_all(int received); void on_have_none(int received); void on_reject_request(int received); void on_allowed_fast(int received); void on_extended(int received); void on_extended_handshake(); typedef void (bt_peer_connection::*message_handler)(int received); // the following functions appends messages // to the send buffer void write_choke(); void write_unchoke(); void write_interested(); void write_not_interested(); void write_request(peer_request const& r); void write_cancel(peer_request const& r); void write_bitfield(); void write_have(int index); void write_piece(peer_request const& r, disk_buffer_holder& buffer); void write_handshake(); #ifndef TORRENT_DISABLE_EXTENSIONS void write_extensions(); #endif void write_chat_message(const std::string& msg); void write_metadata(std::pair<int, int> req); void write_metadata_request(std::pair<int, int> req); void write_keepalive(); // DHT extension void write_dht_port(int listen_port); // FAST extension void write_have_all(); void write_have_none(); void write_reject_request(peer_request const&); void write_allow_fast(int piece); void on_connected(); void on_metadata(); #ifndef NDEBUG void check_invariant() const; ptime m_last_choke; #endif private: bool dispatch_message(int received); // returns the block currently being // downloaded. And the progress of that // block. If the peer isn't downloading // a piece for the moment, the boost::optional // will be invalid. boost::optional<piece_block_progress> downloading_piece_progress() const; #ifndef TORRENT_DISABLE_ENCRYPTION // if (is_local()), we are 'a' otherwise 'b' // // 1. a -> b dhkey, pad // 2. b -> a dhkey, pad // 3. a -> b sync, payload // 4. b -> a sync, payload // 5. a -> b payload void write_pe1_2_dhkey(); void write_pe3_sync(); void write_pe4_sync(int crypto_select); void write_pe_vc_cryptofield(buffer::interval& write_buf, int crypto_field, int pad_size); // stream key (info hash of attached torrent) // secret is the DH shared secret // initializes m_RC4_handler void init_pe_RC4_handler(char const* secret, sha1_hash const& stream_key); public: // these functions encrypt the send buffer if m_rc4_encrypted // is true, otherwise it passes the call to the // peer_connection functions of the same names void send_buffer(char* buf, int size); buffer::interval allocate_send_buffer(int size); template <class Destructor> void append_send_buffer(char* buffer, int size, Destructor const& destructor) { #ifndef TORRENT_DISABLE_ENCRYPTION if (m_rc4_encrypted) m_RC4_handler->encrypt(buffer, size); #endif peer_connection::append_send_buffer(buffer, size, destructor); } void setup_send(); private: // Returns offset at which bytestream (src, src + src_size) // matches bytestream(target, target + target_size). // If no sync found, return -1 int get_syncoffset(char const* src, int src_size, char const* target, int target_size) const; #endif enum state { #ifndef TORRENT_DISABLE_ENCRYPTION read_pe_dhkey = 0, read_pe_syncvc, read_pe_synchash, read_pe_skey_vc, read_pe_cryptofield, read_pe_pad, read_pe_ia, init_bt_handshake, read_protocol_identifier, #else read_protocol_identifier = 0, #endif read_info_hash, read_peer_id, // handshake complete read_packet_size, read_packet }; #ifndef TORRENT_DISABLE_ENCRYPTION enum { handshake_len = 68, dh_key_len = 96 }; #endif std::string m_client_version; // state of on_receive state m_state; // the timeout in seconds int m_timeout; static const message_handler m_message_handler[num_supported_messages]; // this is a queue of ranges that describes // where in the send buffer actual payload // data is located. This is currently // only used to be able to gather statistics // seperately on payload and protocol data. struct range { range(int s, int l) : start(s) , length(l) { TORRENT_ASSERT(s >= 0); TORRENT_ASSERT(l > 0); } int start; int length; }; static bool range_below_zero(const range& r) { return r.start < 0; } std::deque<range> m_payloads; #ifndef TORRENT_DISABLE_EXTENSIONS // this is set to true if the handshake from // the peer indicated that it supports the // extension protocol bool m_supports_extensions; char m_reserved_bits[20]; #endif bool m_supports_dht_port; bool m_supports_fast; #ifndef TORRENT_DISABLE_ENCRYPTION // this is set to true after the encryption method has been // succesfully negotiated (either plaintext or rc4), to signal // automatic encryption/decryption. bool m_encrypted; // true if rc4, false if plaintext bool m_rc4_encrypted; // used to disconnect peer if sync points are not found within // the maximum number of bytes int m_sync_bytes_read; // hold information about latest allocated send buffer // need to check for non zero (begin, end) for operations with this buffer::interval m_enc_send_buffer; // initialized during write_pe1_2_dhkey, and destroyed on // creation of m_RC4_handler. Cannot reinitialize once // initialized. boost::scoped_ptr<DH_key_exchange> m_dh_key_exchange; // if RC4 is negotiated, this is used for // encryption/decryption during the entire session. Destroyed // if plaintext is selected boost::scoped_ptr<RC4_handler> m_RC4_handler; // (outgoing only) synchronize verification constant with // remote peer, this will hold RC4_decrypt(vc). Destroyed // after the sync step. boost::scoped_array<char> m_sync_vc; // (incoming only) synchronize hash with remote peer, holds // the sync hash (hash("req1",secret)). Destroyed after the // sync step. boost::scoped_ptr<sha1_hash> m_sync_hash; #endif // #ifndef TORRENT_DISABLE_ENCRYPTION #ifndef NDEBUG // this is set to true when the client's // bitfield is sent to this peer bool m_sent_bitfield; bool m_in_constructor; bool m_sent_handshake; #endif }; } #endif // TORRENT_BT_PEER_CONNECTION_HPP_INCLUDED <commit_msg>fixed typo<commit_after>/* Copyright (c) 2003 - 2006, Arvid Norberg Copyright (c) 2007, Arvid Norberg, Un Shyam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_BT_PEER_CONNECTION_HPP_INCLUDED #define TORRENT_BT_PEER_CONNECTION_HPP_INCLUDED #include <ctime> #include <algorithm> #include <vector> #include <deque> #include <string> #include "libtorrent/debug.hpp" #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/smart_ptr.hpp> #include <boost/noncopyable.hpp> #include <boost/array.hpp> #include <boost/optional.hpp> #include <boost/cstdint.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/buffer.hpp" #include "libtorrent/peer_connection.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/peer_id.hpp" #include "libtorrent/storage.hpp" #include "libtorrent/stat.hpp" #include "libtorrent/alert.hpp" #include "libtorrent/torrent_handle.hpp" #include "libtorrent/torrent.hpp" #include "libtorrent/peer_request.hpp" #include "libtorrent/piece_block_progress.hpp" #include "libtorrent/config.hpp" #include "libtorrent/pe_crypto.hpp" namespace libtorrent { class torrent; namespace detail { struct session_impl; } class TORRENT_EXPORT bt_peer_connection : public peer_connection { friend class invariant_access; public: // this is the constructor where the we are the active part. // The peer_conenction should handshake and verify that the // other end has the correct id bt_peer_connection( aux::session_impl& ses , boost::weak_ptr<torrent> t , boost::shared_ptr<socket_type> s , tcp::endpoint const& remote , policy::peer* peerinfo); // with this constructor we have been contacted and we still don't // know which torrent the connection belongs to bt_peer_connection( aux::session_impl& ses , boost::shared_ptr<socket_type> s , tcp::endpoint const& remote , policy::peer* peerinfo); void start(); ~bt_peer_connection(); #ifndef TORRENT_DISABLE_ENCRYPTION bool supports_encryption() const { return m_encrypted; } #endif enum message_type { // standard messages msg_choke = 0, msg_unchoke, msg_interested, msg_not_interested, msg_have, msg_bitfield, msg_request, msg_piece, msg_cancel, // DHT extension msg_dht_port, // FAST extension msg_suggest_piece = 0xd, msg_have_all, msg_have_none, msg_reject_request, msg_allowed_fast, // extension protocol message msg_extended = 20, num_supported_messages }; // called from the main loop when this connection has any // work to do. void on_sent(error_code const& error , std::size_t bytes_transferred); void on_receive(error_code const& error , std::size_t bytes_transferred); virtual void get_specific_peer_info(peer_info& p) const; virtual bool in_handshake() const; #ifndef TORRENT_DISABLE_EXTENSIONS bool support_extensions() const { return m_supports_extensions; } template <class T> T* supports_extension() const { for (extension_list_t::const_iterator i = m_extensions.begin() , end(m_extensions.end()); i != end; ++i) { T* ret = dynamic_cast<T*>(i->get()); if (ret) return ret; } return 0; } #endif // the message handlers are called // each time a recv() returns some new // data, the last time it will be called // is when the entire packet has been // received, then it will no longer // be called. i.e. most handlers need // to check how much of the packet they // have received before any processing void on_keepalive(); void on_choke(int received); void on_unchoke(int received); void on_interested(int received); void on_not_interested(int received); void on_have(int received); void on_bitfield(int received); void on_request(int received); void on_piece(int received); void on_cancel(int received); // DHT extension void on_dht_port(int received); // FAST extension void on_suggest_piece(int received); void on_have_all(int received); void on_have_none(int received); void on_reject_request(int received); void on_allowed_fast(int received); void on_extended(int received); void on_extended_handshake(); typedef void (bt_peer_connection::*message_handler)(int received); // the following functions appends messages // to the send buffer void write_choke(); void write_unchoke(); void write_interested(); void write_not_interested(); void write_request(peer_request const& r); void write_cancel(peer_request const& r); void write_bitfield(); void write_have(int index); void write_piece(peer_request const& r, disk_buffer_holder& buffer); void write_handshake(); #ifndef TORRENT_DISABLE_EXTENSIONS void write_extensions(); #endif void write_chat_message(const std::string& msg); void write_metadata(std::pair<int, int> req); void write_metadata_request(std::pair<int, int> req); void write_keepalive(); // DHT extension void write_dht_port(int listen_port); // FAST extension void write_have_all(); void write_have_none(); void write_reject_request(peer_request const&); void write_allow_fast(int piece); void on_connected(); void on_metadata(); #ifndef NDEBUG void check_invariant() const; ptime m_last_choke; #endif private: bool dispatch_message(int received); // returns the block currently being // downloaded. And the progress of that // block. If the peer isn't downloading // a piece for the moment, the boost::optional // will be invalid. boost::optional<piece_block_progress> downloading_piece_progress() const; #ifndef TORRENT_DISABLE_ENCRYPTION // if (is_local()), we are 'a' otherwise 'b' // // 1. a -> b dhkey, pad // 2. b -> a dhkey, pad // 3. a -> b sync, payload // 4. b -> a sync, payload // 5. a -> b payload void write_pe1_2_dhkey(); void write_pe3_sync(); void write_pe4_sync(int crypto_select); void write_pe_vc_cryptofield(buffer::interval& write_buf, int crypto_field, int pad_size); // stream key (info hash of attached torrent) // secret is the DH shared secret // initializes m_RC4_handler void init_pe_RC4_handler(char const* secret, sha1_hash const& stream_key); public: // these functions encrypt the send buffer if m_rc4_encrypted // is true, otherwise it passes the call to the // peer_connection functions of the same names void send_buffer(char* buf, int size); buffer::interval allocate_send_buffer(int size); template <class Destructor> void append_send_buffer(char* buffer, int size, Destructor const& destructor) { #ifndef TORRENT_DISABLE_ENCRYPTION if (m_rc4_encrypted) m_RC4_handler->encrypt(buffer, size); #endif peer_connection::append_send_buffer(buffer, size, destructor); } void setup_send(); private: // Returns offset at which bytestream (src, src + src_size) // matches bytestream(target, target + target_size). // If no sync found, return -1 int get_syncoffset(char const* src, int src_size, char const* target, int target_size) const; #endif enum state { #ifndef TORRENT_DISABLE_ENCRYPTION read_pe_dhkey = 0, read_pe_syncvc, read_pe_synchash, read_pe_skey_vc, read_pe_cryptofield, read_pe_pad, read_pe_ia, init_bt_handshake, read_protocol_identifier, #else read_protocol_identifier = 0, #endif read_info_hash, read_peer_id, // handshake complete read_packet_size, read_packet }; #ifndef TORRENT_DISABLE_ENCRYPTION enum { handshake_len = 68, dh_key_len = 96 }; #endif std::string m_client_version; // state of on_receive state m_state; // the timeout in seconds int m_timeout; static const message_handler m_message_handler[num_supported_messages]; // this is a queue of ranges that describes // where in the send buffer actual payload // data is located. This is currently // only used to be able to gather statistics // seperately on payload and protocol data. struct range { range(int s, int l) : start(s) , length(l) { TORRENT_ASSERT(s >= 0); TORRENT_ASSERT(l > 0); } int start; int length; }; static bool range_below_zero(const range& r) { return r.start < 0; } std::deque<range> m_payloads; #ifndef TORRENT_DISABLE_EXTENSIONS // this is set to true if the handshake from // the peer indicated that it supports the // extension protocol bool m_supports_extensions; char m_reserved_bits[20]; #endif bool m_supports_dht_port; bool m_supports_fast; #ifndef TORRENT_DISABLE_ENCRYPTION // this is set to true after the encryption method has been // succesfully negotiated (either plaintext or rc4), to signal // automatic encryption/decryption. bool m_encrypted; // true if rc4, false if plaintext bool m_rc4_encrypted; // used to disconnect peer if sync points are not found within // the maximum number of bytes int m_sync_bytes_read; // hold information about latest allocated send buffer // need to check for non zero (begin, end) for operations with this buffer::interval m_enc_send_buffer; // initialized during write_pe1_2_dhkey, and destroyed on // creation of m_RC4_handler. Cannot reinitialize once // initialized. boost::scoped_ptr<dh_key_exchange> m_dh_key_exchange; // if RC4 is negotiated, this is used for // encryption/decryption during the entire session. Destroyed // if plaintext is selected boost::scoped_ptr<RC4_handler> m_RC4_handler; // (outgoing only) synchronize verification constant with // remote peer, this will hold RC4_decrypt(vc). Destroyed // after the sync step. boost::scoped_array<char> m_sync_vc; // (incoming only) synchronize hash with remote peer, holds // the sync hash (hash("req1",secret)). Destroyed after the // sync step. boost::scoped_ptr<sha1_hash> m_sync_hash; #endif // #ifndef TORRENT_DISABLE_ENCRYPTION #ifndef NDEBUG // this is set to true when the client's // bitfield is sent to this peer bool m_sent_bitfield; bool m_in_constructor; bool m_sent_handshake; #endif }; } #endif // TORRENT_BT_PEER_CONNECTION_HPP_INCLUDED <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_INTRUSIVE_PTR_BASE #define TORRENT_INTRUSIVE_PTR_BASE #include <boost/detail/atomic_count.hpp> #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" namespace libtorrent { template<class T> struct intrusive_ptr_base { intrusive_ptr_base(intrusive_ptr_base<T> const&) : m_refs(0) {} intrusive_ptr_base& operator=(intrusive_ptr_base const& rhs) {} friend void intrusive_ptr_add_ref(intrusive_ptr_base<T> const* s) { TORRENT_ASSERT(s->m_refs >= 0); TORRENT_ASSERT(s != 0); ++s->m_refs; } friend void intrusive_ptr_release(intrusive_ptr_base<T> const* s) { TORRENT_ASSERT(s->m_refs > 0); TORRENT_ASSERT(s != 0); if (--s->m_refs == 0) delete static_cast<T const*>(s); } boost::intrusive_ptr<T> self() { return boost::intrusive_ptr<T>((T*)this); } boost::intrusive_ptr<const T> self() const { return boost::intrusive_ptr<const T>((T const*)this); } int refcount() const { return m_refs; } intrusive_ptr_base(): m_refs(0) {} private: // reference counter for intrusive_ptr mutable boost::detail::atomic_count m_refs; }; } #endif <commit_msg>intrusive_ptr_base fix<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_INTRUSIVE_PTR_BASE #define TORRENT_INTRUSIVE_PTR_BASE #include <boost/detail/atomic_count.hpp> #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" namespace libtorrent { template<class T> struct intrusive_ptr_base { intrusive_ptr_base(intrusive_ptr_base<T> const&) : m_refs(0) {} intrusive_ptr_base& operator=(intrusive_ptr_base const& rhs) { return *this; } friend void intrusive_ptr_add_ref(intrusive_ptr_base<T> const* s) { TORRENT_ASSERT(s->m_refs >= 0); TORRENT_ASSERT(s != 0); ++s->m_refs; } friend void intrusive_ptr_release(intrusive_ptr_base<T> const* s) { TORRENT_ASSERT(s->m_refs > 0); TORRENT_ASSERT(s != 0); if (--s->m_refs == 0) delete static_cast<T const*>(s); } boost::intrusive_ptr<T> self() { return boost::intrusive_ptr<T>((T*)this); } boost::intrusive_ptr<const T> self() const { return boost::intrusive_ptr<const T>((T const*)this); } int refcount() const { return m_refs; } intrusive_ptr_base(): m_refs(0) {} private: // reference counter for intrusive_ptr mutable boost::detail::atomic_count m_refs; }; } #endif <|endoftext|>
<commit_before>// // cx_grid3D_def.hpp // uzlmath // // Created by Denis-Michael Lux on 08.06.15. // // #ifndef uzlmath_cx_grid3D_def_h #define uzlmath_cx_grid3D_def_h template< typename eT > inline grid3D< complex< eT > >::grid3D() : rows(0) , cols(0) , lays(0) , mem(nullptr) {} template< typename eT > inline grid3D< complex< eT > >::grid3D(const size_t& rows, const size_t& cols, const size_t& lays) : rows(rows) , cols(cols) , lays(lays) { if (rows == 0 || cols == 0 || lays == 0) { mem = nullptr; } else { mem = new complex< eT >[rows * cols * lays]; } } template< typename eT > inline grid3D< complex< eT > >::grid3D(const size_t& rcl) : rows(rcl) , cols(rcl) , lays(rcl) { if (rows == 0 || cols == 0 || lays == 0) { mem = nullptr; } else { mem = new complex< eT >[rows * cols * lays]; } } template< typename eT > inline grid3D< complex< eT > >::grid3D(const size_t& rows, const size_t& cols, const size_t& lays, const complex< eT >& initial) : rows(rows) , cols(cols) , lays(lays) { if (rows == 0 || cols == 0 || lays == 0) { mem = nullptr; } else { mem = new complex< eT >[rows * cols * lays]; // fill with initial values std::fill(mem, mem + rows * cols * lays, initial); } } template< typename eT > inline grid3D< complex< eT > >::grid3D(const size_t& rows, const size_t& cols, const size_t& lays, const eT& initial) : rows(rows) , cols(cols) , lays(lays) { if (rows == 0 || cols == 0 || lays == 0) { mem = nullptr; } else { mem = new complex< eT >[rows * cols * lays]; complex< eT > init(initial, 0); // fill with initial values std::fill(mem, mem + rows * cols * lays, init); } } template< typename eT > inline grid3D< complex< eT > >::grid3D(const size_t& rcl, const complex< eT >& initial) : rows(rcl) , cols(rcl) , lays(rcl) { if (rows == 0 || cols == 0 || lays == 0) { mem = nullptr; } else { mem = new complex< eT >[rows * cols * lays]; // fill with initial values std::fill(mem, mem + rows * cols * lays, initial); } } template< typename eT > inline grid3D< complex< eT > >::grid3D(const size_t& rcl, const eT& initial) : rows(rcl) , cols(rcl) , lays(rcl) { if (rows == 0 || cols == 0 || lays == 0) { mem = nullptr; } else { mem = new complex< eT >[rows * cols * lays]; complex< eT > init(initial, 0); // fill with initial values std::fill(mem, mem + rows * cols * lays, init); } } template< typename eT > inline grid3D< complex< eT > >::grid3D(const grid3D< eT >& c) : rows(c.rows) , cols(c.cols) , lays(c.lays) { mem = new complex< eT >[rows * cols * lays]; size_t i; for (i = 0; i < rows * cols * lays; ++i) { mem[i] = complex< eT >(c.mem[i], 0); } } template< typename eT > inline grid3D< complex< eT > >::grid3D(const grid3D< complex< eT > >& c) : rows(c.rows) , cols(c.cols) , lays(c.lays) { mem = new complex< eT >[rows * cols * lays]; memcpy(mem, c.mem, rows * cols * lays * sizeof(complex< eT >)); } template< typename eT > inline grid3D< complex< eT > >::grid3D(grid3D< complex< eT > >&& c) : rows(c.rows) , cols(c.cols) , lays(c.lays) { complex< eT >* tmp = mem; mem = c.mem; c.mem = tmp; } template< typename eT > inline grid3D< complex< eT > >::~grid3D() { delete [] mem; } template< typename eT > inline const grid3D< complex< eT > >& grid3D< complex< eT > >::operator=(const grid3D< eT >& c) { rows = c.rows; cols = c.cols; lays = c.lays; delete [] mem; mem = new complex< eT >[rows * cols * lays]; size_t i; for (i = 0; i < rows * cols * lays; ++i) { mem[i] = complex< eT >(c.mem[i], 0); } } template< typename eT > inline const grid3D< complex< eT > >& grid3D< complex< eT > >::operator=(const grid3D< complex< eT > >& c) { rows = c.rows; cols = c.cols; lays = c.lays; delete [] mem; mem = new complex< eT >[rows * cols * lays]; memcpy(mem, c.mem, rows * cols * lays * sizeof(complex< eT >)); } template< typename eT > inline const grid3D< complex< eT > >& grid3D< complex< eT > >::operator=(grid3D< complex< eT > >&& c) { rows = c.rows; cols = c.cols; lays = c.lays; complex< eT >* tmp = mem; mem = c.mem; c.mem = tmp; } template< typename eT > inline complex< eT >& grid3D< complex< eT > >::operator()(const size_t& row, const size_t& col, const size_t& lay) { return mem[rows * cols * lay + cols * col + row]; } template< typename eT > inline const complex< eT >& grid3D< complex< eT > >::operator()(const size_t& row, const size_t& col, const size_t& lay) const { return mem[rows * cols * lay + cols * col + row]; } template< typename eT > inline constexpr size_t grid3D< complex< eT > >::n_rows() const { return rows; } template< typename eT > inline constexpr size_t grid3D< complex< eT > >::n_cols() const { return cols; } template< typename eT > inline constexpr size_t grid3D< complex< eT > >::n_lays() const { return lays; } template< typename eT > inline void grid3D< complex< eT > >::layer_wise_DFT2(const complex< double >& scale) { // declare variables size_t i; double* data; // get correct data if (is_double< eT >::value == true) { // If the POD type is double we can just cast the // complex array to an double because memory layout // is guaranteed by the compiler data = reinterpret_cast< double* >(mem); } else { // If the POD type is not double we have to create a // copy of the memory and cast each element directly data = new double[2 * rows * cols * lays]; // Every second element is real or complex. Extract // them and store them in data. for (i = 0; i < rows * cols * lays; ++i) { data[i * 2] = static_cast< double >(mem[i].re); data[i * 2 + 1] = static_cast< double >(mem[i].im); } } // perform layerwise FFT2 uzl_fftw_layer_wise_DFT2_grid3D(cols, rows, lays, data); // skip if scale is default if (scale.re != 1 || scale.im != 0) { // scale data if (is_double< eT >::value == true) { for (i = 0; i < rows * cols * lays; ++i) { mem[i] *= scale; } } else { for (i = 0; i < rows * cols * lays; ++i) { mem[i] = complex< eT >(data[i * 2], data[i * 2 + 1]) * scale; } } } // free allocated memory if (is_double< eT >::value == false) { delete [] data; } } template< typename eT > inline void grid3D< complex< eT > >::layer_wise_IDFT2(const complex< double >& scale) { // declare variables size_t i; double* data; // get correct data if (is_double< eT >::value == true) { // If the POD type is double we can just cast the // complex array to an double because memory layout // is guaranteed by the compiler data = reinterpret_cast< double* >(mem); } else { // If the POD type is not double we have to create a // copy of the memory and cast each element directly data = new double[2 * rows * cols * lays]; // Every second element is real or complex. Extract // them and store them in data. for (i = 0; i < rows * cols * lays; ++i) { data[i * 2] = static_cast< double >(mem[i].re); data[i * 2 + 1] = static_cast< double >(mem[i].im); } } // perform layerwise FFT2 uzl_fftw_layer_wise_IDFT2_grid3D(cols, rows, lays, data); // skip if scale is default if (scale.re != 1 || scale.im != 0) { // scale data if (is_double< eT >::value == true) { for (i = 0; i < rows * cols * lays; ++i) { mem[i] *= scale; } } else { for (i = 0; i < rows * cols * lays; ++i) { mem[i] = complex< eT >(data[i * 2], data[i * 2 + 1]) * scale; } } } // free allocated memory if (is_double< eT >::value == false) { delete [] data; } } template< typename eT > inline complex< eT >* grid3D< complex< eT > >::memptr() { return mem; } template< typename eT > inline const complex< eT >* grid3D< complex< eT > >::memptr() const { return mem; } template< typename S > std::ostream& operator<<(std::ostream& o, const grid3D< complex< S > >& c) { std::ios::fmtflags f( std::cout.flags() ); o << std::endl; int width = 20; auto format = std::fixed; if (is_float< S >::value == false && is_double< S >::value == false && is_ldouble< S >::value == false) { width = 10; } // check values size_t x, y, z; for (z = 0; z < c.n_lays(); ++z) { for (x = 0; x < c.n_rows(); ++x) { for (y = 0; y < c.n_cols(); ++y) { complex< S > val = c(x, y, z); if (std::abs(val.re) >= 10 || std::abs(val.im) >= 10) { width = 22; format = std::fixed; if (is_float< S >::value == false && is_double< S >::value == false && is_ldouble< S >::value == false) { width = 12; } } if (std::abs(val.re) >= 100 || std::abs(val.im) >= 100) { width = 24; format = std::fixed; if (is_float< S >::value == false && is_double< S >::value == false && is_ldouble< S >::value == false) { width = 14; } } if (std::abs(val.re) >= 1000 || std::abs(val.im) >= 1000) { width = 28; format = std::scientific; if (is_float< S >::value == false && is_double< S >::value == false && is_ldouble< S >::value == false) { width = 18; } } } } } // setting decimal precesion for (z = 0; z < c.n_lays(); ++z) { // print layer number o << "layer[" << z << "]" << std::endl; // print numbers of layer for (x = 0; x < c.n_rows(); ++x) { for (y = 0; y < c.n_cols(); ++y) { // get entry complex< S > val = c(x, y, z); // create string std::ostringstream out; // add real value to string out << format << std::setprecision(4) << val.re; out << (val.im < 0 ? " - " : " + ") << (val.im == 0 ? 0 : std::abs(val.im)) << "i"; // get string from steram std::string str = out.str(); // set filling character o << std::setfill(' ') << std::right << std::setw(width) << str; } o << std::endl; } o << std::endl; } std::cout.flags( f ); return o; } #endif <commit_msg>Try to remove some changes<commit_after>// // cx_grid3D_def.hpp // uzlmath // // Created by Denis-Michael Lux on 08.06.15. // // #ifndef uzlmath_cx_grid3D_def_h #define uzlmath_cx_grid3D_def_h template< typename eT > inline grid3D< complex< eT > >::grid3D() : rows(0) , cols(0) , lays(0) , mem(nullptr) {} template< typename eT > inline grid3D< complex< eT > >::grid3D(const size_t& rows, const size_t& cols, const size_t& lays) : rows(rows) , cols(cols) , lays(lays) , mem(nullptr) { if (rows != 0 && cols != 0 && lays != 0) { mem = new complex< eT >[rows * cols * lays]; } } template< typename eT > inline grid3D< complex< eT > >::grid3D(const size_t& rcl) : rows(rcl) , cols(rcl) , lays(rcl) , mem(nullptr) { if (rows != 0 && cols != 0 && lays != 0) { mem = new complex< eT >[rows * cols * lays]; } } template< typename eT > inline grid3D< complex< eT > >::grid3D(const size_t& rows, const size_t& cols, const size_t& lays, const complex< eT >& initial) : rows(rows) , cols(cols) , lays(lays) { if (rows == 0 || cols == 0 || lays == 0) { mem = nullptr; } else { mem = new complex< eT >[rows * cols * lays]; // fill with initial values std::fill(mem, mem + rows * cols * lays, initial); } } template< typename eT > inline grid3D< complex< eT > >::grid3D(const size_t& rows, const size_t& cols, const size_t& lays, const eT& initial) : rows(rows) , cols(cols) , lays(lays) { if (rows == 0 || cols == 0 || lays == 0) { mem = nullptr; } else { mem = new complex< eT >[rows * cols * lays]; complex< eT > init(initial, 0); // fill with initial values std::fill(mem, mem + rows * cols * lays, init); } } template< typename eT > inline grid3D< complex< eT > >::grid3D(const size_t& rcl, const complex< eT >& initial) : rows(rcl) , cols(rcl) , lays(rcl) { if (rows == 0 || cols == 0 || lays == 0) { mem = nullptr; } else { mem = new complex< eT >[rows * cols * lays]; // fill with initial values std::fill(mem, mem + rows * cols * lays, initial); } } template< typename eT > inline grid3D< complex< eT > >::grid3D(const size_t& rcl, const eT& initial) : rows(rcl) , cols(rcl) , lays(rcl) { if (rows == 0 || cols == 0 || lays == 0) { mem = nullptr; } else { mem = new complex< eT >[rows * cols * lays]; complex< eT > init(initial, 0); // fill with initial values std::fill(mem, mem + rows * cols * lays, init); } } template< typename eT > inline grid3D< complex< eT > >::grid3D(const grid3D< eT >& c) : rows(c.rows) , cols(c.cols) , lays(c.lays) { mem = new complex< eT >[rows * cols * lays]; size_t i; for (i = 0; i < rows * cols * lays; ++i) { mem[i] = complex< eT >(c.mem[i], 0); } } template< typename eT > inline grid3D< complex< eT > >::grid3D(const grid3D< complex< eT > >& c) : rows(c.rows) , cols(c.cols) , lays(c.lays) { mem = new complex< eT >[rows * cols * lays]; memcpy(mem, c.mem, rows * cols * lays * sizeof(complex< eT >)); } template< typename eT > inline grid3D< complex< eT > >::grid3D(grid3D< complex< eT > >&& c) : rows(c.rows) , cols(c.cols) , lays(c.lays) { complex< eT >* tmp = mem; mem = c.mem; c.mem = tmp; } template< typename eT > inline grid3D< complex< eT > >::~grid3D() { delete [] mem; } template< typename eT > inline const grid3D< complex< eT > >& grid3D< complex< eT > >::operator=(const grid3D< eT >& c) { rows = c.rows; cols = c.cols; lays = c.lays; delete [] mem; mem = new complex< eT >[rows * cols * lays]; size_t i; for (i = 0; i < rows * cols * lays; ++i) { mem[i] = complex< eT >(c.mem[i], 0); } } template< typename eT > inline const grid3D< complex< eT > >& grid3D< complex< eT > >::operator=(const grid3D< complex< eT > >& c) { rows = c.rows; cols = c.cols; lays = c.lays; delete [] mem; mem = new complex< eT >[rows * cols * lays]; memcpy(mem, c.mem, rows * cols * lays * sizeof(complex< eT >)); } template< typename eT > inline const grid3D< complex< eT > >& grid3D< complex< eT > >::operator=(grid3D< complex< eT > >&& c) { rows = c.rows; cols = c.cols; lays = c.lays; complex< eT >* tmp = mem; mem = c.mem; c.mem = tmp; } template< typename eT > inline complex< eT >& grid3D< complex< eT > >::operator()(const size_t& row, const size_t& col, const size_t& lay) { return mem[rows * cols * lay + cols * col + row]; } template< typename eT > inline const complex< eT >& grid3D< complex< eT > >::operator()(const size_t& row, const size_t& col, const size_t& lay) const { return mem[rows * cols * lay + cols * col + row]; } template< typename eT > inline constexpr size_t grid3D< complex< eT > >::n_rows() const { return rows; } template< typename eT > inline constexpr size_t grid3D< complex< eT > >::n_cols() const { return cols; } template< typename eT > inline constexpr size_t grid3D< complex< eT > >::n_lays() const { return lays; } template< typename eT > inline void grid3D< complex< eT > >::layer_wise_DFT2(const complex< double >& scale) { // declare variables size_t i; double* data; // get correct data if (is_double< eT >::value == true) { // If the POD type is double we can just cast the // complex array to an double because memory layout // is guaranteed by the compiler data = reinterpret_cast< double* >(mem); } else { // If the POD type is not double we have to create a // copy of the memory and cast each element directly data = new double[2 * rows * cols * lays]; // Every second element is real or complex. Extract // them and store them in data. for (i = 0; i < rows * cols * lays; ++i) { data[i * 2] = static_cast< double >(mem[i].re); data[i * 2 + 1] = static_cast< double >(mem[i].im); } } // perform layerwise FFT2 uzl_fftw_layer_wise_DFT2_grid3D(cols, rows, lays, data); // skip if scale is default if (scale.re != 1 || scale.im != 0) { // scale data if (is_double< eT >::value == true) { for (i = 0; i < rows * cols * lays; ++i) { mem[i] *= scale; } } else { for (i = 0; i < rows * cols * lays; ++i) { mem[i] = complex< eT >(data[i * 2], data[i * 2 + 1]) * scale; } } } // free allocated memory if (is_double< eT >::value == false) { delete [] data; } } template< typename eT > inline void grid3D< complex< eT > >::layer_wise_IDFT2(const complex< double >& scale) { // declare variables size_t i; double* data; // get correct data if (is_double< eT >::value == true) { // If the POD type is double we can just cast the // complex array to an double because memory layout // is guaranteed by the compiler data = reinterpret_cast< double* >(mem); } else { // If the POD type is not double we have to create a // copy of the memory and cast each element directly data = new double[2 * rows * cols * lays]; // Every second element is real or complex. Extract // them and store them in data. for (i = 0; i < rows * cols * lays; ++i) { data[i * 2] = static_cast< double >(mem[i].re); data[i * 2 + 1] = static_cast< double >(mem[i].im); } } // perform layerwise FFT2 uzl_fftw_layer_wise_IDFT2_grid3D(cols, rows, lays, data); // skip if scale is default if (scale.re != 1 || scale.im != 0) { // scale data if (is_double< eT >::value == true) { for (i = 0; i < rows * cols * lays; ++i) { mem[i] *= scale; } } else { for (i = 0; i < rows * cols * lays; ++i) { mem[i] = complex< eT >(data[i * 2], data[i * 2 + 1]) * scale; } } } // free allocated memory if (is_double< eT >::value == false) { delete [] data; } } template< typename eT > inline complex< eT >* grid3D< complex< eT > >::memptr() { return mem; } template< typename eT > inline const complex< eT >* grid3D< complex< eT > >::memptr() const { return mem; } template< typename S > std::ostream& operator<<(std::ostream& o, const grid3D< complex< S > >& c) { std::ios::fmtflags f( std::cout.flags() ); o << std::endl; int width = 20; auto format = std::fixed; if (is_float< S >::value == false && is_double< S >::value == false && is_ldouble< S >::value == false) { width = 10; } // check values size_t x, y, z; for (z = 0; z < c.n_lays(); ++z) { for (x = 0; x < c.n_rows(); ++x) { for (y = 0; y < c.n_cols(); ++y) { complex< S > val = c(x, y, z); if (std::abs(val.re) >= 10 || std::abs(val.im) >= 10) { width = 22; format = std::fixed; if (is_float< S >::value == false && is_double< S >::value == false && is_ldouble< S >::value == false) { width = 12; } } if (std::abs(val.re) >= 100 || std::abs(val.im) >= 100) { width = 24; format = std::fixed; if (is_float< S >::value == false && is_double< S >::value == false && is_ldouble< S >::value == false) { width = 14; } } if (std::abs(val.re) >= 1000 || std::abs(val.im) >= 1000) { width = 28; format = std::scientific; if (is_float< S >::value == false && is_double< S >::value == false && is_ldouble< S >::value == false) { width = 18; } } } } } // setting decimal precesion for (z = 0; z < c.n_lays(); ++z) { // print layer number o << "layer[" << z << "]" << std::endl; // print numbers of layer for (x = 0; x < c.n_rows(); ++x) { for (y = 0; y < c.n_cols(); ++y) { // get entry complex< S > val = c(x, y, z); // create string std::ostringstream out; // add real value to string out << format << std::setprecision(4) << val.re; out << (val.im < 0 ? " - " : " + ") << (val.im == 0 ? 0 : std::abs(val.im)) << "i"; // get string from steram std::string str = out.str(); // set filling character o << std::setfill(' ') << std::right << std::setw(width) << str; } o << std::endl; } o << std::endl; } std::cout.flags( f ); return o; } #endif <|endoftext|>
<commit_before>#ifndef VSMC_MPI_NORMALIZING_CONSTANT_HPP #define VSMC_MPI_NORMALIZING_CONSTANT_HPP #include <vsmc/internal/common.hpp> #include <vsmc/core/normalizing_constant.hpp> #include <vsmc/mpi/manager.hpp> namespace vsmc { /// \brief Calculating normalizing constant ratio using MPI /// \ingroup SMP template <typename ID> class NormalizingConstantMPI : public NormalizingConstant { public : NormalizingConstantMPI (std::size_t N) : NormalizingConstant(N), world_(MPICommunicator<ID>::instance().get(), boost::mpi::comm_duplicate), internal_barrier_(true) {} const boost::mpi::communicator &world () const {return world_;} void barrier () const {if (internal_barrier_) world_.barrier();} void internal_barrier (bool use) {internal_barrier_ = use;} protected: double inc_zconst (std::size_t N, const double *weight, const double *inc_weight) const { double linc = NormalizingConstant::inc_zconst(N, weight, inc_weight); double ginc = 0; boost::mpi::all_reduce(world_, linc, ginc, std::plus<double>()); barrier(); return ginc; } private : boost::mpi::communicator world_; bool internal_barrier_; }; // class NormalizingConstantMPI } // namespace vsmc #endif // VSMC_MPI_NORMALIZING_CONSTANT_HPP <commit_msg>fix NormalizingConstantsMPI doc group<commit_after>#ifndef VSMC_MPI_NORMALIZING_CONSTANT_HPP #define VSMC_MPI_NORMALIZING_CONSTANT_HPP #include <vsmc/internal/common.hpp> #include <vsmc/core/normalizing_constant.hpp> #include <vsmc/mpi/manager.hpp> namespace vsmc { /// \brief Calculating normalizing constant ratio using MPI /// \ingroup MPI template <typename ID> class NormalizingConstantMPI : public NormalizingConstant { public : NormalizingConstantMPI (std::size_t N) : NormalizingConstant(N), world_(MPICommunicator<ID>::instance().get(), boost::mpi::comm_duplicate), internal_barrier_(true) {} const boost::mpi::communicator &world () const {return world_;} void barrier () const {if (internal_barrier_) world_.barrier();} void internal_barrier (bool use) {internal_barrier_ = use;} protected: double inc_zconst (std::size_t N, const double *weight, const double *inc_weight) const { double linc = NormalizingConstant::inc_zconst(N, weight, inc_weight); double ginc = 0; boost::mpi::all_reduce(world_, linc, ginc, std::plus<double>()); barrier(); return ginc; } private : boost::mpi::communicator world_; bool internal_barrier_; }; // class NormalizingConstantMPI } // namespace vsmc #endif // VSMC_MPI_NORMALIZING_CONSTANT_HPP <|endoftext|>
<commit_before>//===--- ImplicitBoolCastCheck.cpp - clang-tidy----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ImplicitBoolCastCheck.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Lex/Lexer.h" using namespace clang::ast_matchers; namespace clang { namespace tidy { namespace { const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr; AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) { return Node.getCastKind() == Kind; } AST_MATCHER(QualType, isBool) { return !Node.isNull() && Node->isBooleanType(); } AST_MATCHER(Stmt, isMacroExpansion) { SourceManager &SM = Finder->getASTContext().getSourceManager(); SourceLocation Loc = Node.getLocStart(); return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc); } bool isNULLMacroExpansion(const Stmt *Statement, ASTContext &Context) { SourceManager &SM = Context.getSourceManager(); const LangOptions &LO = Context.getLangOpts(); SourceLocation Loc = Statement->getLocStart(); return SM.isMacroBodyExpansion(Loc) && clang::Lexer::getImmediateMacroName(Loc, SM, LO) == "NULL"; } AST_MATCHER(Stmt, isNULLMacroExpansion) { return isNULLMacroExpansion(&Node, Finder->getASTContext()); } ast_matchers::internal::Matcher<Expr> createExceptionCasesMatcher() { return expr(anyOf(hasParent(explicitCastExpr()), allOf(isMacroExpansion(), unless(isNULLMacroExpansion())), isInTemplateInstantiation(), hasAncestor(functionTemplateDecl()))); } StatementMatcher createImplicitCastFromBoolMatcher() { return implicitCastExpr( unless(createExceptionCasesMatcher()), anyOf(hasCastKind(CK_IntegralCast), hasCastKind(CK_IntegralToFloating), // Prior to C++11 cast from bool literal to pointer was allowed. allOf(anyOf(hasCastKind(CK_NullToPointer), hasCastKind(CK_NullToMemberPointer)), hasSourceExpression(cxxBoolLiteral()))), hasSourceExpression(expr(hasType(qualType(isBool()))))); } StringRef getZeroLiteralToCompareWithForGivenType(CastKind CastExpressionKind, QualType CastSubExpressionType, ASTContext &Context) { switch (CastExpressionKind) { case CK_IntegralToBoolean: return CastSubExpressionType->isUnsignedIntegerType() ? "0u" : "0"; case CK_FloatingToBoolean: return Context.hasSameType(CastSubExpressionType, Context.FloatTy) ? "0.0f" : "0.0"; case CK_PointerToBoolean: case CK_MemberPointerToBoolean: // Fall-through on purpose. return Context.getLangOpts().CPlusPlus11 ? "nullptr" : "0"; default: assert(false && "Unexpected cast kind"); } } bool isUnaryLogicalNotOperator(const Stmt *Statement) { const auto *UnaryOperatorExpression = llvm::dyn_cast<UnaryOperator>(Statement); return UnaryOperatorExpression != nullptr && UnaryOperatorExpression->getOpcode() == UO_LNot; } bool areParensNeededForOverloadedOperator(OverloadedOperatorKind OperatorKind) { switch (OperatorKind) { case OO_New: case OO_Delete: // Fall-through on purpose. case OO_Array_New: case OO_Array_Delete: case OO_ArrowStar: case OO_Arrow: case OO_Call: case OO_Subscript: return false; default: return true; } } bool areParensNeededForStatement(const Stmt *Statement) { if (const CXXOperatorCallExpr *OverloadedOperatorCall = llvm::dyn_cast<CXXOperatorCallExpr>(Statement)) { return areParensNeededForOverloadedOperator( OverloadedOperatorCall->getOperator()); } return llvm::isa<BinaryOperator>(Statement) || llvm::isa<UnaryOperator>(Statement); } void addFixItHintsForGenericExpressionCastToBool( DiagnosticBuilder &Diagnostic, const ImplicitCastExpr *CastExpression, const Stmt *ParentStatement, ASTContext &Context) { // In case of expressions like (! integer), we should remove the redundant not // operator and use inverted comparison (integer == 0). bool InvertComparison = ParentStatement != nullptr && isUnaryLogicalNotOperator(ParentStatement); if (InvertComparison) { SourceLocation ParentStartLoc = ParentStatement->getLocStart(); SourceLocation ParentEndLoc = llvm::cast<UnaryOperator>(ParentStatement)->getSubExpr()->getLocStart(); Diagnostic.AddFixItHint(FixItHint::CreateRemoval( CharSourceRange::getCharRange(ParentStartLoc, ParentEndLoc))); auto FurtherParents = Context.getParents(*ParentStatement); ParentStatement = FurtherParents[0].get<Stmt>(); } const Expr *SubExpression = CastExpression->getSubExpr(); bool NeedInnerParens = areParensNeededForStatement(SubExpression); bool NeedOuterParens = ParentStatement != nullptr && areParensNeededForStatement(ParentStatement); std::string StartLocInsertion; if (NeedOuterParens) { StartLocInsertion += "("; } if (NeedInnerParens) { StartLocInsertion += "("; } if (!StartLocInsertion.empty()) { SourceLocation StartLoc = CastExpression->getLocStart(); Diagnostic.AddFixItHint( FixItHint::CreateInsertion(StartLoc, StartLocInsertion)); } std::string EndLocInsertion; if (NeedInnerParens) { EndLocInsertion += ")"; } if (InvertComparison) { EndLocInsertion += " == "; } else { EndLocInsertion += " != "; } EndLocInsertion += getZeroLiteralToCompareWithForGivenType( CastExpression->getCastKind(), SubExpression->getType(), Context); if (NeedOuterParens) { EndLocInsertion += ")"; } SourceLocation EndLoc = Lexer::getLocForEndOfToken( CastExpression->getLocEnd(), 0, Context.getSourceManager(), Context.getLangOpts()); Diagnostic.AddFixItHint(FixItHint::CreateInsertion(EndLoc, EndLocInsertion)); } StringRef getEquivalentBoolLiteralForExpression(const Expr *Expression, ASTContext &Context) { if (isNULLMacroExpansion(Expression, Context)) { return "false"; } if (const auto *IntLit = llvm::dyn_cast<IntegerLiteral>(Expression)) { return (IntLit->getValue() == 0) ? "false" : "true"; } if (const auto *FloatLit = llvm::dyn_cast<FloatingLiteral>(Expression)) { llvm::APFloat FloatLitAbsValue = FloatLit->getValue(); FloatLitAbsValue.clearSign(); return (FloatLitAbsValue.bitcastToAPInt() == 0) ? "false" : "true"; } if (const auto *CharLit = llvm::dyn_cast<CharacterLiteral>(Expression)) { return (CharLit->getValue() == 0) ? "false" : "true"; } if (llvm::isa<StringLiteral>(Expression->IgnoreCasts())) { return "true"; } return StringRef(); } void addFixItHintsForLiteralCastToBool(DiagnosticBuilder &Diagnostic, const ImplicitCastExpr *CastExpression, StringRef EquivalentLiteralExpression) { SourceLocation StartLoc = CastExpression->getLocStart(); SourceLocation EndLoc = CastExpression->getLocEnd(); Diagnostic.AddFixItHint(FixItHint::CreateReplacement( CharSourceRange::getTokenRange(StartLoc, EndLoc), EquivalentLiteralExpression)); } void addFixItHintsForGenericExpressionCastFromBool( DiagnosticBuilder &Diagnostic, const ImplicitCastExpr *CastExpression, ASTContext &Context, StringRef OtherType) { const Expr *SubExpression = CastExpression->getSubExpr(); bool NeedParens = !llvm::isa<ParenExpr>(SubExpression); std::string StartLocInsertion = "static_cast<"; StartLocInsertion += OtherType.str(); StartLocInsertion += ">"; if (NeedParens) { StartLocInsertion += "("; } SourceLocation StartLoc = CastExpression->getLocStart(); Diagnostic.AddFixItHint( FixItHint::CreateInsertion(StartLoc, StartLocInsertion)); if (NeedParens) { SourceLocation EndLoc = Lexer::getLocForEndOfToken( CastExpression->getLocEnd(), 0, Context.getSourceManager(), Context.getLangOpts()); Diagnostic.AddFixItHint(FixItHint::CreateInsertion(EndLoc, ")")); } } StringRef getEquivalentLiteralForBoolLiteral( const CXXBoolLiteralExpr *BoolLiteralExpression, QualType DestinationType, ASTContext &Context) { // Prior to C++11, false literal could be implicitly converted to pointer. if (!Context.getLangOpts().CPlusPlus11 && (DestinationType->isPointerType() || DestinationType->isMemberPointerType()) && BoolLiteralExpression->getValue() == false) { return "0"; } if (DestinationType->isFloatingType()) { if (BoolLiteralExpression->getValue() == true) { return Context.hasSameType(DestinationType, Context.FloatTy) ? "1.0f" : "1.0"; } return Context.hasSameType(DestinationType, Context.FloatTy) ? "0.0f" : "0.0"; } if (BoolLiteralExpression->getValue() == true) { return DestinationType->isUnsignedIntegerType() ? "1u" : "1"; } return DestinationType->isUnsignedIntegerType() ? "0u" : "0"; } void addFixItHintsForLiteralCastFromBool(DiagnosticBuilder &Diagnostic, const ImplicitCastExpr *CastExpression, ASTContext &Context, QualType DestinationType) { SourceLocation StartLoc = CastExpression->getLocStart(); SourceLocation EndLoc = CastExpression->getLocEnd(); const auto *BoolLiteralExpression = llvm::dyn_cast<CXXBoolLiteralExpr>(CastExpression->getSubExpr()); Diagnostic.AddFixItHint(FixItHint::CreateReplacement( CharSourceRange::getTokenRange(StartLoc, EndLoc), getEquivalentLiteralForBoolLiteral(BoolLiteralExpression, DestinationType, Context))); } StatementMatcher createConditionalExpressionMatcher() { return stmt(anyOf(ifStmt(), conditionalOperator(), parenExpr(hasParent(conditionalOperator())))); } bool isAllowedConditionalCast(const ImplicitCastExpr *CastExpression, ASTContext &Context) { auto AllowedConditionalMatcher = stmt(hasParent(stmt( anyOf(createConditionalExpressionMatcher(), unaryOperator(hasOperatorName("!"), hasParent(createConditionalExpressionMatcher())))))); auto MatchResult = match(AllowedConditionalMatcher, *CastExpression, Context); return !MatchResult.empty(); } } // anonymous namespace void ImplicitBoolCastCheck::registerMatchers(MatchFinder *Finder) { // This check doesn't make much sense if we run it on language without // built-in bool support. if (!getLangOpts().Bool) { return; } Finder->addMatcher( implicitCastExpr( // Exclude cases common to implicit cast to and from bool. unless(createExceptionCasesMatcher()), // Exclude case of using if or while statements with variable // declaration, e.g.: // if (int var = functionCall()) {} unless( hasParent(stmt(anyOf(ifStmt(), whileStmt()), has(declStmt())))), anyOf(hasCastKind(CK_IntegralToBoolean), hasCastKind(CK_FloatingToBoolean), hasCastKind(CK_PointerToBoolean), hasCastKind(CK_MemberPointerToBoolean)), // Retrive also parent statement, to check if we need additional // parens in replacement. anyOf(hasParent(stmt().bind("parentStmt")), anything())) .bind("implicitCastToBool"), this); Finder->addMatcher( implicitCastExpr( createImplicitCastFromBoolMatcher(), // Exclude comparisons of bools, as they are always cast to integers // in such context: // bool_expr_a == bool_expr_b // bool_expr_a != bool_expr_b unless(hasParent(binaryOperator( anyOf(hasOperatorName("=="), hasOperatorName("!=")), hasLHS(createImplicitCastFromBoolMatcher()), hasRHS(createImplicitCastFromBoolMatcher())))), // Check also for nested casts, for example: bool -> int -> float. anyOf(hasParent(implicitCastExpr().bind("furtherImplicitCast")), anything())) .bind("implicitCastFromBool"), this); } void ImplicitBoolCastCheck::check(const MatchFinder::MatchResult &Result) { if (const auto *CastToBool = Result.Nodes.getNodeAs<ImplicitCastExpr>("implicitCastToBool")) { const auto *ParentStatement = Result.Nodes.getNodeAs<Stmt>("parentStmt"); return handleCastToBool(CastToBool, ParentStatement, *Result.Context); } if (const auto *CastFromBool = Result.Nodes.getNodeAs<ImplicitCastExpr>("implicitCastFromBool")) { const auto *FurtherImplicitCastExpression = Result.Nodes.getNodeAs<ImplicitCastExpr>("furtherImplicitCast"); return handleCastFromBool(CastFromBool, FurtherImplicitCastExpression, *Result.Context); } } void ImplicitBoolCastCheck::handleCastToBool( const ImplicitCastExpr *CastExpression, const Stmt *ParentStatement, ASTContext &Context) { if (AllowConditionalPointerCasts && (CastExpression->getCastKind() == CK_PointerToBoolean || CastExpression->getCastKind() == CK_MemberPointerToBoolean) && isAllowedConditionalCast(CastExpression, Context)) { return; } if (AllowConditionalIntegerCasts && CastExpression->getCastKind() == CK_IntegralToBoolean && isAllowedConditionalCast(CastExpression, Context)) { return; } std::string OtherType = CastExpression->getSubExpr()->getType().getAsString(); DiagnosticBuilder Diagnostic = diag(CastExpression->getLocStart(), "implicit cast '%0' -> bool") << OtherType; StringRef EquivalentLiteralExpression = getEquivalentBoolLiteralForExpression( CastExpression->getSubExpr(), Context); if (!EquivalentLiteralExpression.empty()) { addFixItHintsForLiteralCastToBool(Diagnostic, CastExpression, EquivalentLiteralExpression); } else { addFixItHintsForGenericExpressionCastToBool(Diagnostic, CastExpression, ParentStatement, Context); } } void ImplicitBoolCastCheck::handleCastFromBool( const ImplicitCastExpr *CastExpression, const ImplicitCastExpr *FurtherImplicitCastExpression, ASTContext &Context) { QualType DestinationType = (FurtherImplicitCastExpression != nullptr) ? FurtherImplicitCastExpression->getType() : CastExpression->getType(); std::string DestinationTypeString = DestinationType.getAsString(); DiagnosticBuilder Diagnostic = diag(CastExpression->getLocStart(), "implicit cast bool -> '%0'") << DestinationTypeString; if (llvm::isa<CXXBoolLiteralExpr>(CastExpression->getSubExpr())) { addFixItHintsForLiteralCastFromBool(Diagnostic, CastExpression, Context, DestinationType); } else { addFixItHintsForGenericExpressionCastFromBool( Diagnostic, CastExpression, Context, DestinationTypeString); } } } // namespace tidy } // namespace clang <commit_msg>[clang-tidy] Add return value for non-assert builds.<commit_after>//===--- ImplicitBoolCastCheck.cpp - clang-tidy----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ImplicitBoolCastCheck.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Lex/Lexer.h" using namespace clang::ast_matchers; namespace clang { namespace tidy { namespace { const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr; AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) { return Node.getCastKind() == Kind; } AST_MATCHER(QualType, isBool) { return !Node.isNull() && Node->isBooleanType(); } AST_MATCHER(Stmt, isMacroExpansion) { SourceManager &SM = Finder->getASTContext().getSourceManager(); SourceLocation Loc = Node.getLocStart(); return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc); } bool isNULLMacroExpansion(const Stmt *Statement, ASTContext &Context) { SourceManager &SM = Context.getSourceManager(); const LangOptions &LO = Context.getLangOpts(); SourceLocation Loc = Statement->getLocStart(); return SM.isMacroBodyExpansion(Loc) && clang::Lexer::getImmediateMacroName(Loc, SM, LO) == "NULL"; } AST_MATCHER(Stmt, isNULLMacroExpansion) { return isNULLMacroExpansion(&Node, Finder->getASTContext()); } ast_matchers::internal::Matcher<Expr> createExceptionCasesMatcher() { return expr(anyOf(hasParent(explicitCastExpr()), allOf(isMacroExpansion(), unless(isNULLMacroExpansion())), isInTemplateInstantiation(), hasAncestor(functionTemplateDecl()))); } StatementMatcher createImplicitCastFromBoolMatcher() { return implicitCastExpr( unless(createExceptionCasesMatcher()), anyOf(hasCastKind(CK_IntegralCast), hasCastKind(CK_IntegralToFloating), // Prior to C++11 cast from bool literal to pointer was allowed. allOf(anyOf(hasCastKind(CK_NullToPointer), hasCastKind(CK_NullToMemberPointer)), hasSourceExpression(cxxBoolLiteral()))), hasSourceExpression(expr(hasType(qualType(isBool()))))); } StringRef getZeroLiteralToCompareWithForGivenType(CastKind CastExpressionKind, QualType CastSubExpressionType, ASTContext &Context) { switch (CastExpressionKind) { case CK_IntegralToBoolean: return CastSubExpressionType->isUnsignedIntegerType() ? "0u" : "0"; case CK_FloatingToBoolean: return Context.hasSameType(CastSubExpressionType, Context.FloatTy) ? "0.0f" : "0.0"; case CK_PointerToBoolean: case CK_MemberPointerToBoolean: // Fall-through on purpose. return Context.getLangOpts().CPlusPlus11 ? "nullptr" : "0"; default: assert(false && "Unexpected cast kind"); } return ""; } bool isUnaryLogicalNotOperator(const Stmt *Statement) { const auto *UnaryOperatorExpression = llvm::dyn_cast<UnaryOperator>(Statement); return UnaryOperatorExpression != nullptr && UnaryOperatorExpression->getOpcode() == UO_LNot; } bool areParensNeededForOverloadedOperator(OverloadedOperatorKind OperatorKind) { switch (OperatorKind) { case OO_New: case OO_Delete: // Fall-through on purpose. case OO_Array_New: case OO_Array_Delete: case OO_ArrowStar: case OO_Arrow: case OO_Call: case OO_Subscript: return false; default: return true; } } bool areParensNeededForStatement(const Stmt *Statement) { if (const CXXOperatorCallExpr *OverloadedOperatorCall = llvm::dyn_cast<CXXOperatorCallExpr>(Statement)) { return areParensNeededForOverloadedOperator( OverloadedOperatorCall->getOperator()); } return llvm::isa<BinaryOperator>(Statement) || llvm::isa<UnaryOperator>(Statement); } void addFixItHintsForGenericExpressionCastToBool( DiagnosticBuilder &Diagnostic, const ImplicitCastExpr *CastExpression, const Stmt *ParentStatement, ASTContext &Context) { // In case of expressions like (! integer), we should remove the redundant not // operator and use inverted comparison (integer == 0). bool InvertComparison = ParentStatement != nullptr && isUnaryLogicalNotOperator(ParentStatement); if (InvertComparison) { SourceLocation ParentStartLoc = ParentStatement->getLocStart(); SourceLocation ParentEndLoc = llvm::cast<UnaryOperator>(ParentStatement)->getSubExpr()->getLocStart(); Diagnostic.AddFixItHint(FixItHint::CreateRemoval( CharSourceRange::getCharRange(ParentStartLoc, ParentEndLoc))); auto FurtherParents = Context.getParents(*ParentStatement); ParentStatement = FurtherParents[0].get<Stmt>(); } const Expr *SubExpression = CastExpression->getSubExpr(); bool NeedInnerParens = areParensNeededForStatement(SubExpression); bool NeedOuterParens = ParentStatement != nullptr && areParensNeededForStatement(ParentStatement); std::string StartLocInsertion; if (NeedOuterParens) { StartLocInsertion += "("; } if (NeedInnerParens) { StartLocInsertion += "("; } if (!StartLocInsertion.empty()) { SourceLocation StartLoc = CastExpression->getLocStart(); Diagnostic.AddFixItHint( FixItHint::CreateInsertion(StartLoc, StartLocInsertion)); } std::string EndLocInsertion; if (NeedInnerParens) { EndLocInsertion += ")"; } if (InvertComparison) { EndLocInsertion += " == "; } else { EndLocInsertion += " != "; } EndLocInsertion += getZeroLiteralToCompareWithForGivenType( CastExpression->getCastKind(), SubExpression->getType(), Context); if (NeedOuterParens) { EndLocInsertion += ")"; } SourceLocation EndLoc = Lexer::getLocForEndOfToken( CastExpression->getLocEnd(), 0, Context.getSourceManager(), Context.getLangOpts()); Diagnostic.AddFixItHint(FixItHint::CreateInsertion(EndLoc, EndLocInsertion)); } StringRef getEquivalentBoolLiteralForExpression(const Expr *Expression, ASTContext &Context) { if (isNULLMacroExpansion(Expression, Context)) { return "false"; } if (const auto *IntLit = llvm::dyn_cast<IntegerLiteral>(Expression)) { return (IntLit->getValue() == 0) ? "false" : "true"; } if (const auto *FloatLit = llvm::dyn_cast<FloatingLiteral>(Expression)) { llvm::APFloat FloatLitAbsValue = FloatLit->getValue(); FloatLitAbsValue.clearSign(); return (FloatLitAbsValue.bitcastToAPInt() == 0) ? "false" : "true"; } if (const auto *CharLit = llvm::dyn_cast<CharacterLiteral>(Expression)) { return (CharLit->getValue() == 0) ? "false" : "true"; } if (llvm::isa<StringLiteral>(Expression->IgnoreCasts())) { return "true"; } return StringRef(); } void addFixItHintsForLiteralCastToBool(DiagnosticBuilder &Diagnostic, const ImplicitCastExpr *CastExpression, StringRef EquivalentLiteralExpression) { SourceLocation StartLoc = CastExpression->getLocStart(); SourceLocation EndLoc = CastExpression->getLocEnd(); Diagnostic.AddFixItHint(FixItHint::CreateReplacement( CharSourceRange::getTokenRange(StartLoc, EndLoc), EquivalentLiteralExpression)); } void addFixItHintsForGenericExpressionCastFromBool( DiagnosticBuilder &Diagnostic, const ImplicitCastExpr *CastExpression, ASTContext &Context, StringRef OtherType) { const Expr *SubExpression = CastExpression->getSubExpr(); bool NeedParens = !llvm::isa<ParenExpr>(SubExpression); std::string StartLocInsertion = "static_cast<"; StartLocInsertion += OtherType.str(); StartLocInsertion += ">"; if (NeedParens) { StartLocInsertion += "("; } SourceLocation StartLoc = CastExpression->getLocStart(); Diagnostic.AddFixItHint( FixItHint::CreateInsertion(StartLoc, StartLocInsertion)); if (NeedParens) { SourceLocation EndLoc = Lexer::getLocForEndOfToken( CastExpression->getLocEnd(), 0, Context.getSourceManager(), Context.getLangOpts()); Diagnostic.AddFixItHint(FixItHint::CreateInsertion(EndLoc, ")")); } } StringRef getEquivalentLiteralForBoolLiteral( const CXXBoolLiteralExpr *BoolLiteralExpression, QualType DestinationType, ASTContext &Context) { // Prior to C++11, false literal could be implicitly converted to pointer. if (!Context.getLangOpts().CPlusPlus11 && (DestinationType->isPointerType() || DestinationType->isMemberPointerType()) && BoolLiteralExpression->getValue() == false) { return "0"; } if (DestinationType->isFloatingType()) { if (BoolLiteralExpression->getValue() == true) { return Context.hasSameType(DestinationType, Context.FloatTy) ? "1.0f" : "1.0"; } return Context.hasSameType(DestinationType, Context.FloatTy) ? "0.0f" : "0.0"; } if (BoolLiteralExpression->getValue() == true) { return DestinationType->isUnsignedIntegerType() ? "1u" : "1"; } return DestinationType->isUnsignedIntegerType() ? "0u" : "0"; } void addFixItHintsForLiteralCastFromBool(DiagnosticBuilder &Diagnostic, const ImplicitCastExpr *CastExpression, ASTContext &Context, QualType DestinationType) { SourceLocation StartLoc = CastExpression->getLocStart(); SourceLocation EndLoc = CastExpression->getLocEnd(); const auto *BoolLiteralExpression = llvm::dyn_cast<CXXBoolLiteralExpr>(CastExpression->getSubExpr()); Diagnostic.AddFixItHint(FixItHint::CreateReplacement( CharSourceRange::getTokenRange(StartLoc, EndLoc), getEquivalentLiteralForBoolLiteral(BoolLiteralExpression, DestinationType, Context))); } StatementMatcher createConditionalExpressionMatcher() { return stmt(anyOf(ifStmt(), conditionalOperator(), parenExpr(hasParent(conditionalOperator())))); } bool isAllowedConditionalCast(const ImplicitCastExpr *CastExpression, ASTContext &Context) { auto AllowedConditionalMatcher = stmt(hasParent(stmt( anyOf(createConditionalExpressionMatcher(), unaryOperator(hasOperatorName("!"), hasParent(createConditionalExpressionMatcher())))))); auto MatchResult = match(AllowedConditionalMatcher, *CastExpression, Context); return !MatchResult.empty(); } } // anonymous namespace void ImplicitBoolCastCheck::registerMatchers(MatchFinder *Finder) { // This check doesn't make much sense if we run it on language without // built-in bool support. if (!getLangOpts().Bool) { return; } Finder->addMatcher( implicitCastExpr( // Exclude cases common to implicit cast to and from bool. unless(createExceptionCasesMatcher()), // Exclude case of using if or while statements with variable // declaration, e.g.: // if (int var = functionCall()) {} unless( hasParent(stmt(anyOf(ifStmt(), whileStmt()), has(declStmt())))), anyOf(hasCastKind(CK_IntegralToBoolean), hasCastKind(CK_FloatingToBoolean), hasCastKind(CK_PointerToBoolean), hasCastKind(CK_MemberPointerToBoolean)), // Retrive also parent statement, to check if we need additional // parens in replacement. anyOf(hasParent(stmt().bind("parentStmt")), anything())) .bind("implicitCastToBool"), this); Finder->addMatcher( implicitCastExpr( createImplicitCastFromBoolMatcher(), // Exclude comparisons of bools, as they are always cast to integers // in such context: // bool_expr_a == bool_expr_b // bool_expr_a != bool_expr_b unless(hasParent(binaryOperator( anyOf(hasOperatorName("=="), hasOperatorName("!=")), hasLHS(createImplicitCastFromBoolMatcher()), hasRHS(createImplicitCastFromBoolMatcher())))), // Check also for nested casts, for example: bool -> int -> float. anyOf(hasParent(implicitCastExpr().bind("furtherImplicitCast")), anything())) .bind("implicitCastFromBool"), this); } void ImplicitBoolCastCheck::check(const MatchFinder::MatchResult &Result) { if (const auto *CastToBool = Result.Nodes.getNodeAs<ImplicitCastExpr>("implicitCastToBool")) { const auto *ParentStatement = Result.Nodes.getNodeAs<Stmt>("parentStmt"); return handleCastToBool(CastToBool, ParentStatement, *Result.Context); } if (const auto *CastFromBool = Result.Nodes.getNodeAs<ImplicitCastExpr>("implicitCastFromBool")) { const auto *FurtherImplicitCastExpression = Result.Nodes.getNodeAs<ImplicitCastExpr>("furtherImplicitCast"); return handleCastFromBool(CastFromBool, FurtherImplicitCastExpression, *Result.Context); } } void ImplicitBoolCastCheck::handleCastToBool( const ImplicitCastExpr *CastExpression, const Stmt *ParentStatement, ASTContext &Context) { if (AllowConditionalPointerCasts && (CastExpression->getCastKind() == CK_PointerToBoolean || CastExpression->getCastKind() == CK_MemberPointerToBoolean) && isAllowedConditionalCast(CastExpression, Context)) { return; } if (AllowConditionalIntegerCasts && CastExpression->getCastKind() == CK_IntegralToBoolean && isAllowedConditionalCast(CastExpression, Context)) { return; } std::string OtherType = CastExpression->getSubExpr()->getType().getAsString(); DiagnosticBuilder Diagnostic = diag(CastExpression->getLocStart(), "implicit cast '%0' -> bool") << OtherType; StringRef EquivalentLiteralExpression = getEquivalentBoolLiteralForExpression( CastExpression->getSubExpr(), Context); if (!EquivalentLiteralExpression.empty()) { addFixItHintsForLiteralCastToBool(Diagnostic, CastExpression, EquivalentLiteralExpression); } else { addFixItHintsForGenericExpressionCastToBool(Diagnostic, CastExpression, ParentStatement, Context); } } void ImplicitBoolCastCheck::handleCastFromBool( const ImplicitCastExpr *CastExpression, const ImplicitCastExpr *FurtherImplicitCastExpression, ASTContext &Context) { QualType DestinationType = (FurtherImplicitCastExpression != nullptr) ? FurtherImplicitCastExpression->getType() : CastExpression->getType(); std::string DestinationTypeString = DestinationType.getAsString(); DiagnosticBuilder Diagnostic = diag(CastExpression->getLocStart(), "implicit cast bool -> '%0'") << DestinationTypeString; if (llvm::isa<CXXBoolLiteralExpr>(CastExpression->getSubExpr())) { addFixItHintsForLiteralCastFromBool(Diagnostic, CastExpression, Context, DestinationType); } else { addFixItHintsForGenericExpressionCastFromBool( Diagnostic, CastExpression, Context, DestinationTypeString); } } } // namespace tidy } // namespace clang <|endoftext|>
<commit_before>#include "omp.h" inline kth_cv_svm::kth_cv_svm(const std::string in_path, const std::string in_actionNames, const field<std::string> in_all_people, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_dim ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), dim(in_dim) { actions.load( actionNames ); } // Log-Euclidean Distance inline void kth_cv_svm::logEucl() { //logEucl_distances(); logEucl_CV(); //cross validation; } inline void kth_cv_svm::logEucl_CV() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 int n_test = (n_peo-1)*n_actions*total_scenes; // - person13_handclapping_d3 int n_dim = n_test; int sc = 1; // = total scenes fvec dist_vector; float acc=0; vec real_labels; vec est_labels; field<std::string> test_video_list(n_test); real_labels.zeros(n_test); est_labels.zeros(n_test); int j =0; for (int pe_ts=0; pe_ts<n_peo; ++pe_ts) { fmat training_data; fvec lab; training_data.zeros(n_dim,n_test); lab.zeros(n_test); int k=0; for (int pe_tr=0; pe_tr<n_peo; ++pe_tr) { if(pe_tr!=pe_ts) for (int act=0; act<n_actions; act++) { std::stringstream load_vec_dist; load_vec_dist << path << "./classification/kth-svm/logEucl/dist_vector_" << all_people (pe_tr) << "_" << actions(act) << ".h5" ; dist_vector.load( load_vec_dist.str() ); training_data.col(k) = dist_vector; lab(k) = act; ++k; } } //Training the model with OpenCV cout << "Preparing data to train the data" << endl; cv::Mat cvMatTraining(n_test, n_dim, CV_32FC1); float fl_labels[n_test] ; for (uword m=0; m<n_test; ++m) { for (uword d=0; d<n_dim; ++d) { cvMatTraining.at<float>(m,d) = training_data(d,m); //cout << " OpenCV: " << cvMatTraining.at<float>(m,d) << " - Arma: " <<training_data(d,m); } fl_labels[m] = lab(m); //cout <<" OpenCVLabel: " << fl_labels[m] << " ArmaLabel: " << labels(m) << endl; } cv::Mat cvMatLabels(n_test, 1, CV_32FC1,fl_labels ); cout << "Setting parameters" << endl; CvSVMParams params; params.svm_type = CvSVM::C_SVC; params.kernel_type = CvSVM::RBF; params.gamma = 1; params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, (int)1e7, 1e-6); // Train the SVM cout << "Training" << endl; CvSVM SVM; SVM.train( cvMatTraining , cvMatLabels, cv::Mat(), cv::Mat(), params); // y luego si for act=0:total_act //acc para este run //ACC = [ACC acc]; cout << "Using SVM to classify " << all_people (pe_ts) << endl; for (int act_ts =0; act_ts<n_actions; ++act_ts) { vec test_dist; std::stringstream load_vec_dist; load_vec_dist << path << "./classification/kth-svm/logEucl/dist_vector_" << all_people (pe_ts) << "_" << actions(act_ts) << ".h5" ; test_dist.load( load_vec_dist.str() ); cout << all_people (pe_ts) << "_" << actions(act_ts) << endl; cv::Mat cvMatTesting_onevideo(1, n_dim, CV_32FC1); for (uword d=0; d<n_dim; ++d) { cvMatTesting_onevideo.at<float>(0,d) = test_dist(d); } float response = SVM.predict(cvMatTesting_onevideo, true); cout << "response " << response << endl; real_labels(j) = act_ts; est_labels(j) = response; test_video_list(j) = load_vec_dist.str(); j++; if (response == act_ts) { acc++; } } ///cambiar nombres real_labels.save("svm_LogEucl_real_labels.dat", raw_ascii); est_labels.save("svm_LogEucl_est_labels.dat", raw_ascii); test_video_list.save("svm_LogEucl_test_video_list.dat", raw_ascii); getchar(); } //save performance } /// inline void kth_cv_svm::logEucl_distances() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 int n_test = n_peo*n_actions*total_scenes; // - person13_handclapping_d3 int k=0; int sc = 1; // = total scenes mat peo_act(n_test,2); for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { peo_act (k,0) = pe; peo_act (k,1) = act; k++; } } std::stringstream load_sub_path; load_sub_path << path << "cov_matrices/kth-one-cov-mat-dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; //omp_set_num_threads(8); //Use only 8 processors #pragma omp parallel for for (int n = 0; n< n_test; ++n) { int pe = peo_act (n,0); int act = peo_act (n,1); int tid=omp_get_thread_num(); vec dist_video_i; #pragma omp critical cout<< "Processor " << tid <<" doing "<< all_people (pe) << "_" << actions(act) << endl; std::stringstream load_cov; load_cov << load_sub_path.str() << "/LogMcov_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //#pragma omp critical //cout << load_cov_seg.str() << endl; dist_video_i = dist_logEucl_one_video( pe, load_sub_path.str(), load_cov.str()); //save dist_video_i person, action std::stringstream save_vec_dist; save_vec_dist << "./kth-svm/logEucl/dist_vector_" << all_people (pe) << "_" << actions(act) << ".h5" ; #pragma omp critical dist_video_i.save(save_vec_dist.str(), hdf5_binary); } } inline vec kth_cv_svm::dist_logEucl_one_video(int pe_test, std::string load_sub_path, std::string load_cov) { //wall_clock timer; //timer.tic(); mat logMtest_cov; logMtest_cov.load(load_cov); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //double dist; double tmp_dist; vec dist; int num_dist = (n_peo-1)*n_actions; dist.zeros(num_dist); tmp_dist = datum::inf; double est_lab; int sc =1; int k=0; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { if (pe_tr!= pe_test) { //cout << " " << all_people (pe_tr); for (int act=0; act<n_actions; ++act) { std::stringstream load_cov_tr; load_cov_tr << load_sub_path << "/LogMcov_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; mat logMtrain_cov; logMtrain_cov.load( load_cov_tr.str() ); tmp_dist = norm( logMtest_cov - logMtrain_cov, "fro"); dist(k) = tmp_dist; ++k; } } } return dist; } <commit_msg>Test svm_LogEucl<commit_after>#include "omp.h" inline kth_cv_svm::kth_cv_svm(const std::string in_path, const std::string in_actionNames, const field<std::string> in_all_people, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_dim ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), dim(in_dim) { actions.load( actionNames ); } // Log-Euclidean Distance inline void kth_cv_svm::logEucl() { //logEucl_distances(); logEucl_CV(); //cross validation; } inline void kth_cv_svm::logEucl_CV() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 int n_test = (n_peo-1)*n_actions*total_scenes; // - person13_handclapping_d3 int n_dim = n_test; int sc = 1; // = total scenes fvec dist_vector; float acc=0; vec real_labels; vec est_labels; field<std::string> test_video_list(n_peo*n_actions); real_labels.zeros(n_peo*n_actions); est_labels.zeros(n_peo*n_actions); int j =0; for (int pe_ts=0; pe_ts<n_peo; ++pe_ts) { fmat training_data; fvec lab; training_data.zeros(n_dim,n_test); lab.zeros(n_test); int k=0; for (int pe_tr=0; pe_tr<n_peo; ++pe_tr) { if(pe_tr!=pe_ts) for (int act=0; act<n_actions; act++) { std::stringstream load_vec_dist; load_vec_dist << path << "./classification/kth-svm/logEucl/dist_vector_" << all_people (pe_tr) << "_" << actions(act) << ".h5" ; dist_vector.load( load_vec_dist.str() ); training_data.col(k) = dist_vector; lab(k) = act; ++k; } } //Training the model with OpenCV cout << "Preparing data to train the data" << endl; cv::Mat cvMatTraining(n_test, n_dim, CV_32FC1); float fl_labels[n_test] ; for (uword m=0; m<n_test; ++m) { for (uword d=0; d<n_dim; ++d) { cvMatTraining.at<float>(m,d) = training_data(d,m); //cout << " OpenCV: " << cvMatTraining.at<float>(m,d) << " - Arma: " <<training_data(d,m); } fl_labels[m] = lab(m); //cout <<" OpenCVLabel: " << fl_labels[m] << " ArmaLabel: " << labels(m) << endl; } cv::Mat cvMatLabels(n_test, 1, CV_32FC1,fl_labels ); cout << "Setting parameters" << endl; CvSVMParams params; params.svm_type = CvSVM::C_SVC; params.kernel_type = CvSVM::RBF; params.gamma = 1; params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, (int)1e7, 1e-6); // Train the SVM cout << "Training" << endl; CvSVM SVM; SVM.train( cvMatTraining , cvMatLabels, cv::Mat(), cv::Mat(), params); // y luego si for act=0:total_act //acc para este run //ACC = [ACC acc]; cout << "Using SVM to classify " << all_people (pe_ts) << endl; for (int act_ts =0; act_ts<n_actions; ++act_ts) { vec test_dist; std::stringstream load_vec_dist; load_vec_dist << path << "./classification/kth-svm/logEucl/dist_vector_" << all_people (pe_ts) << "_" << actions(act_ts) << ".h5" ; test_dist.load( load_vec_dist.str() ); cout << all_people (pe_ts) << "_" << actions(act_ts) << endl; cv::Mat cvMatTesting_onevideo(1, n_dim, CV_32FC1); for (uword d=0; d<n_dim; ++d) { cvMatTesting_onevideo.at<float>(0,d) = test_dist(d); } float response = SVM.predict(cvMatTesting_onevideo, true); cout << "response " << response << endl; real_labels(j) = act_ts; est_labels(j) = response; test_video_list(j) = load_vec_dist.str(); j++; if (response == act_ts) { acc++; } } ///cambiar nombres real_labels.save("svm_LogEucl_real_labels.dat", raw_ascii); est_labels.save("svm_LogEucl_est_labels.dat", raw_ascii); test_video_list.save("svm_LogEucl_test_video_list.dat", raw_ascii); getchar(); } //save performance } /// inline void kth_cv_svm::logEucl_distances() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 int n_test = n_peo*n_actions*total_scenes; // - person13_handclapping_d3 int k=0; int sc = 1; // = total scenes mat peo_act(n_test,2); for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { peo_act (k,0) = pe; peo_act (k,1) = act; k++; } } std::stringstream load_sub_path; load_sub_path << path << "cov_matrices/kth-one-cov-mat-dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; //omp_set_num_threads(8); //Use only 8 processors #pragma omp parallel for for (int n = 0; n< n_test; ++n) { int pe = peo_act (n,0); int act = peo_act (n,1); int tid=omp_get_thread_num(); vec dist_video_i; #pragma omp critical cout<< "Processor " << tid <<" doing "<< all_people (pe) << "_" << actions(act) << endl; std::stringstream load_cov; load_cov << load_sub_path.str() << "/LogMcov_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //#pragma omp critical //cout << load_cov_seg.str() << endl; dist_video_i = dist_logEucl_one_video( pe, load_sub_path.str(), load_cov.str()); //save dist_video_i person, action std::stringstream save_vec_dist; save_vec_dist << "./kth-svm/logEucl/dist_vector_" << all_people (pe) << "_" << actions(act) << ".h5" ; #pragma omp critical dist_video_i.save(save_vec_dist.str(), hdf5_binary); } } inline vec kth_cv_svm::dist_logEucl_one_video(int pe_test, std::string load_sub_path, std::string load_cov) { //wall_clock timer; //timer.tic(); mat logMtest_cov; logMtest_cov.load(load_cov); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //double dist; double tmp_dist; vec dist; int num_dist = (n_peo-1)*n_actions; dist.zeros(num_dist); tmp_dist = datum::inf; double est_lab; int sc =1; int k=0; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { if (pe_tr!= pe_test) { //cout << " " << all_people (pe_tr); for (int act=0; act<n_actions; ++act) { std::stringstream load_cov_tr; load_cov_tr << load_sub_path << "/LogMcov_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; mat logMtrain_cov; logMtrain_cov.load( load_cov_tr.str() ); tmp_dist = norm( logMtest_cov - logMtrain_cov, "fro"); dist(k) = tmp_dist; ++k; } } } return dist; } <|endoftext|>
<commit_before>#include <cppcutter.h> #include "tuishogi.cpp" namespace tuishogi { void test_showState(void) { // Arrange using namespace osl; std::stringbuf string_out; std::streambuf* std_out = std::cout.rdbuf(&string_out); NumEffectState state((SimpleState(HIRATE))); const char* expected = "\ P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\ P2 * -HI * * * * * -KA * \n\ P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\ P4 * * * * * * * * * \n\ P5 * * * * * * * * * \n\ P6 * * * * * * * * * \n\ P7+FU+FU+FU+FU+FU+FU+FU+FU+FU\n\ P8 * +KA * * * * * +HI * \n\ P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\ +\n\ \n"; // Act showState(state); std::cout << std::flush; std::cout.rdbuf(std_out); // TODO assert it as a std::string std::string str = string_out.str(); const char* actual = str.c_str(); // Assert cut_assert_equal_string(expected, actual); } void test_isMated(void) { using namespace osl; NumEffectState state((SimpleState(HIRATE))); bool mated = isMated(state); cut_assert_false(mated); } void test_computerOperate(void) { using namespace osl; // TODO cleanup std::stringbuf string_out; std::streambuf* std_out = std::cout.rdbuf(&string_out); NumEffectState state((SimpleState(HIRATE))); bool ended = computerOperate(state); std::cout << std::flush; std::cout.rdbuf(std_out); cut_assert_false(ended); } void test_playerOperate_valid(void) { // Arrange using namespace osl; std::stringbuf string_out; std::streambuf* std_out = std::cout.rdbuf(&string_out); NumEffectState state((SimpleState(HIRATE))); const char* expected = "\ P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\ P2 * -HI * * * * * -KA * \n\ P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\ P4 * * * * * * * * * \n\ P5 * * * * * * * * * \n\ P6 * * +FU * * * * * * \n\ P7+FU+FU * +FU+FU+FU+FU+FU+FU\n\ P8 * +KA * * * * * +HI * \n\ P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\ -\n\ \n\ +7776FU\n"; // Act bool failed = playerOperate(state, "+7776FU"); std::cout << std::flush; std::cout.rdbuf(std_out); // TODO assert it as a std::string std::string str = string_out.str(); const char* actual = str.c_str(); // Assert cut_assert_false(failed); cut_assert_equal_string(expected, actual); } void test_playerOperate_invalid_movement(void) { using namespace osl; // TODO cleanup std::stringbuf string_out; std::streambuf* std_out = std::cout.rdbuf(&string_out); NumEffectState state((SimpleState(HIRATE))); bool failed = playerOperate(state, "+5251FU"); std::cout << std::flush; std::cout.rdbuf(std_out); cut_assert_true(failed); } void test_playerOperate_invalid_format(void) { using namespace osl; // TODO cleanup std::stringbuf string_out; std::streambuf* std_out = std::cout.rdbuf(&string_out); NumEffectState state((SimpleState(HIRATE))); bool failed = playerOperate(state, ""); std::cout << std::flush; std::cout.rdbuf(std_out); cut_assert_true(failed); } } // namespace tuishogi <commit_msg>test: extract a using namespace osl<commit_after>#include <cppcutter.h> #include "tuishogi.cpp" namespace tuishogi { using namespace osl; void test_showState(void) { // Arrange std::stringbuf string_out; std::streambuf* std_out = std::cout.rdbuf(&string_out); NumEffectState state((SimpleState(HIRATE))); const char* expected = "\ P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\ P2 * -HI * * * * * -KA * \n\ P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\ P4 * * * * * * * * * \n\ P5 * * * * * * * * * \n\ P6 * * * * * * * * * \n\ P7+FU+FU+FU+FU+FU+FU+FU+FU+FU\n\ P8 * +KA * * * * * +HI * \n\ P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\ +\n\ \n"; // Act showState(state); std::cout << std::flush; std::cout.rdbuf(std_out); // TODO assert it as a std::string std::string str = string_out.str(); const char* actual = str.c_str(); // Assert cut_assert_equal_string(expected, actual); } void test_isMated(void) { NumEffectState state((SimpleState(HIRATE))); bool mated = isMated(state); cut_assert_false(mated); } void test_computerOperate(void) { // TODO cleanup std::stringbuf string_out; std::streambuf* std_out = std::cout.rdbuf(&string_out); NumEffectState state((SimpleState(HIRATE))); bool ended = computerOperate(state); std::cout << std::flush; std::cout.rdbuf(std_out); cut_assert_false(ended); } void test_playerOperate_valid(void) { // Arrange std::stringbuf string_out; std::streambuf* std_out = std::cout.rdbuf(&string_out); NumEffectState state((SimpleState(HIRATE))); const char* expected = "\ P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\ P2 * -HI * * * * * -KA * \n\ P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\ P4 * * * * * * * * * \n\ P5 * * * * * * * * * \n\ P6 * * +FU * * * * * * \n\ P7+FU+FU * +FU+FU+FU+FU+FU+FU\n\ P8 * +KA * * * * * +HI * \n\ P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\ -\n\ \n\ +7776FU\n"; // Act bool failed = playerOperate(state, "+7776FU"); std::cout << std::flush; std::cout.rdbuf(std_out); // TODO assert it as a std::string std::string str = string_out.str(); const char* actual = str.c_str(); // Assert cut_assert_false(failed); cut_assert_equal_string(expected, actual); } void test_playerOperate_invalid_movement(void) { // TODO cleanup std::stringbuf string_out; std::streambuf* std_out = std::cout.rdbuf(&string_out); NumEffectState state((SimpleState(HIRATE))); bool failed = playerOperate(state, "+5251FU"); std::cout << std::flush; std::cout.rdbuf(std_out); cut_assert_true(failed); } void test_playerOperate_invalid_format(void) { // TODO cleanup std::stringbuf string_out; std::streambuf* std_out = std::cout.rdbuf(&string_out); NumEffectState state((SimpleState(HIRATE))); bool failed = playerOperate(state, ""); std::cout << std::flush; std::cout.rdbuf(std_out); cut_assert_true(failed); } } // namespace tuishogi <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief GUI widget_list クラス @n このクラスは、DROP_DOWN 等に相当するクラスで、「widget_menu」@n を内包する。@n メニューの直接操作は、widget_menu のポインター経由で行う。 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/glfw_app/blob/master/LICENSE */ //=====================================================================// #include "widgets/widget_director.hpp" #include "widgets/widget_menu.hpp" namespace gui { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief GUI WidgetList クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct widget_list : public widget { typedef widget_list value_type; typedef utils::strings strings; typedef std::function<void (const std::string& select_text, uint32_t select_pos)> select_func_type; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief widget_list パラメーター */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct param { plate_param plate_param_; ///< プレート・パラメーター color_param color_param_; ///< カラー・パラメーター text_param text_param_; ///< テキスト描画のパラメーター color_param color_param_select_; ///< 選択時カラー・パラメーター strings init_list_; ///< リスト select_func_type select_func_; ///< セレクト関数 bool load_func_; ///< プリファレンス・ロード時に「セレクト関数」を実行しない場合 false bool drop_box_; ///< ドロップ・ボックスの表示 bool scroll_ctrl_; ///< スクロール・コントロール(マウスのダイアル) param(const std::string& text = "") : plate_param_(), color_param_(widget_director::default_list_color_), text_param_(text, img::rgba8(255, 255), img::rgba8(0, 255), vtx::placement(vtx::placement::holizontal::LEFT, vtx::placement::vertical::CENTER)), color_param_select_(widget_director::default_list_color_select_), init_list_(), load_func_(true), drop_box_(true), scroll_ctrl_(true) { } }; private: widget_director& wd_; param param_; gl::mobj::handle objh_; gl::mobj::handle select_objh_; widget_menu* menu_; uint32_t id_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// widget_list(widget_director& wd, const widget::param& bp, const param& p) : widget(bp), wd_(wd), param_(p), objh_(0), select_objh_(0), menu_(nullptr), id_(0) { } //-----------------------------------------------------------------// /*! @brief デストラクター */ //-----------------------------------------------------------------// virtual ~widget_list() { } //-----------------------------------------------------------------// /*! @brief 型を取得 */ //-----------------------------------------------------------------// type_id type() const override { return get_type_id<value_type>(); } //-----------------------------------------------------------------// /*! @brief widget 型の基本名称を取得 @return widget 型の基本名称 */ //-----------------------------------------------------------------// const char* type_name() const override { return "list"; } //-----------------------------------------------------------------// /*! @brief ハイブリッド・ウィジェットのサイン @return ハイブリッド・ウィジェットの場合「true」を返す。 */ //-----------------------------------------------------------------// bool hybrid() const override { return true; } //-----------------------------------------------------------------// /*! @brief 個別パラメーターへの取得(ro) @return 個別パラメーター */ //-----------------------------------------------------------------// const param& get_local_param() const { return param_; } //-----------------------------------------------------------------// /*! @brief 個別パラメーターへの取得 @return 個別パラメーター */ //-----------------------------------------------------------------// param& at_local_param() { return param_; } //-----------------------------------------------------------------// /*! @brief 選択テキストの取得(ボタンの表示テキスト) @return 選択テキスト */ //-----------------------------------------------------------------// std::string get_select_text() const { return param_.text_param_.get_text(); } //-----------------------------------------------------------------// /*! @brief メニュー・リソースの取得 @return メニュー・リソース */ //-----------------------------------------------------------------// widget_menu* get_menu() { return menu_; } //-----------------------------------------------------------------// /*! @brief 初期化 */ //-----------------------------------------------------------------// void initialize() override { // 標準的に固定、リサイズ不可 at_param().state_.set(widget::state::SERVICE); at_param().state_.set(widget::state::POSITION_LOCK); at_param().state_.set(widget::state::SIZE_LOCK); at_param().state_.set(widget::state::MOVE_STALL); vtx::ipos size; if(param_.plate_param_.resizeble_) { vtx::spos rsz = param_.plate_param_.grid_ * 3; if(get_param().rect_.size.x >= rsz.x) size.x = rsz.x; else size.x = get_param().rect_.size.x; if(get_param().rect_.size.y >= rsz.y) size.y = rsz.y; else size.y = get_param().rect_.size.y; } else { size = get_param().rect_.size; } share_t t; t.size_ = size; t.color_param_ = param_.color_param_; t.plate_param_ = param_.plate_param_; objh_ = wd_.share_add(t); t.color_param_ = param_.color_param_select_; select_objh_ = wd_.share_add(t); { // メニューの生成 widget::param wp(vtx::irect(vtx::ipos(0), get_rect().size), this); widget_menu::param wp_; wp_.init_list_ = param_.init_list_; menu_ = wd_.add_widget<widget_menu>(wp, wp_); menu_->enable(false); } } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void update() override { if(!get_state(widget::state::ENABLE)) { return; } if(get_selected()) { // 「ボタン選択」で内包メニューを有効にする。 menu_->enable(); } } //-----------------------------------------------------------------// /*! @brief サービス */ //-----------------------------------------------------------------// void service() override { if(!get_state(state::ENABLE)) { return; } if(id_ != menu_->get_local_param().id_) { param_.text_param_.set_text(menu_->get_select_text()); if(param_.select_func_ != nullptr) { param_.select_func_(param_.text_param_.get_text(), menu_->get_select_pos()); } id_ = menu_->get_local_param().id_; } } //-----------------------------------------------------------------// /*! @brief レンダリング */ //-----------------------------------------------------------------// void render() override { using namespace gl; core& core = core::get_instance(); const vtx::spos& siz = core.get_rect().size; gl::mobj::handle h = objh_; if(get_select()) { h = select_objh_; } if(param_.plate_param_.resizeble_) { wd_.at_mobj().resize(objh_, get_param().rect_.size); } render_text(wd_, h, get_param(), param_.text_param_, param_.plate_param_); if(param_.drop_box_) { wd_.at_mobj().setup_matrix(siz.x, siz.y); wd_.set_TSC(); // チップの描画 gl::mobj::handle h; if((get_rect().org.y + menu_->get_rect().size.y) > siz.y) { h = wd_.get_share_image().up_box_; } else { h = wd_.get_share_image().down_box_; } const vtx::spos& bs = wd_.at_mobj().get_size(h); const vtx::spos& size = get_rect().size; short wf = param_.plate_param_.frame_width_; short space = 4; vtx::spos pos(size.x - bs.x - wf - space, (size.y - bs.y) / 2); wd_.at_mobj().draw(h, gl::mobj::attribute::normal, pos); } } //-----------------------------------------------------------------// /*! @brief 状態のセーブ @param[in] pre プリファレンス参照 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool save(sys::preference& pre) override { std::string path; path += '/'; path += wd_.create_widget_name(this); int err = 0; if(!pre.put_text(path + "/selector", param_.text_param_.get_text())) { ++err; } return err == 0; } //-----------------------------------------------------------------// /*! @brief 状態のロード @param[in] pre プリファレンス参照 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool load(const sys::preference& pre) override { std::string path; path += '/'; path += wd_.create_widget_name(this); int err = 0; std::string text; if(!pre.get_text(path + "/selector", text)) { ++err; } else { param_.text_param_.set_text(text); if(menu_ != nullptr) { menu_->select(text); if(param_.load_func_ && param_.select_func_ != nullptr) { param_.select_func_(menu_->get_select_text(), menu_->get_select_pos()); } } } return err == 0; } }; } <commit_msg>update internal list manage<commit_after>#pragma once //=====================================================================// /*! @file @brief GUI widget_list クラス @n このクラスは、DROP_DOWN 等に相当するクラスで、「widget_menu」@n を内包する。@n メニューの直接操作は、widget_menu のポインター経由で行う。 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/glfw_app/blob/master/LICENSE */ //=====================================================================// #include "widgets/widget_director.hpp" #include "widgets/widget_menu.hpp" namespace gui { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief GUI WidgetList クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct widget_list : public widget { typedef widget_list value_type; typedef utils::strings strings; typedef std::function<void (const std::string& select_text, uint32_t select_pos)> select_func_type; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief widget_list パラメーター */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct param { plate_param plate_param_; ///< プレート・パラメーター color_param color_param_; ///< カラー・パラメーター text_param text_param_; ///< テキスト描画のパラメーター color_param color_param_select_; ///< 選択時カラー・パラメーター strings init_list_; ///< リスト select_func_type select_func_; ///< セレクト関数 bool load_func_; ///< プリファレンス・ロード時に「セレクト関数」を実行しない場合 false bool drop_box_; ///< ドロップ・ボックスの表示 bool scroll_ctrl_; ///< スクロール・コントロール(マウスのダイアル) param(const std::string& text = "") : plate_param_(), color_param_(widget_director::default_list_color_), text_param_(text, img::rgba8(255, 255), img::rgba8(0, 255), vtx::placement(vtx::placement::holizontal::LEFT, vtx::placement::vertical::CENTER)), color_param_select_(widget_director::default_list_color_select_), init_list_(), load_func_(true), drop_box_(true), scroll_ctrl_(true) { } }; private: widget_director& wd_; param param_; gl::mobj::handle objh_; gl::mobj::handle select_objh_; widget_menu* menu_; uint32_t id_; bool enable_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// widget_list(widget_director& wd, const widget::param& bp, const param& p) : widget(bp), wd_(wd), param_(p), objh_(0), select_objh_(0), menu_(nullptr), id_(0), enable_(false) { } //-----------------------------------------------------------------// /*! @brief デストラクター */ //-----------------------------------------------------------------// virtual ~widget_list() { } //-----------------------------------------------------------------// /*! @brief 型を取得 */ //-----------------------------------------------------------------// type_id type() const override { return get_type_id<value_type>(); } //-----------------------------------------------------------------// /*! @brief widget 型の基本名称を取得 @return widget 型の基本名称 */ //-----------------------------------------------------------------// const char* type_name() const override { return "list"; } //-----------------------------------------------------------------// /*! @brief ハイブリッド・ウィジェットのサイン @return ハイブリッド・ウィジェットの場合「true」を返す。 */ //-----------------------------------------------------------------// bool hybrid() const override { return true; } //-----------------------------------------------------------------// /*! @brief 個別パラメーターへの取得(ro) @return 個別パラメーター */ //-----------------------------------------------------------------// const param& get_local_param() const { return param_; } //-----------------------------------------------------------------// /*! @brief 個別パラメーターへの取得 @return 個別パラメーター */ //-----------------------------------------------------------------// param& at_local_param() { return param_; } //-----------------------------------------------------------------// /*! @brief 選択テキストの取得(ボタンの表示テキスト) @return 選択テキスト */ //-----------------------------------------------------------------// std::string get_select_text() const { return param_.text_param_.get_text(); } //-----------------------------------------------------------------// /*! @brief メニュー・リソースの取得 @return メニュー・リソース */ //-----------------------------------------------------------------// widget_menu* get_menu() { return menu_; } //-----------------------------------------------------------------// /*! @brief 初期化 */ //-----------------------------------------------------------------// void initialize() override { // 標準的に固定、リサイズ不可 at_param().state_.set(widget::state::SERVICE); at_param().state_.set(widget::state::POSITION_LOCK); at_param().state_.set(widget::state::SIZE_LOCK); at_param().state_.set(widget::state::MOVE_STALL); vtx::ipos size; if(param_.plate_param_.resizeble_) { vtx::spos rsz = param_.plate_param_.grid_ * 3; if(get_param().rect_.size.x >= rsz.x) size.x = rsz.x; else size.x = get_param().rect_.size.x; if(get_param().rect_.size.y >= rsz.y) size.y = rsz.y; else size.y = get_param().rect_.size.y; } else { size = get_param().rect_.size; } share_t t; t.size_ = size; t.color_param_ = param_.color_param_; t.plate_param_ = param_.plate_param_; objh_ = wd_.share_add(t); t.color_param_ = param_.color_param_select_; select_objh_ = wd_.share_add(t); { // メニューの生成 widget::param wp(vtx::irect(vtx::ipos(0), get_rect().size), this); widget_menu::param wp_; wp_.init_list_ = param_.init_list_; if(!wp_.init_list_.empty()) { param_.text_param_.set_text(wp_.init_list_[0]); } menu_ = wd_.add_widget<widget_menu>(wp, wp_); menu_->enable(false); } } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void update() override { if(!get_state(widget::state::ENABLE)) { return; } if(get_selected()) { // 「ボタン選択」で内包メニューを有効にする。 menu_->enable(); } } //-----------------------------------------------------------------// /*! @brief サービス */ //-----------------------------------------------------------------// void service() override { bool ena = enable_; enable_ = get_state(state::ENABLE); if(!ena && enable_) { // 全体が許可の場合は、メニューをオフラインにする menu_->enable(false); } if(!get_state(state::ENABLE)) { return; } if(id_ != menu_->get_local_param().id_) { param_.text_param_.set_text(menu_->get_select_text()); if(param_.select_func_ != nullptr) { param_.select_func_(param_.text_param_.get_text(), menu_->get_select_pos()); } id_ = menu_->get_local_param().id_; } } //-----------------------------------------------------------------// /*! @brief レンダリング */ //-----------------------------------------------------------------// void render() override { using namespace gl; core& core = core::get_instance(); const vtx::spos& siz = core.get_rect().size; gl::mobj::handle h = objh_; if(get_select()) { h = select_objh_; } if(param_.plate_param_.resizeble_) { wd_.at_mobj().resize(objh_, get_param().rect_.size); } render_text(wd_, h, get_param(), param_.text_param_, param_.plate_param_); if(param_.drop_box_) { wd_.at_mobj().setup_matrix(siz.x, siz.y); wd_.set_TSC(); // チップの描画 gl::mobj::handle h; if((get_rect().org.y + menu_->get_rect().size.y) > siz.y) { h = wd_.get_share_image().up_box_; } else { h = wd_.get_share_image().down_box_; } const vtx::spos& bs = wd_.at_mobj().get_size(h); const vtx::spos& size = get_rect().size; short wf = param_.plate_param_.frame_width_; short space = 4; vtx::spos pos(size.x - bs.x - wf - space, (size.y - bs.y) / 2); wd_.at_mobj().draw(h, gl::mobj::attribute::normal, pos); } } //-----------------------------------------------------------------// /*! @brief 状態のセーブ @param[in] pre プリファレンス参照 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool save(sys::preference& pre) override { std::string path; path += '/'; path += wd_.create_widget_name(this); int err = 0; if(!pre.put_text(path + "/selector", param_.text_param_.get_text())) { ++err; } return err == 0; } //-----------------------------------------------------------------// /*! @brief 状態のロード @param[in] pre プリファレンス参照 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool load(const sys::preference& pre) override { std::string path; path += '/'; path += wd_.create_widget_name(this); int err = 0; std::string text; if(!pre.get_text(path + "/selector", text)) { ++err; } else { param_.text_param_.set_text(text); if(menu_ != nullptr) { menu_->select(text); if(param_.load_func_ && param_.select_func_ != nullptr) { param_.select_func_(menu_->get_select_text(), menu_->get_select_pos()); } } } return err == 0; } }; } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Framework * * * * Authors: The SOFA Team (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <sofa/core/DataEngine.h> namespace sofa { namespace core { DataEngine::DataEngine() { addLink(&(this->core::objectmodel::DDGNode::inputs)); addLink(&(this->core::objectmodel::DDGNode::outputs)); } DataEngine::~DataEngine() { } /// Add a new input to this engine void DataEngine::addInput(objectmodel::BaseData* n) { if (!n->getGroup() || !n->getGroup()[0]) n->setGroup("Inputs"); // set the group of input Datas if not yet set core::objectmodel::DDGNode::addInput(n); } /// Remove an input from this engine void DataEngine::delInput(objectmodel::BaseData* n) { core::objectmodel::DDGNode::delInput(n); } /// Add a new output to this engine void DataEngine::addOutput(objectmodel::BaseData* n) { if (!n->getGroup() || !n->getGroup()[0]) n->setGroup("Outputs"); // set the group of output Datas if not yet set core::objectmodel::DDGNode::addOutput(n); } /// Remove an output from this engine void DataEngine::delOutput(objectmodel::BaseData* n) { core::objectmodel::DDGNode::delOutput(n); } } // namespace core } // namespace sofa <commit_msg>r8983/sofa : FIX: engine + linked data. Update the data when added as a engine input (addInput). So a linked data is copied during this init. Otherwise if the first acces of the linked data is done during the engine::update, its value was modyfied and the engine::update is called again.<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Framework * * * * Authors: The SOFA Team (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <sofa/core/DataEngine.h> namespace sofa { namespace core { DataEngine::DataEngine() { addLink(&(this->core::objectmodel::DDGNode::inputs)); addLink(&(this->core::objectmodel::DDGNode::outputs)); } DataEngine::~DataEngine() { } /// Add a new input to this engine void DataEngine::addInput(objectmodel::BaseData* n) { n->update(); if (!n->getGroup() || !n->getGroup()[0]) n->setGroup("Inputs"); // set the group of input Datas if not yet set core::objectmodel::DDGNode::addInput(n); } /// Remove an input from this engine void DataEngine::delInput(objectmodel::BaseData* n) { core::objectmodel::DDGNode::delInput(n); } /// Add a new output to this engine void DataEngine::addOutput(objectmodel::BaseData* n) { if (!n->getGroup() || !n->getGroup()[0]) n->setGroup("Outputs"); // set the group of output Datas if not yet set core::objectmodel::DDGNode::addOutput(n); } /// Remove an output from this engine void DataEngine::delOutput(objectmodel::BaseData* n) { core::objectmodel::DDGNode::delOutput(n); } } // namespace core } // namespace sofa <|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 "PetscSupport.h" #ifdef LIBMESH_HAVE_PETSC #include "FEProblem.h" #include "DisplacedProblem.h" #include "NonlinearSystem.h" #include "DisplacedProblem.h" #include "PenetrationLocator.h" #include "NearestNodeLocator.h" //libMesh Includes #include "libmesh/libmesh_common.h" #include "libmesh/equation_systems.h" #include "libmesh/nonlinear_implicit_system.h" #include "libmesh/linear_implicit_system.h" #include "libmesh/sparse_matrix.h" #include "libmesh/petsc_vector.h" #include "libmesh/petsc_matrix.h" #include "libmesh/petsc_linear_solver.h" #include "libmesh/petsc_preconditioner.h" #include "libmesh/getpot.h" //PETSc includes #include <petsc.h> #include <petscsnes.h> #include <petscksp.h> #if PETSC_VERSION_LESS_THAN(3,3,0) // PETSc 3.2.x and lower #include <private/kspimpl.h> #include <private/snesimpl.h> #else // PETSc 3.3.0+ #include <petsc-private/kspimpl.h> #include <petsc-private/snesimpl.h> #include <petscdm.h> #endif namespace Moose { namespace PetscSupport { void petscSetOptions(Problem & problem) { const std::vector<MooseEnum> & petsc_options = problem.parameters().get<std::vector<MooseEnum> >("petsc_options"); const std::vector<std::string> & petsc_options_inames = problem.parameters().get<std::vector<std::string> >("petsc_inames"); const std::vector<std::string> & petsc_options_values = problem.parameters().get<std::vector<std::string> >("petsc_values"); if (petsc_options_inames.size() != petsc_options_values.size()) mooseError("Petsc names and options are not the same length"); for (unsigned int i=0; i<petsc_options.size(); ++i) PetscOptionsSetValue(std::string(petsc_options[i]).c_str(), PETSC_NULL); for (unsigned int i=0; i<petsc_options_inames.size(); ++i) PetscOptionsSetValue(petsc_options_inames[i].c_str(), petsc_options_values[i].c_str()); } PetscErrorCode petscConverged(KSP ksp,PetscInt n,PetscReal rnorm,KSPConvergedReason *reason,void *dummy) { FEProblem & problem = *static_cast<FEProblem *>(dummy); NonlinearSystem & system = problem.getNonlinearSystem(); *reason = KSP_CONVERGED_ITERATING; //If it's the beginning of a new set of iterations, reset last_rnorm if (!n) system._last_rnorm = 1e99; PetscReal norm_diff = std::fabs(rnorm - system._last_rnorm); if(norm_diff < system._l_abs_step_tol) { *reason = KSP_CONVERGED_RTOL; return(0); } system._last_rnorm = rnorm; // From here, we want the default behavior of the KSPDefaultConverged // test, but we don't want PETSc to die in that function with a // CHKERRQ call... therefore we Push/Pop a different error handler // and then call KSPDefaultConverged(). Finally, if we hit the // max iteration count, we want to set KSP_CONVERGED_ITS. PetscPushErrorHandler(PetscReturnErrorHandler,/* void* ctx= */PETSC_NULL); // As of PETSc 3.0.0, you must call KSPDefaultConverged with a // non-NULL context pointer which must be created with // KSPDefaultConvergedCreate(), and destroyed with // KSPDefaultConvergedDestroy(). /*PetscErrorCode ierr = */ KSPDefaultConverged(ksp, n, rnorm, reason, dummy); // Pop the Error handler we pushed on the stack to go back // to default PETSc error handling behavior. PetscPopErrorHandler(); // If we hit max its then we consider that converged if (n >= ksp->max_it) *reason = KSP_CONVERGED_ITS; if(*reason == KSP_CONVERGED_ITS || *reason == KSP_CONVERGED_RTOL) system._current_l_its.push_back(n); return 0; } PetscErrorCode petscNonlinearConverged(SNES snes,PetscInt it,PetscReal xnorm,PetscReal snorm,PetscReal fnorm,SNESConvergedReason *reason,void * dummy) { // xnorm: norm of current iterate // pnorm (snorm): norm of // fnorm: norm of function FEProblem & problem = *static_cast<FEProblem *>(dummy); NonlinearSystem & system = problem.getNonlinearSystem(); #if PETSC_VERSION_LESS_THAN(3,3,0) PetscInt stol = snes->xtol; #else PetscInt stol = snes->stol; #endif std::string msg; const Real ref_resid = system._initial_residual; const Real div_threshold = system._initial_residual*(1.0/snes->rtol); MooseNonlinearConvergenceReason moose_reason = problem.checkNonlinearConvergence(msg, it, xnorm, snorm, fnorm, snes->ttol, snes->rtol, stol, snes->abstol, snes->nfuncs, snes->max_funcs, ref_resid, div_threshold); if (msg.length() > 0) PetscInfo(snes,msg.c_str()); switch (moose_reason) { case MOOSE_ITERATING: *reason = SNES_CONVERGED_ITERATING; break; case MOOSE_CONVERGED_FNORM_ABS: *reason = SNES_CONVERGED_FNORM_ABS; break; case MOOSE_CONVERGED_FNORM_RELATIVE: *reason = SNES_CONVERGED_FNORM_RELATIVE; break; case MOOSE_CONVERGED_SNORM_RELATIVE: #if PETSC_VERSION_LESS_THAN(3,3,0) *reason = SNES_CONVERGED_PNORM_RELATIVE; #else *reason = SNES_CONVERGED_SNORM_RELATIVE; #endif break; case MOOSE_DIVERGED_FUNCTION_COUNT: *reason = SNES_DIVERGED_FUNCTION_COUNT; break; case MOOSE_DIVERGED_FNORM_NAN: *reason = SNES_DIVERGED_FNORM_NAN; break; case MOOSE_DIVERGED_LINE_SEARCH: #if PETSC_VERSION_LESS_THAN(3,2,0) *reason = SNES_DIVERGED_LS_FAILURE; #else *reason = SNES_DIVERGED_LINE_SEARCH; #endif break; } return (0); } #if PETSC_VERSION_LESS_THAN(3,3,0) // PETSc 3.2.x- PetscErrorCode dampedCheck(SNES /*snes*/, Vec x, Vec y, Vec w, void *lsctx, PetscBool * /*changed_y*/, PetscBool * changed_w) #else // PETSc 3.3.0+ PetscErrorCode dampedCheck(SNESLineSearch /* linesearch */, Vec x, Vec y, Vec w, PetscBool * /*changed_y*/, PetscBool * changed_w, void *lsctx) #endif { // From SNESLineSearchSetPostCheck docs: // + x - old solution vector // . y - search direction vector // . w - new solution vector w = x-y // . changed_y - indicates that the line search changed y // . changed_w - indicates that the line search changed w int ierr = 0; Real damping = 1.0; FEProblem & problem = *static_cast<FEProblem *>(lsctx); TransientNonlinearImplicitSystem & system = problem.getNonlinearSystem().sys(); // The whole deal here is that we need ghosted versions of vectors y and w (they are parallel, but not ghosted). // So to do that I'm going to duplicate current_local_solution (which has the ghosting we want). // Then stuff values into the duplicates // Then "close()" the vectors which updates their ghosted vaulues. { // cls is a PetscVector wrapper around the Vec in current_local_solution PetscVector<Number> cls(static_cast<PetscVector<Number> *>(system.current_local_solution.get())->vec()); // Create new NumericVectors with the right ghosting - note: these will be destroyed // when this function exits, so nobody better hold pointers to them any more! AutoPtr<NumericVector<Number> > ghosted_y_aptr( cls.zero_clone() ); AutoPtr<NumericVector<Number> > ghosted_w_aptr( cls.zero_clone() ); // Create PetscVector wrappers around the Vecs. PetscVector<Number> ghosted_y( static_cast<PetscVector<Number> *>(ghosted_y_aptr.get())->vec() ); PetscVector<Number> ghosted_w( static_cast<PetscVector<Number> *>(ghosted_w_aptr.get())->vec() ); ierr = VecCopy(y, ghosted_y.vec()); CHKERRABORT(libMesh::COMM_WORLD,ierr); ierr = VecCopy(w, ghosted_w.vec()); CHKERRABORT(libMesh::COMM_WORLD,ierr); ghosted_y.close(); ghosted_w.close(); damping = problem.computeDamping(ghosted_w, ghosted_y); if(damping < 1.0) { //recalculate w=-damping*y + x ierr = VecWAXPY(w, -damping, y, x); CHKERRABORT(libMesh::COMM_WORLD,ierr); *changed_w = PETSC_TRUE; } if (problem.shouldUpdateSolution()) { //Update the ghosted copy of w if (*changed_w == PETSC_TRUE) { ierr = VecCopy(w, ghosted_w.vec()); CHKERRABORT(libMesh::COMM_WORLD,ierr); ghosted_w.close(); } //Create vector to directly modify w PetscVector<Number> vec_w(w); bool updatedSolution = problem.updateSolution(vec_w, ghosted_w); if (updatedSolution) *changed_w = PETSC_TRUE; } } return ierr; } void petscSetupDampers(NonlinearImplicitSystem& sys) { FEProblem * problem = sys.get_equation_systems().parameters.get<FEProblem *>("_fe_problem"); NonlinearSystem & nl = problem->getNonlinearSystem(); PetscNonlinearSolver<Number> * petsc_solver = dynamic_cast<PetscNonlinearSolver<Number> *>(nl.sys().nonlinear_solver.get()); SNES snes = petsc_solver->snes(); #if PETSC_VERSION_LESS_THAN(3,3,0) // PETSc 3.2.x- SNESLineSearchSetPostCheck(snes, dampedCheck, problem); #else // PETSc 3.3.0+ SNESLineSearch linesearch; PetscErrorCode ierr = SNESGetSNESLineSearch(snes, &linesearch); CHKERRABORT(libMesh::COMM_WORLD,ierr); ierr = SNESLineSearchSetPostCheck(linesearch, dampedCheck, problem); CHKERRABORT(libMesh::COMM_WORLD,ierr); #endif } void petscSetDefaults(FEProblem & problem) { // dig out Petsc solver NonlinearSystem & nl = problem.getNonlinearSystem(); PetscNonlinearSolver<Number> * petsc_solver = dynamic_cast<PetscNonlinearSolver<Number> *>(nl.sys().nonlinear_solver.get()); SNES snes = petsc_solver->snes(); KSP ksp; SNESGetKSP(snes, &ksp); #if PETSC_VERSION_LESS_THAN(3,2,0) // PETSc 3.1.x- KSPSetPreconditionerSide(ksp, PC_RIGHT); #else // PETSc 3.2.x+ KSPSetPCSide(ksp, PC_RIGHT); #endif SNESSetMaxLinearSolveFailures(snes, 1000000); #if PETSC_VERSION_LESS_THAN(3,0,0) // PETSc 2.3.3- KSPSetConvergenceTest(ksp, petscConverged, &problem); SNESSetConvergenceTest(snes, petscNonlinearConverged, &problem); #else // PETSc 3.0.0+ // In 3.0.0, the context pointer must actually be used, and the // final argument to KSPSetConvergenceTest() is a pointer to a // routine for destroying said private data context. In this case, // we use the default context provided by PETSc in addition to // a few other tests. { PetscErrorCode ierr = KSPSetConvergenceTest(ksp, petscConverged, &problem, PETSC_NULL); CHKERRABORT(libMesh::COMM_WORLD,ierr); ierr = SNESSetConvergenceTest(snes, petscNonlinearConverged, &problem, PETSC_NULL); CHKERRABORT(libMesh::COMM_WORLD,ierr); } #endif } } // Namespace PetscSupport } // Namespace MOOSE #endif //LIBMESH_HAVE_PETSC <commit_msg>clear petsc options and rebuild them before each solve closes #1872<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 "PetscSupport.h" #ifdef LIBMESH_HAVE_PETSC #include "FEProblem.h" #include "DisplacedProblem.h" #include "NonlinearSystem.h" #include "DisplacedProblem.h" #include "PenetrationLocator.h" #include "NearestNodeLocator.h" //libMesh Includes #include "libmesh/libmesh_common.h" #include "libmesh/equation_systems.h" #include "libmesh/nonlinear_implicit_system.h" #include "libmesh/linear_implicit_system.h" #include "libmesh/sparse_matrix.h" #include "libmesh/petsc_vector.h" #include "libmesh/petsc_matrix.h" #include "libmesh/petsc_linear_solver.h" #include "libmesh/petsc_preconditioner.h" #include "libmesh/getpot.h" //PETSc includes #include <petsc.h> #include <petscsnes.h> #include <petscksp.h> #if PETSC_VERSION_LESS_THAN(3,3,0) // PETSc 3.2.x and lower #include <private/kspimpl.h> #include <private/snesimpl.h> #else // PETSc 3.3.0+ #include <petsc-private/kspimpl.h> #include <petsc-private/snesimpl.h> #include <petscdm.h> #endif namespace Moose { namespace PetscSupport { void petscSetOptions(Problem & problem) { const std::vector<MooseEnum> & petsc_options = problem.parameters().get<std::vector<MooseEnum> >("petsc_options"); const std::vector<std::string> & petsc_options_inames = problem.parameters().get<std::vector<std::string> >("petsc_inames"); const std::vector<std::string> & petsc_options_values = problem.parameters().get<std::vector<std::string> >("petsc_values"); if (petsc_options_inames.size() != petsc_options_values.size()) mooseError("Petsc names and options are not the same length"); PetscOptionsClear(); { // Get any options specified on the command-line int argc; char ** args; PetscGetArgs(&argc, &args); PetscOptionsInsert(&argc, &args, NULL); } // Add any options specified in the input file for (unsigned int i=0; i<petsc_options.size(); ++i) PetscOptionsSetValue(std::string(petsc_options[i]).c_str(), PETSC_NULL); for (unsigned int i=0; i<petsc_options_inames.size(); ++i) PetscOptionsSetValue(petsc_options_inames[i].c_str(), petsc_options_values[i].c_str()); } PetscErrorCode petscConverged(KSP ksp,PetscInt n,PetscReal rnorm,KSPConvergedReason *reason,void *dummy) { FEProblem & problem = *static_cast<FEProblem *>(dummy); NonlinearSystem & system = problem.getNonlinearSystem(); *reason = KSP_CONVERGED_ITERATING; //If it's the beginning of a new set of iterations, reset last_rnorm if (!n) system._last_rnorm = 1e99; PetscReal norm_diff = std::fabs(rnorm - system._last_rnorm); if(norm_diff < system._l_abs_step_tol) { *reason = KSP_CONVERGED_RTOL; return(0); } system._last_rnorm = rnorm; // From here, we want the default behavior of the KSPDefaultConverged // test, but we don't want PETSc to die in that function with a // CHKERRQ call... therefore we Push/Pop a different error handler // and then call KSPDefaultConverged(). Finally, if we hit the // max iteration count, we want to set KSP_CONVERGED_ITS. PetscPushErrorHandler(PetscReturnErrorHandler,/* void* ctx= */PETSC_NULL); // As of PETSc 3.0.0, you must call KSPDefaultConverged with a // non-NULL context pointer which must be created with // KSPDefaultConvergedCreate(), and destroyed with // KSPDefaultConvergedDestroy(). /*PetscErrorCode ierr = */ KSPDefaultConverged(ksp, n, rnorm, reason, dummy); // Pop the Error handler we pushed on the stack to go back // to default PETSc error handling behavior. PetscPopErrorHandler(); // If we hit max its then we consider that converged if (n >= ksp->max_it) *reason = KSP_CONVERGED_ITS; if(*reason == KSP_CONVERGED_ITS || *reason == KSP_CONVERGED_RTOL) system._current_l_its.push_back(n); return 0; } PetscErrorCode petscNonlinearConverged(SNES snes,PetscInt it,PetscReal xnorm,PetscReal snorm,PetscReal fnorm,SNESConvergedReason *reason,void * dummy) { // xnorm: norm of current iterate // pnorm (snorm): norm of // fnorm: norm of function FEProblem & problem = *static_cast<FEProblem *>(dummy); NonlinearSystem & system = problem.getNonlinearSystem(); #if PETSC_VERSION_LESS_THAN(3,3,0) PetscInt stol = snes->xtol; #else PetscInt stol = snes->stol; #endif std::string msg; const Real ref_resid = system._initial_residual; const Real div_threshold = system._initial_residual*(1.0/snes->rtol); MooseNonlinearConvergenceReason moose_reason = problem.checkNonlinearConvergence(msg, it, xnorm, snorm, fnorm, snes->ttol, snes->rtol, stol, snes->abstol, snes->nfuncs, snes->max_funcs, ref_resid, div_threshold); if (msg.length() > 0) PetscInfo(snes,msg.c_str()); switch (moose_reason) { case MOOSE_ITERATING: *reason = SNES_CONVERGED_ITERATING; break; case MOOSE_CONVERGED_FNORM_ABS: *reason = SNES_CONVERGED_FNORM_ABS; break; case MOOSE_CONVERGED_FNORM_RELATIVE: *reason = SNES_CONVERGED_FNORM_RELATIVE; break; case MOOSE_CONVERGED_SNORM_RELATIVE: #if PETSC_VERSION_LESS_THAN(3,3,0) *reason = SNES_CONVERGED_PNORM_RELATIVE; #else *reason = SNES_CONVERGED_SNORM_RELATIVE; #endif break; case MOOSE_DIVERGED_FUNCTION_COUNT: *reason = SNES_DIVERGED_FUNCTION_COUNT; break; case MOOSE_DIVERGED_FNORM_NAN: *reason = SNES_DIVERGED_FNORM_NAN; break; case MOOSE_DIVERGED_LINE_SEARCH: #if PETSC_VERSION_LESS_THAN(3,2,0) *reason = SNES_DIVERGED_LS_FAILURE; #else *reason = SNES_DIVERGED_LINE_SEARCH; #endif break; } return (0); } #if PETSC_VERSION_LESS_THAN(3,3,0) // PETSc 3.2.x- PetscErrorCode dampedCheck(SNES /*snes*/, Vec x, Vec y, Vec w, void *lsctx, PetscBool * /*changed_y*/, PetscBool * changed_w) #else // PETSc 3.3.0+ PetscErrorCode dampedCheck(SNESLineSearch /* linesearch */, Vec x, Vec y, Vec w, PetscBool * /*changed_y*/, PetscBool * changed_w, void *lsctx) #endif { // From SNESLineSearchSetPostCheck docs: // + x - old solution vector // . y - search direction vector // . w - new solution vector w = x-y // . changed_y - indicates that the line search changed y // . changed_w - indicates that the line search changed w int ierr = 0; Real damping = 1.0; FEProblem & problem = *static_cast<FEProblem *>(lsctx); TransientNonlinearImplicitSystem & system = problem.getNonlinearSystem().sys(); // The whole deal here is that we need ghosted versions of vectors y and w (they are parallel, but not ghosted). // So to do that I'm going to duplicate current_local_solution (which has the ghosting we want). // Then stuff values into the duplicates // Then "close()" the vectors which updates their ghosted vaulues. { // cls is a PetscVector wrapper around the Vec in current_local_solution PetscVector<Number> cls(static_cast<PetscVector<Number> *>(system.current_local_solution.get())->vec()); // Create new NumericVectors with the right ghosting - note: these will be destroyed // when this function exits, so nobody better hold pointers to them any more! AutoPtr<NumericVector<Number> > ghosted_y_aptr( cls.zero_clone() ); AutoPtr<NumericVector<Number> > ghosted_w_aptr( cls.zero_clone() ); // Create PetscVector wrappers around the Vecs. PetscVector<Number> ghosted_y( static_cast<PetscVector<Number> *>(ghosted_y_aptr.get())->vec() ); PetscVector<Number> ghosted_w( static_cast<PetscVector<Number> *>(ghosted_w_aptr.get())->vec() ); ierr = VecCopy(y, ghosted_y.vec()); CHKERRABORT(libMesh::COMM_WORLD,ierr); ierr = VecCopy(w, ghosted_w.vec()); CHKERRABORT(libMesh::COMM_WORLD,ierr); ghosted_y.close(); ghosted_w.close(); damping = problem.computeDamping(ghosted_w, ghosted_y); if(damping < 1.0) { //recalculate w=-damping*y + x ierr = VecWAXPY(w, -damping, y, x); CHKERRABORT(libMesh::COMM_WORLD,ierr); *changed_w = PETSC_TRUE; } if (problem.shouldUpdateSolution()) { //Update the ghosted copy of w if (*changed_w == PETSC_TRUE) { ierr = VecCopy(w, ghosted_w.vec()); CHKERRABORT(libMesh::COMM_WORLD,ierr); ghosted_w.close(); } //Create vector to directly modify w PetscVector<Number> vec_w(w); bool updatedSolution = problem.updateSolution(vec_w, ghosted_w); if (updatedSolution) *changed_w = PETSC_TRUE; } } return ierr; } void petscSetupDampers(NonlinearImplicitSystem& sys) { FEProblem * problem = sys.get_equation_systems().parameters.get<FEProblem *>("_fe_problem"); NonlinearSystem & nl = problem->getNonlinearSystem(); PetscNonlinearSolver<Number> * petsc_solver = dynamic_cast<PetscNonlinearSolver<Number> *>(nl.sys().nonlinear_solver.get()); SNES snes = petsc_solver->snes(); #if PETSC_VERSION_LESS_THAN(3,3,0) // PETSc 3.2.x- SNESLineSearchSetPostCheck(snes, dampedCheck, problem); #else // PETSc 3.3.0+ SNESLineSearch linesearch; PetscErrorCode ierr = SNESGetSNESLineSearch(snes, &linesearch); CHKERRABORT(libMesh::COMM_WORLD,ierr); ierr = SNESLineSearchSetPostCheck(linesearch, dampedCheck, problem); CHKERRABORT(libMesh::COMM_WORLD,ierr); #endif } void petscSetDefaults(FEProblem & problem) { // dig out Petsc solver NonlinearSystem & nl = problem.getNonlinearSystem(); PetscNonlinearSolver<Number> * petsc_solver = dynamic_cast<PetscNonlinearSolver<Number> *>(nl.sys().nonlinear_solver.get()); SNES snes = petsc_solver->snes(); KSP ksp; SNESGetKSP(snes, &ksp); #if PETSC_VERSION_LESS_THAN(3,2,0) // PETSc 3.1.x- KSPSetPreconditionerSide(ksp, PC_RIGHT); #else // PETSc 3.2.x+ KSPSetPCSide(ksp, PC_RIGHT); #endif SNESSetMaxLinearSolveFailures(snes, 1000000); #if PETSC_VERSION_LESS_THAN(3,0,0) // PETSc 2.3.3- KSPSetConvergenceTest(ksp, petscConverged, &problem); SNESSetConvergenceTest(snes, petscNonlinearConverged, &problem); #else // PETSc 3.0.0+ // In 3.0.0, the context pointer must actually be used, and the // final argument to KSPSetConvergenceTest() is a pointer to a // routine for destroying said private data context. In this case, // we use the default context provided by PETSc in addition to // a few other tests. { PetscErrorCode ierr = KSPSetConvergenceTest(ksp, petscConverged, &problem, PETSC_NULL); CHKERRABORT(libMesh::COMM_WORLD,ierr); ierr = SNESSetConvergenceTest(snes, petscNonlinearConverged, &problem, PETSC_NULL); CHKERRABORT(libMesh::COMM_WORLD,ierr); } #endif } } // Namespace PetscSupport } // Namespace MOOSE #endif //LIBMESH_HAVE_PETSC <|endoftext|>
<commit_before><commit_msg>GLES2: skip GL_ prefix for WEBGL_ extensions<commit_after><|endoftext|>
<commit_before>/* * * Copyright 2016, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/compiler/plugin.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream.h> using google::protobuf::Descriptor; using google::protobuf::FileDescriptor; using google::protobuf::MethodDescriptor; using google::protobuf::ServiceDescriptor; using google::protobuf::compiler::CodeGenerator; using google::protobuf::compiler::GeneratorContext; using google::protobuf::compiler::ParseGeneratorParameter; using google::protobuf::compiler::PluginMain; using google::protobuf::io::Printer; using google::protobuf::io::ZeroCopyOutputStream; namespace grpc { namespace web { namespace { enum Mode { OP = 0, // first party google3 one platform services GATEWAY = 1, // open-source gRPC Gateway, currently nginx OPJSPB = 2, // first party google3 one platform services with JSPB }; std::string GetMode(const Mode mode) { switch (mode) { case OP: return "OP"; case GATEWAY: return "Gateway"; case OPJSPB: return "OPJspb"; } } /* Finds all message types used in all services in the file, and returns them * as a map of fully qualified message type name to message descriptor */ std::map<std::string, const Descriptor *> GetAllMessages( const FileDescriptor *file) { std::map<std::string, const Descriptor *> message_types; for (int service_index = 0; service_index < file->service_count(); ++service_index) { const ServiceDescriptor* service = file->service(service_index); for (int method_index = 0; method_index < service->method_count(); ++method_index) { const MethodDescriptor *method = service->method(method_index); const Descriptor *input_type = method->input_type(); const Descriptor *output_type = method->output_type(); message_types[input_type->full_name()] = input_type; message_types[output_type->full_name()] = output_type; } } return message_types; } void PrintMessagesDeps(Printer* printer, const FileDescriptor* file) { std::map<std::string, const Descriptor *> messages = GetAllMessages(file); std::map<std::string, std::string> vars; for (std::map<std::string, const Descriptor *>::iterator it = messages.begin(); it != messages.end(); it++) { vars["full_name"] = it->first; printer->Print( vars, "goog.require('proto.$full_name$');\n"); } printer->Print("\n\n\n"); } void PrintFileHeader(Printer* printer, std::map<std::string, std::string> vars) { printer->Print( vars, "/**\n" " * @fileoverview gRPC Web JS generated client stub for $package$\n" " * @enhanceable\n" " * @public\n" " */\n" "// GENERATED CODE -- DO NOT EDIT!\n\n\n"); } void PrintServiceConstructor(Printer* printer, std::map<std::string, std::string> vars) { printer->Print( vars, "/**\n" "* @constructor\n" "*/\n" "proto.$package$.$service_name$Client =\n" " function(hostname, credentials, options) {\n" " /**\n" " * @private {!grpc.web.$mode$ClientBase} the client\n" " */\n" " this.client_ = new grpc.web.$mode$ClientBase();\n\n" " /**\n" " * @private {!string} the hostname\n" " */\n" " this.hostname_ = hostname;\n\n\n" " /**\n" " * @private {?Object} the credentials to be used to connect\n" " * to the server\n" " */\n" " this.credentials_ = credentials;\n\n" " /**\n" " * @private {?Object} options for the client\n" " */\n" " this.options_ = options;\n" " };\n\n"); } void PrintUnaryCall(Printer* printer, std::map<std::string, std::string> vars) { printer->Print( vars, "/**\n" " * @param {!proto.$in$} request The\n" " * request proto\n" " * @param {!Object<string, string>} metadata User defined\n" " * call metadata\n" " * @param {function(?string, (?Object|undefined))} callback " "The callback\n" " * function(error, response)\n" " * @return {!grpc.web.ClientReadableStream|undefined} The XHR Node\n" " * Readable Stream\n" " */\n" "proto.$package$.$service_name$Client.prototype.$method_name$ =\n"); printer->Indent(); printer->Print( vars, "function(request, metadata, callback) {\n"); if (vars["mode"] == GetMode(Mode::OP) || vars["mode"] == GetMode(Mode::OPJSPB)) { printer->Print( vars, "var call = this.client_.rpcCall(this.hostname_ +\n" " '/$$rpc/$package$.$service_name$/$method_name$',\n"); } else { printer->Print( vars, "var call = this.client_.rpcCall(this.hostname_ +\n" " '/$package$.$service_name$/$method_name$',\n"); } printer->Indent(); printer->Print(vars, "request,\n" "metadata,\n"); std::string deserializeFunc; if (vars["mode"] == GetMode(Mode::OP) || vars["mode"] == GetMode(Mode::GATEWAY)) { deserializeFunc = "deserializeBinary"; } else { deserializeFunc = "deserialize"; } printer->Print(vars, ("proto.$out$." + deserializeFunc + ",\n").c_str()); printer->Print("callback);\n"); printer->Outdent(); printer->Print("return call;\n"); printer->Outdent(); printer->Print("};\n\n\n"); } void PrintServerStreamingCall(Printer* printer, std::map<std::string, std::string> vars) { printer->Print( vars, "/**\n" " * @param {!proto.$in$} request The request proto\n" " * @param {!Object<string, string>} metadata User defined\n" " * call metadata\n" " * @return {!grpc.web.ClientReadableStream} The XHR Node\n" " * Readable Stream\n" " */\n" "proto.$package$.$service_name$Client.prototype.$method_name$ =\n"); printer->Indent(); printer->Print( "function(request, metadata) {\n" "var stream = this.client_.serverStreaming(\n"); printer->Indent(); printer->Print( vars, "this.hostname_ +\n" " '/$package$.$service_name$/$method_name$',\n" "request,\n" "metadata,\n" "proto.$out$.deserializeBinary);\n\n"); printer->Outdent(); printer->Print("return stream;\n"); printer->Outdent(); printer->Print("};\n\n\n"); } class GrpcCodeGenerator : public CodeGenerator { public: GrpcCodeGenerator() {} ~GrpcCodeGenerator() override {} bool Generate(const FileDescriptor* file, const std::string& parameter, GeneratorContext* context, std::string* error) const { if (!file->service_count()) { // No services, nothing to do. return true; } std::vector<std::pair<std::string, std::string> > options; ParseGeneratorParameter(parameter, &options); std::string file_name; std::string mode; for (int i = 0; i < options.size(); ++i) { if (options[i].first == "out") { file_name = options[i].second; } else if (options[i].first == "mode") { mode = options[i].second; } else { *error = "unsupported options: " + options[i].first; return false; } } if (file_name.empty()) { *error = "options: out is required"; return false; } if (mode.empty()) { *error = "options: mode is required"; return false; } std::map<std::string, std::string> vars; vars["package"] = file->package(); if (mode == "binary") { vars["mode"] = GetMode(Mode::OP); } else if (mode == "base64") { vars["mode"] = GetMode(Mode::GATEWAY); } else if (mode == "jspb") { vars["mode"] = GetMode(Mode::OPJSPB); } else { *error = "options: invalid mode - " + mode; return false; } std::unique_ptr<ZeroCopyOutputStream> output( context->Open(file_name)); Printer printer(output.get(), '$'); PrintFileHeader(&printer, vars); for (int i = 0; i < file->service_count(); ++i) { const ServiceDescriptor* service = file->service(i); vars["service_name"] = service->name(); printer.Print( vars, "goog.provide('proto.$package$.$service_name$Client');\n"); } printer.Print("\n\n"); printer.Print(vars, "goog.require('grpc.web.$mode$ClientBase');\n\n\n\n"); PrintMessagesDeps(&printer, file); for (int service_index = 0; service_index < file->service_count(); ++service_index) { const ServiceDescriptor* service = file->service(service_index); vars["service_name"] = service->name(); PrintServiceConstructor(&printer, vars); for (int method_index = 0; method_index < service->method_count(); ++method_index) { const MethodDescriptor* method = service->method(method_index); vars["method_name"] = method->name(); vars["in"] = method->input_type()->full_name(); vars["out"] = method->output_type()->full_name(); // Client streaming is not supported yet if (!method->client_streaming()) { if (method->server_streaming()) { if (mode == "base64") { PrintServerStreamingCall(&printer, vars); } } else { PrintUnaryCall(&printer, vars); } } } } return true; } }; } // namespace } // namespace web } // namespace grpc int main(int argc, char* argv[]) { grpc::web::GrpcCodeGenerator generator; PluginMain(argc, argv, &generator); return 0; } <commit_msg>Updated codegen<commit_after>/** * * Copyright 2016, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/compiler/plugin.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream.h> using google::protobuf::Descriptor; using google::protobuf::FileDescriptor; using google::protobuf::MethodDescriptor; using google::protobuf::ServiceDescriptor; using google::protobuf::compiler::CodeGenerator; using google::protobuf::compiler::GeneratorContext; using google::protobuf::compiler::ParseGeneratorParameter; using google::protobuf::compiler::PluginMain; using google::protobuf::io::Printer; using google::protobuf::io::ZeroCopyOutputStream; namespace grpc { namespace web { namespace { using std::string; enum Mode { OP = 0, // first party google3 one platform services GATEWAY = 1, // open-source gRPC Gateway, currently nginx OPJSPB = 2, // first party google3 one platform services with JSPB }; string GetModeVar(const Mode mode) { switch (mode) { case OP: return "OP"; case GATEWAY: return "Gateway"; case OPJSPB: return "OPJspb"; } } string GetDeserializeMethodName(const string& mode_var) { if (mode_var == GetModeVar(Mode::OPJSPB)) { return "deserialize"; } return "deserializeBinary"; } /* Finds all message types used in all services in the file, and returns them * as a map of fully qualified message type name to message descriptor */ std::map<string, const Descriptor*> GetAllMessages(const FileDescriptor* file) { std::map<string, const Descriptor*> message_types; for (int service_index = 0; service_index < file->service_count(); ++service_index) { const ServiceDescriptor* service = file->service(service_index); for (int method_index = 0; method_index < service->method_count(); ++method_index) { const MethodDescriptor *method = service->method(method_index); const Descriptor *input_type = method->input_type(); const Descriptor *output_type = method->output_type(); message_types[input_type->full_name()] = input_type; message_types[output_type->full_name()] = output_type; } } return message_types; } void PrintMessagesDeps(Printer* printer, const FileDescriptor* file) { std::map<string, const Descriptor*> messages = GetAllMessages(file); std::map<string, string> vars; for (std::map<string, const Descriptor*>::iterator it = messages.begin(); it != messages.end(); it++) { vars["full_name"] = it->first; printer->Print( vars, "goog.require('proto.$full_name$');\n"); } printer->Print("\n\n\n"); } void PrintFileHeader(Printer* printer, const std::map<string, string>& vars) { printer->Print( vars, "/**\n" " * @fileoverview gRPC Web JS generated client stub for $package$\n" " * @enhanceable\n" " * @public\n" " */\n" "// GENERATED CODE -- DO NOT EDIT!\n\n\n"); } void PrintServiceConstructor(Printer* printer, const std::map<string, string>& vars) { printer->Print( vars, "/**\n" "* @constructor\n" "*/\n" "proto.$package$.$service_name$Client =\n" " function(hostname, credentials, options) {\n" " /**\n" " * @private {!grpc.web.$mode$ClientBase} the client\n" " */\n" " this.client_ = new grpc.web.$mode$ClientBase();\n\n" " /**\n" " * @private {!string} the hostname\n" " */\n" " this.hostname_ = hostname;\n\n\n" " /**\n" " * @private {?Object} the credentials to be used to connect\n" " * to the server\n" " */\n" " this.credentials_ = credentials;\n\n" " /**\n" " * @private {?Object} options for the client\n" " */\n" " this.options_ = options;\n" " };\n\n"); } void PrintUnaryCall(Printer* printer, std::map<string, string> vars) { printer->Print( vars, "/**\n" " * @param {!proto.$in$} request The\n" " * request proto\n" " * @param {!Object<string, string>} metadata User defined\n" " * call metadata\n" " * @param {function(?string, (?Object|undefined))} callback " "The callback\n" " * function(error, response)\n" " * @return {!grpc.web.ClientReadableStream|undefined} The XHR Node\n" " * Readable Stream\n" " */\n" "proto.$package$.$service_name$Client.prototype.$method_name$ =\n"); printer->Indent(); printer->Print(vars, "function(request, metadata, callback) {\n" "var call = this.client_.rpcCall(this.hostname_ +\n"); if (vars["mode"] == GetModeVar(Mode::OP) || vars["mode"] == GetModeVar(Mode::OPJSPB)) { printer->Print(vars, " '/$$rpc/$package$.$service_name$/$method_name$',\n"); } else { printer->Print(vars, " '/$package$.$service_name$/$method_name$',\n"); } printer->Indent(); printer->Print(vars, "request,\n" "metadata,\n"); string deserializeMethod = GetDeserializeMethodName(vars["mode"]); printer->Print(vars, ("proto.$out$." + deserializeMethod + ",\n").c_str()); printer->Print("callback);\n"); printer->Outdent(); printer->Print("return call;\n"); printer->Outdent(); printer->Print("};\n\n\n"); } void PrintServerStreamingCall(Printer* printer, std::map<string, string> vars) { printer->Print( vars, "/**\n" " * @param {!proto.$in$} request The request proto\n" " * @param {!Object<string, string>} metadata User defined\n" " * call metadata\n" " * @return {!grpc.web.ClientReadableStream} The XHR Node\n" " * Readable Stream\n" " */\n" "proto.$package$.$service_name$Client.prototype.$method_name$ =\n"); printer->Indent(); printer->Print( "function(request, metadata) {\n" "var stream = this.client_.serverStreaming(this.hostname_ +\n"); printer->Indent(); if (vars["mode"] == GetModeVar(Mode::OP) || vars["mode"] == GetModeVar(Mode::OPJSPB)) { printer->Print(vars, " '/$$rpc/$package$.$service_name$/$method_name$',\n"); } else { printer->Print(vars, " '/$package$.$service_name$/$method_name$',\n"); } printer->Indent(); printer->Print(vars, "request,\n" "metadata,\n"); string deserializeMethod = GetDeserializeMethodName(vars["mode"]); printer->Print(vars, ("proto.$out$." + deserializeMethod + ");\n\n").c_str()); printer->Outdent(); printer->Print("return stream;\n"); printer->Outdent(); printer->Print("};\n\n\n"); } class GrpcCodeGenerator : public CodeGenerator { public: GrpcCodeGenerator() {} ~GrpcCodeGenerator() override {} bool Generate(const FileDescriptor* file, const string& parameter, GeneratorContext* context, string* error) const override { if (!file->service_count()) { // No services, nothing to do. return true; } std::vector<std::pair<string, string> > options; ParseGeneratorParameter(parameter, &options); string file_name; string mode; for (int i = 0; i < options.size(); ++i) { if (options[i].first == "out") { file_name = options[i].second; } else if (options[i].first == "mode") { mode = options[i].second; } else { *error = "unsupported options: " + options[i].first; return false; } } if (file_name.empty()) { *error = "options: out is required"; return false; } if (mode.empty()) { *error = "options: mode is required"; return false; } std::map<string, string> vars; vars["package"] = file->package(); if (mode == "binary") { vars["mode"] = GetModeVar(Mode::OP); } else if (mode == "base64") { vars["mode"] = GetModeVar(Mode::GATEWAY); } else if (mode == "jspb") { vars["mode"] = GetModeVar(Mode::OPJSPB); } else { *error = "options: invalid mode - " + mode; return false; } std::unique_ptr<ZeroCopyOutputStream> output( context->Open(file_name)); Printer printer(output.get(), '$'); PrintFileHeader(&printer, vars); for (int i = 0; i < file->service_count(); ++i) { const ServiceDescriptor* service = file->service(i); vars["service_name"] = service->name(); printer.Print( vars, "goog.provide('proto.$package$.$service_name$Client');\n"); } printer.Print("\n\n"); printer.Print(vars, "goog.require('grpc.web.$mode$ClientBase');\n\n\n\n"); PrintMessagesDeps(&printer, file); for (int service_index = 0; service_index < file->service_count(); ++service_index) { const ServiceDescriptor* service = file->service(service_index); vars["service_name"] = service->name(); PrintServiceConstructor(&printer, vars); for (int method_index = 0; method_index < service->method_count(); ++method_index) { const MethodDescriptor* method = service->method(method_index); vars["method_name"] = method->name(); vars["in"] = method->input_type()->full_name(); vars["out"] = method->output_type()->full_name(); // Client streaming is not supported yet if (!method->client_streaming()) { if (method->server_streaming()) { if (mode == "base64" || mode == "jspb") { PrintServerStreamingCall(&printer, vars); } } else { PrintUnaryCall(&printer, vars); } } } } return true; } }; } // namespace } // namespace web } // namespace grpc int main(int argc, char* argv[]) { grpc::web::GrpcCodeGenerator generator; PluginMain(argc, argv, &generator); return 0; } <|endoftext|>
<commit_before>// (C) 2014 Arek Olek #pragma once #include <tuple> #include <vector> #include <queue> #include "range.hpp" template <class Graph> Graph bfs_tree(Graph const & G) { typedef std::pair<int, int> edge; Graph T; int parent, v = 0; std::queue<edge> Q; std::vector<bool> V(num_vertices(G)); Q.emplace(-1, v); V[v] = true; while(!Q.empty()) { std::tie(parent, v) = Q.front(); Q.pop(); for(auto w : range(adjacent_vertices(v, G))) { if(!V[w]) { V[w] = true; add_edge(v, w, T); Q.emplace(v, w); } } } return T; } <commit_msg>add num vertices parameter to tree constructor<commit_after>// (C) 2014 Arek Olek #pragma once #include <tuple> #include <vector> #include <queue> #include "range.hpp" template <class Graph> Graph bfs_tree(Graph const & G) { typedef std::pair<int, int> edge; Graph T(num_vertices(G)); int parent, v = 0; std::queue<edge> Q; std::vector<bool> V(num_vertices(G)); Q.emplace(-1, v); V[v] = true; while(!Q.empty()) { std::tie(parent, v) = Q.front(); Q.pop(); for(auto w : range(adjacent_vertices(v, G))) { if(!V[w]) { V[w] = true; add_edge(v, w, T); Q.emplace(v, w); } } } return T; } <|endoftext|>
<commit_before>// Copyright 2019 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 "google/cloud/spanner/transaction.h" #include <gmock/gmock.h> namespace google { namespace cloud { namespace spanner { inline namespace SPANNER_CLIENT_NS { namespace { TEST(TransactionOptions, Construction) { Timestamp read_timestamp{}; std::chrono::nanoseconds staleness{}; Transaction::ReadOnlyOptions strong; Transaction::ReadOnlyOptions exact_ts(read_timestamp); Transaction::ReadOnlyOptions exact_dur(staleness); Transaction::ReadWriteOptions none; Transaction::SingleUseOptions su_strong(strong); Transaction::SingleUseOptions su_exact_ts(exact_ts); Transaction::SingleUseOptions su_exact_dur(exact_dur); Transaction::SingleUseOptions su_bounded_ts(read_timestamp); Transaction::SingleUseOptions su_bounded_dur(staleness); } TEST(Transaction, RegularSemantics) { Transaction::ReadOnlyOptions strong; Transaction a(strong); Transaction b = MakeReadOnlyTransaction(); EXPECT_NE(a, b); Transaction c = b; EXPECT_EQ(c, b); EXPECT_NE(c, a); c = a; EXPECT_EQ(c, a); EXPECT_NE(c, b); Transaction d(c); EXPECT_EQ(d, c); EXPECT_EQ(d, a); Transaction::ReadWriteOptions none; Transaction e(none); Transaction f = MakeReadWriteTransaction(); EXPECT_NE(e, f); Transaction g = f; EXPECT_EQ(g, f); EXPECT_NE(g, e); Transaction h = internal::MakeSingleUseTransaction(strong); Transaction i = internal::MakeSingleUseTransaction(strong); EXPECT_NE(h, i); Transaction j = i; EXPECT_EQ(j, i); EXPECT_NE(j, h); } TEST(Transaction, Visit) { Transaction a = MakeReadOnlyTransaction(); std::int64_t a_seqno; internal::Visit(a, [&a_seqno](internal::SessionHolder& /*session*/, google::spanner::v1::TransactionSelector& s, std::int64_t seqno) { EXPECT_TRUE(s.has_begin()); EXPECT_TRUE(s.begin().has_read_only()); s.set_id("test-txn-id"); a_seqno = seqno; return 0; }); internal::Visit(a, [a_seqno](internal::SessionHolder& /*session*/, google::spanner::v1::TransactionSelector& s, std::int64_t seqno) { EXPECT_EQ("test-txn-id", s.id()); EXPECT_GT(seqno, a_seqno); return 0; }); } } // namespace } // namespace SPANNER_CLIENT_NS } // namespace spanner } // namespace cloud } // namespace google <commit_msg>chore: update to googletest-1.10.0 (googleapis/google-cloud-cpp-spanner#994)<commit_after>// Copyright 2019 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 "google/cloud/spanner/transaction.h" #include <gmock/gmock.h> namespace google { namespace cloud { namespace spanner { inline namespace SPANNER_CLIENT_NS { namespace { TEST(TransactionOptions, Construction) { Timestamp read_timestamp{}; std::chrono::nanoseconds staleness{}; Transaction::ReadOnlyOptions strong; Transaction::ReadOnlyOptions exact_ts(read_timestamp); Transaction::ReadOnlyOptions exact_dur(staleness); Transaction::ReadWriteOptions none; Transaction::SingleUseOptions su_strong(strong); Transaction::SingleUseOptions su_exact_ts(exact_ts); Transaction::SingleUseOptions su_exact_dur(exact_dur); Transaction::SingleUseOptions su_bounded_ts(read_timestamp); Transaction::SingleUseOptions su_bounded_dur(staleness); } TEST(Transaction, RegularSemantics) { Transaction::ReadOnlyOptions strong; Transaction a(strong); Transaction b = MakeReadOnlyTransaction(); EXPECT_NE(a, b); Transaction c = b; EXPECT_EQ(c, b); EXPECT_NE(c, a); c = a; EXPECT_EQ(c, a); EXPECT_NE(c, b); Transaction d(c); EXPECT_EQ(d, c); EXPECT_EQ(d, a); Transaction::ReadWriteOptions none; Transaction e(none); Transaction f = MakeReadWriteTransaction(); EXPECT_NE(e, f); Transaction g = f; // NOLINT(performance-unnecessary-copy-initialization) EXPECT_EQ(g, f); EXPECT_NE(g, e); Transaction h = internal::MakeSingleUseTransaction(strong); Transaction i = internal::MakeSingleUseTransaction(strong); EXPECT_NE(h, i); Transaction j = i; // NOLINT(performance-unnecessary-copy-initialization) EXPECT_EQ(j, i); EXPECT_NE(j, h); } TEST(Transaction, Visit) { Transaction a = MakeReadOnlyTransaction(); std::int64_t a_seqno; internal::Visit(a, [&a_seqno](internal::SessionHolder& /*session*/, google::spanner::v1::TransactionSelector& s, std::int64_t seqno) { EXPECT_TRUE(s.has_begin()); EXPECT_TRUE(s.begin().has_read_only()); s.set_id("test-txn-id"); a_seqno = seqno; return 0; }); internal::Visit(a, [a_seqno](internal::SessionHolder& /*session*/, google::spanner::v1::TransactionSelector& s, std::int64_t seqno) { EXPECT_EQ("test-txn-id", s.id()); EXPECT_GT(seqno, a_seqno); return 0; }); } } // namespace } // namespace SPANNER_CLIENT_NS } // namespace spanner } // namespace cloud } // namespace google <|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 "content/browser/renderer_host/render_widget_host_view_android.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/utf_string_conversions.h" #include "content/browser/android/content_view_impl.h" #include "content/browser/android/device_info.h" #include "content/browser/gpu/gpu_surface_tracker.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/common/view_messages.h" namespace content { RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid( RenderWidgetHostImpl* widget_host, ContentViewImpl* content_view) : host_(widget_host), // ContentViewImpl represents the native side of the Java ContentView. // It being NULL means that it is not attached to the View system yet, // so we treat it as hidden. is_hidden_(!content_view), content_view_(content_view) { host_->SetView(this); // RenderWidgetHost is initialized as visible. If is_hidden_ is true, tell // RenderWidgetHost to hide. if (is_hidden_) host_->WasHidden(); } RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() { } void RenderWidgetHostViewAndroid::InitAsChild(gfx::NativeView parent_view) { NOTIMPLEMENTED(); } void RenderWidgetHostViewAndroid::InitAsPopup( RenderWidgetHostView* parent_host_view, const gfx::Rect& pos) { NOTIMPLEMENTED(); } void RenderWidgetHostViewAndroid::InitAsFullscreen( RenderWidgetHostView* reference_host_view) { NOTIMPLEMENTED(); } RenderWidgetHost* RenderWidgetHostViewAndroid::GetRenderWidgetHost() const { return host_; } void RenderWidgetHostViewAndroid::WasRestored() { if (!is_hidden_) return; is_hidden_ = false; host_->WasRestored(); } void RenderWidgetHostViewAndroid::WasHidden() { if (is_hidden_) return; // If we receive any more paint messages while we are hidden, we want to // ignore them so we don't re-allocate the backing store. We will paint // everything again when we become visible again. // is_hidden_ = true; // Inform the renderer that we are being hidden so it can reduce its resource // utilization. host_->WasHidden(); } void RenderWidgetHostViewAndroid::SetSize(const gfx::Size& size) { // Update the size of the RWH. if (requested_size_.width() != size.width() || requested_size_.height() != size.height()) { requested_size_ = gfx::Size(size.width(), size.height()); host_->WasResized(); } } void RenderWidgetHostViewAndroid::SetBounds(const gfx::Rect& rect) { if (rect.origin().x() || rect.origin().y()) { VLOG(0) << "SetBounds not implemented for (x,y)!=(0,0)"; } SetSize(rect.size()); } gfx::NativeView RenderWidgetHostViewAndroid::GetNativeView() const { return content_view_; } gfx::NativeViewId RenderWidgetHostViewAndroid::GetNativeViewId() const { return reinterpret_cast<gfx::NativeViewId>( const_cast<RenderWidgetHostViewAndroid*>(this)); } gfx::NativeViewAccessible RenderWidgetHostViewAndroid::GetNativeViewAccessible() { NOTIMPLEMENTED(); return NULL; } void RenderWidgetHostViewAndroid::MovePluginWindows( const std::vector<webkit::npapi::WebPluginGeometry>& moves) { // We don't have plugin windows on Android. Do nothing. Note: this is called // from RenderWidgetHost::OnMsgUpdateRect which is itself invoked while // processing the corresponding message from Renderer. } void RenderWidgetHostViewAndroid::Focus() { host_->Focus(); host_->SetInputMethodActive(true); } void RenderWidgetHostViewAndroid::Blur() { host_->Send(new ViewMsg_ExecuteEditCommand( host_->GetRoutingID(), "Unselect", "")); host_->SetInputMethodActive(false); host_->Blur(); } bool RenderWidgetHostViewAndroid::HasFocus() const { if (!content_view_) return false; // ContentView not created yet. return content_view_->HasFocus(); } bool RenderWidgetHostViewAndroid::IsSurfaceAvailableForCopy() const { NOTIMPLEMENTED(); return false; } void RenderWidgetHostViewAndroid::Show() { // nothing to do } void RenderWidgetHostViewAndroid::Hide() { // nothing to do } bool RenderWidgetHostViewAndroid::IsShowing() { return !is_hidden_; } gfx::Rect RenderWidgetHostViewAndroid::GetViewBounds() const { if (content_view_) { return content_view_->GetBounds(); } else { // The ContentView has not been created yet. This only happens when // renderer asks for creating new window, for example, // javascript window.open(). return gfx::Rect(0, 0, 0, 0); } } void RenderWidgetHostViewAndroid::UpdateCursor(const WebCursor& cursor) { // There are no cursors on Android. } void RenderWidgetHostViewAndroid::SetIsLoading(bool is_loading) { // Do nothing. The UI notification is handled through ContentViewClient which // is TabContentsDelegate. } void RenderWidgetHostViewAndroid::ImeUpdateTextInputState( const ViewHostMsg_TextInputState_Params& params) { NOTIMPLEMENTED(); } void RenderWidgetHostViewAndroid::TextInputStateChanged( ui::TextInputType type, bool can_compose_inline) { NOTIMPLEMENTED(); } void RenderWidgetHostViewAndroid::ImeCancelComposition() { } void RenderWidgetHostViewAndroid::DidUpdateBackingStore( const gfx::Rect& scroll_rect, int scroll_dx, int scroll_dy, const std::vector<gfx::Rect>& copy_rects) { NOTIMPLEMENTED(); } void RenderWidgetHostViewAndroid::RenderViewGone( base::TerminationStatus status, int error_code) { Destroy(); } void RenderWidgetHostViewAndroid::Destroy() { content_view_ = NULL; // The RenderWidgetHost's destruction led here, so don't call it. host_ = NULL; delete this; } void RenderWidgetHostViewAndroid::SetTooltipText( const string16& tooltip_text) { // Tooltips don't makes sense on Android. } void RenderWidgetHostViewAndroid::SelectionChanged(const string16& text, size_t offset, const ui::Range& range) { RenderWidgetHostViewBase::SelectionChanged(text, offset, range); if (text.empty() || range.is_empty() || !content_view_) return; size_t pos = range.GetMin() - offset; size_t n = range.length(); DCHECK(pos + n <= text.length()) << "The text can not fully cover range."; if (pos >= text.length()) { NOTREACHED() << "The text can not cover range."; return; } std::string utf8_selection = UTF16ToUTF8(text.substr(pos, n)); content_view_->OnSelectionChanged(utf8_selection); } BackingStore* RenderWidgetHostViewAndroid::AllocBackingStore( const gfx::Size& size) { NOTIMPLEMENTED(); return NULL; } void RenderWidgetHostViewAndroid::SetBackground(const SkBitmap& background) { RenderWidgetHostViewBase::SetBackground(background); host_->Send(new ViewMsg_SetBackground(host_->GetRoutingID(), background)); } void RenderWidgetHostViewAndroid::CopyFromCompositingSurface( const gfx::Size& size, skia::PlatformCanvas* output, base::Callback<void(bool)> callback) { NOTIMPLEMENTED(); callback.Run(false); } void RenderWidgetHostViewAndroid::OnAcceleratedCompositingStateChange() { const bool activated = host_->is_accelerated_compositing_active(); if (content_view_) content_view_->OnAcceleratedCompositingStateChange(this, activated, false); } void RenderWidgetHostViewAndroid::AcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params, int gpu_host_id) { NOTREACHED(); } void RenderWidgetHostViewAndroid::AcceleratedSurfacePostSubBuffer( const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params, int gpu_host_id) { NOTREACHED(); } void RenderWidgetHostViewAndroid::AcceleratedSurfaceSuspend() { NOTREACHED(); } bool RenderWidgetHostViewAndroid::HasAcceleratedSurface( const gfx::Size& desired_size) { NOTREACHED(); return false; } gfx::GLSurfaceHandle RenderWidgetHostViewAndroid::GetCompositingSurface() { // On Android, we cannot generate a window handle that can be passed to the // GPU process through the native side. Instead, we send the surface handle // through Binder after the compositing context has been created. return gfx::GLSurfaceHandle(gfx::kNullPluginWindow, true); } void RenderWidgetHostViewAndroid::GetScreenInfo(WebKit::WebScreenInfo* result) { // ScreenInfo isn't tied to the widget on Android. Always return the default. RenderWidgetHostViewBase::GetDefaultScreenInfo(result); } // TODO(jrg): Find out the implications and answer correctly here, // as we are returning the WebView and not root window bounds. gfx::Rect RenderWidgetHostViewAndroid::GetRootWindowBounds() { return GetViewBounds(); } void RenderWidgetHostViewAndroid::UnhandledWheelEvent( const WebKit::WebMouseWheelEvent& event) { // intentionally empty, like RenderWidgetHostViewViews } void RenderWidgetHostViewAndroid::ProcessTouchAck( WebKit::WebInputEvent::Type type, bool processed) { // intentionally empty, like RenderWidgetHostViewViews } void RenderWidgetHostViewAndroid::SetHasHorizontalScrollbar( bool has_horizontal_scrollbar) { // intentionally empty, like RenderWidgetHostViewViews } void RenderWidgetHostViewAndroid::SetScrollOffsetPinning( bool is_pinned_to_left, bool is_pinned_to_right) { // intentionally empty, like RenderWidgetHostViewViews } bool RenderWidgetHostViewAndroid::LockMouse() { NOTIMPLEMENTED(); return false; } void RenderWidgetHostViewAndroid::UnlockMouse() { NOTIMPLEMENTED(); } void RenderWidgetHostViewAndroid::SetContentView( ContentViewImpl* content_view) { content_view_ = content_view; if (host_) { GpuSurfaceTracker::Get()->SetSurfaceHandle( host_->surface_id(), content_view_ ? GetCompositingSurface() : gfx::GLSurfaceHandle()); } } // static void RenderWidgetHostViewPort::GetDefaultScreenInfo( ::WebKit::WebScreenInfo* results) { DeviceInfo info; const int width = info.GetWidth(); const int height = info.GetHeight(); results->horizontalDPI = 160 * info.GetDPIScale(); results->verticalDPI = 160 * info.GetDPIScale(); results->depth = info.GetBitsPerPixel(); results->depthPerComponent = info.GetBitsPerComponent(); results->isMonochrome = (results->depthPerComponent == 0); results->rect = ::WebKit::WebRect(0, 0, width, height); // TODO(husky): Remove any system controls from availableRect. results->availableRect = ::WebKit::WebRect(0, 0, width, height); } //////////////////////////////////////////////////////////////////////////////// // RenderWidgetHostView, public: // static RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget(RenderWidgetHost* widget) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(widget); return new RenderWidgetHostViewAndroid(rwhi, NULL); } } // namespace content <commit_msg>Change include directive for content/common/android/device_info.h<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 "content/browser/renderer_host/render_widget_host_view_android.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/utf_string_conversions.h" #include "content/browser/android/content_view_impl.h" #include "content/browser/gpu/gpu_surface_tracker.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/common/android/device_info.h" #include "content/common/view_messages.h" namespace content { RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid( RenderWidgetHostImpl* widget_host, ContentViewImpl* content_view) : host_(widget_host), // ContentViewImpl represents the native side of the Java ContentView. // It being NULL means that it is not attached to the View system yet, // so we treat it as hidden. is_hidden_(!content_view), content_view_(content_view) { host_->SetView(this); // RenderWidgetHost is initialized as visible. If is_hidden_ is true, tell // RenderWidgetHost to hide. if (is_hidden_) host_->WasHidden(); } RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() { } void RenderWidgetHostViewAndroid::InitAsChild(gfx::NativeView parent_view) { NOTIMPLEMENTED(); } void RenderWidgetHostViewAndroid::InitAsPopup( RenderWidgetHostView* parent_host_view, const gfx::Rect& pos) { NOTIMPLEMENTED(); } void RenderWidgetHostViewAndroid::InitAsFullscreen( RenderWidgetHostView* reference_host_view) { NOTIMPLEMENTED(); } RenderWidgetHost* RenderWidgetHostViewAndroid::GetRenderWidgetHost() const { return host_; } void RenderWidgetHostViewAndroid::WasRestored() { if (!is_hidden_) return; is_hidden_ = false; host_->WasRestored(); } void RenderWidgetHostViewAndroid::WasHidden() { if (is_hidden_) return; // If we receive any more paint messages while we are hidden, we want to // ignore them so we don't re-allocate the backing store. We will paint // everything again when we become visible again. // is_hidden_ = true; // Inform the renderer that we are being hidden so it can reduce its resource // utilization. host_->WasHidden(); } void RenderWidgetHostViewAndroid::SetSize(const gfx::Size& size) { // Update the size of the RWH. if (requested_size_.width() != size.width() || requested_size_.height() != size.height()) { requested_size_ = gfx::Size(size.width(), size.height()); host_->WasResized(); } } void RenderWidgetHostViewAndroid::SetBounds(const gfx::Rect& rect) { if (rect.origin().x() || rect.origin().y()) { VLOG(0) << "SetBounds not implemented for (x,y)!=(0,0)"; } SetSize(rect.size()); } gfx::NativeView RenderWidgetHostViewAndroid::GetNativeView() const { return content_view_; } gfx::NativeViewId RenderWidgetHostViewAndroid::GetNativeViewId() const { return reinterpret_cast<gfx::NativeViewId>( const_cast<RenderWidgetHostViewAndroid*>(this)); } gfx::NativeViewAccessible RenderWidgetHostViewAndroid::GetNativeViewAccessible() { NOTIMPLEMENTED(); return NULL; } void RenderWidgetHostViewAndroid::MovePluginWindows( const std::vector<webkit::npapi::WebPluginGeometry>& moves) { // We don't have plugin windows on Android. Do nothing. Note: this is called // from RenderWidgetHost::OnMsgUpdateRect which is itself invoked while // processing the corresponding message from Renderer. } void RenderWidgetHostViewAndroid::Focus() { host_->Focus(); host_->SetInputMethodActive(true); } void RenderWidgetHostViewAndroid::Blur() { host_->Send(new ViewMsg_ExecuteEditCommand( host_->GetRoutingID(), "Unselect", "")); host_->SetInputMethodActive(false); host_->Blur(); } bool RenderWidgetHostViewAndroid::HasFocus() const { if (!content_view_) return false; // ContentView not created yet. return content_view_->HasFocus(); } bool RenderWidgetHostViewAndroid::IsSurfaceAvailableForCopy() const { NOTIMPLEMENTED(); return false; } void RenderWidgetHostViewAndroid::Show() { // nothing to do } void RenderWidgetHostViewAndroid::Hide() { // nothing to do } bool RenderWidgetHostViewAndroid::IsShowing() { return !is_hidden_; } gfx::Rect RenderWidgetHostViewAndroid::GetViewBounds() const { if (content_view_) { return content_view_->GetBounds(); } else { // The ContentView has not been created yet. This only happens when // renderer asks for creating new window, for example, // javascript window.open(). return gfx::Rect(0, 0, 0, 0); } } void RenderWidgetHostViewAndroid::UpdateCursor(const WebCursor& cursor) { // There are no cursors on Android. } void RenderWidgetHostViewAndroid::SetIsLoading(bool is_loading) { // Do nothing. The UI notification is handled through ContentViewClient which // is TabContentsDelegate. } void RenderWidgetHostViewAndroid::ImeUpdateTextInputState( const ViewHostMsg_TextInputState_Params& params) { NOTIMPLEMENTED(); } void RenderWidgetHostViewAndroid::TextInputStateChanged( ui::TextInputType type, bool can_compose_inline) { NOTIMPLEMENTED(); } void RenderWidgetHostViewAndroid::ImeCancelComposition() { } void RenderWidgetHostViewAndroid::DidUpdateBackingStore( const gfx::Rect& scroll_rect, int scroll_dx, int scroll_dy, const std::vector<gfx::Rect>& copy_rects) { NOTIMPLEMENTED(); } void RenderWidgetHostViewAndroid::RenderViewGone( base::TerminationStatus status, int error_code) { Destroy(); } void RenderWidgetHostViewAndroid::Destroy() { content_view_ = NULL; // The RenderWidgetHost's destruction led here, so don't call it. host_ = NULL; delete this; } void RenderWidgetHostViewAndroid::SetTooltipText( const string16& tooltip_text) { // Tooltips don't makes sense on Android. } void RenderWidgetHostViewAndroid::SelectionChanged(const string16& text, size_t offset, const ui::Range& range) { RenderWidgetHostViewBase::SelectionChanged(text, offset, range); if (text.empty() || range.is_empty() || !content_view_) return; size_t pos = range.GetMin() - offset; size_t n = range.length(); DCHECK(pos + n <= text.length()) << "The text can not fully cover range."; if (pos >= text.length()) { NOTREACHED() << "The text can not cover range."; return; } std::string utf8_selection = UTF16ToUTF8(text.substr(pos, n)); content_view_->OnSelectionChanged(utf8_selection); } BackingStore* RenderWidgetHostViewAndroid::AllocBackingStore( const gfx::Size& size) { NOTIMPLEMENTED(); return NULL; } void RenderWidgetHostViewAndroid::SetBackground(const SkBitmap& background) { RenderWidgetHostViewBase::SetBackground(background); host_->Send(new ViewMsg_SetBackground(host_->GetRoutingID(), background)); } void RenderWidgetHostViewAndroid::CopyFromCompositingSurface( const gfx::Size& size, skia::PlatformCanvas* output, base::Callback<void(bool)> callback) { NOTIMPLEMENTED(); callback.Run(false); } void RenderWidgetHostViewAndroid::OnAcceleratedCompositingStateChange() { const bool activated = host_->is_accelerated_compositing_active(); if (content_view_) content_view_->OnAcceleratedCompositingStateChange(this, activated, false); } void RenderWidgetHostViewAndroid::AcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params, int gpu_host_id) { NOTREACHED(); } void RenderWidgetHostViewAndroid::AcceleratedSurfacePostSubBuffer( const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params, int gpu_host_id) { NOTREACHED(); } void RenderWidgetHostViewAndroid::AcceleratedSurfaceSuspend() { NOTREACHED(); } bool RenderWidgetHostViewAndroid::HasAcceleratedSurface( const gfx::Size& desired_size) { NOTREACHED(); return false; } gfx::GLSurfaceHandle RenderWidgetHostViewAndroid::GetCompositingSurface() { // On Android, we cannot generate a window handle that can be passed to the // GPU process through the native side. Instead, we send the surface handle // through Binder after the compositing context has been created. return gfx::GLSurfaceHandle(gfx::kNullPluginWindow, true); } void RenderWidgetHostViewAndroid::GetScreenInfo(WebKit::WebScreenInfo* result) { // ScreenInfo isn't tied to the widget on Android. Always return the default. RenderWidgetHostViewBase::GetDefaultScreenInfo(result); } // TODO(jrg): Find out the implications and answer correctly here, // as we are returning the WebView and not root window bounds. gfx::Rect RenderWidgetHostViewAndroid::GetRootWindowBounds() { return GetViewBounds(); } void RenderWidgetHostViewAndroid::UnhandledWheelEvent( const WebKit::WebMouseWheelEvent& event) { // intentionally empty, like RenderWidgetHostViewViews } void RenderWidgetHostViewAndroid::ProcessTouchAck( WebKit::WebInputEvent::Type type, bool processed) { // intentionally empty, like RenderWidgetHostViewViews } void RenderWidgetHostViewAndroid::SetHasHorizontalScrollbar( bool has_horizontal_scrollbar) { // intentionally empty, like RenderWidgetHostViewViews } void RenderWidgetHostViewAndroid::SetScrollOffsetPinning( bool is_pinned_to_left, bool is_pinned_to_right) { // intentionally empty, like RenderWidgetHostViewViews } bool RenderWidgetHostViewAndroid::LockMouse() { NOTIMPLEMENTED(); return false; } void RenderWidgetHostViewAndroid::UnlockMouse() { NOTIMPLEMENTED(); } void RenderWidgetHostViewAndroid::SetContentView( ContentViewImpl* content_view) { content_view_ = content_view; if (host_) { GpuSurfaceTracker::Get()->SetSurfaceHandle( host_->surface_id(), content_view_ ? GetCompositingSurface() : gfx::GLSurfaceHandle()); } } // static void RenderWidgetHostViewPort::GetDefaultScreenInfo( ::WebKit::WebScreenInfo* results) { DeviceInfo info; const int width = info.GetWidth(); const int height = info.GetHeight(); results->horizontalDPI = 160 * info.GetDPIScale(); results->verticalDPI = 160 * info.GetDPIScale(); results->depth = info.GetBitsPerPixel(); results->depthPerComponent = info.GetBitsPerComponent(); results->isMonochrome = (results->depthPerComponent == 0); results->rect = ::WebKit::WebRect(0, 0, width, height); // TODO(husky): Remove any system controls from availableRect. results->availableRect = ::WebKit::WebRect(0, 0, width, height); } //////////////////////////////////////////////////////////////////////////////// // RenderWidgetHostView, public: // static RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget(RenderWidgetHost* widget) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(widget); return new RenderWidgetHostViewAndroid(rwhi, NULL); } } // namespace content <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2007 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // logDetail.cpp : Plugin module for logging server events to stdout // #include <iostream> #include "bzfsAPI.h" BZ_GET_PLUGIN_VERSION using namespace std; class logDetail : public bz_EventHandler { public: logDetail() {}; virtual ~logDetail() {}; virtual void process( bz_EventData *eventData ); private: void displayPlayerPrivs( int playerID ); void displayCallsign( bz_ApiString callsign ); void displayCallsign( int playerID ); void displayTeam( bz_eTeamType team ); }; logDetail logDetailHandler; BZF_PLUGIN_CALL int bz_Load ( const char* /*commandLine*/ ) { bz_registerEvent(bz_eSlashCommandEvent, &logDetailHandler); bz_registerEvent(bz_eRawChatMessageEvent, &logDetailHandler); bz_registerEvent(bz_eServerMsgEvent, &logDetailHandler); bz_registerEvent(bz_ePlayerJoinEvent, &logDetailHandler); bz_registerEvent(bz_ePlayerPartEvent, &logDetailHandler); bz_registerEvent(bz_ePlayerAuthEvent, &logDetailHandler); bz_debugMessage(4, "logDetail plugin loaded"); return 0; } BZF_PLUGIN_CALL int bz_Unload ( void ) { bz_removeEvent(bz_eSlashCommandEvent, &logDetailHandler); bz_removeEvent(bz_eRawChatMessageEvent, &logDetailHandler); bz_removeEvent(bz_eServerMsgEvent, &logDetailHandler); bz_removeEvent(bz_ePlayerJoinEvent, &logDetailHandler); bz_removeEvent(bz_ePlayerPartEvent, &logDetailHandler); bz_removeEvent(bz_ePlayerAuthEvent, &logDetailHandler); bz_debugMessage(4, "logDetail plugin unloaded"); return 0; } void logDetail::process( bz_EventData *eventData ) { bz_ChatEventData_V1 *chatData = (bz_ChatEventData_V1 *) eventData; bz_ServerMsgEventData_V1 *serverMsgData = (bz_ServerMsgEventData_V1 *) eventData; bz_SlashCommandEventData_V1 *cmdData = (bz_SlashCommandEventData_V1 *) eventData; bz_PlayerJoinPartEventData_V1 *joinPartData = (bz_PlayerJoinPartEventData_V1 *) eventData; bz_PlayerAuthEventData_V1 *authData = (bz_PlayerAuthEventData_V1 *) eventData; char temp[9] = {0}; if (eventData) { switch (eventData->eventType) { case bz_eSlashCommandEvent: // Slash commands are case insensitive // Tokenize the stream and check the first word // /report -> MSG-REPORT // anything -> MSG-COMMAND strncpy(temp, cmdData->message.c_str() , 8); if (strcasecmp( temp, "/REPORT ") == 0 ) { cout << "MSG-REPORT "; displayCallsign( cmdData->from ); cout << " " << cmdData->message.c_str()+8 << endl; } else { cout << "MSG-COMMAND "; displayCallsign( cmdData->from ); cout << " " << cmdData->message.c_str()+1 << endl; } break; case bz_eRawChatMessageEvent: if ((chatData->to == BZ_ALLUSERS) and (chatData->team == eNoTeam)) { cout << "MSG-BROADCAST "; displayCallsign( chatData->from ); cout << " " << chatData->message.c_str() << endl; } else if (chatData->to == BZ_NULLUSER) { if (chatData->team == eAdministrators) { cout << "MSG-ADMIN "; displayCallsign( chatData->from ); cout << " " << chatData->message.c_str() << endl; } else { cout << "MSG-TEAM "; displayCallsign( chatData->from ); displayTeam( chatData->team ); cout << " " << chatData->message.c_str() << endl; } } else { cout << "MSG-DIRECT "; displayCallsign( chatData->from ); cout << " "; displayCallsign( chatData->to ); cout << " " << chatData->message.c_str() << endl; } break; case bz_eServerMsgEvent: if ((serverMsgData->to == BZ_ALLUSERS) and (serverMsgData->team == eNoTeam)) { cout << "MSG-BROADCAST 6:SERVER"; cout << " " << serverMsgData->message.c_str() << endl; } else if (serverMsgData->to == BZ_NULLUSER) { if (serverMsgData->team == eAdministrators) { cout << "MSG-ADMIN 6:SERVER"; cout << " " << serverMsgData->message.c_str() << endl; } else { cout << "MSG-TEAM 6:SERVER"; displayTeam( serverMsgData->team ); cout << " " << chatData->message.c_str() << endl; } } else { cout << "MSG-DIRECT 6:SERVER"; cout << " "; displayCallsign( serverMsgData->to ); cout << " " << serverMsgData->message.c_str() << endl; } break; case bz_ePlayerJoinEvent: { bz_BasePlayerRecord *player = bz_getPlayerByIndex( joinPartData->playerID ); if (player) { cout << "PLAYER-JOIN "; displayCallsign( player->callsign ); cout << " #" << joinPartData->playerID; displayTeam( joinPartData->team ); displayPlayerPrivs( joinPartData->playerID ); cout << endl; } } break; case bz_ePlayerPartEvent: cout << "PLAYER-PART "; displayCallsign( joinPartData->playerID ); cout << " #" << joinPartData->playerID; cout << " " << joinPartData->reason.c_str(); cout << endl; break; case bz_ePlayerAuthEvent: cout << "PLAYER-AUTH "; displayCallsign( authData->playerID ); displayPlayerPrivs( authData->playerID ); cout << endl; break; default : break; } } } void logDetail::displayPlayerPrivs( int playerID ) { bz_BasePlayerRecord *player = bz_getPlayerByIndex( playerID ); if (player) { cout << " IP:" << player->ipAddress.c_str(); if (player->verified ) cout << " VERIFIED"; if (player->globalUser ) cout << " GLOBALUSER"; if (player->admin ) cout << " ADMIN"; if (player->op ) cout << " OPERATOR"; } else { cout << " IP:0.0.0.0"; } } void logDetail::displayCallsign( bz_ApiString callsign ) { cout << strlen( callsign.c_str() ) << ":"; cout << callsign.c_str(); } void logDetail::displayCallsign( int playerID ) { bz_BasePlayerRecord *player = bz_getPlayerByIndex( playerID ); if (player) { cout << strlen( player->callsign.c_str() ) << ":"; cout << player->callsign.c_str(); } else { cout << "7:UNKNOWN"; } } void logDetail::displayTeam( bz_eTeamType team ) { // Display the player team switch ( team ) { case eRogueTeam: cout << " ROGUE"; break; case eRedTeam: cout << " RED"; break; case eGreenTeam: cout << " GREEN"; break; case eBlueTeam: cout << " BLUE"; break; case ePurpleTeam: cout << " PURPLE"; break; case eRabbitTeam: cout << " RABBIT"; break; case eHunterTeam: cout << " HUNTER"; break; case eObservers: cout << " OBSERVER"; break; default : cout << " NOTEAM"; break; } } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>Add SERVER-STATUS messages - assumes plugin is loaded on startup and unloaded on server shutdown<commit_after>/* bzflag * Copyright (c) 1993 - 2007 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // logDetail.cpp : Plugin module for logging server events to stdout // #include <iostream> #include <sstream> #include "bzfsAPI.h" BZ_GET_PLUGIN_VERSION using namespace std; enum action { join , auth , part }; class logDetail : public bz_EventHandler { public: logDetail(); virtual ~logDetail(); virtual void process( bz_EventData *eventData ); private: void displayPlayerPrivs( int playerID ); void displayCallsign( bz_ApiString callsign ); void displayCallsign( int playerID ); void displayBZid( int playerID ); void displayTeam( bz_eTeamType team ); virtual void listPlayers( action act, bz_PlayerJoinPartEventData_V1 *data ); }; logDetail logDetailHandler; BZF_PLUGIN_CALL int bz_Load ( const char* /*commandLine*/ ) { bz_registerEvent(bz_eSlashCommandEvent, &logDetailHandler); bz_registerEvent(bz_eRawChatMessageEvent, &logDetailHandler); bz_registerEvent(bz_eServerMsgEvent, &logDetailHandler); bz_registerEvent(bz_ePlayerJoinEvent, &logDetailHandler); bz_registerEvent(bz_ePlayerPartEvent, &logDetailHandler); bz_registerEvent(bz_ePlayerAuthEvent, &logDetailHandler); bz_debugMessage(4, "logDetail plugin loaded"); return 0; } BZF_PLUGIN_CALL int bz_Unload ( void ) { bz_removeEvent(bz_eSlashCommandEvent, &logDetailHandler); bz_removeEvent(bz_eRawChatMessageEvent, &logDetailHandler); bz_removeEvent(bz_eServerMsgEvent, &logDetailHandler); bz_removeEvent(bz_ePlayerJoinEvent, &logDetailHandler); bz_removeEvent(bz_ePlayerPartEvent, &logDetailHandler); bz_removeEvent(bz_ePlayerAuthEvent, &logDetailHandler); bz_debugMessage(4, "logDetail plugin unloaded"); return 0; } logDetail::logDetail() { cout << "SERVER-STATUS Running" << endl; listPlayers( join , NULL ); } logDetail::~logDetail() { listPlayers( part , NULL ); cout << "SERVER-STATUS Stopped" << endl; } void logDetail::process( bz_EventData *eventData ) { bz_ChatEventData_V1 *chatData = (bz_ChatEventData_V1 *) eventData; bz_ServerMsgEventData_V1 *serverMsgData = (bz_ServerMsgEventData_V1 *) eventData; bz_SlashCommandEventData_V1 *cmdData = (bz_SlashCommandEventData_V1 *) eventData; bz_PlayerJoinPartEventData_V1 *joinPartData = (bz_PlayerJoinPartEventData_V1 *) eventData; bz_PlayerAuthEventData_V1 *authData = (bz_PlayerAuthEventData_V1 *) eventData; char temp[9] = {0}; if (eventData) { switch (eventData->eventType) { case bz_eSlashCommandEvent: // Slash commands are case insensitive // Tokenize the stream and check the first word // /report -> MSG-REPORT // anything -> MSG-COMMAND strncpy(temp, cmdData->message.c_str(), 8); if (strcasecmp(temp, "/REPORT ") == 0) { cout << "MSG-REPORT "; displayCallsign( cmdData->from ); cout << " " << cmdData->message.c_str()+8 << endl; } else { cout << "MSG-COMMAND "; displayCallsign( cmdData->from ); cout << " " << cmdData->message.c_str()+1 << endl; } break; case bz_eRawChatMessageEvent: if ((chatData->to == BZ_ALLUSERS) and (chatData->team == eNoTeam)) { cout << "MSG-BROADCAST "; displayCallsign( chatData->from ); cout << " " << chatData->message.c_str() << endl; } else if (chatData->to == BZ_NULLUSER) { if (chatData->team == eAdministrators) { cout << "MSG-ADMIN "; displayCallsign( chatData->from ); cout << " " << chatData->message.c_str() << endl; } else { cout << "MSG-TEAM "; displayCallsign( chatData->from ); displayTeam( chatData->team ); cout << " " << chatData->message.c_str() << endl; } } else { cout << "MSG-DIRECT "; displayCallsign( chatData->from ); cout << " "; displayCallsign( chatData->to ); cout << " " << chatData->message.c_str() << endl; } break; case bz_eServerMsgEvent: if ((serverMsgData->to == BZ_ALLUSERS) and (serverMsgData->team == eNoTeam)) { cout << "MSG-BROADCAST 6:SERVER"; cout << " " << serverMsgData->message.c_str() << endl; } else if (serverMsgData->to == BZ_NULLUSER) { if (serverMsgData->team == eAdministrators) { cout << "MSG-ADMIN 6:SERVER"; cout << " " << serverMsgData->message.c_str() << endl; } else { cout << "MSG-TEAM 6:SERVER"; displayTeam( serverMsgData->team ); cout << " " << chatData->message.c_str() << endl; } } else { cout << "MSG-DIRECT 6:SERVER"; cout << " "; displayCallsign( serverMsgData->to ); cout << " " << serverMsgData->message.c_str() << endl; } break; case bz_ePlayerJoinEvent: { bz_BasePlayerRecord *player = bz_getPlayerByIndex( joinPartData->playerID ); if (player) { cout << "PLAYER-JOIN "; displayCallsign( player->callsign ); cout << " #" << joinPartData->playerID; displayBZid( joinPartData->playerID ); displayTeam( joinPartData->team ); displayPlayerPrivs( joinPartData->playerID ); cout << endl; listPlayers( join, joinPartData ); } } break; case bz_ePlayerPartEvent: cout << "PLAYER-PART "; displayCallsign( joinPartData->playerID ); cout << " #" << joinPartData->playerID; displayBZid( joinPartData->playerID ); cout << " " << joinPartData->reason.c_str(); cout << endl; listPlayers( part, joinPartData ); break; case bz_ePlayerAuthEvent: cout << "PLAYER-AUTH "; displayCallsign( authData->playerID ); displayPlayerPrivs( authData->playerID ); cout << endl; listPlayers( join, joinPartData ); break; default : break; } } } void logDetail::displayBZid( int playerID ) { bz_BasePlayerRecord *player = bz_getPlayerByIndex( playerID ); if (player && player->globalUser) cout << " BZid:" << player->bzID.c_str(); } void logDetail::displayPlayerPrivs( int playerID ) { bz_BasePlayerRecord *player = bz_getPlayerByIndex( playerID ); if (player) { cout << " IP:" << player->ipAddress.c_str(); if (player->verified ) cout << " VERIFIED"; if (player->globalUser ) cout << " GLOBALUSER"; if (player->admin ) cout << " ADMIN"; if (player->op ) cout << " OPERATOR"; } else { cout << " IP:0.0.0.0"; } } void logDetail::displayCallsign( bz_ApiString callsign ) { cout << strlen( callsign.c_str() ) << ":"; cout << callsign.c_str(); } void logDetail::displayCallsign( int playerID ) { bz_BasePlayerRecord *player = bz_getPlayerByIndex( playerID ); if (player) { cout << strlen( player->callsign.c_str() ) << ":"; cout << player->callsign.c_str(); } else { cout << "7:UNKNOWN"; } } void logDetail::displayTeam( bz_eTeamType team ) { // Display the player team switch ( team ) { case eRogueTeam: cout << " ROGUE"; break; case eRedTeam: cout << " RED"; break; case eGreenTeam: cout << " GREEN"; break; case eBlueTeam: cout << " BLUE"; break; case ePurpleTeam: cout << " PURPLE"; break; case eRabbitTeam: cout << " RABBIT"; break; case eHunterTeam: cout << " HUNTER"; break; case eObservers: cout << " OBSERVER"; break; default : cout << " NOTEAM"; break; } } void logDetail::listPlayers( action act , bz_PlayerJoinPartEventData_V1 *data ) { bz_APIIntList *playerList = bz_newIntList(); bz_BasePlayerRecord *player; ostringstream msg; string str; char playerStatus; int numPlayers; bz_getPlayerIndexList( playerList ); bz_debugMessage( 4 , "Players:" ); // // Count number of players // numPlayers = 0; for ( unsigned int i = 0; i < playerList->size(); i++ ) { player = bz_getPlayerByIndex( playerList->get(i)); if (player) { if ((player->callsign != "") && (act == join || act == auth || (data && (player->playerID != data->playerID)))) numPlayers++; bz_freePlayerRecord( player ); } } // // Display number of players, callsign, and email string in the following format: // // PLAYERS (nn) [G]cc:callsign(ee:emailstring) // nn - number of players // G - global auth identifier (+|-| |@) // cc - count of characters in player callsign // callsign - player callsign // ee - count of characters in email string // emailstring - player email string // // eg. // PLAYERS (2) [@]7:Thumper(16:me@somewhere.net) [ ]3:xxx() // msg.str(""); msg << "PLAYERS (" << numPlayers << ") "; for ( unsigned int i = 0; i < playerList->size(); i++ ) { player = bz_getPlayerByIndex( playerList->get(i)); if (player) { if ((player->callsign != "") && (act == join || act == auth || (data && (player->playerID != data->playerID)))) { playerStatus = ' '; if (player->globalUser) playerStatus = '+'; if (player->verified) playerStatus = '+'; if (player->admin and !bz_hasPerm(player->playerID, bz_perm_hideAdmin)) playerStatus = '@'; msg << "[" << playerStatus << "]"; msg << player->callsign.size() << ':'; msg << player->callsign.c_str(); msg << "("; if (player->email != "") msg << player->email.size() << ":" << player->email.c_str(); msg << ") "; } bz_freePlayerRecord( player ); } } str = msg.str(); cout << str << endl; bz_deleteIntList(playerList); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* * CFG_EARLEY_PARSE.hpp * * Created on: Mar 10, 2011 * Author: Peter Goodman * Version: $Id$ * * Copyright 2011 Peter Goodman, all rights reserved. */ #ifndef FLTL_CFG_EARLEY_PARSE_HPP_ #define FLTL_CFG_EARLEY_PARSE_HPP_ #include <set> #include <vector> #include "fltl/include/CFG.hpp" #include "fltl/include/helper/BlockAllocator.hpp" #include "grail/include/cfg/ParseTree.hpp" #include "grail/include/io/verbose.hpp" #include "grail/include/io/UTF8FileLineBuffer.hpp" namespace grail { namespace algorithm { /// parse a context free grammar using an Earley-style parser template <typename AlphaT, const unsigned MAX_TOK_LENGTH> class CFG_PARSE_EARLEY { public: // take off the templates! typedef fltl::CFG<AlphaT> CFG; typedef typename CFG::alphabet_type alphabet_type; typedef typename CFG::symbol_type symbol_type; typedef typename CFG::traits_type traits_type; typedef typename CFG::variable_type variable_type; typedef typename CFG::pattern_type pattern_type; typedef typename CFG::terminal_type terminal_type; typedef typename CFG::production_type production_type; typedef typename CFG::generator_type generator_type; typedef typename CFG::symbol_string_type symbol_string_type; typedef typename CFG::production_builder_type production_builder_type; typedef cfg::ParseTree<AlphaT> parse_tree_type; class earley_item_type; /// Earley set class earley_set_type { public: // first item in the set earley_item_type *first; earley_item_type *last; // next set earley_set_type *next; earley_set_type *prev; // offset into the terminal stream unsigned offset; earley_set_type(void) : first(0) , last(0) , next(0) , prev(0) , offset(0) { } void push(earley_item_type *item) throw() { if(0 == item) { return; } if(0 == first) { first = item; last = item; } else { last->next = item; last = item; } item->next = 0; } void set_next(earley_set_type *set) throw() { set->prev = this; set->next = 0; next = set; set->offset = offset + 1; } }; /// Earley item class earley_item_type { public: // dotted production unsigned short dot; production_type production; // next item in the set earley_item_type *next; // the set that first introduced the production being used. that // is, sliding the dot changes the set that owns an item, but not // the set that initiated an item. earley_set_type *initial_set; // the next item in the same set that has the same initial // set earley_item_type *next_with_same_initial_set; earley_item_type(void) : dot(0) , production() , next(0) , initial_set(0) , next_with_same_initial_set(0) { } void scanned_from( earley_item_type *scan ) throw() { dot = scan->dot + 1U; production = scan->production; initial_set = scan->initial_set; } void predicted_from( earley_set_type *set, const production_type &prod ) throw() { dot = 0; production = prod; initial_set = set; } }; private: enum { NUM_BLOCKS = 1024U }; static void clear_index(std::vector<earley_item_type *> &index) throw() { for(unsigned i(0); i < index.size(); ++i) { index[i] = 0; } } /// check the index for the existence of item, if it's in, return 0, /// otherwise return the item and add it to the index static earley_item_type * indexed_push( earley_set_type *set, std::vector<earley_item_type *> &index, fltl::helper::BlockAllocator< earley_item_type, NUM_BLOCKS > &allocator, earley_item_type *item ) throw() { const unsigned offset(item->initial_set->offset); earley_item_type *&items(index[offset]); earley_item_type *prev(0); for(earley_item_type *curr(items); 0 != curr; prev = curr, curr = curr->next_with_same_initial_set) { // found an insertion point if(item->dot < curr->dot) { item->next_with_same_initial_set = curr; if(0 == prev) { items = item; } else { prev->next_with_same_initial_set = item; } set->push(item); return item; // skip } else if(item->dot > curr->dot) { continue; // same dot values, check if the productions are equivalent } else if(curr->production == item->production) { allocator.deallocate(item); return curr; } } // the set was empty if(0 == prev) { items = item; // this item is going at the end } else { prev->next_with_same_initial_set = item; } set->push(item); return item; } public: /// run the parser; assumes that the NULLABLE set is properly filled /// for this grammar static bool run( CFG &cfg, std::vector<bool> &is_nullable, const bool use_first_set, std::vector<std::vector<bool> *> &first_terminals, io::UTF8FileLineBuffer<MAX_TOK_LENGTH> &reader ) throw() { bool parse_result(false); const char *token(reader.read()); // allocator for Earley sets static fltl::helper::BlockAllocator< earley_set_type, NUM_BLOCKS > set_allocator; /// allocator for Earley items static fltl::helper::BlockAllocator< earley_item_type, NUM_BLOCKS > item_allocator; // the actual start variable; we will end up adding a fake // start variable later const variable_type ASV(cfg.get_start_variable()); // is it worth parsing? if(0 == cfg.num_productions() || !cfg.has_start_variable() || 0 == cfg.num_productions(ASV)) { if(0 == token || '\0' == *token) { io::verbose("Parsed. Accepted empty language.\n"); return true; } else { io::verbose("Failed to parse. Language is empty.\n"); return false; } } // add in a fake start variable; this variable and its productions // will be removed at the end variable_type SV(cfg.add_variable()); production_type SP(cfg.add_production(SV, ASV)); is_nullable[SV.number()] = is_nullable[ASV.number()]; if(use_first_set) { first_terminals[SV.number()] = new std::vector<bool>( *(first_terminals[ASV.number()]) ); } // set up the base case for the earley parser earley_item_type *curr_item(item_allocator.allocate()); earley_set_type *curr_set(set_allocator.allocate()); earley_set_type *prev_set(0); earley_item_type *first_item(curr_item); earley_set_type *first_set(curr_set); curr_set->next = 0; curr_item->production = SP; curr_item->initial_set = curr_set; curr_set->push(first_item); // variables used in the patterns unsigned dot; variable_type A; variable_type B; terminal_type a; production_type prod; pattern_type scanner_known((~A) --->* cfg.__(dot) + a + cfg.__); pattern_type scanner_unknown((~A) --->* cfg.__(dot) + ~a + cfg.__); pattern_type predictor((~A) --->* cfg.__(dot) + ~B + cfg.__); pattern_type completer((~A) --->* cfg.__(dot)); generator_type predictor_related(cfg.search(~prod, B --->* cfg.__)); pattern_type completer_related(cfg._ --->* cfg.__(dot) + A + cfg.__); // terminals unsigned i(0); alphabet_type lexeme; bool solve_for_variable_terminal(false); // indexes for the sets to test membership, +1 as there are n+1 // sets (S_0 ... S_n) for a string of length n. std::vector<earley_item_type *> set_index[2]; set_index[0].assign(1U, static_cast<earley_item_type *>(0)); set_index[1].assign(1U, static_cast<earley_item_type *>(0)); unsigned curr_index(0U); // for each set bool not_at_end(true); earley_set_type *next_set(0); earley_item_type *next_item(0); for(; 0 != curr_set && not_at_end; prev_set = curr_set, curr_set = curr_set->next, curr_index = 1U - curr_index, ++i, token = reader.read()) { set_index[curr_index].push_back(0); // done the tokens if(0 == token || '\0' == *token) { not_at_end = false; io::verbose(" Looking at EOF\n"); } else { traits_type::unserialize(token, lexeme); // try to get the terminal solve_for_variable_terminal = !cfg.has_terminal(lexeme); if(!solve_for_variable_terminal) { a = cfg.get_terminal(lexeme); // found a token but this grammar has no variable terminals // and so it can't be substituted for anything } else if(0 == cfg.num_variable_terminals()){ io::verbose( " Unrecognized terminal '%s'.\n", token ); goto parse_error; } io::verbose(" Looking at '%s'...\n", token); } // for each item curr_item = curr_set->first; for(next_item = 0; 0 != curr_item; curr_item = curr_item->next) { // move the dot to where the current item is looking so // that the patterns see the right value dot = curr_item->dot; // the item has the form A --> ... * B ... if(predictor.match(curr_item->production)) { // if B is nullable then add A --> ... B * ... to // the item set if(is_nullable[B.number()]) { next_item = item_allocator.allocate(); next_item->scanned_from(curr_item); indexed_push( curr_set, set_index[curr_index], item_allocator, next_item ); } // if we're using FIRST sets then use them to skip // useless predictions if(use_first_set && not_at_end && !solve_for_variable_terminal && !(first_terminals[B.number()]->operator[](a.number()))) { continue; } // for each B --> alpha, add B --> * alpha to the // item set for(predictor_related.rewind(); predictor_related.match_next();) { next_item = item_allocator.allocate(); next_item->predicted_from(curr_set, prod); indexed_push( curr_set, set_index[curr_index], item_allocator, next_item ); } // the item has the form A --> ... * } else if(completer.match(curr_item->production)) { for(earley_item_type *rel_item(curr_item->initial_set->first); 0 != rel_item; rel_item = rel_item->next) { dot = rel_item->dot; if(!completer_related.match(rel_item->production)) { continue; } next_item = item_allocator.allocate(); next_item->scanned_from(rel_item); next_item = indexed_push( curr_set, set_index[curr_index], item_allocator, next_item ); } // try to "solve" this terminal } else if(not_at_end) { // we don't know the terminal of this lexeme, lets // see if we can substitute a variable terminal if(solve_for_variable_terminal) { // try to match this production as // A --> ... * a ... for some variable terminal // a. if(!scanner_unknown.match(curr_item->production) || !cfg.is_variable_terminal(a)) { continue; } io::verbose( " Substituting as %s...\n", cfg.get_name(a) ); // we know the terminal of this lexeme } else { // try to match this production as // A --> ... * a ... where "a" is the terminal // of the current lexeme. if(!scanner_known.match(curr_item->production)) { continue; } } next_set = curr_set->next; if(0 == next_set) { next_set = set_allocator.allocate(); curr_set->set_next(next_set); set_index[1U - curr_index].push_back(0); clear_index(set_index[1U - curr_index]); } next_item = item_allocator.allocate(); next_item->scanned_from(curr_item); next_item = indexed_push( next_set, set_index[1U - curr_index], item_allocator, next_item ); } } } if(0 != token && '\0' == *token) { // handle the case where we accept the empty string if(0 == curr_set) { curr_set = prev_set; } if(0 == curr_set) { goto parse_error; } // go look for the final production for(curr_item = curr_set->first; 0 != curr_item; curr_item = curr_item->next) { if(1U == curr_item->dot && SV == curr_item->production.variable()) { io::verbose("Successfully parsed.\n"); parse_result = true; goto done; } } } parse_error: parse_result = false; io::verbose("Failed to parse all input.\n"); done: io::verbose("Cleaning up Earley items/sets...\n"); next_set = 0; for(curr_set = first_set; 0 != curr_set; curr_set = next_set) { next_set = curr_set->next; for(curr_item = curr_set->first; 0 != curr_item; curr_item = next_item) { next_item = curr_item->next; item_allocator.deallocate(curr_item); } set_allocator.deallocate(curr_set); } // done; clean up cfg.unsafe_remove_variable(SV); io::verbose("Done.\n"); return parse_result; } }; }} #endif /* FLTL_CFG_EARLEY_PARSE_HPP_ */ <commit_msg>got rid of a useless short that can now be an unsigned.<commit_after>/* * CFG_EARLEY_PARSE.hpp * * Created on: Mar 10, 2011 * Author: Peter Goodman * Version: $Id$ * * Copyright 2011 Peter Goodman, all rights reserved. */ #ifndef FLTL_CFG_EARLEY_PARSE_HPP_ #define FLTL_CFG_EARLEY_PARSE_HPP_ #include <set> #include <vector> #include "fltl/include/CFG.hpp" #include "fltl/include/helper/BlockAllocator.hpp" #include "grail/include/cfg/ParseTree.hpp" #include "grail/include/io/verbose.hpp" #include "grail/include/io/UTF8FileLineBuffer.hpp" namespace grail { namespace algorithm { /// parse a context free grammar using an Earley-style parser template <typename AlphaT, const unsigned MAX_TOK_LENGTH> class CFG_PARSE_EARLEY { public: // take off the templates! typedef fltl::CFG<AlphaT> CFG; typedef typename CFG::alphabet_type alphabet_type; typedef typename CFG::symbol_type symbol_type; typedef typename CFG::traits_type traits_type; typedef typename CFG::variable_type variable_type; typedef typename CFG::pattern_type pattern_type; typedef typename CFG::terminal_type terminal_type; typedef typename CFG::production_type production_type; typedef typename CFG::generator_type generator_type; typedef typename CFG::symbol_string_type symbol_string_type; typedef typename CFG::production_builder_type production_builder_type; typedef cfg::ParseTree<AlphaT> parse_tree_type; class earley_item_type; /// Earley set class earley_set_type { public: // first item in the set earley_item_type *first; earley_item_type *last; // next set earley_set_type *next; earley_set_type *prev; // offset into the terminal stream unsigned offset; earley_set_type(void) : first(0) , last(0) , next(0) , prev(0) , offset(0) { } void push(earley_item_type *item) throw() { if(0 == item) { return; } if(0 == first) { first = item; last = item; } else { last->next = item; last = item; } item->next = 0; } void set_next(earley_set_type *set) throw() { set->prev = this; set->next = 0; next = set; set->offset = offset + 1; } }; /// Earley item class earley_item_type { public: // dotted production unsigned dot; production_type production; // next item in the set earley_item_type *next; // the set that first introduced the production being used. that // is, sliding the dot changes the set that owns an item, but not // the set that initiated an item. earley_set_type *initial_set; // the next item in the same set that has the same initial // set earley_item_type *next_with_same_initial_set; earley_item_type(void) : dot(0) , production() , next(0) , initial_set(0) , next_with_same_initial_set(0) { } void scanned_from( earley_item_type *scan ) throw() { dot = scan->dot + 1U; production = scan->production; initial_set = scan->initial_set; } void predicted_from( earley_set_type *set, const production_type &prod ) throw() { dot = 0; production = prod; initial_set = set; } }; private: enum { NUM_BLOCKS = 1024U }; static void clear_index(std::vector<earley_item_type *> &index) throw() { for(unsigned i(0); i < index.size(); ++i) { index[i] = 0; } } /// check the index for the existence of item, if it's in, return 0, /// otherwise return the item and add it to the index static earley_item_type * indexed_push( earley_set_type *set, std::vector<earley_item_type *> &index, fltl::helper::BlockAllocator< earley_item_type, NUM_BLOCKS > &allocator, earley_item_type *item ) throw() { const unsigned offset(item->initial_set->offset); earley_item_type *&items(index[offset]); earley_item_type *prev(0); for(earley_item_type *curr(items); 0 != curr; prev = curr, curr = curr->next_with_same_initial_set) { // found an insertion point if(item->dot < curr->dot) { item->next_with_same_initial_set = curr; if(0 == prev) { items = item; } else { prev->next_with_same_initial_set = item; } set->push(item); return item; // skip } else if(item->dot > curr->dot) { continue; // same dot values, check if the productions are equivalent } else if(curr->production == item->production) { allocator.deallocate(item); return curr; } } // the set was empty if(0 == prev) { items = item; // this item is going at the end } else { prev->next_with_same_initial_set = item; } set->push(item); return item; } public: /// run the parser; assumes that the NULLABLE set is properly filled /// for this grammar static bool run( CFG &cfg, std::vector<bool> &is_nullable, const bool use_first_set, std::vector<std::vector<bool> *> &first_terminals, io::UTF8FileLineBuffer<MAX_TOK_LENGTH> &reader ) throw() { bool parse_result(false); const char *token(reader.read()); // allocator for Earley sets static fltl::helper::BlockAllocator< earley_set_type, NUM_BLOCKS > set_allocator; /// allocator for Earley items static fltl::helper::BlockAllocator< earley_item_type, NUM_BLOCKS > item_allocator; // the actual start variable; we will end up adding a fake // start variable later const variable_type ASV(cfg.get_start_variable()); // is it worth parsing? if(0 == cfg.num_productions() || !cfg.has_start_variable() || 0 == cfg.num_productions(ASV)) { if(0 == token || '\0' == *token) { io::verbose("Parsed. Accepted empty language.\n"); return true; } else { io::verbose("Failed to parse. Language is empty.\n"); return false; } } // add in a fake start variable; this variable and its productions // will be removed at the end variable_type SV(cfg.add_variable()); production_type SP(cfg.add_production(SV, ASV)); is_nullable[SV.number()] = is_nullable[ASV.number()]; if(use_first_set) { first_terminals[SV.number()] = new std::vector<bool>( *(first_terminals[ASV.number()]) ); } // set up the base case for the earley parser earley_item_type *curr_item(item_allocator.allocate()); earley_set_type *curr_set(set_allocator.allocate()); earley_set_type *prev_set(0); earley_item_type *first_item(curr_item); earley_set_type *first_set(curr_set); curr_set->next = 0; curr_item->production = SP; curr_item->initial_set = curr_set; curr_set->push(first_item); // variables used in the patterns unsigned dot; variable_type A; variable_type B; terminal_type a; production_type prod; pattern_type scanner_known((~A) --->* cfg.__(dot) + a + cfg.__); pattern_type scanner_unknown((~A) --->* cfg.__(dot) + ~a + cfg.__); pattern_type predictor((~A) --->* cfg.__(dot) + ~B + cfg.__); pattern_type completer((~A) --->* cfg.__(dot)); generator_type predictor_related(cfg.search(~prod, B --->* cfg.__)); pattern_type completer_related(cfg._ --->* cfg.__(dot) + A + cfg.__); // terminals unsigned i(0); alphabet_type lexeme; bool solve_for_variable_terminal(false); // indexes for the sets to test membership, +1 as there are n+1 // sets (S_0 ... S_n) for a string of length n. std::vector<earley_item_type *> set_index[2]; set_index[0].assign(1U, static_cast<earley_item_type *>(0)); set_index[1].assign(1U, static_cast<earley_item_type *>(0)); unsigned curr_index(0U); // for each set bool not_at_end(true); earley_set_type *next_set(0); earley_item_type *next_item(0); for(; 0 != curr_set && not_at_end; prev_set = curr_set, curr_set = curr_set->next, curr_index = 1U - curr_index, ++i, token = reader.read()) { set_index[curr_index].push_back(0); // done the tokens if(0 == token || '\0' == *token) { not_at_end = false; io::verbose(" Looking at EOF\n"); } else { traits_type::unserialize(token, lexeme); // try to get the terminal solve_for_variable_terminal = !cfg.has_terminal(lexeme); if(!solve_for_variable_terminal) { a = cfg.get_terminal(lexeme); // found a token but this grammar has no variable terminals // and so it can't be substituted for anything } else if(0 == cfg.num_variable_terminals()){ io::verbose( " Unrecognized terminal '%s'.\n", token ); goto parse_error; } io::verbose(" Looking at '%s'...\n", token); } // for each item curr_item = curr_set->first; for(next_item = 0; 0 != curr_item; curr_item = curr_item->next) { // move the dot to where the current item is looking so // that the patterns see the right value dot = curr_item->dot; // the item has the form A --> ... * B ... if(predictor.match(curr_item->production)) { // if B is nullable then add A --> ... B * ... to // the item set if(is_nullable[B.number()]) { next_item = item_allocator.allocate(); next_item->scanned_from(curr_item); indexed_push( curr_set, set_index[curr_index], item_allocator, next_item ); } // if we're using FIRST sets then use them to skip // useless predictions if(use_first_set && not_at_end && !solve_for_variable_terminal && !(first_terminals[B.number()]->operator[](a.number()))) { continue; } // for each B --> alpha, add B --> * alpha to the // item set for(predictor_related.rewind(); predictor_related.match_next();) { next_item = item_allocator.allocate(); next_item->predicted_from(curr_set, prod); indexed_push( curr_set, set_index[curr_index], item_allocator, next_item ); } // the item has the form A --> ... * } else if(completer.match(curr_item->production)) { for(earley_item_type *rel_item(curr_item->initial_set->first); 0 != rel_item; rel_item = rel_item->next) { dot = rel_item->dot; if(!completer_related.match(rel_item->production)) { continue; } next_item = item_allocator.allocate(); next_item->scanned_from(rel_item); next_item = indexed_push( curr_set, set_index[curr_index], item_allocator, next_item ); } // try to "solve" this terminal } else if(not_at_end) { // we don't know the terminal of this lexeme, lets // see if we can substitute a variable terminal if(solve_for_variable_terminal) { // try to match this production as // A --> ... * a ... for some variable terminal // a. if(!scanner_unknown.match(curr_item->production) || !cfg.is_variable_terminal(a)) { continue; } io::verbose( " Substituting as %s...\n", cfg.get_name(a) ); // we know the terminal of this lexeme } else { // try to match this production as // A --> ... * a ... where "a" is the terminal // of the current lexeme. if(!scanner_known.match(curr_item->production)) { continue; } } next_set = curr_set->next; if(0 == next_set) { next_set = set_allocator.allocate(); curr_set->set_next(next_set); set_index[1U - curr_index].push_back(0); clear_index(set_index[1U - curr_index]); } next_item = item_allocator.allocate(); next_item->scanned_from(curr_item); next_item = indexed_push( next_set, set_index[1U - curr_index], item_allocator, next_item ); } } } if(0 != token && '\0' == *token) { // handle the case where we accept the empty string if(0 == curr_set) { curr_set = prev_set; } if(0 == curr_set) { goto parse_error; } // go look for the final production for(curr_item = curr_set->first; 0 != curr_item; curr_item = curr_item->next) { if(1U == curr_item->dot && SV == curr_item->production.variable()) { io::verbose("Successfully parsed.\n"); parse_result = true; goto done; } } } parse_error: parse_result = false; io::verbose("Failed to parse all input.\n"); done: io::verbose("Cleaning up Earley items/sets...\n"); next_set = 0; for(curr_set = first_set; 0 != curr_set; curr_set = next_set) { next_set = curr_set->next; for(curr_item = curr_set->first; 0 != curr_item; curr_item = next_item) { next_item = curr_item->next; item_allocator.deallocate(curr_item); } set_allocator.deallocate(curr_set); } // done; clean up cfg.unsafe_remove_variable(SV); io::verbose("Done.\n"); return parse_result; } }; }} #endif /* FLTL_CFG_EARLEY_PARSE_HPP_ */ <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2006 Mikio L. Braun * Written (W) 1999-2009 Soeren Sonnenburg * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society */ #include <shogun/lib/config.h> #ifdef HAVE_LAPACK #include <shogun/regression/KernelRidgeRegression.h> #include <shogun/mathematics/lapack.h> #include <shogun/mathematics/Math.h> #include <shogun/labels/RegressionLabels.h> using namespace shogun; CKernelRidgeRegression::CKernelRidgeRegression() : CKernelMachine() { init(); } CKernelRidgeRegression::CKernelRidgeRegression(float64_t tau, CKernel* k, CLabels* lab, ETrainingType m) : CKernelMachine() { init(); m_tau=tau; set_labels(lab); set_kernel(k); set_epsilon(0.0001); m_train_func=m; } void CKernelRidgeRegression::init() { m_tau=1e-6; SG_ADD(&m_tau, "tau", "Regularization parameter", MS_AVAILABLE); } bool CKernelRidgeRegression::train_machine_pinv() { // Get kernel matrix SGMatrix<float64_t> kernel_matrix=kernel->get_kernel_matrix<float64_t>(); int32_t n = kernel_matrix.num_cols; int32_t m = kernel_matrix.num_rows; ASSERT(kernel_matrix.matrix && m>0 && n>0) for(int32_t i=0; i < n; i++) kernel_matrix.matrix[i+i*n]+=m_tau; /* re-set alphas of kernel machine */ m_alpha=((CRegressionLabels*) m_labels)->get_labels_copy(); /* tell kernel machine that all alphas are needed as'support vectors' */ m_svs=SGVector<index_t>(m_alpha.vlen); m_svs.range_fill(); if (get_alphas().vlen!=n) { SG_ERROR("Number of labels does not match number of kernel" " columns (num_labels=%d cols=%d\n", m_alpha.vlen, n); } clapack_dposv(CblasRowMajor,CblasUpper, n, 1, kernel_matrix.matrix, n, m_alpha.vector, n); return true; } bool CKernelRidgeRegression::train_machine_gs() { int32_t n = kernel->get_num_vec_rhs(); int32_t m = kernel->get_num_vec_lhs(); ASSERT(m>0 && n>0) // re-set alphas of kernel machine SGVector<float64_t> b; float64_t alpha_old; b=((CRegressionLabels*) m_labels)->get_labels_copy(); m_alpha=((CRegressionLabels*) m_labels)->get_labels_copy(); m_alpha.zero(); // tell kernel machine that all alphas are needed as 'support vectors' m_svs=SGVector<index_t>(m_alpha.vlen); m_svs.range_fill(); if (get_alphas().vlen!=n) { SG_ERROR("Number of labels does not match number of kernel" " columns (num_labels=%d cols=%d\n", m_alpha.vlen, n); } // Gauss-Seidel iterative method float64_t sigma, err, d; bool flag=true; while(flag) { err=0.0; for(int32_t i=0; i<n; i++) { sigma=b[i]; for(int32_t j=0; j<n; j++) if (i!=j) sigma-=kernel->kernel(j, i)*m_alpha[j]; alpha_old=m_alpha[i]; m_alpha[i]=sigma/(kernel->kernel(i, i)+m_tau); d=fabs(alpha_old-m_alpha[i]); if(d>err) err=d; } if (err<=m_epsilon) flag=false; } return true; } bool CKernelRidgeRegression::train_machine(CFeatures *data) { if (!m_labels) SG_ERROR("No labels set\n") if (m_labels->get_label_type() != LT_REGRESSION) SG_ERROR("Real labels needed for kernel ridge regression.\n") if (data) { if (m_labels->get_num_labels() != data->get_num_vectors()) SG_ERROR("Number of training vectors does not match number of labels\n") kernel->init(data, data); } ASSERT(kernel && kernel->has_features()) switch (m_train_func) { case PINV: return train_machine_pinv(); break; case GS: return train_machine_gs(); break; default: return train_machine_pinv(); break; } } bool CKernelRidgeRegression::load(FILE* srcfile) { SG_SET_LOCALE_C; SG_RESET_LOCALE; return false; } bool CKernelRidgeRegression::save(FILE* dstfile) { SG_SET_LOCALE_C; SG_RESET_LOCALE; return false; } #endif <commit_msg>set epsilon 1e-4 by default for krr<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2006 Mikio L. Braun * Written (W) 1999-2009 Soeren Sonnenburg * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society */ #include <shogun/lib/config.h> #ifdef HAVE_LAPACK #include <shogun/regression/KernelRidgeRegression.h> #include <shogun/mathematics/lapack.h> #include <shogun/mathematics/Math.h> #include <shogun/labels/RegressionLabels.h> using namespace shogun; CKernelRidgeRegression::CKernelRidgeRegression() : CKernelMachine() { init(); } CKernelRidgeRegression::CKernelRidgeRegression(float64_t tau, CKernel* k, CLabels* lab, ETrainingType m) : CKernelMachine() { init(); m_tau=tau; set_labels(lab); set_kernel(k); m_train_func=m; } void CKernelRidgeRegression::init() { m_tau=1e-6; m_epsilon=0.0001; SG_ADD(&m_tau, "tau", "Regularization parameter", MS_AVAILABLE); } bool CKernelRidgeRegression::train_machine_pinv() { // Get kernel matrix SGMatrix<float64_t> kernel_matrix=kernel->get_kernel_matrix<float64_t>(); int32_t n = kernel_matrix.num_cols; int32_t m = kernel_matrix.num_rows; ASSERT(kernel_matrix.matrix && m>0 && n>0) for(int32_t i=0; i < n; i++) kernel_matrix.matrix[i+i*n]+=m_tau; /* re-set alphas of kernel machine */ m_alpha=((CRegressionLabels*) m_labels)->get_labels_copy(); /* tell kernel machine that all alphas are needed as'support vectors' */ m_svs=SGVector<index_t>(m_alpha.vlen); m_svs.range_fill(); if (get_alphas().vlen!=n) { SG_ERROR("Number of labels does not match number of kernel" " columns (num_labels=%d cols=%d\n", m_alpha.vlen, n); } clapack_dposv(CblasRowMajor,CblasUpper, n, 1, kernel_matrix.matrix, n, m_alpha.vector, n); return true; } bool CKernelRidgeRegression::train_machine_gs() { int32_t n = kernel->get_num_vec_rhs(); int32_t m = kernel->get_num_vec_lhs(); ASSERT(m>0 && n>0) // re-set alphas of kernel machine SGVector<float64_t> b; float64_t alpha_old; b=((CRegressionLabels*) m_labels)->get_labels_copy(); m_alpha=((CRegressionLabels*) m_labels)->get_labels_copy(); m_alpha.zero(); // tell kernel machine that all alphas are needed as 'support vectors' m_svs=SGVector<index_t>(m_alpha.vlen); m_svs.range_fill(); if (get_alphas().vlen!=n) { SG_ERROR("Number of labels does not match number of kernel" " columns (num_labels=%d cols=%d\n", m_alpha.vlen, n); } // Gauss-Seidel iterative method float64_t sigma, err, d; bool flag=true; while(flag) { err=0.0; for(int32_t i=0; i<n; i++) { sigma=b[i]; for(int32_t j=0; j<n; j++) if (i!=j) sigma-=kernel->kernel(j, i)*m_alpha[j]; alpha_old=m_alpha[i]; m_alpha[i]=sigma/(kernel->kernel(i, i)+m_tau); d=fabs(alpha_old-m_alpha[i]); if(d>err) err=d; } if (err<=m_epsilon) flag=false; } return true; } bool CKernelRidgeRegression::train_machine(CFeatures *data) { if (!m_labels) SG_ERROR("No labels set\n") if (m_labels->get_label_type() != LT_REGRESSION) SG_ERROR("Real labels needed for kernel ridge regression.\n") if (data) { if (m_labels->get_num_labels() != data->get_num_vectors()) SG_ERROR("Number of training vectors does not match number of labels\n") kernel->init(data, data); } ASSERT(kernel && kernel->has_features()) switch (m_train_func) { case PINV: return train_machine_pinv(); break; case GS: return train_machine_gs(); break; default: return train_machine_pinv(); break; } } bool CKernelRidgeRegression::load(FILE* srcfile) { SG_SET_LOCALE_C; SG_RESET_LOCALE; return false; } bool CKernelRidgeRegression::save(FILE* dstfile) { SG_SET_LOCALE_C; SG_RESET_LOCALE; return false; } #endif <|endoftext|>
<commit_before>#include "Repo.hpp" #include "../inanity/data/sqlite.hpp" #include "../inanity/MemoryFile.hpp" #include "../inanity/Exception.hpp" #include <sstream> BEGIN_INANITY_OIL const char Repo::protocolMagic[14] = { 'I', 'N', 'A', 'N', 'I', 'T', 'Y', 'O', 'I', 'L', 'R', 'E', 'P', 'O' }; const int Repo::protocolVersion = 1; const int Repo::serverRepoAppVersion = 0x424C494F; // "OILB" in little-endian const int Repo::clientRepoAppVersion = 0x314C494F; // "OIL1" in little-endian const size_t Repo::defaultMaxKeySize = 128; const size_t Repo::defaultMaxValueSize = 1024 * 1024 * 16; const int Repo::defaultMaxPushKeysCount = 128; const size_t Repo::defaultMaxPushTotalSize = 1024 * 1024 * 32; const int Repo::defaultMaxPullKeysCount = 256; const size_t Repo::defaultMaxPullTotalSize = 1024 * 1024 * 32; const char* Repo::fileNameMemory = ":memory:"; const char* Repo::fileNameTemp = ""; Repo::Repo(const char* fileName) : maxKeySize(defaultMaxKeySize), maxValueSize(defaultMaxValueSize), maxPushKeysCount(defaultMaxPushKeysCount), maxPushTotalSize(defaultMaxPushTotalSize), maxPullKeysCount(defaultMaxPullKeysCount), maxPullTotalSize(defaultMaxPullTotalSize) { BEGIN_TRY(); db = Data::SqliteDb::Open(fileName); keyBufferFile = NEW(MemoryFile(maxKeySize)); valueBufferFile = NEW(MemoryFile(maxValueSize)); END_TRY("Can't create repo"); } void Repo::CheckAppVersion(int appVersion) { ptr<Data::SqliteStatement> stmt = db->CreateStatement("PRAGMA application_id"); if(stmt->Step() != SQLITE_ROW) THROW_SECONDARY("Error getting application_id", db->Error()); int existingAppVersion = stmt->ColumnInt(0); if(existingAppVersion == 0) { // app version hasn't been set yet; set it std::ostringstream ss; ss << "PRAGMA application_id = " << appVersion; stmt = db->CreateStatement(ss.str().c_str()); if(stmt->Step() != SQLITE_DONE) THROW_SECONDARY("Error setting application_id", db->Error()); } else if(existingAppVersion == appVersion) { // all ok } else THROW("Wrong repo format"); } END_INANITY_OIL <commit_msg>change default repo limits: more keys, but less sizes<commit_after>#include "Repo.hpp" #include "../inanity/data/sqlite.hpp" #include "../inanity/MemoryFile.hpp" #include "../inanity/Exception.hpp" #include <sstream> BEGIN_INANITY_OIL const char Repo::protocolMagic[14] = { 'I', 'N', 'A', 'N', 'I', 'T', 'Y', 'O', 'I', 'L', 'R', 'E', 'P', 'O' }; const int Repo::protocolVersion = 1; const int Repo::serverRepoAppVersion = 0x424C494F; // "OILB" in little-endian const int Repo::clientRepoAppVersion = 0x314C494F; // "OIL1" in little-endian const size_t Repo::defaultMaxKeySize = 128; const size_t Repo::defaultMaxValueSize = 1024 * 1024; const int Repo::defaultMaxPushKeysCount = 1024; const size_t Repo::defaultMaxPushTotalSize = 1024 * 1024 * 2; const int Repo::defaultMaxPullKeysCount = 1024; const size_t Repo::defaultMaxPullTotalSize = 1024 * 1024 * 2; const char* Repo::fileNameMemory = ":memory:"; const char* Repo::fileNameTemp = ""; Repo::Repo(const char* fileName) : maxKeySize(defaultMaxKeySize), maxValueSize(defaultMaxValueSize), maxPushKeysCount(defaultMaxPushKeysCount), maxPushTotalSize(defaultMaxPushTotalSize), maxPullKeysCount(defaultMaxPullKeysCount), maxPullTotalSize(defaultMaxPullTotalSize) { BEGIN_TRY(); db = Data::SqliteDb::Open(fileName); keyBufferFile = NEW(MemoryFile(maxKeySize)); valueBufferFile = NEW(MemoryFile(maxValueSize)); END_TRY("Can't create repo"); } void Repo::CheckAppVersion(int appVersion) { ptr<Data::SqliteStatement> stmt = db->CreateStatement("PRAGMA application_id"); if(stmt->Step() != SQLITE_ROW) THROW_SECONDARY("Error getting application_id", db->Error()); int existingAppVersion = stmt->ColumnInt(0); if(existingAppVersion == 0) { // app version hasn't been set yet; set it std::ostringstream ss; ss << "PRAGMA application_id = " << appVersion; stmt = db->CreateStatement(ss.str().c_str()); if(stmt->Step() != SQLITE_DONE) THROW_SECONDARY("Error setting application_id", db->Error()); } else if(existingAppVersion == appVersion) { // all ok } else THROW("Wrong repo format"); } END_INANITY_OIL <|endoftext|>
<commit_before>#include "series.h" #include <stdexcept> using namespace std; namespace series { vector<int> digits(string const& sequence) { vector<int> result; for (const char digit : sequence) { result.push_back(digit - '0'); } return result; } vector<vector<int>> slice(string const& sequence, int span) { if (span > sequence.length()) { throw domain_error("Requested span too long for sequence"); } vector<vector<int>> result; for (size_t i = 0; i < sequence.length() - (span - 1); ++i) { result.push_back(digits(sequence.substr(i, span))); } return result; } } <commit_msg>Eliminate signed/unsigned comparison warning<commit_after>#include "series.h" #include <stdexcept> using namespace std; namespace series { vector<int> digits(string const& sequence) { vector<int> result; for (const char digit : sequence) { result.push_back(digit - '0'); } return result; } vector<vector<int>> slice(string const& sequence, int span) { if (span > static_cast<int>(sequence.length())) { throw domain_error("Requested span too long for sequence"); } vector<vector<int>> result; for (size_t i = 0; i < sequence.length() - (span - 1); ++i) { result.push_back(digits(sequence.substr(i, span))); } return result; } } <|endoftext|>
<commit_before>// Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/sfm/sfm.hpp" #include "openMVG/exif/exif_IO_EasyExif.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #ifdef HAVE_BOOST #include <boost/system/error_code.hpp> #include <boost/filesystem.hpp> #endif #include <string> #include <vector> using namespace openMVG; using namespace openMVG::sfm; /** * @brief Update all viewID referenced in the observation of each landmark according * to the provided mapping. * * @param[in,out] landmarks The landmarks to update. * @param[in] oldIdToNew The mapping between the old ID and the reconmputed UID. */ void updateStructureWithNewUID(Landmarks &landmarks, const std::map<std::size_t, std::size_t> &oldIdToNew) { // update the id in the visibility of each 3D point for(auto &iter : landmarks) { Landmark& currentLandmark = iter.second; // the new observations where to copy the existing ones // (needed as the key of the map is the idview) Observations newObservations; for(const auto &iterObs : currentLandmark.obs) { const auto idview = iterObs.first; const Observation &obs = iterObs.second; newObservations.emplace(oldIdToNew.at(idview), obs); } assert(currentLandmark.obs.size() == newObservations.size()); currentLandmark.obs.swap(newObservations); } } void regenerateUID(sfm::SfM_Data &sfmdata, std::map<std::size_t, std::size_t> &oldIdToNew, bool sanityCheck = false) { // if the views are empty, nothing to be done. if(sfmdata.GetViews().empty()) return; Views newViews; for(auto const &iter : sfmdata.views) { const View& currentView = *iter.second.get(); const auto &imageName = currentView.s_Img_path; exif::Exif_IO_EasyExif exifReader(imageName); // compute the view UID const std::size_t uid = exif::computeUID(exifReader, imageName); // update the mapping assert(oldIdToNew.count(currentView.id_view) == 0); oldIdToNew.emplace(currentView.id_view, uid); // add the view to the new map using the uid as key and change the id assert(newViews.count(uid) == 0); newViews.emplace(uid, iter.second); newViews[uid]->id_view = uid; } assert(newViews.size() == sfmdata.GetViews().size()); sfmdata.views.swap(newViews); // update the id in the visibility of each 3D point updateStructureWithNewUID(sfmdata.structure, oldIdToNew); // update the id in the visibility of each 3D point updateStructureWithNewUID(sfmdata.control_points, oldIdToNew); if(!sanityCheck) return; // sanity check for(auto &iter : sfmdata.structure) { Landmark& currentLandmark = iter.second; for(const auto &iterObs : currentLandmark.obs) { const auto idview = iterObs.first; const Observation &obs = iterObs.second; // there must be a view with that id (in the map) and the view must have // the same id (the member) assert(sfmdata.views.count(idview) == 1); assert(sfmdata.views.at(idview)->id_view == idview); } } // sanity check for(auto &iter : sfmdata.control_points) { Landmark& currentLandmark = iter.second; for(const auto &iterObs : currentLandmark.obs) { const auto idview = iterObs.first; const Observation &obs = iterObs.second; // there must be a view with that id (in the map) and the view must have // the same id (the member) assert(sfmdata.views.count(idview) == 1); assert(sfmdata.views.at(idview)->id_view == idview); } } } // Convert from a SfM_Data format to another int main(int argc, char **argv) { CmdLine cmd; std::string sSfM_Data_Filename_In; std::string sSfM_Data_Filename_Out; #ifdef HAVE_BOOST std::string matchDir; #endif cmd.add(make_option('i', sSfM_Data_Filename_In, "input_file")); cmd.add(make_switch('V', "VIEWS")); cmd.add(make_switch('I', "INTRINSICS")); cmd.add(make_switch('E', "EXTRINSICS")); cmd.add(make_switch('S', "STRUCTURE")); cmd.add(make_switch('O', "OBSERVATIONS")); cmd.add(make_switch('C', "CONTROL_POINTS")); cmd.add(make_switch('u', "uid")); cmd.add(make_option('o', sSfM_Data_Filename_Out, "output_file")); #ifdef HAVE_BOOST cmd.add(make_option('m', matchDir, "matchDirectory")); #endif try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--input_file] path to the input SfM_Data scene\n" << "[-o|--output_file] path to the output SfM_Data scene\n" << "\t .json, .bin, .xml, .ply, .baf" #if HAVE_ALEMBIC ", .abc" #endif "\n" << "\n[Options to export partial data (by default all data are exported)]\n" << "\nUsable for json/bin/xml format\n" << "[-V|--VIEWS] export views\n" << "[-I|--INTRINSICS] export intrinsics\n" << "[-E|--EXTRINSICS] export extrinsics (view poses)\n" << "[-S|--STRUCTURE] export structure\n" << "[-O|--OBSERVATIONS] export 2D observations associated with 3D structure\n" << "[-C|--CONTROL_POINTS] export control points\n" << "[-u|--uid] (re-)compute the unique ID (UID) for the views\n" #ifdef HAVE_BOOST << "[-m|--matchDirectory] the directory containing the features used for the\n" " reconstruction. If provided along the -u option, it creates symbolic\n" " links to the .desc and .feat with the new UID as name. This can be\n" " for legacy reconstructions that were not made using UID" #endif << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } if (sSfM_Data_Filename_In.empty() || sSfM_Data_Filename_Out.empty()) { std::cerr << "Invalid input or output filename." << std::endl; return EXIT_FAILURE; } // OptionSwitch is cloned in cmd.add(), // so we must use cmd.used() instead of testing OptionSwitch.used int flags = (cmd.used('V') ? VIEWS : 0) | (cmd.used('I') ? INTRINSICS : 0) | (cmd.used('E') ? EXTRINSICS : 0) | (cmd.used('O') ? OBSERVATIONS : 0) | (cmd.used('S') ? STRUCTURE : 0); flags = (flags) ? flags : ALL; const bool recomputeUID = cmd.used('u'); // Load input SfM_Data scene SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename_In, ESfM_Data(ALL))) { std::cerr << std::endl << "The input SfM_Data file \"" << sSfM_Data_Filename_In << "\" cannot be read." << std::endl; return EXIT_FAILURE; } if(recomputeUID) { std::cout << "Recomputing the UID of the views..." << std::endl; std::map<std::size_t, std::size_t> oldIdToNew; regenerateUID(sfm_data, oldIdToNew); #ifdef HAVE_BOOST if(!matchDir.empty()) { std::cout << "Generating alias for .feat and .desc with the UIDs" << std::endl; for(const auto& iter : oldIdToNew) { const auto oldID = iter.first; const auto newID = iter.second; const auto oldFeatfilename = stlplus::create_filespec(matchDir, std::to_string(oldID), ".feat"); const auto newFeatfilename = stlplus::create_filespec(matchDir, std::to_string(newID), ".feat"); const auto oldDescfilename = stlplus::create_filespec(matchDir, std::to_string(oldID), ".desc"); const auto newDescfilename = stlplus::create_filespec(matchDir, std::to_string(newID), ".desc"); if(!(stlplus::is_file(oldFeatfilename) && stlplus::is_file(oldDescfilename))) { std::cerr << "Cannot find the features file for view ID " << oldID << std::endl; return EXIT_FAILURE; } boost::system::error_code ec; boost::filesystem::create_symlink(oldFeatfilename, newFeatfilename, ec); if(ec) { std::cerr << "Error while creating " << newFeatfilename << ": " << ec.message() << std::endl; return EXIT_FAILURE; } boost::filesystem::create_symlink(oldDescfilename, newDescfilename, ec); if(ec) { std::cerr << "Error while creating " << newDescfilename << ": " << ec.message() << std::endl; return EXIT_FAILURE; } } } #endif } // Export the SfM_Data scene in the expected format if (!Save(sfm_data, sSfM_Data_Filename_Out, ESfM_Data(flags))) { std::cerr << std::endl << "An error occured while trying to save \"" << sSfM_Data_Filename_Out << "\"." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>[software] doc regenerateUID<commit_after>// Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/sfm/sfm.hpp" #include "openMVG/exif/exif_IO_EasyExif.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #ifdef HAVE_BOOST #include <boost/system/error_code.hpp> #include <boost/filesystem.hpp> #endif #include <string> #include <vector> using namespace openMVG; using namespace openMVG::sfm; /** * @brief Update all viewID referenced in the observation of each landmark according * to the provided mapping. * * @param[in,out] landmarks The landmarks to update. * @param[in] oldIdToNew The mapping between the old ID and the reconmputed UID. */ void updateStructureWithNewUID(Landmarks &landmarks, const std::map<std::size_t, std::size_t> &oldIdToNew) { // update the id in the visibility of each 3D point for(auto &iter : landmarks) { Landmark& currentLandmark = iter.second; // the new observations where to copy the existing ones // (needed as the key of the map is the idview) Observations newObservations; for(const auto &iterObs : currentLandmark.obs) { const auto idview = iterObs.first; const Observation &obs = iterObs.second; newObservations.emplace(oldIdToNew.at(idview), obs); } assert(currentLandmark.obs.size() == newObservations.size()); currentLandmark.obs.swap(newObservations); } } /** * @brief Recompute the UID from the metadata of the original input images and * modify the ID if it's not the same. * * @param[in,out] sfmdata The sfmdata scene for which to recompute the UID. * @param[out] oldIdToNew A map that holds the mapping between the old ID and the * reconmputed UID. * @param[in] sanityCheck Enable a sanity check at the end to assure that the * observations of 3D points and the control points have been correctly updated. */ void regenerateUID(sfm::SfM_Data &sfmdata, std::map<std::size_t, std::size_t> &oldIdToNew, bool sanityCheck = false) { // if the views are empty, nothing to be done. if(sfmdata.GetViews().empty()) return; Views newViews; for(auto const &iter : sfmdata.views) { const View& currentView = *iter.second.get(); const auto &imageName = currentView.s_Img_path; exif::Exif_IO_EasyExif exifReader(imageName); // compute the view UID const std::size_t uid = exif::computeUID(exifReader, imageName); // update the mapping assert(oldIdToNew.count(currentView.id_view) == 0); oldIdToNew.emplace(currentView.id_view, uid); // add the view to the new map using the uid as key and change the id assert(newViews.count(uid) == 0); newViews.emplace(uid, iter.second); newViews[uid]->id_view = uid; } assert(newViews.size() == sfmdata.GetViews().size()); sfmdata.views.swap(newViews); // update the id in the visibility of each 3D point updateStructureWithNewUID(sfmdata.structure, oldIdToNew); // update the id in the visibility of each 3D point updateStructureWithNewUID(sfmdata.control_points, oldIdToNew); if(!sanityCheck) return; // sanity check for(auto &iter : sfmdata.structure) { Landmark& currentLandmark = iter.second; for(const auto &iterObs : currentLandmark.obs) { const auto idview = iterObs.first; const Observation &obs = iterObs.second; // there must be a view with that id (in the map) and the view must have // the same id (the member) assert(sfmdata.views.count(idview) == 1); assert(sfmdata.views.at(idview)->id_view == idview); } } // sanity check for(auto &iter : sfmdata.control_points) { Landmark& currentLandmark = iter.second; for(const auto &iterObs : currentLandmark.obs) { const auto idview = iterObs.first; const Observation &obs = iterObs.second; // there must be a view with that id (in the map) and the view must have // the same id (the member) assert(sfmdata.views.count(idview) == 1); assert(sfmdata.views.at(idview)->id_view == idview); } } } // Convert from a SfM_Data format to another int main(int argc, char **argv) { CmdLine cmd; std::string sSfM_Data_Filename_In; std::string sSfM_Data_Filename_Out; #ifdef HAVE_BOOST std::string matchDir; #endif cmd.add(make_option('i', sSfM_Data_Filename_In, "input_file")); cmd.add(make_switch('V', "VIEWS")); cmd.add(make_switch('I', "INTRINSICS")); cmd.add(make_switch('E', "EXTRINSICS")); cmd.add(make_switch('S', "STRUCTURE")); cmd.add(make_switch('O', "OBSERVATIONS")); cmd.add(make_switch('C', "CONTROL_POINTS")); cmd.add(make_switch('u', "uid")); cmd.add(make_option('o', sSfM_Data_Filename_Out, "output_file")); #ifdef HAVE_BOOST cmd.add(make_option('m', matchDir, "matchDirectory")); #endif try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--input_file] path to the input SfM_Data scene\n" << "[-o|--output_file] path to the output SfM_Data scene\n" << "\t .json, .bin, .xml, .ply, .baf" #if HAVE_ALEMBIC ", .abc" #endif "\n" << "\n[Options to export partial data (by default all data are exported)]\n" << "\nUsable for json/bin/xml format\n" << "[-V|--VIEWS] export views\n" << "[-I|--INTRINSICS] export intrinsics\n" << "[-E|--EXTRINSICS] export extrinsics (view poses)\n" << "[-S|--STRUCTURE] export structure\n" << "[-O|--OBSERVATIONS] export 2D observations associated with 3D structure\n" << "[-C|--CONTROL_POINTS] export control points\n" << "[-u|--uid] (re-)compute the unique ID (UID) for the views\n" #ifdef HAVE_BOOST << "[-m|--matchDirectory] the directory containing the features used for the\n" " reconstruction. If provided along the -u option, it creates symbolic\n" " links to the .desc and .feat with the new UID as name. This can be\n" " for legacy reconstructions that were not made using UID" #endif << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } if (sSfM_Data_Filename_In.empty() || sSfM_Data_Filename_Out.empty()) { std::cerr << "Invalid input or output filename." << std::endl; return EXIT_FAILURE; } // OptionSwitch is cloned in cmd.add(), // so we must use cmd.used() instead of testing OptionSwitch.used int flags = (cmd.used('V') ? VIEWS : 0) | (cmd.used('I') ? INTRINSICS : 0) | (cmd.used('E') ? EXTRINSICS : 0) | (cmd.used('O') ? OBSERVATIONS : 0) | (cmd.used('S') ? STRUCTURE : 0); flags = (flags) ? flags : ALL; const bool recomputeUID = cmd.used('u'); // Load input SfM_Data scene SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename_In, ESfM_Data(ALL))) { std::cerr << std::endl << "The input SfM_Data file \"" << sSfM_Data_Filename_In << "\" cannot be read." << std::endl; return EXIT_FAILURE; } if(recomputeUID) { std::cout << "Recomputing the UID of the views..." << std::endl; std::map<std::size_t, std::size_t> oldIdToNew; regenerateUID(sfm_data, oldIdToNew); #ifdef HAVE_BOOST if(!matchDir.empty()) { std::cout << "Generating alias for .feat and .desc with the UIDs" << std::endl; for(const auto& iter : oldIdToNew) { const auto oldID = iter.first; const auto newID = iter.second; const auto oldFeatfilename = stlplus::create_filespec(matchDir, std::to_string(oldID), ".feat"); const auto newFeatfilename = stlplus::create_filespec(matchDir, std::to_string(newID), ".feat"); const auto oldDescfilename = stlplus::create_filespec(matchDir, std::to_string(oldID), ".desc"); const auto newDescfilename = stlplus::create_filespec(matchDir, std::to_string(newID), ".desc"); if(!(stlplus::is_file(oldFeatfilename) && stlplus::is_file(oldDescfilename))) { std::cerr << "Cannot find the features file for view ID " << oldID << std::endl; return EXIT_FAILURE; } boost::system::error_code ec; boost::filesystem::create_symlink(oldFeatfilename, newFeatfilename, ec); if(ec) { std::cerr << "Error while creating " << newFeatfilename << ": " << ec.message() << std::endl; return EXIT_FAILURE; } boost::filesystem::create_symlink(oldDescfilename, newDescfilename, ec); if(ec) { std::cerr << "Error while creating " << newDescfilename << ": " << ec.message() << std::endl; return EXIT_FAILURE; } } } #endif } // Export the SfM_Data scene in the expected format if (!Save(sfm_data, sSfM_Data_Filename_Out, ESfM_Data(flags))) { std::cerr << std::endl << "An error occured while trying to save \"" << sSfM_Data_Filename_Out << "\"." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* This file is part of Kontact. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qclipboard.h> #include <qeventloop.h> #include <qhbox.h> #include <qlayout.h> #include <qpixmap.h> #include <qpopupmenu.h> #include <qcursor.h> #include <dcopclient.h> #include <kapplication.h> #include <kcharsets.h> #include <kconfig.h> #include <kdebug.h> #include <kglobal.h> #include <kiconloader.h> #include <klocale.h> #include <kurllabel.h> #include "summarywidget.h" SummaryWidget::SummaryWidget( QWidget *parent, const char *name ) : Kontact::Summary( parent, name ), DCOPObject( "NewsTickerPlugin" ), mLayout( 0 ), mFeedCounter( 0 ) { QVBoxLayout *vlay = new QVBoxLayout( this, 3, 3 ); QPixmap icon = KGlobal::iconLoader()->loadIcon( "kontact_news", KIcon::Desktop, KIcon::SizeMedium ); QWidget *header = createHeader( this, icon, i18n( "News Feeds" ) ); vlay->addWidget( header ); QString error; QCString appID; bool dcopAvailable = true; if ( !kapp->dcopClient()->isApplicationRegistered( "rssservice" ) ) { if ( KApplication::startServiceByDesktopName( "rssservice", QStringList(), &error, &appID ) ) { QLabel *label = new QLabel( i18n( "No rss dcop service available.\nYou need rssservice to use this plugin." ), this ); vlay->addWidget( label, Qt::AlignHCenter ); dcopAvailable = false; } } mBaseWidget = new QWidget( this, "baseWidget" ); vlay->addWidget( mBaseWidget ); connect( &mTimer, SIGNAL( timeout() ), this, SLOT( updateDocuments() ) ); readConfig(); connectDCOPSignal( 0, 0, "documentUpdateError(DCOPRef,int)", "documentUpdateError(DCOPRef, int)", false ); if ( dcopAvailable ) initDocuments(); connectDCOPSignal( 0, 0, "added(QString)", "documentAdded(QString)", false ); connectDCOPSignal( 0, 0, "removed(QString)", "documentRemoved(QString)", false ); } int SummaryWidget::summaryHeight() const { return ( mFeeds.count() == 0 ? 1 : mFeeds.count() ); } void SummaryWidget::documentAdded( QString ) { initDocuments(); } void SummaryWidget::documentRemoved( QString ) { initDocuments(); } void SummaryWidget::configChanged() { readConfig(); updateView(); } void SummaryWidget::readConfig() { KConfig config( "kcmkontactkntrc" ); config.setGroup( "General" ); mUpdateInterval = config.readNumEntry( "UpdateInterval", 600 ); mArticleCount = config.readNumEntry( "ArticleCount", 4 ); } void SummaryWidget::initDocuments() { mFeeds.clear(); DCOPRef dcopCall( "rssservice", "RSSService" ); QStringList urls; dcopCall.call( "list()" ).get( urls ); if ( urls.isEmpty() ) { // add default urls.append( "http://www.kde.org/dotkdeorg.rdf" ); dcopCall.send( "add(QString)", urls[ 0 ] ); } QStringList::Iterator it; for ( it = urls.begin(); it != urls.end(); ++it ) { DCOPRef feedRef = dcopCall.call( "document(QString)", *it ); Feed feed; feed.ref = feedRef; feedRef.call( "title()" ).get( feed.title ); feedRef.call( "link()" ).get( feed.url ); feedRef.call( "pixmap()" ).get( feed.logo ); mFeeds.append( feed ); disconnectDCOPSignal( "rssservice", feedRef.obj(), "documentUpdated(DCOPRef)", 0 ); connectDCOPSignal( "rssservice", feedRef.obj(), "documentUpdated(DCOPRef)", "documentUpdated(DCOPRef)", false ); qApp->processEvents( QEventLoop::ExcludeUserInput | QEventLoop::ExcludeSocketNotifiers ); } updateDocuments(); } void SummaryWidget::updateDocuments() { mTimer.stop(); FeedList::Iterator it; for ( it = mFeeds.begin(); it != mFeeds.end(); ++it ) (*it).ref.send( "refresh()" ); mTimer.start( 1000 * mUpdateInterval ); } void SummaryWidget::documentUpdated( DCOPRef feedRef ) { ArticleMap map; int numArticles = feedRef.call( "count()" ); for ( int i = 0; i < numArticles; ++i ) { DCOPRef artRef = feedRef.call( "article(int)", i ); QString title, url; qApp->processEvents( QEventLoop::ExcludeUserInput | QEventLoop::ExcludeSocketNotifiers ); artRef.call( "title()" ).get( title ); artRef.call( "link()" ).get( url ); QPair<QString, KURL> article(title, KURL( url )); map.append( article ); } FeedList::Iterator it; for ( it = mFeeds.begin(); it != mFeeds.end(); ++it ) if ( (*it).ref.obj() == feedRef.obj() ) { (*it).map = map; if ( (*it).title.isEmpty() ) feedRef.call( "title()" ).get( (*it).title ); if ( (*it).url.isEmpty() ) feedRef.call( "link()" ).get( (*it).url ); if ( (*it).logo.isNull() ) feedRef.call( "pixmap()" ).get( (*it).logo ); } mFeedCounter++; if ( mFeedCounter == mFeeds.count() ) { mFeedCounter = 0; updateView(); } } void SummaryWidget::updateView() { mLabels.setAutoDelete( true ); mLabels.clear(); mLabels.setAutoDelete( false ); delete mLayout; mLayout = new QVBoxLayout( mBaseWidget, 3 ); QFont boldFont; boldFont.setBold( true ); boldFont.setPointSize( boldFont.pointSize() + 2 ); FeedList::Iterator it; for ( it = mFeeds.begin(); it != mFeeds.end(); ++it ) { QHBox *hbox = new QHBox( mBaseWidget ); mLayout->addWidget( hbox ); // icon KURLLabel *urlLabel = new KURLLabel( hbox ); urlLabel->setURL( (*it).url ); urlLabel->setPixmap( (*it).logo ); urlLabel->setMaximumSize( urlLabel->minimumSizeHint() ); mLabels.append( urlLabel ); connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ), kapp, SLOT( invokeBrowser( const QString& ) ) ); connect( urlLabel, SIGNAL( rightClickedURL( const QString& ) ), this, SLOT( rmbMenu( const QString& ) ) ); // header QLabel *label = new QLabel( hbox ); label->setText( KCharsets::resolveEntities( (*it).title ) ); label->setAlignment( AlignLeft|AlignVCenter ); label->setFont( boldFont ); label->setIndent( 6 ); label->setMaximumSize( label->minimumSizeHint() ); mLabels.append( label ); hbox->setMaximumWidth( hbox->minimumSizeHint().width() ); hbox->show(); // articles ArticleMap articles = (*it).map; ArticleMap::Iterator artIt; int numArticles = 0; for ( artIt = articles.begin(); artIt != articles.end() && numArticles < mArticleCount; ++artIt ) { urlLabel = new KURLLabel( (*artIt).second.url(), (*artIt).first, mBaseWidget ); urlLabel->installEventFilter( this ); //TODO: RichText causes too much horizontal space between articles //urlLabel->setTextFormat( RichText ); mLabels.append( urlLabel ); mLayout->addWidget( urlLabel ); connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ), kapp, SLOT( invokeBrowser( const QString& ) ) ); connect( urlLabel, SIGNAL( rightClickedURL( const QString& ) ), this, SLOT( rmbMenu( const QString& ) ) ); numArticles++; } } for ( QLabel *label = mLabels.first(); label; label = mLabels.next() ) label->show(); } void SummaryWidget::documentUpdateError( DCOPRef feedRef, int errorCode ) { kdDebug() << " error while updating document, error code: " << errorCode << endl; FeedList::Iterator it; for ( it = mFeeds.begin(); it != mFeeds.end(); ++it ) { if ( (*it).ref.obj() == feedRef.obj() ) { mFeeds.remove( it ); break; } } if ( mFeedCounter == mFeeds.count() ) { mFeedCounter = 0; updateView(); } } QStringList SummaryWidget::configModules() const { return "kcmkontactknt.desktop"; } void SummaryWidget::updateSummary( bool ) { updateDocuments(); } void SummaryWidget::rmbMenu( const QString& url ) { QPopupMenu menu; menu.insertItem( i18n( "Copy URL to Clipboard" ) ); int id = menu.exec( QCursor::pos() ); if ( id != -1 ) kapp->clipboard()->setText( url, QClipboard::Clipboard ); } bool SummaryWidget::eventFilter( QObject *obj, QEvent* e ) { if ( obj->inherits( "KURLLabel" ) ) { KURLLabel* label = static_cast<KURLLabel*>( obj ); if ( e->type() == QEvent::Enter ) emit message( i18n( "Open URL %1" ).arg( label->text() ) ); if ( e->type() == QEvent::Leave ) emit message( QString::null ); } return Kontact::Summary::eventFilter( obj, e ); } #include "summarywidget.moc" <commit_msg>Nicer. plus, this way, we don't have to worry about stripping out funky characters that may be in the URL title.<commit_after>/* This file is part of Kontact. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qclipboard.h> #include <qeventloop.h> #include <qhbox.h> #include <qlayout.h> #include <qpixmap.h> #include <qpopupmenu.h> #include <qcursor.h> #include <dcopclient.h> #include <kapplication.h> #include <kcharsets.h> #include <kconfig.h> #include <kdebug.h> #include <kglobal.h> #include <kiconloader.h> #include <klocale.h> #include <kurllabel.h> #include "summarywidget.h" SummaryWidget::SummaryWidget( QWidget *parent, const char *name ) : Kontact::Summary( parent, name ), DCOPObject( "NewsTickerPlugin" ), mLayout( 0 ), mFeedCounter( 0 ) { QVBoxLayout *vlay = new QVBoxLayout( this, 3, 3 ); QPixmap icon = KGlobal::iconLoader()->loadIcon( "kontact_news", KIcon::Desktop, KIcon::SizeMedium ); QWidget *header = createHeader( this, icon, i18n( "News Feeds" ) ); vlay->addWidget( header ); QString error; QCString appID; bool dcopAvailable = true; if ( !kapp->dcopClient()->isApplicationRegistered( "rssservice" ) ) { if ( KApplication::startServiceByDesktopName( "rssservice", QStringList(), &error, &appID ) ) { QLabel *label = new QLabel( i18n( "No rss dcop service available.\nYou need rssservice to use this plugin." ), this ); vlay->addWidget( label, Qt::AlignHCenter ); dcopAvailable = false; } } mBaseWidget = new QWidget( this, "baseWidget" ); vlay->addWidget( mBaseWidget ); connect( &mTimer, SIGNAL( timeout() ), this, SLOT( updateDocuments() ) ); readConfig(); connectDCOPSignal( 0, 0, "documentUpdateError(DCOPRef,int)", "documentUpdateError(DCOPRef, int)", false ); if ( dcopAvailable ) initDocuments(); connectDCOPSignal( 0, 0, "added(QString)", "documentAdded(QString)", false ); connectDCOPSignal( 0, 0, "removed(QString)", "documentRemoved(QString)", false ); } int SummaryWidget::summaryHeight() const { return ( mFeeds.count() == 0 ? 1 : mFeeds.count() ); } void SummaryWidget::documentAdded( QString ) { initDocuments(); } void SummaryWidget::documentRemoved( QString ) { initDocuments(); } void SummaryWidget::configChanged() { readConfig(); updateView(); } void SummaryWidget::readConfig() { KConfig config( "kcmkontactkntrc" ); config.setGroup( "General" ); mUpdateInterval = config.readNumEntry( "UpdateInterval", 600 ); mArticleCount = config.readNumEntry( "ArticleCount", 4 ); } void SummaryWidget::initDocuments() { mFeeds.clear(); DCOPRef dcopCall( "rssservice", "RSSService" ); QStringList urls; dcopCall.call( "list()" ).get( urls ); if ( urls.isEmpty() ) { // add default urls.append( "http://www.kde.org/dotkdeorg.rdf" ); dcopCall.send( "add(QString)", urls[ 0 ] ); } QStringList::Iterator it; for ( it = urls.begin(); it != urls.end(); ++it ) { DCOPRef feedRef = dcopCall.call( "document(QString)", *it ); Feed feed; feed.ref = feedRef; feedRef.call( "title()" ).get( feed.title ); feedRef.call( "link()" ).get( feed.url ); feedRef.call( "pixmap()" ).get( feed.logo ); mFeeds.append( feed ); disconnectDCOPSignal( "rssservice", feedRef.obj(), "documentUpdated(DCOPRef)", 0 ); connectDCOPSignal( "rssservice", feedRef.obj(), "documentUpdated(DCOPRef)", "documentUpdated(DCOPRef)", false ); qApp->processEvents( QEventLoop::ExcludeUserInput | QEventLoop::ExcludeSocketNotifiers ); } updateDocuments(); } void SummaryWidget::updateDocuments() { mTimer.stop(); FeedList::Iterator it; for ( it = mFeeds.begin(); it != mFeeds.end(); ++it ) (*it).ref.send( "refresh()" ); mTimer.start( 1000 * mUpdateInterval ); } void SummaryWidget::documentUpdated( DCOPRef feedRef ) { ArticleMap map; int numArticles = feedRef.call( "count()" ); for ( int i = 0; i < numArticles; ++i ) { DCOPRef artRef = feedRef.call( "article(int)", i ); QString title, url; qApp->processEvents( QEventLoop::ExcludeUserInput | QEventLoop::ExcludeSocketNotifiers ); artRef.call( "title()" ).get( title ); artRef.call( "link()" ).get( url ); QPair<QString, KURL> article(title, KURL( url )); map.append( article ); } FeedList::Iterator it; for ( it = mFeeds.begin(); it != mFeeds.end(); ++it ) if ( (*it).ref.obj() == feedRef.obj() ) { (*it).map = map; if ( (*it).title.isEmpty() ) feedRef.call( "title()" ).get( (*it).title ); if ( (*it).url.isEmpty() ) feedRef.call( "link()" ).get( (*it).url ); if ( (*it).logo.isNull() ) feedRef.call( "pixmap()" ).get( (*it).logo ); } mFeedCounter++; if ( mFeedCounter == mFeeds.count() ) { mFeedCounter = 0; updateView(); } } void SummaryWidget::updateView() { mLabels.setAutoDelete( true ); mLabels.clear(); mLabels.setAutoDelete( false ); delete mLayout; mLayout = new QVBoxLayout( mBaseWidget, 3 ); QFont boldFont; boldFont.setBold( true ); boldFont.setPointSize( boldFont.pointSize() + 2 ); FeedList::Iterator it; for ( it = mFeeds.begin(); it != mFeeds.end(); ++it ) { QHBox *hbox = new QHBox( mBaseWidget ); mLayout->addWidget( hbox ); // icon KURLLabel *urlLabel = new KURLLabel( hbox ); urlLabel->setURL( (*it).url ); urlLabel->setPixmap( (*it).logo ); urlLabel->setMaximumSize( urlLabel->minimumSizeHint() ); mLabels.append( urlLabel ); connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ), kapp, SLOT( invokeBrowser( const QString& ) ) ); connect( urlLabel, SIGNAL( rightClickedURL( const QString& ) ), this, SLOT( rmbMenu( const QString& ) ) ); // header QLabel *label = new QLabel( hbox ); label->setText( KCharsets::resolveEntities( (*it).title ) ); label->setAlignment( AlignLeft|AlignVCenter ); label->setFont( boldFont ); label->setIndent( 6 ); label->setMaximumSize( label->minimumSizeHint() ); mLabels.append( label ); hbox->setMaximumWidth( hbox->minimumSizeHint().width() ); hbox->show(); // articles ArticleMap articles = (*it).map; ArticleMap::Iterator artIt; int numArticles = 0; for ( artIt = articles.begin(); artIt != articles.end() && numArticles < mArticleCount; ++artIt ) { urlLabel = new KURLLabel( (*artIt).second.url(), (*artIt).first, mBaseWidget ); urlLabel->installEventFilter( this ); //TODO: RichText causes too much horizontal space between articles //urlLabel->setTextFormat( RichText ); mLabels.append( urlLabel ); mLayout->addWidget( urlLabel ); connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ), kapp, SLOT( invokeBrowser( const QString& ) ) ); connect( urlLabel, SIGNAL( rightClickedURL( const QString& ) ), this, SLOT( rmbMenu( const QString& ) ) ); numArticles++; } } for ( QLabel *label = mLabels.first(); label; label = mLabels.next() ) label->show(); } void SummaryWidget::documentUpdateError( DCOPRef feedRef, int errorCode ) { kdDebug() << " error while updating document, error code: " << errorCode << endl; FeedList::Iterator it; for ( it = mFeeds.begin(); it != mFeeds.end(); ++it ) { if ( (*it).ref.obj() == feedRef.obj() ) { mFeeds.remove( it ); break; } } if ( mFeedCounter == mFeeds.count() ) { mFeedCounter = 0; updateView(); } } QStringList SummaryWidget::configModules() const { return "kcmkontactknt.desktop"; } void SummaryWidget::updateSummary( bool ) { updateDocuments(); } void SummaryWidget::rmbMenu( const QString& url ) { QPopupMenu menu; menu.insertItem( i18n( "Copy URL to Clipboard" ) ); int id = menu.exec( QCursor::pos() ); if ( id != -1 ) kapp->clipboard()->setText( url, QClipboard::Clipboard ); } bool SummaryWidget::eventFilter( QObject *obj, QEvent* e ) { if ( obj->inherits( "KURLLabel" ) ) { KURLLabel* label = static_cast<KURLLabel*>( obj ); if ( e->type() == QEvent::Enter ) emit message( label->url() ); if ( e->type() == QEvent::Leave ) emit message( QString::null ); } return Kontact::Summary::eventFilter( obj, e ); } #include "summarywidget.moc" <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libetonyek project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "IWORKMetadataElement.h" #include "IWORKCollector.h" #include "IWORKStringElement.h" #include "IWORKToken.h" #include "IWORKTypes.h" #include "IWORKXMLParserState.h" namespace libetonyek { using boost::optional; using std::string; namespace { class TitleElement : public IWORKXMLElementContextBase { public: explicit TitleElement(IWORKXMLParserState &state, optional<string> &value); private: virtual IWORKXMLContextPtr_t element(int name); private: optional<string> &m_value; }; TitleElement::TitleElement(IWORKXMLParserState &state, optional<string> &value) : IWORKXMLElementContextBase(state) , m_value(value) { } IWORKXMLContextPtr_t TitleElement::element(const int name) { if (name == (IWORKToken::NS_URI_SF | IWORKToken::string)) return makeContext<IWORKStringElement>(getState(), m_value); return IWORKXMLContextPtr_t(); } } namespace { class AuthorsElement : public IWORKXMLElementContextBase { public: AuthorsElement(IWORKXMLParserState &state, optional<string> &value); private: virtual IWORKXMLContextPtr_t element(int name); private: optional<string> &m_value; }; AuthorsElement::AuthorsElement(IWORKXMLParserState &state, optional<string> &value) : IWORKXMLElementContextBase(state) , m_value(value) { } IWORKXMLContextPtr_t AuthorsElement::element(const int name) { if (name == (IWORKToken::NS_URI_SF | IWORKToken::string)) return makeContext<IWORKStringElement>(getState(), m_value); return IWORKXMLContextPtr_t(); } } namespace { class KeywordsElement : public IWORKXMLElementContextBase { public: KeywordsElement(IWORKXMLParserState &state, optional<string> &value); private: virtual IWORKXMLContextPtr_t element(int name); private: optional<string> &m_value; }; KeywordsElement::KeywordsElement(IWORKXMLParserState &state, optional<string> &value) : IWORKXMLElementContextBase(state) , m_value(value) { } IWORKXMLContextPtr_t KeywordsElement::element(const int name) { if (name == (IWORKToken::NS_URI_SF | IWORKToken::string)) return makeContext<IWORKStringElement>(getState(), m_value); return IWORKXMLContextPtr_t(); } } namespace { class CommentElement : public IWORKXMLElementContextBase { public: explicit CommentElement(IWORKXMLParserState &state, optional<string> &m_value); private: virtual IWORKXMLContextPtr_t element(int name); private: optional<string> &m_value; }; CommentElement::CommentElement(IWORKXMLParserState &state, optional<string> &value) : IWORKXMLElementContextBase(state) , m_value(value) { } IWORKXMLContextPtr_t CommentElement::element(const int name) { if (name == (IWORKToken::NS_URI_SF | IWORKToken::string)) return makeContext<IWORKStringElement>(getState(), m_value); return IWORKXMLContextPtr_t(); } } IWORKMetadataElement::IWORKMetadataElement(IWORKXMLParserState &state) : IWORKXMLElementContextBase(state) , m_author() , m_title() , m_keywords() , m_comment() { } IWORKXMLContextPtr_t IWORKMetadataElement::element(const int name) { switch (name) { case IWORKToken::NS_URI_SF | IWORKToken::authors : return makeContext<AuthorsElement>(getState(), m_author); case IWORKToken::NS_URI_SF | IWORKToken::comment : return makeContext<CommentElement>(getState(), m_comment); case IWORKToken::NS_URI_SF | IWORKToken::keywords : return makeContext<KeywordsElement>(getState(), m_keywords); case IWORKToken::NS_URI_SF | IWORKToken::title : return makeContext<TitleElement>(getState(), m_title); } return IWORKXMLContextPtr_t(); } void IWORKMetadataElement::endOfElement() { IWORKMetadata metadata; if (m_author) metadata.m_author = get(m_author); if (m_title) metadata.m_title = get(m_title); if (m_keywords) metadata.m_keywords = get(m_keywords); if (m_comment) metadata.m_comment = get(m_comment); if (isCollector()) getCollector().collectMetadata(metadata); } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <commit_msg>reduce copy-pasta<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libetonyek project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "IWORKMetadataElement.h" #include "IWORKCollector.h" #include "IWORKStringElement.h" #include "IWORKToken.h" #include "IWORKTypes.h" #include "IWORKXMLParserState.h" namespace libetonyek { using boost::optional; using std::string; namespace { class StringContext : public IWORKXMLElementContextBase { public: explicit StringContext(IWORKXMLParserState &state, optional<string> &value); private: virtual IWORKXMLContextPtr_t element(int name); private: optional<string> &m_value; }; StringContext::StringContext(IWORKXMLParserState &state, optional<string> &value) : IWORKXMLElementContextBase(state) , m_value(value) { } IWORKXMLContextPtr_t StringContext::element(const int name) { if (name == (IWORKToken::NS_URI_SF | IWORKToken::string)) return makeContext<IWORKStringElement>(getState(), m_value); return IWORKXMLContextPtr_t(); } } IWORKMetadataElement::IWORKMetadataElement(IWORKXMLParserState &state) : IWORKXMLElementContextBase(state) , m_author() , m_title() , m_keywords() , m_comment() { } IWORKXMLContextPtr_t IWORKMetadataElement::element(const int name) { switch (name) { case IWORKToken::NS_URI_SF | IWORKToken::authors : return makeContext<StringContext>(getState(), m_author); case IWORKToken::NS_URI_SF | IWORKToken::comment : return makeContext<StringContext>(getState(), m_comment); case IWORKToken::NS_URI_SF | IWORKToken::keywords : return makeContext<StringContext>(getState(), m_keywords); case IWORKToken::NS_URI_SF | IWORKToken::title : return makeContext<StringContext>(getState(), m_title); } return IWORKXMLContextPtr_t(); } void IWORKMetadataElement::endOfElement() { IWORKMetadata metadata; if (m_author) metadata.m_author = get(m_author); if (m_title) metadata.m_title = get(m_title); if (m_keywords) metadata.m_keywords = get(m_keywords); if (m_comment) metadata.m_comment = get(m_comment); if (isCollector()) getCollector().collectMetadata(metadata); } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <|endoftext|>