text
stringlengths
54
60.6k
<commit_before>/** \file LocalDataDB.cc * \brief Implementation of the LocalDataDB class. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2020 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "LocalDataDB.h" #include "Compiler.h" #include "DbConnection.h" #include "StringUtil.h" #include "UBTools.h" LocalDataDB::LocalDataDB(const OpenMode open_mode) { db_connection_ = new DbConnection(UBTools::GetTuelibPath() + "local_data.sq3" /* must be the same path as in fetch_marc_updates.py */, (open_mode == READ_WRITE) ? DbConnection::READWRITE : DbConnection::READONLY); if (open_mode == READ_ONLY) return; db_connection_->queryOrDie("CREATE TABLE IF NOT EXISTS local_data (" " title_ppn TEXT PRIMARY KEY," " local_fields BLOB NOT NULL" ") WITHOUT ROWID"); db_connection_->queryOrDie("CREATE TABLE IF NOT EXISTS local_ppns_to_title_ppns_map (" " local_ppn TEXT PRIMARY KEY," " title_ppn TEXT NOT NULL," " FOREIGN KEY(title_ppn) REFERENCES local_data(title_ppn)" ") WITHOUT ROWID"); } LocalDataDB::~LocalDataDB() { delete db_connection_; } void LocalDataDB::clear() { db_connection_->queryOrDie("DELETE * FROM local_data"); db_connection_->queryOrDie("DELETE * FROM local_ppns_to_title_ppns_map"); } static std::vector<std::string> BlobToLocalFieldsVector(const std::string &local_fields_blob, const std::string &title_ppn) { std::vector<std::string> local_fields; size_t processed_size(0); do { // Convert the 4 character hex string to the size of the following field contents: const size_t field_contents_size(StringUtil::ToUnsignedLong(local_fields_blob.substr(processed_size, 4), 16)); processed_size += 4; // Sanity check: if (unlikely(processed_size + field_contents_size > local_fields_blob.size())) LOG_ERROR("inconsistent blob length for record with PPN " + title_ppn + " (1)"); local_fields.emplace_back(local_fields_blob.substr(processed_size, field_contents_size)); processed_size += field_contents_size; } while (processed_size < local_fields_blob.size()); // Sanity check: if (unlikely(processed_size != local_fields_blob.size())) LOG_ERROR("inconsistent blob length for record with PPN " + title_ppn + " (2))"); return local_fields; } std::vector<std::string> ExtractLocalPPNsFromLocalFieldsVector(const std::vector<std::string> &local_fields) { std::vector<std::string> local_ppns; for (const auto &local_field : local_fields) { if (StringUtil::StartsWith(local_field, "001 ")) local_ppns.emplace_back(local_field.substr(__builtin_strlen("001 "))); } return local_ppns; } static std::string ConvertLocalFieldsVectorToBlob(const std::vector<std::string> &local_fields) { std::string local_fields_blob; for (const auto &local_field : local_fields) { local_fields_blob += StringUtil::ToString(local_field.length(), /* radix = */16, /* width = */4, /* padding_char = */'0'); local_fields_blob += local_field; } return local_fields_blob; } void LocalDataDB::insertOrReplace(const std::string &title_ppn, const std::vector<std::string> &local_fields) { // 1. Clear out any local PPNs associated with "title_ppn": db_connection_->queryOrDie("SELECT local_fields FROM local_data WHERE title_ppn = " + db_connection_->escapeAndQuoteString(title_ppn)); auto result_set(db_connection_->getLastResultSet()); if (not result_set.empty()) { const auto row(result_set.getNextRow()); const auto previous_local_fields(BlobToLocalFieldsVector(row["local_fields"], title_ppn)); const auto local_ppns(ExtractLocalPPNsFromLocalFieldsVector(previous_local_fields)); for (const auto &local_ppn : local_ppns) db_connection_->queryOrDie("DELETE * FROM local_ppns_to_title_ppns_map WHERE local_ppn=" + db_connection_->escapeAndQuoteString(local_ppn)); } // 2. Replace or insert the local data keyed by the title PPN's: db_connection_->queryOrDie("REPLACE INTO local_data (title_ppn, local_fields) VALUES(" + db_connection_->escapeAndQuoteString(title_ppn) + "," + db_connection_->sqliteEscapeBlobData(ConvertLocalFieldsVectorToBlob(local_fields)) + ")"); // 3. Insert the mappings from the local PPN's to the title PPN's: for (const auto &local_ppn : ExtractLocalPPNsFromLocalFieldsVector(local_fields)) { db_connection_->queryOrDie("INSERT INTO local_ppns_to_title_ppns_map (local_ppn, title_ppn) VALUES(" + db_connection_->escapeAndQuoteString(local_ppn) + "," + db_connection_->escapeAndQuoteString(title_ppn) + ")"); } } std::vector<std::string> LocalDataDB::getLocalFields(const std::string &title_ppn) const { db_connection_->queryOrDie("SELECT local_fields FROM local_data WHERE title_ppn = " + db_connection_->escapeAndQuoteString(title_ppn)); auto result_set(db_connection_->getLastResultSet()); if (result_set.empty()) return {}; // empty vector const auto row(result_set.getNextRow()); return BlobToLocalFieldsVector(row["local_fields"], title_ppn); } bool LocalDataDB::removeTitleDataSet(const std::string &title_ppn) { // 1. Clear out any local PPNs associated with "title_ppn": db_connection_->queryOrDie("SELECT local_fields FROM local_data WHERE title_ppn = " + db_connection_->escapeAndQuoteString(title_ppn)); auto result_set(db_connection_->getLastResultSet()); if (result_set.empty()) return false; const auto row(result_set.getNextRow()); const auto previous_local_fields(BlobToLocalFieldsVector(row["local_fields"], title_ppn)); const auto local_ppns(ExtractLocalPPNsFromLocalFieldsVector(previous_local_fields)); for (const auto &local_ppn : local_ppns) db_connection_->queryOrDie("DELETE * FROM local_ppns_to_title_ppns_map WHERE local_ppn=" + db_connection_->escapeAndQuoteString(local_ppn)); // 2. Delete the local data for the title PPN: db_connection_->queryOrDie("DELETE FROM local_data WHERE title_ppn = " + db_connection_->escapeAndQuoteString(title_ppn)); return true; } // Removes all fields from "local_fields" that are associated w/ "local_ppn". static std::vector<std::string> RemoveLocalDataSet(const std::string &local_ppn, const std::vector<std::string> &local_fields) { std::vector<std::string> filtered_local_fields; filtered_local_fields.reserve(local_fields.size()); bool skipping(false); for (const auto &local_field : local_fields) { if (StringUtil::StartsWith(local_field, "001 ")) skipping = local_field.substr(__builtin_strlen("001 ")) == local_ppn; if (not skipping) filtered_local_fields.emplace_back(local_field); } return filtered_local_fields; } bool LocalDataDB::removeLocalDataSet(const std::string &local_ppn) { // 1. Determine the title PPN associated w/ the local PPN: db_connection_->queryOrDie("SELECT title_ppn FROM local_ppns_to_title_ppns_map WHERE local_ppn=" + db_connection_->escapeAndQuoteString(local_ppn)); auto result_set(db_connection_->getLastResultSet()); if (result_set.empty()) return false; const auto row(result_set.getNextRow()); const auto title_ppn(row["title_ppn"]); // 2. Retrieve the local data associated w/ the title PPN: auto local_fields(getLocalFields(title_ppn)); // 3. Remove the local data associsted w/ the local PPN: const auto filtered_local_fields(RemoveLocalDataSet(local_ppn, local_fields)); // 4. Update our SQL tables: db_connection_->queryOrDie("DELETE FROM local_ppns_to_title_ppns_map WHERE ocal_ppn=" + db_connection_->escapeAndQuoteString(local_ppn)); if (filtered_local_fields.empty()) db_connection_->queryOrDie("DELETE * FROM local_fields WHERE title_ppn=" + db_connection_->escapeAndQuoteString(title_ppn)); else db_connection_->queryOrDie("REPLACE INTO local_data (titel_ppn, local_fields) VALUES(" + db_connection_->escapeAndQuoteString(title_ppn) + "," + db_connection_->sqliteEscapeBlobData(ConvertLocalFieldsVectorToBlob(local_fields)) + ")"); return true; } <commit_msg>Bug fix.<commit_after>/** \file LocalDataDB.cc * \brief Implementation of the LocalDataDB class. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2020 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "LocalDataDB.h" #include "Compiler.h" #include "DbConnection.h" #include "StringUtil.h" #include "UBTools.h" LocalDataDB::LocalDataDB(const OpenMode open_mode) { db_connection_ = new DbConnection(UBTools::GetTuelibPath() + "local_data.sq3" /* must be the same path as in fetch_marc_updates.py */, (open_mode == READ_WRITE) ? DbConnection::CREATE : DbConnection::READONLY); if (open_mode == READ_ONLY) return; db_connection_->queryOrDie("CREATE TABLE IF NOT EXISTS local_data (" " title_ppn TEXT PRIMARY KEY," " local_fields BLOB NOT NULL" ") WITHOUT ROWID"); db_connection_->queryOrDie("CREATE TABLE IF NOT EXISTS local_ppns_to_title_ppns_map (" " local_ppn TEXT PRIMARY KEY," " title_ppn TEXT NOT NULL," " FOREIGN KEY(title_ppn) REFERENCES local_data(title_ppn)" ") WITHOUT ROWID"); } LocalDataDB::~LocalDataDB() { delete db_connection_; } void LocalDataDB::clear() { db_connection_->queryOrDie("DELETE * FROM local_data"); db_connection_->queryOrDie("DELETE * FROM local_ppns_to_title_ppns_map"); } static std::vector<std::string> BlobToLocalFieldsVector(const std::string &local_fields_blob, const std::string &title_ppn) { std::vector<std::string> local_fields; size_t processed_size(0); do { // Convert the 4 character hex string to the size of the following field contents: const size_t field_contents_size(StringUtil::ToUnsignedLong(local_fields_blob.substr(processed_size, 4), 16)); processed_size += 4; // Sanity check: if (unlikely(processed_size + field_contents_size > local_fields_blob.size())) LOG_ERROR("inconsistent blob length for record with PPN " + title_ppn + " (1)"); local_fields.emplace_back(local_fields_blob.substr(processed_size, field_contents_size)); processed_size += field_contents_size; } while (processed_size < local_fields_blob.size()); // Sanity check: if (unlikely(processed_size != local_fields_blob.size())) LOG_ERROR("inconsistent blob length for record with PPN " + title_ppn + " (2))"); return local_fields; } std::vector<std::string> ExtractLocalPPNsFromLocalFieldsVector(const std::vector<std::string> &local_fields) { std::vector<std::string> local_ppns; for (const auto &local_field : local_fields) { if (StringUtil::StartsWith(local_field, "001 ")) local_ppns.emplace_back(local_field.substr(__builtin_strlen("001 "))); } return local_ppns; } static std::string ConvertLocalFieldsVectorToBlob(const std::vector<std::string> &local_fields) { std::string local_fields_blob; for (const auto &local_field : local_fields) { local_fields_blob += StringUtil::ToString(local_field.length(), /* radix = */16, /* width = */4, /* padding_char = */'0'); local_fields_blob += local_field; } return local_fields_blob; } void LocalDataDB::insertOrReplace(const std::string &title_ppn, const std::vector<std::string> &local_fields) { // 1. Clear out any local PPNs associated with "title_ppn": db_connection_->queryOrDie("SELECT local_fields FROM local_data WHERE title_ppn = " + db_connection_->escapeAndQuoteString(title_ppn)); auto result_set(db_connection_->getLastResultSet()); if (not result_set.empty()) { const auto row(result_set.getNextRow()); const auto previous_local_fields(BlobToLocalFieldsVector(row["local_fields"], title_ppn)); const auto local_ppns(ExtractLocalPPNsFromLocalFieldsVector(previous_local_fields)); for (const auto &local_ppn : local_ppns) db_connection_->queryOrDie("DELETE * FROM local_ppns_to_title_ppns_map WHERE local_ppn=" + db_connection_->escapeAndQuoteString(local_ppn)); } // 2. Replace or insert the local data keyed by the title PPN's: db_connection_->queryOrDie("REPLACE INTO local_data (title_ppn, local_fields) VALUES(" + db_connection_->escapeAndQuoteString(title_ppn) + "," + db_connection_->sqliteEscapeBlobData(ConvertLocalFieldsVectorToBlob(local_fields)) + ")"); // 3. Insert the mappings from the local PPN's to the title PPN's: for (const auto &local_ppn : ExtractLocalPPNsFromLocalFieldsVector(local_fields)) { db_connection_->queryOrDie("INSERT INTO local_ppns_to_title_ppns_map (local_ppn, title_ppn) VALUES(" + db_connection_->escapeAndQuoteString(local_ppn) + "," + db_connection_->escapeAndQuoteString(title_ppn) + ")"); } } std::vector<std::string> LocalDataDB::getLocalFields(const std::string &title_ppn) const { db_connection_->queryOrDie("SELECT local_fields FROM local_data WHERE title_ppn = " + db_connection_->escapeAndQuoteString(title_ppn)); auto result_set(db_connection_->getLastResultSet()); if (result_set.empty()) return {}; // empty vector const auto row(result_set.getNextRow()); return BlobToLocalFieldsVector(row["local_fields"], title_ppn); } bool LocalDataDB::removeTitleDataSet(const std::string &title_ppn) { // 1. Clear out any local PPNs associated with "title_ppn": db_connection_->queryOrDie("SELECT local_fields FROM local_data WHERE title_ppn = " + db_connection_->escapeAndQuoteString(title_ppn)); auto result_set(db_connection_->getLastResultSet()); if (result_set.empty()) return false; const auto row(result_set.getNextRow()); const auto previous_local_fields(BlobToLocalFieldsVector(row["local_fields"], title_ppn)); const auto local_ppns(ExtractLocalPPNsFromLocalFieldsVector(previous_local_fields)); for (const auto &local_ppn : local_ppns) db_connection_->queryOrDie("DELETE * FROM local_ppns_to_title_ppns_map WHERE local_ppn=" + db_connection_->escapeAndQuoteString(local_ppn)); // 2. Delete the local data for the title PPN: db_connection_->queryOrDie("DELETE FROM local_data WHERE title_ppn = " + db_connection_->escapeAndQuoteString(title_ppn)); return true; } // Removes all fields from "local_fields" that are associated w/ "local_ppn". static std::vector<std::string> RemoveLocalDataSet(const std::string &local_ppn, const std::vector<std::string> &local_fields) { std::vector<std::string> filtered_local_fields; filtered_local_fields.reserve(local_fields.size()); bool skipping(false); for (const auto &local_field : local_fields) { if (StringUtil::StartsWith(local_field, "001 ")) skipping = local_field.substr(__builtin_strlen("001 ")) == local_ppn; if (not skipping) filtered_local_fields.emplace_back(local_field); } return filtered_local_fields; } bool LocalDataDB::removeLocalDataSet(const std::string &local_ppn) { // 1. Determine the title PPN associated w/ the local PPN: db_connection_->queryOrDie("SELECT title_ppn FROM local_ppns_to_title_ppns_map WHERE local_ppn=" + db_connection_->escapeAndQuoteString(local_ppn)); auto result_set(db_connection_->getLastResultSet()); if (result_set.empty()) return false; const auto row(result_set.getNextRow()); const auto title_ppn(row["title_ppn"]); // 2. Retrieve the local data associated w/ the title PPN: auto local_fields(getLocalFields(title_ppn)); // 3. Remove the local data associsted w/ the local PPN: const auto filtered_local_fields(RemoveLocalDataSet(local_ppn, local_fields)); // 4. Update our SQL tables: db_connection_->queryOrDie("DELETE FROM local_ppns_to_title_ppns_map WHERE ocal_ppn=" + db_connection_->escapeAndQuoteString(local_ppn)); if (filtered_local_fields.empty()) db_connection_->queryOrDie("DELETE * FROM local_fields WHERE title_ppn=" + db_connection_->escapeAndQuoteString(title_ppn)); else db_connection_->queryOrDie("REPLACE INTO local_data (titel_ppn, local_fields) VALUES(" + db_connection_->escapeAndQuoteString(title_ppn) + "," + db_connection_->sqliteEscapeBlobData(ConvertLocalFieldsVectorToBlob(local_fields)) + ")"); return true; } <|endoftext|>
<commit_before>/** \brief Utility for updating SQL schemata etc. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <stdexcept> #include <vector> #include <cstdio> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "DbConnection.h" #include "StringUtil.h" #include "util.h" namespace { void SplitIntoDatabaseTableAndVersion(const std::string &update_filename, std::string * const database, std::string * const table, unsigned * const version) { std::vector<std::string> parts; if (unlikely(StringUtil::Split(update_filename, '.', &parts) != 3)) LOG_ERROR("failed to split \"" + update_filename + "\" into \"database.table.version\"!"); *database = parts[0]; *table = parts[1]; *version = StringUtil::ToUnsigned(parts[2]); } __attribute__((__const__)) inline std::string GetFirstTableName(const std::string &compound_table_name) { const auto first_plus_pos(compound_table_name.find('+')); return (first_plus_pos == std::string::npos) ? compound_table_name : compound_table_name.substr(0, first_plus_pos); } // The filenames being compared are assumed to have the "structure database.table.version" bool FileNameCompare(const std::string &filename1, const std::string &filename2) { std::string database1, table1; unsigned version1; SplitIntoDatabaseTableAndVersion(filename1, &database1, &table1, &version1); std::string database2, table2; unsigned version2; SplitIntoDatabaseTableAndVersion(filename2, &database2, &table2, &version2); // Compare database names: if (database1 < database2) return true; if (database1 > database2) return false; // Compare table names: if (GetFirstTableName(table1) < GetFirstTableName(table2)) return true; if (GetFirstTableName(table1) > GetFirstTableName(table2)) return false; return version1 < version2; } void LoadAndSortUpdateFilenames(const std::string &directory_path, std::vector<std::string> * const update_filenames) { FileUtil::Directory directory(directory_path, "[^.]+\\.[^.]+\\.\\d+"); for (const auto &entry : directory) update_filenames->emplace_back(entry.getName()); std::sort(update_filenames->begin(), update_filenames->end(), FileNameCompare); } std::vector<std::string> GetAllTableNames(const std::string &compound_table_name) { std::vector<std::string> all_table_names; std::string current_table_name; for (const char ch : compound_table_name) { if (ch == '+') { if (unlikely(current_table_name.empty())) LOG_ERROR("bad compound table name \"" + compound_table_name + "\"! (2)"); all_table_names.emplace_back(current_table_name); current_table_name.clear(); } else current_table_name += ch; } if (unlikely(current_table_name.empty())) LOG_ERROR("bad compound table name \"" + compound_table_name + "\"! (2)"); all_table_names.emplace_back(current_table_name); return all_table_names; } void ApplyUpdate(DbConnection * const db_connection, const std::string &update_directory_path, const std::string &update_filename) { std::string database, tables; unsigned update_version; SplitIntoDatabaseTableAndVersion(update_filename, &database, &tables, &update_version); db_connection->queryOrDie("START TRANSACTION"); db_connection->queryFileOrDie(update_directory_path + "/" + update_filename); bool can_update(true); for (const auto &table : GetAllTableNames(tables)) { unsigned current_version(0); db_connection->queryOrDie("SELECT version FROM ub_tools.table_versions WHERE database_name='" + db_connection->escapeString(database) + "' AND table_name='" + db_connection->escapeString(table) + "'"); DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.empty()) { db_connection->queryOrDie("INSERT INTO ub_tools.table_versions (database_name,table_name,version) VALUES ('" + db_connection->escapeString(database) + "','" + db_connection->escapeString(table) + "',0)"); LOG_INFO("Created a new entry for " + database + "." + table + " in ub_tools.table_versions."); } else current_version = StringUtil::ToUnsigned(result_set.getNextRow()["version"]); if (update_version <= current_version) { if (unlikely(not can_update)) LOG_ERROR("inconsistent updates for tables \"" + tables + "\"!"); can_update = false; continue; } db_connection->queryOrDie("UPDATE ub_tools.table_versions SET version=" + std::to_string(update_version) + " WHERE database_name='" + db_connection->escapeString(database) + "' AND table_name='" + db_connection->escapeString(table) + "'"); if (unlikely(update_version != current_version + 1)) LOG_ERROR("update version is " + std::to_string(update_version) + ", current version is " + std::to_string(current_version) + " for table \"" + database + "." + table + "\"!"); LOG_INFO("applying update \"" + database + "." + table + "." + std::to_string(update_version) + "\"."); } db_connection->queryOrDie("COMMIT"); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 2) ::Usage("[--verbose] update_directory_path"); std::vector<std::string> update_filenames; const std::string update_directory_path(argv[1]); LoadAndSortUpdateFilenames(update_directory_path, &update_filenames); DbConnection db_connection; if (not db_connection.tableExists("ub_tools", "table_versions")) { db_connection.queryOrDie("CREATE TABLE ub_tools.table_versions (version INT UNSIGNED NOT NULL, database_name VARCHAR(64) NOT NULL, " "table_name VARCHAR(64) NOT NULL, UNIQUE(database_name,table_name)) " "CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"); LOG_INFO("Created the ub_tools.table_versions table."); } for (const auto &update_filename : update_filenames) ApplyUpdate(&db_connection, update_directory_path, update_filename); return EXIT_SUCCESS; } <commit_msg>Using a library function instead of rolling our own.<commit_after>/** \brief Utility for updating SQL schemata etc. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <stdexcept> #include <vector> #include <cstdio> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "DbConnection.h" #include "StringUtil.h" #include "util.h" namespace { void SplitIntoDatabaseTableAndVersion(const std::string &update_filename, std::string * const database, std::string * const table, unsigned * const version) { std::vector<std::string> parts; if (unlikely(StringUtil::Split(update_filename, '.', &parts) != 3)) LOG_ERROR("failed to split \"" + update_filename + "\" into \"database.table.version\"!"); *database = parts[0]; *table = parts[1]; *version = StringUtil::ToUnsigned(parts[2]); } __attribute__((__const__)) inline std::string GetFirstTableName(const std::string &compound_table_name) { const auto first_plus_pos(compound_table_name.find('+')); return (first_plus_pos == std::string::npos) ? compound_table_name : compound_table_name.substr(0, first_plus_pos); } // The filenames being compared are assumed to have the "structure database.table.version" bool FileNameCompare(const std::string &filename1, const std::string &filename2) { std::string database1, table1; unsigned version1; SplitIntoDatabaseTableAndVersion(filename1, &database1, &table1, &version1); std::string database2, table2; unsigned version2; SplitIntoDatabaseTableAndVersion(filename2, &database2, &table2, &version2); // Compare database names: if (database1 < database2) return true; if (database1 > database2) return false; // Compare table names: if (GetFirstTableName(table1) < GetFirstTableName(table2)) return true; if (GetFirstTableName(table1) > GetFirstTableName(table2)) return false; return version1 < version2; } void LoadAndSortUpdateFilenames(const std::string &directory_path, std::vector<std::string> * const update_filenames) { FileUtil::Directory directory(directory_path, "[^.]+\\.[^.]+\\.\\d+"); for (const auto &entry : directory) update_filenames->emplace_back(entry.getName()); std::sort(update_filenames->begin(), update_filenames->end(), FileNameCompare); } std::vector<std::string> GetAllTableNames(const std::string &compound_table_name) { std::vector<std::string> all_table_names; StringUtil::Split(compound_table_name, '+', &all_table_names); return all_table_names; } void ApplyUpdate(DbConnection * const db_connection, const std::string &update_directory_path, const std::string &update_filename) { std::string database, tables; unsigned update_version; SplitIntoDatabaseTableAndVersion(update_filename, &database, &tables, &update_version); db_connection->queryOrDie("START TRANSACTION"); db_connection->queryFileOrDie(update_directory_path + "/" + update_filename); bool can_update(true); for (const auto &table : GetAllTableNames(tables)) { unsigned current_version(0); db_connection->queryOrDie("SELECT version FROM ub_tools.table_versions WHERE database_name='" + db_connection->escapeString(database) + "' AND table_name='" + db_connection->escapeString(table) + "'"); DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.empty()) { db_connection->queryOrDie("INSERT INTO ub_tools.table_versions (database_name,table_name,version) VALUES ('" + db_connection->escapeString(database) + "','" + db_connection->escapeString(table) + "',0)"); LOG_INFO("Created a new entry for " + database + "." + table + " in ub_tools.table_versions."); } else current_version = StringUtil::ToUnsigned(result_set.getNextRow()["version"]); if (update_version <= current_version) { if (unlikely(not can_update)) LOG_ERROR("inconsistent updates for tables \"" + tables + "\"!"); can_update = false; continue; } db_connection->queryOrDie("UPDATE ub_tools.table_versions SET version=" + std::to_string(update_version) + " WHERE database_name='" + db_connection->escapeString(database) + "' AND table_name='" + db_connection->escapeString(table) + "'"); if (unlikely(update_version != current_version + 1)) LOG_ERROR("update version is " + std::to_string(update_version) + ", current version is " + std::to_string(current_version) + " for table \"" + database + "." + table + "\"!"); LOG_INFO("applying update \"" + database + "." + table + "." + std::to_string(update_version) + "\"."); } db_connection->queryOrDie("COMMIT"); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 2) ::Usage("[--verbose] update_directory_path"); std::vector<std::string> update_filenames; const std::string update_directory_path(argv[1]); LoadAndSortUpdateFilenames(update_directory_path, &update_filenames); DbConnection db_connection; if (not db_connection.tableExists("ub_tools", "table_versions")) { db_connection.queryOrDie("CREATE TABLE ub_tools.table_versions (version INT UNSIGNED NOT NULL, database_name VARCHAR(64) NOT NULL, " "table_name VARCHAR(64) NOT NULL, UNIQUE(database_name,table_name)) " "CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"); LOG_INFO("Created the ub_tools.table_versions table."); } for (const auto &update_filename : update_filenames) ApplyUpdate(&db_connection, update_directory_path, update_filename); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "test_bits.hpp" #include "proton/connection.hpp" #include "proton/connection_options.hpp" #include "proton/container.hpp" #include "proton/messaging_handler.hpp" #include "proton/listener.hpp" #include "proton/listen_handler.hpp" #include "proton/work_queue.hpp" #include <cstdlib> #include <ctime> #include <string> #include <cstdio> #include <sstream> #if PN_CPP_SUPPORTS_THREADS # include <thread> # include <mutex> # include <condition_variable> #endif namespace { std::string make_url(std::string host, int port) { std::ostringstream url; url << "//" << host << ":" << port; return url.str(); } struct test_listen_handler : public proton::listen_handler { bool on_open_, on_accept_, on_close_; std::string on_error_; std::string host_; proton::connection_options opts_; test_listen_handler(const std::string& host=std::string(), const proton::connection_options& opts=proton::connection_options() ) : on_open_(false), on_accept_(false), on_close_(false), host_(host), opts_(opts) {} proton::connection_options on_accept(proton::listener&) PN_CPP_OVERRIDE { on_accept_ = true; return proton::connection_options(); } void on_open(proton::listener& l) PN_CPP_OVERRIDE { on_open_ = true; ASSERT(!on_accept_); ASSERT(on_error_.empty()); ASSERT(!on_close_); l.container().connect(make_url(host_, l.port()), opts_); } void on_close(proton::listener&) PN_CPP_OVERRIDE { on_close_ = true; ASSERT(on_open_ || on_error_.size()); } void on_error(proton::listener&, const std::string& e) PN_CPP_OVERRIDE { on_error_ = e; ASSERT(!on_close_); } }; class test_handler : public proton::messaging_handler { public: bool closing; bool done; std::string peer_vhost; std::string peer_container_id; std::vector<proton::symbol> peer_offered_capabilities; std::vector<proton::symbol> peer_desired_capabilities; proton::listener listener; test_listen_handler listen_handler; test_handler(const std::string h, const proton::connection_options& c_opts) : closing(false), done(false), listen_handler(h, c_opts) {} void on_container_start(proton::container &c) PN_CPP_OVERRIDE { listener = c.listen("//:0", listen_handler); } void on_connection_open(proton::connection &c) PN_CPP_OVERRIDE { ASSERT(listen_handler.on_open_); ASSERT(!listen_handler.on_close_); ASSERT(listen_handler.on_error_.empty()); // First call is the incoming server-side of the connection, that we are interested in. // Second call is for the response to the client, ignore that. if (!closing) { peer_vhost = c.virtual_host(); peer_container_id = c.container_id(); peer_offered_capabilities = c.offered_capabilities(); peer_desired_capabilities = c.desired_capabilities(); c.close(); } closing = true; } void on_connection_close(proton::connection &) PN_CPP_OVERRIDE { if (!done) listener.stop(); done = true; } }; int test_container_default_container_id() { proton::connection_options opts; test_handler th("", opts); proton::container(th).run(); ASSERT(!th.peer_container_id.empty()); ASSERT(th.listen_handler.on_error_.empty()); ASSERT(th.listen_handler.on_close_); return 0; } int test_container_vhost() { proton::connection_options opts; opts.virtual_host("a.b.c"); test_handler th("", opts); proton::container(th).run(); ASSERT_EQUAL(th.peer_vhost, "a.b.c"); return 0; } int test_container_default_vhost() { proton::connection_options opts; test_handler th("127.0.0.1", opts); proton::container(th).run(); ASSERT_EQUAL(th.peer_vhost, "127.0.0.1"); return 0; } int test_container_no_vhost() { // explicitly setting an empty virtual-host will cause the Open // performative to be sent without a hostname field present. // Sadly whether or not a 'hostname' field was received cannot be // determined from here, so just exercise the code proton::connection_options opts; opts.virtual_host(""); test_handler th("127.0.0.1", opts); proton::container(th).run(); ASSERT_EQUAL(th.peer_vhost, ""); return 0; } std::vector<proton::symbol> make_caps(const std::string& s) { std::vector<proton::symbol> caps; caps.push_back(s); return caps; } int test_container_capabilities() { proton::connection_options opts; opts.offered_capabilities(make_caps("offered")); opts.desired_capabilities(make_caps("desired")); test_handler th("", opts); proton::container(th).run(); ASSERT_EQUAL(th.peer_offered_capabilities.size(), 1); ASSERT_EQUAL(th.peer_offered_capabilities[0], proton::symbol("offered")); ASSERT_EQUAL(th.peer_desired_capabilities.size(), 1); ASSERT_EQUAL(th.peer_desired_capabilities[0], proton::symbol("desired")); return 0; } int test_container_bad_address() { // Listen on a bad address, check for leaks // Regression test for https://issues.apache.org/jira/browse/PROTON-1217 proton::container c; // Default fixed-option listener. Valgrind for leaks. try { c.listen("999.666.999.666:0"); } catch (const proton::error&) {} c.run(); // Dummy listener. test_listen_handler l; test_handler h2("999.999.999.666", proton::connection_options()); try { c.listen("999.666.999.666:0", l); } catch (const proton::error&) {} c.run(); ASSERT(!l.on_open_); ASSERT(!l.on_accept_); ASSERT(l.on_close_); ASSERT(!l.on_error_.empty()); return 0; } class stop_tester : public proton::messaging_handler { proton::listener listener; test_listen_handler listen_handler; // Set up a listener which would block forever void on_container_start(proton::container& c) PN_CPP_OVERRIDE { ASSERT(state==0); listener = c.listen("//:0", listen_handler); c.auto_stop(false); state = 1; } // Get here twice - once for listener, once for connector void on_connection_open(proton::connection &c) PN_CPP_OVERRIDE { c.close(); state++; } void on_connection_close(proton::connection &c) PN_CPP_OVERRIDE { ASSERT(state==3); c.container().stop(); state = 4; } void on_container_stop(proton::container & ) PN_CPP_OVERRIDE { ASSERT(state==4); state = 5; } void on_transport_error(proton::transport & t) PN_CPP_OVERRIDE { // Do nothing - ignore transport errors - we're going to get one when // the container stops. } public: stop_tester(): state(0) {} int state; }; int test_container_stop() { stop_tester t; proton::container(t).run(); ASSERT(t.state==5); return 0; } struct hang_tester : public proton::messaging_handler { proton::listener listener; bool done; hang_tester() : done(false) {} void connect(proton::container* c) { c->connect(make_url("", listener.port())); } void on_container_start(proton::container& c) PN_CPP_OVERRIDE { listener = c.listen("//:0"); c.schedule(proton::duration(250), proton::make_work(&hang_tester::connect, this, &c)); } void on_connection_open(proton::connection& c) PN_CPP_OVERRIDE { c.close(); } void on_connection_close(proton::connection& c) PN_CPP_OVERRIDE { if (!done) { done = true; listener.stop(); } } }; int test_container_schedule_nohang() { hang_tester t; proton::container(t).run(); return 0; } class immediate_stop_tester : public proton::messaging_handler { public: void on_container_start(proton::container &c) PN_CPP_OVERRIDE { c.stop(); } }; int test_container_immediate_stop() { immediate_stop_tester t; proton::container(t).run(); // Should return after on_container_start return 0; } int test_container_pre_stop() { proton::container c; c.stop(); c.run(); // Should return immediately return 0; } struct schedule_tester : public proton::messaging_handler { void stop(proton::container* c) { c->stop(); } void on_container_start(proton::container& c) PN_CPP_OVERRIDE { c.schedule(proton::duration(250), proton::make_work(&schedule_tester::stop, this, &c)); } }; int test_container_schedule_stop() { schedule_tester tester; proton::container c(tester); c.auto_stop(false); c.run(); return 0; } #if PN_CPP_SUPPORTS_THREADS // Tests that require thread support class test_mt_handler : public proton::messaging_handler { public: std::mutex lock_; std::condition_variable cond_; std::string str_; proton::error_condition err_; void set(const std::string& s) { std::lock_guard<std::mutex> l(lock_); str_ = s; cond_.notify_one(); } std::string wait() { std::unique_lock<std::mutex> l(lock_); while (str_.empty()) cond_.wait(l); std::string s = str_; str_.clear(); return s; } proton::error_condition error() const { return err_; } void on_container_start(proton::container &) PN_CPP_OVERRIDE { set("start"); } void on_connection_open(proton::connection &) PN_CPP_OVERRIDE { set("open"); } // Catch errors and save. void on_error(const proton::error_condition& e) PN_CPP_OVERRIDE { err_ = e; } }; class container_runner { proton::container& c_; public: container_runner(proton::container& c) : c_(c) {} void operator()() {c_.run();} }; int test_container_mt_stop_empty() { test_mt_handler th; proton::container c(th); c.auto_stop( false ); container_runner runner(c); auto t = std::thread(runner); ASSERT_EQUAL("start", th.wait()); c.stop(); t.join(); ASSERT_EQUAL("", th.error().name()); return 0; } int test_container_mt_stop() { test_mt_handler th; proton::container c(th); c.auto_stop(false); container_runner runner(c); auto t = std::thread(runner); test_listen_handler lh; c.listen("//:0", lh); // Also opens a connection ASSERT_EQUAL("start", th.wait()); ASSERT_EQUAL("open", th.wait()); c.stop(); t.join(); // It is possible to get sporadic connection errors from this test depending on timing of stop() return 0; } #endif } // namespace int main(int argc, char** argv) { int failed = 0; RUN_ARGV_TEST(failed, test_container_default_container_id()); RUN_ARGV_TEST(failed, test_container_vhost()); RUN_ARGV_TEST(failed, test_container_capabilities()); RUN_ARGV_TEST(failed, test_container_default_vhost()); RUN_ARGV_TEST(failed, test_container_no_vhost()); RUN_ARGV_TEST(failed, test_container_bad_address()); RUN_ARGV_TEST(failed, test_container_stop()); RUN_ARGV_TEST(failed, test_container_schedule_nohang()); RUN_ARGV_TEST(failed, test_container_immediate_stop()); RUN_ARGV_TEST(failed, test_container_pre_stop()); RUN_ARGV_TEST(failed, test_container_schedule_stop()); #if PN_CPP_SUPPORTS_THREADS RUN_ARGV_TEST(failed, test_container_mt_stop_empty()); RUN_ARGV_TEST(failed, test_container_mt_stop()); #endif return failed; } <commit_msg>PROTON-1897: Make sure that we don't exit tests with unjoined threads - The tests signal assertion failures with exceptions if there are unjoined threads the assertion failure exceptions get overridden by terminate due to threads still hanging about.<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "test_bits.hpp" #include "proton/connection.hpp" #include "proton/connection_options.hpp" #include "proton/container.hpp" #include "proton/messaging_handler.hpp" #include "proton/listener.hpp" #include "proton/listen_handler.hpp" #include "proton/work_queue.hpp" #include <cstdlib> #include <ctime> #include <string> #include <cstdio> #include <sstream> #if PN_CPP_SUPPORTS_THREADS # include <thread> # include <mutex> # include <condition_variable> #endif namespace { std::string make_url(std::string host, int port) { std::ostringstream url; url << "//" << host << ":" << port; return url.str(); } struct test_listen_handler : public proton::listen_handler { bool on_open_, on_accept_, on_close_; std::string on_error_; std::string host_; proton::connection_options opts_; test_listen_handler(const std::string& host=std::string(), const proton::connection_options& opts=proton::connection_options() ) : on_open_(false), on_accept_(false), on_close_(false), host_(host), opts_(opts) {} proton::connection_options on_accept(proton::listener&) PN_CPP_OVERRIDE { on_accept_ = true; return proton::connection_options(); } void on_open(proton::listener& l) PN_CPP_OVERRIDE { on_open_ = true; ASSERT(!on_accept_); ASSERT(on_error_.empty()); ASSERT(!on_close_); l.container().connect(make_url(host_, l.port()), opts_); } void on_close(proton::listener&) PN_CPP_OVERRIDE { on_close_ = true; ASSERT(on_open_ || on_error_.size()); } void on_error(proton::listener&, const std::string& e) PN_CPP_OVERRIDE { on_error_ = e; ASSERT(!on_close_); } }; class test_handler : public proton::messaging_handler { public: bool closing; bool done; std::string peer_vhost; std::string peer_container_id; std::vector<proton::symbol> peer_offered_capabilities; std::vector<proton::symbol> peer_desired_capabilities; proton::listener listener; test_listen_handler listen_handler; test_handler(const std::string h, const proton::connection_options& c_opts) : closing(false), done(false), listen_handler(h, c_opts) {} void on_container_start(proton::container &c) PN_CPP_OVERRIDE { listener = c.listen("//:0", listen_handler); } void on_connection_open(proton::connection &c) PN_CPP_OVERRIDE { ASSERT(listen_handler.on_open_); ASSERT(!listen_handler.on_close_); ASSERT(listen_handler.on_error_.empty()); // First call is the incoming server-side of the connection, that we are interested in. // Second call is for the response to the client, ignore that. if (!closing) { peer_vhost = c.virtual_host(); peer_container_id = c.container_id(); peer_offered_capabilities = c.offered_capabilities(); peer_desired_capabilities = c.desired_capabilities(); c.close(); } closing = true; } void on_connection_close(proton::connection &) PN_CPP_OVERRIDE { if (!done) listener.stop(); done = true; } }; int test_container_default_container_id() { proton::connection_options opts; test_handler th("", opts); proton::container(th).run(); ASSERT(!th.peer_container_id.empty()); ASSERT(th.listen_handler.on_error_.empty()); ASSERT(th.listen_handler.on_close_); return 0; } int test_container_vhost() { proton::connection_options opts; opts.virtual_host("a.b.c"); test_handler th("", opts); proton::container(th).run(); ASSERT_EQUAL(th.peer_vhost, "a.b.c"); return 0; } int test_container_default_vhost() { proton::connection_options opts; test_handler th("127.0.0.1", opts); proton::container(th).run(); ASSERT_EQUAL(th.peer_vhost, "127.0.0.1"); return 0; } int test_container_no_vhost() { // explicitly setting an empty virtual-host will cause the Open // performative to be sent without a hostname field present. // Sadly whether or not a 'hostname' field was received cannot be // determined from here, so just exercise the code proton::connection_options opts; opts.virtual_host(""); test_handler th("127.0.0.1", opts); proton::container(th).run(); ASSERT_EQUAL(th.peer_vhost, ""); return 0; } std::vector<proton::symbol> make_caps(const std::string& s) { std::vector<proton::symbol> caps; caps.push_back(s); return caps; } int test_container_capabilities() { proton::connection_options opts; opts.offered_capabilities(make_caps("offered")); opts.desired_capabilities(make_caps("desired")); test_handler th("", opts); proton::container(th).run(); ASSERT_EQUAL(th.peer_offered_capabilities.size(), 1); ASSERT_EQUAL(th.peer_offered_capabilities[0], proton::symbol("offered")); ASSERT_EQUAL(th.peer_desired_capabilities.size(), 1); ASSERT_EQUAL(th.peer_desired_capabilities[0], proton::symbol("desired")); return 0; } int test_container_bad_address() { // Listen on a bad address, check for leaks // Regression test for https://issues.apache.org/jira/browse/PROTON-1217 proton::container c; // Default fixed-option listener. Valgrind for leaks. try { c.listen("999.666.999.666:0"); } catch (const proton::error&) {} c.run(); // Dummy listener. test_listen_handler l; test_handler h2("999.999.999.666", proton::connection_options()); try { c.listen("999.666.999.666:0", l); } catch (const proton::error&) {} c.run(); ASSERT(!l.on_open_); ASSERT(!l.on_accept_); ASSERT(l.on_close_); ASSERT(!l.on_error_.empty()); return 0; } class stop_tester : public proton::messaging_handler { proton::listener listener; test_listen_handler listen_handler; // Set up a listener which would block forever void on_container_start(proton::container& c) PN_CPP_OVERRIDE { ASSERT(state==0); listener = c.listen("//:0", listen_handler); c.auto_stop(false); state = 1; } // Get here twice - once for listener, once for connector void on_connection_open(proton::connection &c) PN_CPP_OVERRIDE { c.close(); state++; } void on_connection_close(proton::connection &c) PN_CPP_OVERRIDE { ASSERT(state==3); c.container().stop(); state = 4; } void on_container_stop(proton::container & ) PN_CPP_OVERRIDE { ASSERT(state==4); state = 5; } void on_transport_error(proton::transport & t) PN_CPP_OVERRIDE { // Do nothing - ignore transport errors - we're going to get one when // the container stops. } public: stop_tester(): state(0) {} int state; }; int test_container_stop() { stop_tester t; proton::container(t).run(); ASSERT(t.state==5); return 0; } struct hang_tester : public proton::messaging_handler { proton::listener listener; bool done; hang_tester() : done(false) {} void connect(proton::container* c) { c->connect(make_url("", listener.port())); } void on_container_start(proton::container& c) PN_CPP_OVERRIDE { listener = c.listen("//:0"); c.schedule(proton::duration(250), proton::make_work(&hang_tester::connect, this, &c)); } void on_connection_open(proton::connection& c) PN_CPP_OVERRIDE { c.close(); } void on_connection_close(proton::connection& c) PN_CPP_OVERRIDE { if (!done) { done = true; listener.stop(); } } }; int test_container_schedule_nohang() { hang_tester t; proton::container(t).run(); return 0; } class immediate_stop_tester : public proton::messaging_handler { public: void on_container_start(proton::container &c) PN_CPP_OVERRIDE { c.stop(); } }; int test_container_immediate_stop() { immediate_stop_tester t; proton::container(t).run(); // Should return after on_container_start return 0; } int test_container_pre_stop() { proton::container c; c.stop(); c.run(); // Should return immediately return 0; } struct schedule_tester : public proton::messaging_handler { void stop(proton::container* c) { c->stop(); } void on_container_start(proton::container& c) PN_CPP_OVERRIDE { c.schedule(proton::duration(250), proton::make_work(&schedule_tester::stop, this, &c)); } }; int test_container_schedule_stop() { schedule_tester tester; proton::container c(tester); c.auto_stop(false); c.run(); return 0; } #if PN_CPP_SUPPORTS_THREADS // Tests that require thread support class test_mt_handler : public proton::messaging_handler { public: std::mutex lock_; std::condition_variable cond_; std::string str_; proton::error_condition err_; void set(const std::string& s) { std::lock_guard<std::mutex> l(lock_); str_ = s; cond_.notify_one(); } std::string wait() { std::unique_lock<std::mutex> l(lock_); while (str_.empty()) cond_.wait(l); std::string s = str_; str_.clear(); return s; } proton::error_condition error() const { return err_; } void on_container_start(proton::container &) PN_CPP_OVERRIDE { set("start"); } void on_connection_open(proton::connection &) PN_CPP_OVERRIDE { set("open"); } // Catch errors and save. void on_error(const proton::error_condition& e) PN_CPP_OVERRIDE { err_ = e; } }; class container_runner { proton::container& c_; public: container_runner(proton::container& c) : c_(c) {} void operator()() {c_.run();} }; void test_container_mt_stop_empty() { test_mt_handler th; proton::container c(th); c.auto_stop( false ); container_runner runner(c); auto t = std::thread(runner); // Must ensure that thread is joined or detached try { ASSERT_EQUAL("start", th.wait()); c.stop(); t.join(); ASSERT_EQUAL("", th.error().name()); } catch (...) { // We don't join as we don't know if we'll be stuck waiting if (t.joinable()) { t.detach(); } } } void test_container_mt_stop() { test_mt_handler th; proton::container c(th); c.auto_stop(false); container_runner runner(c); auto t = std::thread(runner); // Must ensure that thread is joined or detached try { test_listen_handler lh; c.listen("//:0", lh); // Also opens a connection ASSERT_EQUAL("start", th.wait()); ASSERT_EQUAL("open", th.wait()); c.stop(); t.join(); } catch (...) { // We don't join as we don't know if we'll be stuck waiting if (t.joinable()) { t.detach(); } } } #endif } // namespace int main(int argc, char** argv) { int failed = 0; RUN_ARGV_TEST(failed, test_container_default_container_id()); RUN_ARGV_TEST(failed, test_container_vhost()); RUN_ARGV_TEST(failed, test_container_capabilities()); RUN_ARGV_TEST(failed, test_container_default_vhost()); RUN_ARGV_TEST(failed, test_container_no_vhost()); RUN_ARGV_TEST(failed, test_container_bad_address()); RUN_ARGV_TEST(failed, test_container_stop()); RUN_ARGV_TEST(failed, test_container_schedule_nohang()); RUN_ARGV_TEST(failed, test_container_immediate_stop()); RUN_ARGV_TEST(failed, test_container_pre_stop()); RUN_ARGV_TEST(failed, test_container_schedule_stop()); #if PN_CPP_SUPPORTS_THREADS RUN_ARGV_TEST(failed, test_container_mt_stop_empty()); RUN_ARGV_TEST(failed, test_container_mt_stop()); #endif return failed; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: Mapping.test.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2007-03-14 08:31:58 $ * * 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 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 * ************************************************************************/ // Test for uno/mapping.hxx respectively com::sun::star::uno::Mapping #include <iostream> #include "sal/main.h" #include "uno/mapping.hxx" using namespace com::sun::star; static rtl::OUString s_comment; static void s_test__constructor_env_env(void) { s_comment += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("\ts_test__constructor_env_env\n")); uno::Mapping mapping(uno::Environment(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(UNO_LB_UNO))), uno::Environment(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(CPPU_CURRENT_LANGUAGE_BINDING_NAME)))); if (!mapping.get()) s_comment += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("\t\tcouldn't get a Mapping - FAILURE\n")); } SAL_IMPLEMENT_MAIN_WITH_ARGS(/*argc*/, argv) { s_test__constructor_env_env(); int ret; if (s_comment.indexOf(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("FAILURE"))) == -1) { s_comment += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("TESTS PASSED\n")); ret = 0; } else { s_comment += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("TESTS _NOT_ PASSED\n")); ret = -1; } std::cerr << argv[0] << std::endl << rtl::OUStringToOString(s_comment, RTL_TEXTENCODING_ASCII_US).getStr() << std::endl; return ret; } <commit_msg>INTEGRATION: CWS bunoexttm (1.2.20); FILE MERGED 2007/01/25 14:13:08 kr 1.2.20.1: fixed: license<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: Mapping.test.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2007-05-09 13:40:02 $ * * 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 * ************************************************************************/ // Test for uno/mapping.hxx respectively com::sun::star::uno::Mapping #include <iostream> #include "sal/main.h" #include "uno/mapping.hxx" using namespace com::sun::star; static rtl::OUString s_comment; static void s_test__constructor_env_env(void) { s_comment += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("\ts_test__constructor_env_env\n")); uno::Mapping mapping(uno::Environment(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(UNO_LB_UNO))), uno::Environment(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(CPPU_CURRENT_LANGUAGE_BINDING_NAME)))); if (!mapping.get()) s_comment += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("\t\tcouldn't get a Mapping - FAILURE\n")); } SAL_IMPLEMENT_MAIN_WITH_ARGS(/*argc*/, argv) { s_test__constructor_env_env(); int ret; if (s_comment.indexOf(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("FAILURE"))) == -1) { s_comment += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("TESTS PASSED\n")); ret = 0; } else { s_comment += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("TESTS _NOT_ PASSED\n")); ret = -1; } std::cerr << argv[0] << std::endl << rtl::OUStringToOString(s_comment, RTL_TEXTENCODING_ASCII_US).getStr() << std::endl; return ret; } <|endoftext|>
<commit_before>//===- ARCRegisterInfo.cpp - ARC Register Information -----------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains the ARC implementation of the MRegisterInfo class. // //===----------------------------------------------------------------------===// #include "ARCRegisterInfo.h" #include "ARC.h" #include "ARCInstrInfo.h" #include "ARCMachineFunctionInfo.h" #include "ARCSubtarget.h" #include "llvm/ADT/BitVector.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/RegisterScavenging.h" #include "llvm/IR/Function.h" #include "llvm/Support/Debug.h" #include "llvm/CodeGen/TargetFrameLowering.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; #define DEBUG_TYPE "arc-reg-info" #define GET_REGINFO_TARGET_DESC #include "ARCGenRegisterInfo.inc" static void ReplaceFrameIndex(MachineBasicBlock::iterator II, const ARCInstrInfo &TII, unsigned Reg, unsigned FrameReg, int Offset, int StackSize, int ObjSize, RegScavenger *RS, int SPAdj) { assert(RS && "Need register scavenger."); MachineInstr &MI = *II; MachineBasicBlock &MBB = *MI.getParent(); DebugLoc dl = MI.getDebugLoc(); unsigned BaseReg = FrameReg; unsigned KillState = 0; if (MI.getOpcode() == ARC::LD_rs9 && (Offset >= 256 || Offset < -256)) { // Loads can always be reached with LD_rlimm. BuildMI(MBB, II, dl, TII.get(ARC::LD_rlimm), Reg) .addReg(BaseReg) .addImm(Offset) .addMemOperand(*MI.memoperands_begin()); MBB.erase(II); return; } if (MI.getOpcode() != ARC::GETFI && (Offset >= 256 || Offset < -256)) { // We need to use a scratch register to reach the far-away frame indexes. BaseReg = RS->FindUnusedReg(&ARC::GPR32RegClass); if (!BaseReg) { // We can be sure that the scavenged-register slot is within the range // of the load offset. const TargetRegisterInfo *TRI = MBB.getParent()->getSubtarget().getRegisterInfo(); BaseReg = RS->scavengeRegister(&ARC::GPR32RegClass, II, SPAdj); assert(BaseReg && "Register scavenging failed."); LLVM_DEBUG(dbgs() << "Scavenged register " << printReg(BaseReg, TRI) << " for FrameReg=" << printReg(FrameReg, TRI) << "+Offset=" << Offset << "\n"); (void)TRI; RS->setRegUsed(BaseReg); } unsigned AddOpc = isUInt<6>(Offset) ? ARC::ADD_rru6 : ARC::ADD_rrlimm; BuildMI(MBB, II, dl, TII.get(AddOpc)) .addReg(BaseReg, RegState::Define) .addReg(FrameReg) .addImm(Offset); Offset = 0; KillState = RegState::Kill; } switch (MI.getOpcode()) { case ARC::LD_rs9: assert((Offset % 4 == 0) && "LD needs 4 byte alignment."); case ARC::LDH_rs9: case ARC::LDH_X_rs9: assert((Offset % 2 == 0) && "LDH needs 2 byte alignment."); case ARC::LDB_rs9: case ARC::LDB_X_rs9: LLVM_DEBUG(dbgs() << "Building LDFI\n"); BuildMI(MBB, II, dl, TII.get(MI.getOpcode()), Reg) .addReg(BaseReg, KillState) .addImm(Offset) .addMemOperand(*MI.memoperands_begin()); break; case ARC::ST_rs9: assert((Offset % 4 == 0) && "ST needs 4 byte alignment."); case ARC::STH_rs9: assert((Offset % 2 == 0) && "STH needs 2 byte alignment."); case ARC::STB_rs9: LLVM_DEBUG(dbgs() << "Building STFI\n"); BuildMI(MBB, II, dl, TII.get(MI.getOpcode())) .addReg(Reg, getKillRegState(MI.getOperand(0).isKill())) .addReg(BaseReg, KillState) .addImm(Offset) .addMemOperand(*MI.memoperands_begin()); break; case ARC::GETFI: LLVM_DEBUG(dbgs() << "Building GETFI\n"); BuildMI(MBB, II, dl, TII.get(isUInt<6>(Offset) ? ARC::ADD_rru6 : ARC::ADD_rrlimm)) .addReg(Reg, RegState::Define) .addReg(FrameReg) .addImm(Offset); break; default: llvm_unreachable("Unhandled opcode."); } // Erase old instruction. MBB.erase(II); } ARCRegisterInfo::ARCRegisterInfo() : ARCGenRegisterInfo(ARC::BLINK) {} bool ARCRegisterInfo::needsFrameMoves(const MachineFunction &MF) { return MF.getMMI().hasDebugInfo() || MF.getFunction().needsUnwindTableEntry(); } const MCPhysReg * ARCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const { return CSR_ARC_SaveList; } BitVector ARCRegisterInfo::getReservedRegs(const MachineFunction &MF) const { BitVector Reserved(getNumRegs()); Reserved.set(ARC::ILINK); Reserved.set(ARC::SP); Reserved.set(ARC::GP); Reserved.set(ARC::R25); Reserved.set(ARC::BLINK); Reserved.set(ARC::FP); return Reserved; } bool ARCRegisterInfo::requiresRegisterScavenging( const MachineFunction &MF) const { return true; } bool ARCRegisterInfo::trackLivenessAfterRegAlloc( const MachineFunction &MF) const { return true; } bool ARCRegisterInfo::useFPForScavengingIndex(const MachineFunction &MF) const { return true; } void ARCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj, unsigned FIOperandNum, RegScavenger *RS) const { assert(SPAdj == 0 && "Unexpected"); MachineInstr &MI = *II; MachineOperand &FrameOp = MI.getOperand(FIOperandNum); int FrameIndex = FrameOp.getIndex(); MachineFunction &MF = *MI.getParent()->getParent(); const ARCInstrInfo &TII = *MF.getSubtarget<ARCSubtarget>().getInstrInfo(); const ARCFrameLowering *TFI = getFrameLowering(MF); int Offset = MF.getFrameInfo().getObjectOffset(FrameIndex); int ObjSize = MF.getFrameInfo().getObjectSize(FrameIndex); int StackSize = MF.getFrameInfo().getStackSize(); int LocalFrameSize = MF.getFrameInfo().getLocalFrameSize(); LLVM_DEBUG(dbgs() << "\nFunction : " << MF.getName() << "\n"); LLVM_DEBUG(dbgs() << "<--------->\n"); LLVM_DEBUG(dbgs() << MI << "\n"); LLVM_DEBUG(dbgs() << "FrameIndex : " << FrameIndex << "\n"); LLVM_DEBUG(dbgs() << "ObjSize : " << ObjSize << "\n"); LLVM_DEBUG(dbgs() << "FrameOffset : " << Offset << "\n"); LLVM_DEBUG(dbgs() << "StackSize : " << StackSize << "\n"); LLVM_DEBUG(dbgs() << "LocalFrameSize : " << LocalFrameSize << "\n"); (void)LocalFrameSize; // Special handling of DBG_VALUE instructions. if (MI.isDebugValue()) { Register FrameReg = getFrameRegister(MF); MI.getOperand(FIOperandNum).ChangeToRegister(FrameReg, false /*isDef*/); MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset); return; } // fold constant into offset. Offset += MI.getOperand(FIOperandNum + 1).getImm(); // TODO: assert based on the load type: // ldb needs no alignment, // ldh needs 2 byte alignment // ld needs 4 byte alignment LLVM_DEBUG(dbgs() << "Offset : " << Offset << "\n" << "<--------->\n"); unsigned Reg = MI.getOperand(0).getReg(); assert(ARC::GPR32RegClass.contains(Reg) && "Unexpected register operand"); if (!TFI->hasFP(MF)) { Offset = StackSize + Offset; if (FrameIndex >= 0) assert((Offset >= 0 && Offset < StackSize) && "SP Offset not in bounds."); } else { if (FrameIndex >= 0) { assert((Offset < 0 && -Offset <= StackSize) && "FP Offset not in bounds."); } } ReplaceFrameIndex(II, TII, Reg, getFrameRegister(MF), Offset, StackSize, ObjSize, RS, SPAdj); } Register ARCRegisterInfo::getFrameRegister(const MachineFunction &MF) const { const ARCFrameLowering *TFI = getFrameLowering(MF); return TFI->hasFP(MF) ? ARC::FP : ARC::SP; } const uint32_t * ARCRegisterInfo::getCallPreservedMask(const MachineFunction &MF, CallingConv::ID CC) const { return CSR_ARC_RegMask; } <commit_msg>ARC: Fix -Wimplicit-fallthrough<commit_after>//===- ARCRegisterInfo.cpp - ARC Register Information -----------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains the ARC implementation of the MRegisterInfo class. // //===----------------------------------------------------------------------===// #include "ARCRegisterInfo.h" #include "ARC.h" #include "ARCInstrInfo.h" #include "ARCMachineFunctionInfo.h" #include "ARCSubtarget.h" #include "llvm/ADT/BitVector.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/RegisterScavenging.h" #include "llvm/IR/Function.h" #include "llvm/Support/Debug.h" #include "llvm/CodeGen/TargetFrameLowering.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; #define DEBUG_TYPE "arc-reg-info" #define GET_REGINFO_TARGET_DESC #include "ARCGenRegisterInfo.inc" static void ReplaceFrameIndex(MachineBasicBlock::iterator II, const ARCInstrInfo &TII, unsigned Reg, unsigned FrameReg, int Offset, int StackSize, int ObjSize, RegScavenger *RS, int SPAdj) { assert(RS && "Need register scavenger."); MachineInstr &MI = *II; MachineBasicBlock &MBB = *MI.getParent(); DebugLoc dl = MI.getDebugLoc(); unsigned BaseReg = FrameReg; unsigned KillState = 0; if (MI.getOpcode() == ARC::LD_rs9 && (Offset >= 256 || Offset < -256)) { // Loads can always be reached with LD_rlimm. BuildMI(MBB, II, dl, TII.get(ARC::LD_rlimm), Reg) .addReg(BaseReg) .addImm(Offset) .addMemOperand(*MI.memoperands_begin()); MBB.erase(II); return; } if (MI.getOpcode() != ARC::GETFI && (Offset >= 256 || Offset < -256)) { // We need to use a scratch register to reach the far-away frame indexes. BaseReg = RS->FindUnusedReg(&ARC::GPR32RegClass); if (!BaseReg) { // We can be sure that the scavenged-register slot is within the range // of the load offset. const TargetRegisterInfo *TRI = MBB.getParent()->getSubtarget().getRegisterInfo(); BaseReg = RS->scavengeRegister(&ARC::GPR32RegClass, II, SPAdj); assert(BaseReg && "Register scavenging failed."); LLVM_DEBUG(dbgs() << "Scavenged register " << printReg(BaseReg, TRI) << " for FrameReg=" << printReg(FrameReg, TRI) << "+Offset=" << Offset << "\n"); (void)TRI; RS->setRegUsed(BaseReg); } unsigned AddOpc = isUInt<6>(Offset) ? ARC::ADD_rru6 : ARC::ADD_rrlimm; BuildMI(MBB, II, dl, TII.get(AddOpc)) .addReg(BaseReg, RegState::Define) .addReg(FrameReg) .addImm(Offset); Offset = 0; KillState = RegState::Kill; } switch (MI.getOpcode()) { case ARC::LD_rs9: assert((Offset % 4 == 0) && "LD needs 4 byte alignment."); LLVM_FALLTHROUGH; case ARC::LDH_rs9: case ARC::LDH_X_rs9: assert((Offset % 2 == 0) && "LDH needs 2 byte alignment."); LLVM_FALLTHROUGH; case ARC::LDB_rs9: case ARC::LDB_X_rs9: LLVM_DEBUG(dbgs() << "Building LDFI\n"); BuildMI(MBB, II, dl, TII.get(MI.getOpcode()), Reg) .addReg(BaseReg, KillState) .addImm(Offset) .addMemOperand(*MI.memoperands_begin()); break; case ARC::ST_rs9: assert((Offset % 4 == 0) && "ST needs 4 byte alignment."); LLVM_FALLTHROUGH; case ARC::STH_rs9: assert((Offset % 2 == 0) && "STH needs 2 byte alignment."); LLVM_FALLTHROUGH; case ARC::STB_rs9: LLVM_DEBUG(dbgs() << "Building STFI\n"); BuildMI(MBB, II, dl, TII.get(MI.getOpcode())) .addReg(Reg, getKillRegState(MI.getOperand(0).isKill())) .addReg(BaseReg, KillState) .addImm(Offset) .addMemOperand(*MI.memoperands_begin()); break; case ARC::GETFI: LLVM_DEBUG(dbgs() << "Building GETFI\n"); BuildMI(MBB, II, dl, TII.get(isUInt<6>(Offset) ? ARC::ADD_rru6 : ARC::ADD_rrlimm)) .addReg(Reg, RegState::Define) .addReg(FrameReg) .addImm(Offset); break; default: llvm_unreachable("Unhandled opcode."); } // Erase old instruction. MBB.erase(II); } ARCRegisterInfo::ARCRegisterInfo() : ARCGenRegisterInfo(ARC::BLINK) {} bool ARCRegisterInfo::needsFrameMoves(const MachineFunction &MF) { return MF.getMMI().hasDebugInfo() || MF.getFunction().needsUnwindTableEntry(); } const MCPhysReg * ARCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const { return CSR_ARC_SaveList; } BitVector ARCRegisterInfo::getReservedRegs(const MachineFunction &MF) const { BitVector Reserved(getNumRegs()); Reserved.set(ARC::ILINK); Reserved.set(ARC::SP); Reserved.set(ARC::GP); Reserved.set(ARC::R25); Reserved.set(ARC::BLINK); Reserved.set(ARC::FP); return Reserved; } bool ARCRegisterInfo::requiresRegisterScavenging( const MachineFunction &MF) const { return true; } bool ARCRegisterInfo::trackLivenessAfterRegAlloc( const MachineFunction &MF) const { return true; } bool ARCRegisterInfo::useFPForScavengingIndex(const MachineFunction &MF) const { return true; } void ARCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj, unsigned FIOperandNum, RegScavenger *RS) const { assert(SPAdj == 0 && "Unexpected"); MachineInstr &MI = *II; MachineOperand &FrameOp = MI.getOperand(FIOperandNum); int FrameIndex = FrameOp.getIndex(); MachineFunction &MF = *MI.getParent()->getParent(); const ARCInstrInfo &TII = *MF.getSubtarget<ARCSubtarget>().getInstrInfo(); const ARCFrameLowering *TFI = getFrameLowering(MF); int Offset = MF.getFrameInfo().getObjectOffset(FrameIndex); int ObjSize = MF.getFrameInfo().getObjectSize(FrameIndex); int StackSize = MF.getFrameInfo().getStackSize(); int LocalFrameSize = MF.getFrameInfo().getLocalFrameSize(); LLVM_DEBUG(dbgs() << "\nFunction : " << MF.getName() << "\n"); LLVM_DEBUG(dbgs() << "<--------->\n"); LLVM_DEBUG(dbgs() << MI << "\n"); LLVM_DEBUG(dbgs() << "FrameIndex : " << FrameIndex << "\n"); LLVM_DEBUG(dbgs() << "ObjSize : " << ObjSize << "\n"); LLVM_DEBUG(dbgs() << "FrameOffset : " << Offset << "\n"); LLVM_DEBUG(dbgs() << "StackSize : " << StackSize << "\n"); LLVM_DEBUG(dbgs() << "LocalFrameSize : " << LocalFrameSize << "\n"); (void)LocalFrameSize; // Special handling of DBG_VALUE instructions. if (MI.isDebugValue()) { Register FrameReg = getFrameRegister(MF); MI.getOperand(FIOperandNum).ChangeToRegister(FrameReg, false /*isDef*/); MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset); return; } // fold constant into offset. Offset += MI.getOperand(FIOperandNum + 1).getImm(); // TODO: assert based on the load type: // ldb needs no alignment, // ldh needs 2 byte alignment // ld needs 4 byte alignment LLVM_DEBUG(dbgs() << "Offset : " << Offset << "\n" << "<--------->\n"); unsigned Reg = MI.getOperand(0).getReg(); assert(ARC::GPR32RegClass.contains(Reg) && "Unexpected register operand"); if (!TFI->hasFP(MF)) { Offset = StackSize + Offset; if (FrameIndex >= 0) assert((Offset >= 0 && Offset < StackSize) && "SP Offset not in bounds."); } else { if (FrameIndex >= 0) { assert((Offset < 0 && -Offset <= StackSize) && "FP Offset not in bounds."); } } ReplaceFrameIndex(II, TII, Reg, getFrameRegister(MF), Offset, StackSize, ObjSize, RS, SPAdj); } Register ARCRegisterInfo::getFrameRegister(const MachineFunction &MF) const { const ARCFrameLowering *TFI = getFrameLowering(MF); return TFI->hasFP(MF) ? ARC::FP : ARC::SP; } const uint32_t * ARCRegisterInfo::getCallPreservedMask(const MachineFunction &MF, CallingConv::ID CC) const { return CSR_ARC_RegMask; } <|endoftext|>
<commit_before>//===-- SIFoldOperands.cpp - Fold operands --- ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // /// \file //===----------------------------------------------------------------------===// // #include "AMDGPU.h" #include "AMDGPUSubtarget.h" #include "SIInstrInfo.h" #include "llvm/CodeGen/LiveIntervalAnalysis.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Function.h" #include "llvm/Support/Debug.h" #include "llvm/Target/TargetMachine.h" #define DEBUG_TYPE "si-fold-operands" using namespace llvm; namespace { class SIFoldOperands : public MachineFunctionPass { public: static char ID; public: SIFoldOperands() : MachineFunctionPass(ID) { initializeSIFoldOperandsPass(*PassRegistry::getPassRegistry()); } bool runOnMachineFunction(MachineFunction &MF) override; const char *getPassName() const override { return "SI Fold Operands"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<MachineDominatorTree>(); AU.setPreservesCFG(); MachineFunctionPass::getAnalysisUsage(AU); } }; struct FoldCandidate { MachineInstr *UseMI; unsigned UseOpNo; MachineOperand *OpToFold; uint64_t ImmToFold; FoldCandidate(MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp) : UseMI(MI), UseOpNo(OpNo) { if (FoldOp->isImm()) { OpToFold = nullptr; ImmToFold = FoldOp->getImm(); } else { assert(FoldOp->isReg()); OpToFold = FoldOp; } } bool isImm() const { return !OpToFold; } }; } // End anonymous namespace. INITIALIZE_PASS_BEGIN(SIFoldOperands, DEBUG_TYPE, "SI Fold Operands", false, false) INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) INITIALIZE_PASS_END(SIFoldOperands, DEBUG_TYPE, "SI Fold Operands", false, false) char SIFoldOperands::ID = 0; char &llvm::SIFoldOperandsID = SIFoldOperands::ID; FunctionPass *llvm::createSIFoldOperandsPass() { return new SIFoldOperands(); } static bool isSafeToFold(unsigned Opcode) { switch(Opcode) { case AMDGPU::V_MOV_B32_e32: case AMDGPU::V_MOV_B32_e64: case AMDGPU::V_MOV_B64_PSEUDO: case AMDGPU::S_MOV_B32: case AMDGPU::S_MOV_B64: case AMDGPU::COPY: return true; default: return false; } } static bool updateOperand(FoldCandidate &Fold, const TargetRegisterInfo &TRI) { MachineInstr *MI = Fold.UseMI; MachineOperand &Old = MI->getOperand(Fold.UseOpNo); assert(Old.isReg()); if (Fold.isImm()) { Old.ChangeToImmediate(Fold.ImmToFold); return true; } MachineOperand *New = Fold.OpToFold; if (TargetRegisterInfo::isVirtualRegister(Old.getReg()) && TargetRegisterInfo::isVirtualRegister(New->getReg())) { Old.substVirtReg(New->getReg(), New->getSubReg(), TRI); return true; } // FIXME: Handle physical registers. return false; } static bool tryAddToFoldList(std::vector<FoldCandidate> &FoldList, MachineInstr *MI, unsigned OpNo, MachineOperand *OpToFold, const SIInstrInfo *TII) { if (!TII->isOperandLegal(MI, OpNo, OpToFold)) { // Operand is not legal, so try to commute the instruction to // see if this makes it possible to fold. unsigned CommuteIdx0; unsigned CommuteIdx1; bool CanCommute = TII->findCommutedOpIndices(MI, CommuteIdx0, CommuteIdx1); if (CanCommute) { if (CommuteIdx0 == OpNo) OpNo = CommuteIdx1; else if (CommuteIdx1 == OpNo) OpNo = CommuteIdx0; } if (!CanCommute || !TII->commuteInstruction(MI)) return false; if (!TII->isOperandLegal(MI, OpNo, OpToFold)) return false; } FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold)); return true; } bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) { MachineRegisterInfo &MRI = MF.getRegInfo(); const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(MF.getSubtarget().getInstrInfo()); const SIRegisterInfo &TRI = TII->getRegisterInfo(); for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE; ++BI) { MachineBasicBlock &MBB = *BI; MachineBasicBlock::iterator I, Next; for (I = MBB.begin(); I != MBB.end(); I = Next) { Next = std::next(I); MachineInstr &MI = *I; if (!isSafeToFold(MI.getOpcode())) continue; unsigned OpSize = TII->getOpSize(MI, 1); MachineOperand &OpToFold = MI.getOperand(1); bool FoldingImm = OpToFold.isImm(); // FIXME: We could also be folding things like FrameIndexes and // TargetIndexes. if (!FoldingImm && !OpToFold.isReg()) continue; // Folding immediates with more than one use will increase program size. // FIXME: This will also reduce register usage, which may be better // in some cases. A better heuristic is needed. if (FoldingImm && !TII->isInlineConstant(OpToFold, OpSize) && !MRI.hasOneUse(MI.getOperand(0).getReg())) continue; // FIXME: Fold operands with subregs. if (OpToFold.isReg() && (!TargetRegisterInfo::isVirtualRegister(OpToFold.getReg()) || OpToFold.getSubReg())) continue; std::vector<FoldCandidate> FoldList; for (MachineRegisterInfo::use_iterator Use = MRI.use_begin(MI.getOperand(0).getReg()), E = MRI.use_end(); Use != E; ++Use) { MachineInstr *UseMI = Use->getParent(); const MachineOperand &UseOp = UseMI->getOperand(Use.getOperandNo()); // FIXME: Fold operands with subregs. if (UseOp.isReg() && UseOp.getSubReg() && OpToFold.isReg()) { continue; } APInt Imm; if (FoldingImm) { const TargetRegisterClass *UseRC = MRI.getRegClass(UseOp.getReg()); Imm = APInt(64, OpToFold.getImm()); // Split 64-bit constants into 32-bits for folding. if (UseOp.getSubReg()) { if (UseRC->getSize() != 8) continue; if (UseOp.getSubReg() == AMDGPU::sub0) { Imm = Imm.getLoBits(32); } else { assert(UseOp.getSubReg() == AMDGPU::sub1); Imm = Imm.getHiBits(32); } } // In order to fold immediates into copies, we need to change the // copy to a MOV. if (UseMI->getOpcode() == AMDGPU::COPY) { unsigned MovOp = TII->getMovOpcode( MRI.getRegClass(UseMI->getOperand(0).getReg())); if (MovOp == AMDGPU::COPY) continue; UseMI->setDesc(TII->get(MovOp)); } } const MCInstrDesc &UseDesc = UseMI->getDesc(); // Don't fold into target independent nodes. Target independent opcodes // don't have defined register classes. if (UseDesc.isVariadic() || UseDesc.OpInfo[Use.getOperandNo()].RegClass == -1) continue; if (FoldingImm) { MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue()); tryAddToFoldList(FoldList, UseMI, Use.getOperandNo(), &ImmOp, TII); continue; } tryAddToFoldList(FoldList, UseMI, Use.getOperandNo(), &OpToFold, TII); // FIXME: We could try to change the instruction from 64-bit to 32-bit // to enable more folding opportunites. The shrink operands pass // already does this. } for (FoldCandidate &Fold : FoldList) { if (updateOperand(Fold, TRI)) { // Clear kill flags. if (!Fold.isImm()) { assert(Fold.OpToFold && Fold.OpToFold->isReg()); Fold.OpToFold->setIsKill(false); } DEBUG(dbgs() << "Folded source from " << MI << " into OpNo " << Fold.UseOpNo << " of " << *Fold.UseMI << '\n'); } } } } return false; } <commit_msg>R600/SI: Fix phys reg copies in SIFoldOperands<commit_after>//===-- SIFoldOperands.cpp - Fold operands --- ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // /// \file //===----------------------------------------------------------------------===// // #include "AMDGPU.h" #include "AMDGPUSubtarget.h" #include "SIInstrInfo.h" #include "llvm/CodeGen/LiveIntervalAnalysis.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Function.h" #include "llvm/Support/Debug.h" #include "llvm/Target/TargetMachine.h" #define DEBUG_TYPE "si-fold-operands" using namespace llvm; namespace { class SIFoldOperands : public MachineFunctionPass { public: static char ID; public: SIFoldOperands() : MachineFunctionPass(ID) { initializeSIFoldOperandsPass(*PassRegistry::getPassRegistry()); } bool runOnMachineFunction(MachineFunction &MF) override; const char *getPassName() const override { return "SI Fold Operands"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<MachineDominatorTree>(); AU.setPreservesCFG(); MachineFunctionPass::getAnalysisUsage(AU); } }; struct FoldCandidate { MachineInstr *UseMI; unsigned UseOpNo; MachineOperand *OpToFold; uint64_t ImmToFold; FoldCandidate(MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp) : UseMI(MI), UseOpNo(OpNo) { if (FoldOp->isImm()) { OpToFold = nullptr; ImmToFold = FoldOp->getImm(); } else { assert(FoldOp->isReg()); OpToFold = FoldOp; } } bool isImm() const { return !OpToFold; } }; } // End anonymous namespace. INITIALIZE_PASS_BEGIN(SIFoldOperands, DEBUG_TYPE, "SI Fold Operands", false, false) INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) INITIALIZE_PASS_END(SIFoldOperands, DEBUG_TYPE, "SI Fold Operands", false, false) char SIFoldOperands::ID = 0; char &llvm::SIFoldOperandsID = SIFoldOperands::ID; FunctionPass *llvm::createSIFoldOperandsPass() { return new SIFoldOperands(); } static bool isSafeToFold(unsigned Opcode) { switch(Opcode) { case AMDGPU::V_MOV_B32_e32: case AMDGPU::V_MOV_B32_e64: case AMDGPU::V_MOV_B64_PSEUDO: case AMDGPU::S_MOV_B32: case AMDGPU::S_MOV_B64: case AMDGPU::COPY: return true; default: return false; } } static bool updateOperand(FoldCandidate &Fold, const TargetRegisterInfo &TRI) { MachineInstr *MI = Fold.UseMI; MachineOperand &Old = MI->getOperand(Fold.UseOpNo); assert(Old.isReg()); if (Fold.isImm()) { Old.ChangeToImmediate(Fold.ImmToFold); return true; } MachineOperand *New = Fold.OpToFold; if (TargetRegisterInfo::isVirtualRegister(Old.getReg()) && TargetRegisterInfo::isVirtualRegister(New->getReg())) { Old.substVirtReg(New->getReg(), New->getSubReg(), TRI); return true; } // FIXME: Handle physical registers. return false; } static bool tryAddToFoldList(std::vector<FoldCandidate> &FoldList, MachineInstr *MI, unsigned OpNo, MachineOperand *OpToFold, const SIInstrInfo *TII) { if (!TII->isOperandLegal(MI, OpNo, OpToFold)) { // Operand is not legal, so try to commute the instruction to // see if this makes it possible to fold. unsigned CommuteIdx0; unsigned CommuteIdx1; bool CanCommute = TII->findCommutedOpIndices(MI, CommuteIdx0, CommuteIdx1); if (CanCommute) { if (CommuteIdx0 == OpNo) OpNo = CommuteIdx1; else if (CommuteIdx1 == OpNo) OpNo = CommuteIdx0; } if (!CanCommute || !TII->commuteInstruction(MI)) return false; if (!TII->isOperandLegal(MI, OpNo, OpToFold)) return false; } FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold)); return true; } bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) { MachineRegisterInfo &MRI = MF.getRegInfo(); const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(MF.getSubtarget().getInstrInfo()); const SIRegisterInfo &TRI = TII->getRegisterInfo(); for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE; ++BI) { MachineBasicBlock &MBB = *BI; MachineBasicBlock::iterator I, Next; for (I = MBB.begin(); I != MBB.end(); I = Next) { Next = std::next(I); MachineInstr &MI = *I; if (!isSafeToFold(MI.getOpcode())) continue; unsigned OpSize = TII->getOpSize(MI, 1); MachineOperand &OpToFold = MI.getOperand(1); bool FoldingImm = OpToFold.isImm(); // FIXME: We could also be folding things like FrameIndexes and // TargetIndexes. if (!FoldingImm && !OpToFold.isReg()) continue; // Folding immediates with more than one use will increase program size. // FIXME: This will also reduce register usage, which may be better // in some cases. A better heuristic is needed. if (FoldingImm && !TII->isInlineConstant(OpToFold, OpSize) && !MRI.hasOneUse(MI.getOperand(0).getReg())) continue; // FIXME: Fold operands with subregs. if (OpToFold.isReg() && (!TargetRegisterInfo::isVirtualRegister(OpToFold.getReg()) || OpToFold.getSubReg())) continue; std::vector<FoldCandidate> FoldList; for (MachineRegisterInfo::use_iterator Use = MRI.use_begin(MI.getOperand(0).getReg()), E = MRI.use_end(); Use != E; ++Use) { MachineInstr *UseMI = Use->getParent(); const MachineOperand &UseOp = UseMI->getOperand(Use.getOperandNo()); // FIXME: Fold operands with subregs. if (UseOp.isReg() && UseOp.getSubReg() && OpToFold.isReg()) { continue; } APInt Imm; if (FoldingImm) { unsigned UseReg = UseOp.getReg(); const TargetRegisterClass *UseRC = TargetRegisterInfo::isVirtualRegister(UseReg) ? MRI.getRegClass(UseReg) : TRI.getRegClass(UseReg); Imm = APInt(64, OpToFold.getImm()); // Split 64-bit constants into 32-bits for folding. if (UseOp.getSubReg()) { if (UseRC->getSize() != 8) continue; if (UseOp.getSubReg() == AMDGPU::sub0) { Imm = Imm.getLoBits(32); } else { assert(UseOp.getSubReg() == AMDGPU::sub1); Imm = Imm.getHiBits(32); } } // In order to fold immediates into copies, we need to change the // copy to a MOV. if (UseMI->getOpcode() == AMDGPU::COPY) { unsigned DestReg = UseMI->getOperand(0).getReg(); const TargetRegisterClass *DestRC = TargetRegisterInfo::isVirtualRegister(DestReg) ? MRI.getRegClass(DestReg) : TRI.getRegClass(DestReg); unsigned MovOp = TII->getMovOpcode(DestRC); if (MovOp == AMDGPU::COPY) continue; UseMI->setDesc(TII->get(MovOp)); } } const MCInstrDesc &UseDesc = UseMI->getDesc(); // Don't fold into target independent nodes. Target independent opcodes // don't have defined register classes. if (UseDesc.isVariadic() || UseDesc.OpInfo[Use.getOperandNo()].RegClass == -1) continue; if (FoldingImm) { MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue()); tryAddToFoldList(FoldList, UseMI, Use.getOperandNo(), &ImmOp, TII); continue; } tryAddToFoldList(FoldList, UseMI, Use.getOperandNo(), &OpToFold, TII); // FIXME: We could try to change the instruction from 64-bit to 32-bit // to enable more folding opportunites. The shrink operands pass // already does this. } for (FoldCandidate &Fold : FoldList) { if (updateOperand(Fold, TRI)) { // Clear kill flags. if (!Fold.isImm()) { assert(Fold.OpToFold && Fold.OpToFold->isReg()); Fold.OpToFold->setIsKill(false); } DEBUG(dbgs() << "Folded source from " << MI << " into OpNo " << Fold.UseOpNo << " of " << *Fold.UseMI << '\n'); } } } } return false; } <|endoftext|>
<commit_before>#include "shmcache_wrapper.h" #include "bson_wrapper.h" // Wrapper Impl Nan::Persistent<v8::FunctionTemplate> ShmCacheWrapper::constructor_template; NAN_MODULE_INIT(ShmCacheWrapper::Init) { v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); tpl->SetClassName(Nan::New("ShmCacheWrapper").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "Set", Set); Nan::SetPrototypeMethod(tpl, "Get", Get); Nan::SetPrototypeMethod(tpl, "Remove", Remove); Nan::SetPrototypeMethod(tpl, "Stats", Stats); Nan::SetPrototypeMethod(tpl, "Clear", Clear); constructor_template.Reset(tpl); Nan::Set(target, Nan::New("ShmCacheWrapper").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked()); } ShmCacheWrapper::ShmCacheWrapper(struct shmcache_config config) { this->config = config; log_init(); if (shmcache_init(&this->context, &config, true, true) != 0) { Nan::ThrowError(Nan::New<v8::String>("init shmcache err").ToLocalChecked()); } } ShmCacheWrapper::~ShmCacheWrapper() { } NAN_METHOD(ShmCacheWrapper::New) { if (info.IsConstructCall()) { v8::Local<v8::Object> cfgObj = Nan::To<v8::Object>(info[0]).ToLocalChecked(); v8::Local<v8::Object> vaObj = Nan::To<v8::Object>(Nan::Get(cfgObj, Nan::New<v8::String>("vaPolicy").ToLocalChecked()).ToLocalChecked()).ToLocalChecked(); v8::Local<v8::Object> lockObj = Nan::To<v8::Object>(Nan::Get(cfgObj, Nan::New<v8::String>("lockPolicy").ToLocalChecked()).ToLocalChecked()).ToLocalChecked(); struct shmcache_config config; v8::String::Utf8Value filenameString(cfgObj->Get(Nan::New<v8::String>("filename").ToLocalChecked())); strncpy(config.filename, *filenameString, filenameString.length()); config.max_memory = cfgObj->Get(Nan::New<v8::String>("maxMemory").ToLocalChecked())->Int32Value(); config.segment_size = cfgObj->Get(Nan::New<v8::String>("segmentSize").ToLocalChecked())->Int32Value(); config.max_key_count = cfgObj->Get(Nan::New<v8::String>("maxKeyCount").ToLocalChecked())->Int32Value(); config.max_value_size = cfgObj->Get(Nan::New<v8::String>("maxValueSize").ToLocalChecked())->Int32Value(); config.type = cfgObj->Get(Nan::New<v8::String>("type").ToLocalChecked())->Int32Value(); config.recycle_key_once = cfgObj ->Get(Nan::New<v8::String>("recycleKeyOnce").ToLocalChecked())->Int32Value(); config.va_policy.avg_key_ttl = vaObj->Get(Nan::New<v8::String>("avgKeyTTL").ToLocalChecked())->Int32Value(); config.va_policy.discard_memory_size = vaObj->Get( Nan::New<v8::String>("discardMemorySize").ToLocalChecked())->Int32Value(); config.va_policy.max_fail_times = vaObj->Get( Nan::New<v8::String>("maxFailTimes").ToLocalChecked())->Int32Value(); config.va_policy.sleep_us_when_recycle_valid_entries = vaObj->Get( Nan::New<v8::String>("seelpUsWhenRecycleValidEntries").ToLocalChecked())->Int32Value(); config.lock_policy.trylock_interval_us = lockObj->Get( Nan::New<v8::String>("tryLockIntervalUs").ToLocalChecked())->Int32Value(); config.lock_policy.detect_deadlock_interval_ms = lockObj->Get( Nan::New<v8::String>("detect_deadlock_interval_ms").ToLocalChecked())->Int32Value(); config.hash_func = simple_hash; ShmCacheWrapper *obj = new ShmCacheWrapper(config); obj->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { const int argc = 1; v8::Local<v8::Value> argv[argc] = {info[0]}; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(constructor_template)->GetFunction(); info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); } } NAN_METHOD(ShmCacheWrapper::Get) { ShmCacheWrapper* obj = Nan::ObjectWrap::Unwrap<ShmCacheWrapper>(info.This()); struct shmcache_key_info key; struct shmcache_value_info value; v8::String::Utf8Value keyString(Nan::To<v8::String>(info[0]).ToLocalChecked()); key.data = *keyString; key.length = keyString.length(); int result = shmcache_get(&obj->context, &key, &value); if (result == 0) { BSONWrapper bsonWrapper(value.data, value.length); info.GetReturnValue().Set(bsonWrapper.getValue()); } else { info.GetReturnValue().Set(Nan::Undefined()); } } NAN_METHOD(ShmCacheWrapper::Set) { ShmCacheWrapper* obj = Nan::ObjectWrap::Unwrap<ShmCacheWrapper>(info.This()); struct shmcache_key_info key; v8::String::Utf8Value keyString(Nan::To<v8::String>(info[0]).ToLocalChecked()); //v8::String::Utf8Value valueString(Nan::To<v8::String>(info[1]).ToLocalChecked()); int ttl = info[2]->Int32Value(); key.data = *keyString; key.length = keyString.length(); BSONWrapper bsonWrapper(info[1]); int result = shmcache_set(&obj->context, &key, bsonWrapper.getBuffer(), bsonWrapper.getBufferLen(), ttl); if (result == 0) { info.GetReturnValue().Set(Nan::True()); } else { info.GetReturnValue().Set(Nan::False()); } } NAN_METHOD(ShmCacheWrapper::Remove) { ShmCacheWrapper* obj = Nan::ObjectWrap::Unwrap<ShmCacheWrapper>(info.This()); struct shmcache_key_info key; v8::String::Utf8Value keyString(Nan::To<v8::String>(info[0]).ToLocalChecked()); key.data = *keyString; key.length = keyString.length(); int result = shmcache_delete(&obj->context, &key); if (result == 0) { info.GetReturnValue().Set(Nan::True()); } else { info.GetReturnValue().Set(Nan::False()); } } NAN_METHOD(ShmCacheWrapper::Stats) { ShmCacheWrapper* obj = Nan::ObjectWrap::Unwrap<ShmCacheWrapper>(info.This()); struct shmcache_stats stats; shmcache_stats(&obj->context, &stats); v8::Local<v8::Object> retObj = Nan::New<v8::Object>(); v8::Local<v8::Object> memObj = Nan::New<v8::Object>(); v8::Local<v8::Object> tableObj = Nan::New<v8::Object>(); v8::Local<v8::Object> lockObj = Nan::New<v8::Object>(); retObj->Set(Nan::New<v8::String>("memory").ToLocalChecked(), memObj); retObj->Set(Nan::New<v8::String>("hashTable").ToLocalChecked(), tableObj); retObj->Set(Nan::New<v8::String>("lock").ToLocalChecked(), lockObj); memObj->Set(Nan::New<v8::String>("total").ToLocalChecked(), Nan::New<v8::Number>(stats.memory.max)); memObj->Set(Nan::New<v8::String>("allocated").ToLocalChecked(), Nan::New<v8::Number>(stats.memory.usage.alloced)); memObj->Set(Nan::New<v8::String>("used").ToLocalChecked(), Nan::New<v8::Number>(stats.memory.used)); tableObj->Set(Nan::New<v8::String>("maxKeyCount").ToLocalChecked(), Nan::New<v8::Number>(stats.max_key_count)); tableObj->Set(Nan::New<v8::String>("currentKeyCount").ToLocalChecked(), Nan::New<v8::Number>(stats.hashtable.count)); lockObj->Set(Nan::New<v8::String>("totalCount").ToLocalChecked(), Nan::New<v8::Number>(stats.shm.lock.total)); lockObj->Set(Nan::New<v8::String>("retryCount").ToLocalChecked(), Nan::New<v8::Number>(stats.shm.lock.retry)); lockObj->Set(Nan::New<v8::String>("detectDeadLockCount").ToLocalChecked(), Nan::New<v8::Number>(stats.shm.lock.detect_deadlock)); lockObj->Set(Nan::New<v8::String>("unlockDeadLockCount").ToLocalChecked(), Nan::New<v8::Number>(stats.shm.lock.unlock_deadlock)); info.GetReturnValue().Set(retObj); } NAN_METHOD(ShmCacheWrapper::Clear) { ShmCacheWrapper* obj = Nan::ObjectWrap::Unwrap<ShmCacheWrapper>(info.This()); int result = shmcache_remove_all(&obj->context); if (result == 0) { info.GetReturnValue().Set(Nan::True()); } else { info.GetReturnValue().Set(Nan::False()); } } <commit_msg>fix: non terminate string<commit_after>#include "shmcache_wrapper.h" #include "bson_wrapper.h" // Wrapper Impl Nan::Persistent<v8::FunctionTemplate> ShmCacheWrapper::constructor_template; NAN_MODULE_INIT(ShmCacheWrapper::Init) { v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); tpl->SetClassName(Nan::New("ShmCacheWrapper").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "Set", Set); Nan::SetPrototypeMethod(tpl, "Get", Get); Nan::SetPrototypeMethod(tpl, "Remove", Remove); Nan::SetPrototypeMethod(tpl, "Stats", Stats); Nan::SetPrototypeMethod(tpl, "Clear", Clear); constructor_template.Reset(tpl); Nan::Set(target, Nan::New("ShmCacheWrapper").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked()); } ShmCacheWrapper::ShmCacheWrapper(struct shmcache_config config) { this->config = config; log_init(); if (shmcache_init(&this->context, &config, true, true) != 0) { Nan::ThrowError(Nan::New<v8::String>("init shmcache err").ToLocalChecked()); } } ShmCacheWrapper::~ShmCacheWrapper() { } NAN_METHOD(ShmCacheWrapper::New) { if (info.IsConstructCall()) { v8::Local<v8::Object> cfgObj = Nan::To<v8::Object>(info[0]).ToLocalChecked(); v8::Local<v8::Object> vaObj = Nan::To<v8::Object>(Nan::Get(cfgObj, Nan::New<v8::String>("vaPolicy").ToLocalChecked()).ToLocalChecked()).ToLocalChecked(); v8::Local<v8::Object> lockObj = Nan::To<v8::Object>(Nan::Get(cfgObj, Nan::New<v8::String>("lockPolicy").ToLocalChecked()).ToLocalChecked()).ToLocalChecked(); struct shmcache_config config; memset(config.filename, 0, sizeof(config.filename)); v8::String::Utf8Value filenameString(cfgObj->Get(Nan::New<v8::String>("filename").ToLocalChecked())); strncpy(config.filename, *filenameString, filenameString.length()); config.max_memory = cfgObj->Get(Nan::New<v8::String>("maxMemory").ToLocalChecked())->Int32Value(); config.segment_size = cfgObj->Get(Nan::New<v8::String>("segmentSize").ToLocalChecked())->Int32Value(); config.max_key_count = cfgObj->Get(Nan::New<v8::String>("maxKeyCount").ToLocalChecked())->Int32Value(); config.max_value_size = cfgObj->Get(Nan::New<v8::String>("maxValueSize").ToLocalChecked())->Int32Value(); config.type = cfgObj->Get(Nan::New<v8::String>("type").ToLocalChecked())->Int32Value(); config.recycle_key_once = cfgObj ->Get(Nan::New<v8::String>("recycleKeyOnce").ToLocalChecked())->Int32Value(); config.va_policy.avg_key_ttl = vaObj->Get(Nan::New<v8::String>("avgKeyTTL").ToLocalChecked())->Int32Value(); config.va_policy.discard_memory_size = vaObj->Get( Nan::New<v8::String>("discardMemorySize").ToLocalChecked())->Int32Value(); config.va_policy.max_fail_times = vaObj->Get( Nan::New<v8::String>("maxFailTimes").ToLocalChecked())->Int32Value(); config.va_policy.sleep_us_when_recycle_valid_entries = vaObj->Get( Nan::New<v8::String>("seelpUsWhenRecycleValidEntries").ToLocalChecked())->Int32Value(); config.lock_policy.trylock_interval_us = lockObj->Get( Nan::New<v8::String>("tryLockIntervalUs").ToLocalChecked())->Int32Value(); config.lock_policy.detect_deadlock_interval_ms = lockObj->Get( Nan::New<v8::String>("detect_deadlock_interval_ms").ToLocalChecked())->Int32Value(); config.hash_func = simple_hash; ShmCacheWrapper *obj = new ShmCacheWrapper(config); obj->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { const int argc = 1; v8::Local<v8::Value> argv[argc] = {info[0]}; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(constructor_template)->GetFunction(); info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); } } NAN_METHOD(ShmCacheWrapper::Get) { ShmCacheWrapper* obj = Nan::ObjectWrap::Unwrap<ShmCacheWrapper>(info.This()); struct shmcache_key_info key; struct shmcache_value_info value; v8::String::Utf8Value keyString(Nan::To<v8::String>(info[0]).ToLocalChecked()); key.data = *keyString; key.length = keyString.length(); int result = shmcache_get(&obj->context, &key, &value); if (result == 0) { BSONWrapper bsonWrapper(value.data, value.length); info.GetReturnValue().Set(bsonWrapper.getValue()); } else { info.GetReturnValue().Set(Nan::Undefined()); } } NAN_METHOD(ShmCacheWrapper::Set) { ShmCacheWrapper* obj = Nan::ObjectWrap::Unwrap<ShmCacheWrapper>(info.This()); struct shmcache_key_info key; v8::String::Utf8Value keyString(Nan::To<v8::String>(info[0]).ToLocalChecked()); //v8::String::Utf8Value valueString(Nan::To<v8::String>(info[1]).ToLocalChecked()); int ttl = info[2]->Int32Value(); key.data = *keyString; key.length = keyString.length(); BSONWrapper bsonWrapper(info[1]); int result = shmcache_set(&obj->context, &key, bsonWrapper.getBuffer(), bsonWrapper.getBufferLen(), ttl); if (result == 0) { info.GetReturnValue().Set(Nan::True()); } else { info.GetReturnValue().Set(Nan::False()); } } NAN_METHOD(ShmCacheWrapper::Remove) { ShmCacheWrapper* obj = Nan::ObjectWrap::Unwrap<ShmCacheWrapper>(info.This()); struct shmcache_key_info key; v8::String::Utf8Value keyString(Nan::To<v8::String>(info[0]).ToLocalChecked()); key.data = *keyString; key.length = keyString.length(); int result = shmcache_delete(&obj->context, &key); if (result == 0) { info.GetReturnValue().Set(Nan::True()); } else { info.GetReturnValue().Set(Nan::False()); } } NAN_METHOD(ShmCacheWrapper::Stats) { ShmCacheWrapper* obj = Nan::ObjectWrap::Unwrap<ShmCacheWrapper>(info.This()); struct shmcache_stats stats; shmcache_stats(&obj->context, &stats); v8::Local<v8::Object> retObj = Nan::New<v8::Object>(); v8::Local<v8::Object> memObj = Nan::New<v8::Object>(); v8::Local<v8::Object> tableObj = Nan::New<v8::Object>(); v8::Local<v8::Object> lockObj = Nan::New<v8::Object>(); retObj->Set(Nan::New<v8::String>("memory").ToLocalChecked(), memObj); retObj->Set(Nan::New<v8::String>("hashTable").ToLocalChecked(), tableObj); retObj->Set(Nan::New<v8::String>("lock").ToLocalChecked(), lockObj); memObj->Set(Nan::New<v8::String>("total").ToLocalChecked(), Nan::New<v8::Number>(stats.memory.max)); memObj->Set(Nan::New<v8::String>("allocated").ToLocalChecked(), Nan::New<v8::Number>(stats.memory.usage.alloced)); memObj->Set(Nan::New<v8::String>("used").ToLocalChecked(), Nan::New<v8::Number>(stats.memory.used)); tableObj->Set(Nan::New<v8::String>("maxKeyCount").ToLocalChecked(), Nan::New<v8::Number>(stats.max_key_count)); tableObj->Set(Nan::New<v8::String>("currentKeyCount").ToLocalChecked(), Nan::New<v8::Number>(stats.hashtable.count)); lockObj->Set(Nan::New<v8::String>("totalCount").ToLocalChecked(), Nan::New<v8::Number>(stats.shm.lock.total)); lockObj->Set(Nan::New<v8::String>("retryCount").ToLocalChecked(), Nan::New<v8::Number>(stats.shm.lock.retry)); lockObj->Set(Nan::New<v8::String>("detectDeadLockCount").ToLocalChecked(), Nan::New<v8::Number>(stats.shm.lock.detect_deadlock)); lockObj->Set(Nan::New<v8::String>("unlockDeadLockCount").ToLocalChecked(), Nan::New<v8::Number>(stats.shm.lock.unlock_deadlock)); info.GetReturnValue().Set(retObj); } NAN_METHOD(ShmCacheWrapper::Clear) { ShmCacheWrapper* obj = Nan::ObjectWrap::Unwrap<ShmCacheWrapper>(info.This()); int result = shmcache_remove_all(&obj->context); if (result == 0) { info.GetReturnValue().Set(Nan::True()); } else { info.GetReturnValue().Set(Nan::False()); } } <|endoftext|>
<commit_before>//===-- Internalize.cpp - Mark functions internal -------------------------===// // // This pass loops over all of the functions in the input module, looking for a // main function. If a main function is found, all other functions and all // global variables with initializers are marked as internal. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/Pass.h" #include "llvm/Module.h" #include "Support/Statistic.h" #include "Support/CommandLine.h" #include <fstream> #include <set> namespace { Statistic<> NumFunctions("internalize", "Number of functions internalized"); Statistic<> NumGlobals ("internalize", "Number of global vars internalized"); // APIFile - A file which contains a list of symbols that should not be marked // external. cl::opt<std::string> APIFile("internalize-public-api-file", cl::value_desc("filename"), cl::desc("A file containing list of globals to not internalize")); class InternalizePass : public Pass { std::set<std::string> ExternalNames; public: InternalizePass() { if (!APIFile.empty()) LoadFile(APIFile.c_str()); else ExternalNames.insert("main"); } void LoadFile(const char *Filename) { // Load the APIFile... std::ifstream In(Filename); if (!In.good()) { std::cerr << "WARNING: Internalize couldn't load file '" << Filename << "'!: Not internalizing.\n"; return; // Do not internalize anything... } while (In) { std::string Symbol; In >> Symbol; if (!Symbol.empty()) ExternalNames.insert(Symbol); } } virtual bool run(Module &M) { if (ExternalNames.empty()) return false; // Error loading file... bool Changed = false; // Found a main function, mark all functions not named main as internal. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isExternal() && // Function must be defined here !I->hasInternalLinkage() && // Can't already have internal linkage !ExternalNames.count(I->getName())) {// Not marked to keep external? I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumFunctions; DEBUG(std::cerr << "Internalizing func " << I->getName() << "\n"); } // Mark all global variables with initializers as internal as well... for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) if (!I->isExternal() && !I->hasInternalLinkage() && !ExternalNames.count(I->getName())) { I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumGlobals; DEBUG(std::cerr << "Internalizing gvar " << I->getName() << "\n"); } return Changed; } }; RegisterOpt<InternalizePass> X("internalize", "Internalize Global Symbols"); } // end anonymous namespace Pass *createInternalizePass() { return new InternalizePass(); } <commit_msg>* Revert to old behavior of ignoring a module if it doesn't contain a main function and no symbols were explicitly marked to be externalized. * Add new -internalize-public-api-list option that can be used if the symbol list is small, and making a new file is annoying.<commit_after>//===-- Internalize.cpp - Mark functions internal -------------------------===// // // This pass loops over all of the functions in the input module, looking for a // main function. If a main function is found, all other functions and all // global variables with initializers are marked as internal. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/Pass.h" #include "llvm/Module.h" #include "Support/Statistic.h" #include "Support/CommandLine.h" #include <fstream> #include <set> namespace { Statistic<> NumFunctions("internalize", "Number of functions internalized"); Statistic<> NumGlobals ("internalize", "Number of global vars internalized"); // APIFile - A file which contains a list of symbols that should not be marked // external. cl::opt<std::string> APIFile("internalize-public-api-file", cl::value_desc("filename"), cl::desc("A file containing list of symbol names to preserve")); // APIList - A list of symbols that should not be marked internal. cl::list<std::string> APIList("internalize-public-api-list", cl::value_desc("list"), cl::desc("A list of symbol names to preserve")); class InternalizePass : public Pass { std::set<std::string> ExternalNames; public: InternalizePass() { if (!APIFile.empty()) // If a filename is specified, use it LoadFile(APIFile.c_str()); else // Else, if a list is specified, use it. ExternalNames.insert(APIList.begin(), APIList.end()); } void LoadFile(const char *Filename) { // Load the APIFile... std::ifstream In(Filename); if (!In.good()) { std::cerr << "WARNING: Internalize couldn't load file '" << Filename << "'!\n"; return; // Do not internalize anything... } while (In) { std::string Symbol; In >> Symbol; if (!Symbol.empty()) ExternalNames.insert(Symbol); } } virtual bool run(Module &M) { // If no list or file of symbols was specified, check to see if there is a // "main" symbol defined in the module. If so, use it, otherwise do not // internalize the module, it must be a library or something. // if (ExternalNames.empty()) { Function *MainFunc = M.getMainFunction(); if (MainFunc == 0 || MainFunc->isExternal()) return false; // No main found, must be a library... // Preserve main, internalize all else. ExternalNames.insert(MainFunc->getName()); } bool Changed = false; // Found a main function, mark all functions not named main as internal. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isExternal() && // Function must be defined here !I->hasInternalLinkage() && // Can't already have internal linkage !ExternalNames.count(I->getName())) {// Not marked to keep external? I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumFunctions; DEBUG(std::cerr << "Internalizing func " << I->getName() << "\n"); } // Mark all global variables with initializers as internal as well... for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) if (!I->isExternal() && !I->hasInternalLinkage() && !ExternalNames.count(I->getName())) { I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumGlobals; DEBUG(std::cerr << "Internalizing gvar " << I->getName() << "\n"); } return Changed; } }; RegisterOpt<InternalizePass> X("internalize", "Internalize Global Symbols"); } // end anonymous namespace Pass *createInternalizePass() { return new InternalizePass(); } <|endoftext|>
<commit_before>#include "../../include/EnemyTypes/SmallRat.h" SmallRat::SmallRat() { name = "Small Rat"; ExperienceAmount = 15; CoinsDrop = 3 + rand() % 28; } EnemyType SmallRat::GetType() { return etRat; } int SmallRat::ReturnDamage() { return 2 + rand() % 5; } int SmallRat::ReturnRiskAttackDamage() { int selector = rand() % 10; switch (selector){ case 0: case 1: case 2: case 3: return 0; break; case 4: case 5: case 6: case 7: case 8: return 2; break; case 9: return 5; break; case 10: return 10; break; default: return 0; break; } } int SmallRat::ReturnHealAmount() { return 3 + rand() % 15; } <commit_msg>Corrected typo<commit_after>#include "../../include/EnemyTypes/SmallRat.h" SmallRat::SmallRat() { name = "Small Rat"; ExperienceAmount = 15; CoinsDrop = 3 + rand() % 28; } EnemyType SmallRat::GetType() { return etSmallRat; } int SmallRat::ReturnDamage() { return 2 + rand() % 5; } int SmallRat::ReturnRiskAttackDamage() { int selector = rand() % 10; switch (selector){ case 0: case 1: case 2: case 3: return 0; break; case 4: case 5: case 6: case 7: case 8: return 2; break; case 9: return 5; break; case 10: return 10; break; default: return 0; break; } } int SmallRat::ReturnHealAmount() { return 3 + rand() % 15; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: nativethreadpool.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2003-10-09 10:20:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "jvmaccess/virtualmachine.hxx" #include "rtl/byteseq.h" #include "rtl/byteseq.hxx" #include "rtl/memory.h" #include "rtl/ref.hxx" #include "sal/types.h" #include "uno/threadpool.h" #include "jni.h" #include <new> /* The native implementation part of * jurt/com/sun/star/lib/uno/environments/remote/NativeThreadPool.java. */ namespace { struct Pool { Pool(rtl::Reference< jvmaccess::VirtualMachine > const & theVirtualMachine, jmethodID theExecute, uno_ThreadPool thePool): virtualMachine(theVirtualMachine), execute(theExecute), pool(thePool) {} rtl::Reference< jvmaccess::VirtualMachine > virtualMachine; jmethodID execute; uno_ThreadPool pool; }; struct Job { Job(Pool * thePool, jobject theJob): pool(thePool), job(theJob) {} Pool * pool; jobject job; }; void throwOutOfMemory(JNIEnv * env) { jclass c = env->FindClass("java/lang/OutOfMemoryError"); if (c != 0) { env->ThrowNew(c, ""); } } } extern "C" { static void SAL_CALL executeRequest(void * data) { Job * job = static_cast< Job * >(data); try { jvmaccess::VirtualMachine::AttachGuard guard(job->pool->virtualMachine); JNIEnv * env = guard.getEnvironment(); // Failure of the following Job.execute Java call is ignored; if that // call fails, it should be due to a java.lang.Error, which is not // handled well, anyway: env->CallObjectMethod(job->job, job->pool->execute); env->DeleteGlobalRef(job->job); delete job; } catch (jvmaccess::VirtualMachine::AttachGuard::CreationException & e) { //TODO: DeleteGlobalRef(job->job) delete job; } } } extern "C" JNIEXPORT jbyteArray JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_threadId( JNIEnv * env, jclass) SAL_THROW_EXTERN_C() { sal_Sequence * s = 0; uno_getIdOfCurrentThread(&s); //TODO: out of memory uno_releaseIdFromCurrentThread(); rtl::ByteSequence seq(s); rtl_byte_sequence_release(s); sal_Int32 n = seq.getLength(); jbyteArray a = env->NewByteArray(n); // sal_Int32 and jsize are compatible here if (a == 0) { return 0; } void * p = env->GetPrimitiveArrayCritical(a, 0); if (p == 0) { return 0; } rtl_copyMemory(p, seq.getConstArray(), n); // sal_Int8 and jbyte ought to be compatible env->ReleasePrimitiveArrayCritical(a, p, 0); return a; } extern "C" JNIEXPORT jlong JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_create( JNIEnv * env, jclass) SAL_THROW_EXTERN_C() { JavaVM * vm; if (env->GetJavaVM(&vm) != JNI_OK) { //TODO: no Java exception raised? jclass c = env->FindClass("java/lang/RuntimeException"); if (c != 0) { env->ThrowNew(c, "JNI GetJavaVM failed"); } return 0; } jclass c = env->FindClass("com/sun/star/lib/uno/environments/remote/Job"); if (c == 0) { return 0; } jmethodID execute = env->GetMethodID(c, "execute", "()Ljava/lang/Object;"); if (execute == 0) { return 0; } try { return reinterpret_cast< jlong >(new Pool( new jvmaccess::VirtualMachine(vm, env->GetVersion(), false, env), execute, uno_threadpool_create())); } catch (std::bad_alloc) { throwOutOfMemory(env); return 0; } } extern "C" JNIEXPORT void JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_attach( JNIEnv *, jclass, jlong pool) SAL_THROW_EXTERN_C() { uno_threadpool_attach(reinterpret_cast< Pool * >(pool)->pool); } extern "C" JNIEXPORT jobject JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_enter( JNIEnv * env, jclass, jlong pool) SAL_THROW_EXTERN_C() { jobject job; uno_threadpool_enter( reinterpret_cast< Pool * >(pool)->pool, reinterpret_cast< void ** >(&job)); if (job == 0) { return 0; } jobject ref = env->NewLocalRef(job); env->DeleteGlobalRef(job); return ref; } extern "C" JNIEXPORT void JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_detach( JNIEnv *, jclass, jlong pool) SAL_THROW_EXTERN_C() { uno_threadpool_detach(reinterpret_cast< Pool * >(pool)->pool); } extern "C" JNIEXPORT void JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_putJob( JNIEnv * env, jclass, jlong pool, jbyteArray threadId, jobject job, jboolean request, jboolean oneWay) SAL_THROW_EXTERN_C() { void * s = env->GetPrimitiveArrayCritical(threadId, 0); if (s == 0) { return; } rtl::ByteSequence seq( static_cast< sal_Int8 * >(s), env->GetArrayLength(threadId)); // sal_Int8 and jbyte ought to be compatible; sal_Int32 and jsize are // compatible here //TODO: out of memory env->ReleasePrimitiveArrayCritical(threadId, s, JNI_ABORT); Pool * p = reinterpret_cast< Pool * >(pool); jobject ref = env->NewGlobalRef(job); if (ref == 0) { return; } Job * j = 0; if (request) { j = new(std::nothrow) Job(p, ref); if (j == 0) { env->DeleteGlobalRef(ref); throwOutOfMemory(env); return; } } uno_threadpool_putJob( p->pool, seq.getHandle(), request ? static_cast< void * >(j) : static_cast< void * >(ref), request ? executeRequest : 0, oneWay); } extern "C" JNIEXPORT void JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_dispose( JNIEnv *, jclass, jlong pool) SAL_THROW_EXTERN_C() { uno_threadpool_dispose(reinterpret_cast< Pool * >(pool)->pool); } extern "C" JNIEXPORT void JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_destroy( JNIEnv *, jclass, jlong pool) SAL_THROW_EXTERN_C() { Pool * p = reinterpret_cast< Pool * >(pool); uno_threadpool_destroy(p->pool); delete p; } <commit_msg>INTEGRATION: CWS ooo19126 (1.2.112); FILE MERGED 2005/09/05 17:07:43 rt 1.2.112.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: nativethreadpool.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-07 22:38:35 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "jvmaccess/virtualmachine.hxx" #include "rtl/byteseq.h" #include "rtl/byteseq.hxx" #include "rtl/memory.h" #include "rtl/ref.hxx" #include "sal/types.h" #include "uno/threadpool.h" #include "jni.h" #include <new> /* The native implementation part of * jurt/com/sun/star/lib/uno/environments/remote/NativeThreadPool.java. */ namespace { struct Pool { Pool(rtl::Reference< jvmaccess::VirtualMachine > const & theVirtualMachine, jmethodID theExecute, uno_ThreadPool thePool): virtualMachine(theVirtualMachine), execute(theExecute), pool(thePool) {} rtl::Reference< jvmaccess::VirtualMachine > virtualMachine; jmethodID execute; uno_ThreadPool pool; }; struct Job { Job(Pool * thePool, jobject theJob): pool(thePool), job(theJob) {} Pool * pool; jobject job; }; void throwOutOfMemory(JNIEnv * env) { jclass c = env->FindClass("java/lang/OutOfMemoryError"); if (c != 0) { env->ThrowNew(c, ""); } } } extern "C" { static void SAL_CALL executeRequest(void * data) { Job * job = static_cast< Job * >(data); try { jvmaccess::VirtualMachine::AttachGuard guard(job->pool->virtualMachine); JNIEnv * env = guard.getEnvironment(); // Failure of the following Job.execute Java call is ignored; if that // call fails, it should be due to a java.lang.Error, which is not // handled well, anyway: env->CallObjectMethod(job->job, job->pool->execute); env->DeleteGlobalRef(job->job); delete job; } catch (jvmaccess::VirtualMachine::AttachGuard::CreationException & e) { //TODO: DeleteGlobalRef(job->job) delete job; } } } extern "C" JNIEXPORT jbyteArray JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_threadId( JNIEnv * env, jclass) SAL_THROW_EXTERN_C() { sal_Sequence * s = 0; uno_getIdOfCurrentThread(&s); //TODO: out of memory uno_releaseIdFromCurrentThread(); rtl::ByteSequence seq(s); rtl_byte_sequence_release(s); sal_Int32 n = seq.getLength(); jbyteArray a = env->NewByteArray(n); // sal_Int32 and jsize are compatible here if (a == 0) { return 0; } void * p = env->GetPrimitiveArrayCritical(a, 0); if (p == 0) { return 0; } rtl_copyMemory(p, seq.getConstArray(), n); // sal_Int8 and jbyte ought to be compatible env->ReleasePrimitiveArrayCritical(a, p, 0); return a; } extern "C" JNIEXPORT jlong JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_create( JNIEnv * env, jclass) SAL_THROW_EXTERN_C() { JavaVM * vm; if (env->GetJavaVM(&vm) != JNI_OK) { //TODO: no Java exception raised? jclass c = env->FindClass("java/lang/RuntimeException"); if (c != 0) { env->ThrowNew(c, "JNI GetJavaVM failed"); } return 0; } jclass c = env->FindClass("com/sun/star/lib/uno/environments/remote/Job"); if (c == 0) { return 0; } jmethodID execute = env->GetMethodID(c, "execute", "()Ljava/lang/Object;"); if (execute == 0) { return 0; } try { return reinterpret_cast< jlong >(new Pool( new jvmaccess::VirtualMachine(vm, env->GetVersion(), false, env), execute, uno_threadpool_create())); } catch (std::bad_alloc) { throwOutOfMemory(env); return 0; } } extern "C" JNIEXPORT void JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_attach( JNIEnv *, jclass, jlong pool) SAL_THROW_EXTERN_C() { uno_threadpool_attach(reinterpret_cast< Pool * >(pool)->pool); } extern "C" JNIEXPORT jobject JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_enter( JNIEnv * env, jclass, jlong pool) SAL_THROW_EXTERN_C() { jobject job; uno_threadpool_enter( reinterpret_cast< Pool * >(pool)->pool, reinterpret_cast< void ** >(&job)); if (job == 0) { return 0; } jobject ref = env->NewLocalRef(job); env->DeleteGlobalRef(job); return ref; } extern "C" JNIEXPORT void JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_detach( JNIEnv *, jclass, jlong pool) SAL_THROW_EXTERN_C() { uno_threadpool_detach(reinterpret_cast< Pool * >(pool)->pool); } extern "C" JNIEXPORT void JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_putJob( JNIEnv * env, jclass, jlong pool, jbyteArray threadId, jobject job, jboolean request, jboolean oneWay) SAL_THROW_EXTERN_C() { void * s = env->GetPrimitiveArrayCritical(threadId, 0); if (s == 0) { return; } rtl::ByteSequence seq( static_cast< sal_Int8 * >(s), env->GetArrayLength(threadId)); // sal_Int8 and jbyte ought to be compatible; sal_Int32 and jsize are // compatible here //TODO: out of memory env->ReleasePrimitiveArrayCritical(threadId, s, JNI_ABORT); Pool * p = reinterpret_cast< Pool * >(pool); jobject ref = env->NewGlobalRef(job); if (ref == 0) { return; } Job * j = 0; if (request) { j = new(std::nothrow) Job(p, ref); if (j == 0) { env->DeleteGlobalRef(ref); throwOutOfMemory(env); return; } } uno_threadpool_putJob( p->pool, seq.getHandle(), request ? static_cast< void * >(j) : static_cast< void * >(ref), request ? executeRequest : 0, oneWay); } extern "C" JNIEXPORT void JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_dispose( JNIEnv *, jclass, jlong pool) SAL_THROW_EXTERN_C() { uno_threadpool_dispose(reinterpret_cast< Pool * >(pool)->pool); } extern "C" JNIEXPORT void JNICALL Java_com_sun_star_lib_uno_environments_remote_NativeThreadPool_destroy( JNIEnv *, jclass, jlong pool) SAL_THROW_EXTERN_C() { Pool * p = reinterpret_cast< Pool * >(pool); uno_threadpool_destroy(p->pool); delete p; } <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/log.h" #include "kernel/register.h" #include "kernel/sigtools.h" #include "kernel/consteval.h" #include "kernel/celltypes.h" #include "fsmdata.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN static RTLIL::Module *module; static SigMap assign_map; typedef std::pair<RTLIL::Cell*, RTLIL::IdString> sig2driver_entry_t; static SigSet<sig2driver_entry_t> sig2driver, sig2user; static std::set<RTLIL::Cell*> muxtree_cells; static SigPool sig_at_port; static bool check_state_mux_tree(RTLIL::SigSpec old_sig, RTLIL::SigSpec sig, SigPool &recursion_monitor) { if (sig_at_port.check_any(assign_map(sig))) return false; if (sig.is_fully_const() || old_sig == sig) return true; if (recursion_monitor.check_any(sig)) { log_warning("logic loop in mux tree at signal %s in module %s.\n", log_signal(sig), RTLIL::id2cstr(module->name)); return false; } recursion_monitor.add(sig); std::set<sig2driver_entry_t> cellport_list; sig2driver.find(sig, cellport_list); for (auto &cellport : cellport_list) { if ((cellport.first->type != "$mux" && cellport.first->type != "$pmux") || cellport.second != "\\Y") return false; RTLIL::SigSpec sig_a = assign_map(cellport.first->getPort("\\A")); RTLIL::SigSpec sig_b = assign_map(cellport.first->getPort("\\B")); if (!check_state_mux_tree(old_sig, sig_a, recursion_monitor)) return false; for (int i = 0; i < sig_b.size(); i += sig_a.size()) if (!check_state_mux_tree(old_sig, sig_b.extract(i, sig_a.size()), recursion_monitor)) return false; muxtree_cells.insert(cellport.first); } recursion_monitor.del(sig); return true; } static bool check_state_users(RTLIL::SigSpec sig) { if (sig_at_port.check_any(assign_map(sig))) return false; std::set<sig2driver_entry_t> cellport_list; sig2user.find(sig, cellport_list); for (auto &cellport : cellport_list) { RTLIL::Cell *cell = cellport.first; if (muxtree_cells.count(cell) > 0) continue; if (cellport.second != "\\A" && cellport.second != "\\B") return false; if (!cell->hasPort("\\A") || !cell->hasPort("\\B") || !cell->hasPort("\\Y")) return false; for (auto &port_it : cell->connections()) if (port_it.first != "\\A" && port_it.first != "\\B" && port_it.first != "\\Y") return false; if (assign_map(cell->getPort("\\A")) == sig && cell->getPort("\\B").is_fully_const()) continue; if (assign_map(cell->getPort("\\B")) == sig && cell->getPort("\\A").is_fully_const()) continue; return false; } return true; } static void detect_fsm(RTLIL::Wire *wire) { if (wire->attributes.count("\\fsm_encoding") > 0 || wire->width <= 1) return; if (sig_at_port.check_any(assign_map(RTLIL::SigSpec(wire)))) return; std::set<sig2driver_entry_t> cellport_list; sig2driver.find(RTLIL::SigSpec(wire), cellport_list); for (auto &cellport : cellport_list) { if ((cellport.first->type != "$dff" && cellport.first->type != "$adff") || cellport.second != "\\Q") continue; muxtree_cells.clear(); SigPool recursion_monitor; RTLIL::SigSpec sig_q = assign_map(cellport.first->getPort("\\Q")); RTLIL::SigSpec sig_d = assign_map(cellport.first->getPort("\\D")); if (sig_q == RTLIL::SigSpec(wire) && check_state_mux_tree(sig_q, sig_d, recursion_monitor) && check_state_users(sig_q)) { log("Found FSM state register %s in module %s.\n", wire->name.c_str(), module->name.c_str()); wire->attributes["\\fsm_encoding"] = RTLIL::Const("auto"); return; } } } struct FsmDetectPass : public Pass { FsmDetectPass() : Pass("fsm_detect", "finding FSMs in design") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" fsm_detect [selection]\n"); log("\n"); log("This pass detects finite state machines by identifying the state signal.\n"); log("The state signal is then marked by setting the attribute 'fsm_encoding'\n"); log("on the state signal to \"auto\".\n"); log("\n"); log("Existing 'fsm_encoding' attributes are not changed by this pass.\n"); log("\n"); log("Signals can be protected from being detected by this pass by setting the\n"); log("'fsm_encoding' attribute to \"none\".\n"); log("\n"); } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) { log_header("Executing FSM_DETECT pass (finding FSMs in design).\n"); extra_args(args, 1, design); CellTypes ct; ct.setup_internals(); ct.setup_internals_mem(); ct.setup_stdcells(); ct.setup_stdcells_mem(); for (auto &mod_it : design->modules_) { if (!design->selected(mod_it.second)) continue; module = mod_it.second; assign_map.set(module); sig2driver.clear(); sig2user.clear(); sig_at_port.clear(); for (auto &cell_it : module->cells_) for (auto &conn_it : cell_it.second->connections()) { if (ct.cell_output(cell_it.second->type, conn_it.first) || !ct.cell_known(cell_it.second->type)) { RTLIL::SigSpec sig = conn_it.second; assign_map.apply(sig); sig2driver.insert(sig, sig2driver_entry_t(cell_it.second, conn_it.first)); } if (!ct.cell_known(cell_it.second->type) || ct.cell_input(cell_it.second->type, conn_it.first)) { RTLIL::SigSpec sig = conn_it.second; assign_map.apply(sig); sig2user.insert(sig, sig2driver_entry_t(cell_it.second, conn_it.first)); } } for (auto &wire_it : module->wires_) if (wire_it.second->port_id != 0) sig_at_port.add(assign_map(RTLIL::SigSpec(wire_it.second))); for (auto &wire_it : module->wires_) if (design->selected(module, wire_it.second)) detect_fsm(wire_it.second); } assign_map.clear(); sig2driver.clear(); sig2user.clear(); muxtree_cells.clear(); } } FsmDetectPass; PRIVATE_NAMESPACE_END <commit_msg>Bugfix in fsm_detect for complex muxtrees<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/log.h" #include "kernel/register.h" #include "kernel/sigtools.h" #include "kernel/consteval.h" #include "kernel/celltypes.h" #include "fsmdata.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN static RTLIL::Module *module; static SigMap assign_map; typedef std::pair<RTLIL::Cell*, RTLIL::IdString> sig2driver_entry_t; static SigSet<sig2driver_entry_t> sig2driver, sig2user; static std::set<RTLIL::Cell*> muxtree_cells; static SigPool sig_at_port; static bool check_state_mux_tree(RTLIL::SigSpec old_sig, RTLIL::SigSpec sig, pool<Cell*> &recursion_monitor) { if (sig_at_port.check_any(assign_map(sig))) return false; if (sig.is_fully_const() || old_sig == sig) return true; std::set<sig2driver_entry_t> cellport_list; sig2driver.find(sig, cellport_list); for (auto &cellport : cellport_list) { if ((cellport.first->type != "$mux" && cellport.first->type != "$pmux") || cellport.second != "\\Y") return false; if (recursion_monitor.count(cellport.first)) { log_warning("logic loop in mux tree at signal %s in module %s.\n", log_signal(sig), RTLIL::id2cstr(module->name)); return false; } recursion_monitor.insert(cellport.first); RTLIL::SigSpec sig_a = assign_map(cellport.first->getPort("\\A")); RTLIL::SigSpec sig_b = assign_map(cellport.first->getPort("\\B")); if (!check_state_mux_tree(old_sig, sig_a, recursion_monitor)) { recursion_monitor.erase(cellport.first); return false; } for (int i = 0; i < sig_b.size(); i += sig_a.size()) if (!check_state_mux_tree(old_sig, sig_b.extract(i, sig_a.size()), recursion_monitor)) { recursion_monitor.erase(cellport.first); return false; } recursion_monitor.erase(cellport.first); muxtree_cells.insert(cellport.first); } return true; } static bool check_state_users(RTLIL::SigSpec sig) { if (sig_at_port.check_any(assign_map(sig))) return false; std::set<sig2driver_entry_t> cellport_list; sig2user.find(sig, cellport_list); for (auto &cellport : cellport_list) { RTLIL::Cell *cell = cellport.first; if (muxtree_cells.count(cell) > 0) continue; if (cellport.second != "\\A" && cellport.second != "\\B") return false; if (!cell->hasPort("\\A") || !cell->hasPort("\\B") || !cell->hasPort("\\Y")) return false; for (auto &port_it : cell->connections()) if (port_it.first != "\\A" && port_it.first != "\\B" && port_it.first != "\\Y") return false; if (assign_map(cell->getPort("\\A")) == sig && cell->getPort("\\B").is_fully_const()) continue; if (assign_map(cell->getPort("\\B")) == sig && cell->getPort("\\A").is_fully_const()) continue; return false; } return true; } static void detect_fsm(RTLIL::Wire *wire) { if (wire->attributes.count("\\fsm_encoding") > 0 || wire->width <= 1) return; if (sig_at_port.check_any(assign_map(RTLIL::SigSpec(wire)))) return; std::set<sig2driver_entry_t> cellport_list; sig2driver.find(RTLIL::SigSpec(wire), cellport_list); for (auto &cellport : cellport_list) { if ((cellport.first->type != "$dff" && cellport.first->type != "$adff") || cellport.second != "\\Q") continue; muxtree_cells.clear(); pool<Cell*> recursion_monitor; RTLIL::SigSpec sig_q = assign_map(cellport.first->getPort("\\Q")); RTLIL::SigSpec sig_d = assign_map(cellport.first->getPort("\\D")); if (sig_q == RTLIL::SigSpec(wire) && check_state_mux_tree(sig_q, sig_d, recursion_monitor) && check_state_users(sig_q)) { log("Found FSM state register %s in module %s.\n", wire->name.c_str(), module->name.c_str()); wire->attributes["\\fsm_encoding"] = RTLIL::Const("auto"); return; } } } struct FsmDetectPass : public Pass { FsmDetectPass() : Pass("fsm_detect", "finding FSMs in design") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" fsm_detect [selection]\n"); log("\n"); log("This pass detects finite state machines by identifying the state signal.\n"); log("The state signal is then marked by setting the attribute 'fsm_encoding'\n"); log("on the state signal to \"auto\".\n"); log("\n"); log("Existing 'fsm_encoding' attributes are not changed by this pass.\n"); log("\n"); log("Signals can be protected from being detected by this pass by setting the\n"); log("'fsm_encoding' attribute to \"none\".\n"); log("\n"); } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) { log_header("Executing FSM_DETECT pass (finding FSMs in design).\n"); extra_args(args, 1, design); CellTypes ct; ct.setup_internals(); ct.setup_internals_mem(); ct.setup_stdcells(); ct.setup_stdcells_mem(); for (auto &mod_it : design->modules_) { if (!design->selected(mod_it.second)) continue; module = mod_it.second; assign_map.set(module); sig2driver.clear(); sig2user.clear(); sig_at_port.clear(); for (auto &cell_it : module->cells_) for (auto &conn_it : cell_it.second->connections()) { if (ct.cell_output(cell_it.second->type, conn_it.first) || !ct.cell_known(cell_it.second->type)) { RTLIL::SigSpec sig = conn_it.second; assign_map.apply(sig); sig2driver.insert(sig, sig2driver_entry_t(cell_it.second, conn_it.first)); } if (!ct.cell_known(cell_it.second->type) || ct.cell_input(cell_it.second->type, conn_it.first)) { RTLIL::SigSpec sig = conn_it.second; assign_map.apply(sig); sig2user.insert(sig, sig2driver_entry_t(cell_it.second, conn_it.first)); } } for (auto &wire_it : module->wires_) if (wire_it.second->port_id != 0) sig_at_port.add(assign_map(RTLIL::SigSpec(wire_it.second))); for (auto &wire_it : module->wires_) if (design->selected(module, wire_it.second)) detect_fsm(wire_it.second); } assign_map.clear(); sig2driver.clear(); sig2user.clear(); muxtree_cells.clear(); } } FsmDetectPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/****************************************************************************** * c7a/core/hash_table.hpp * * Hash table with support for reduce and partitions. * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_CORE_HASH_TABLE_HEADER #define C7A_CORE_HASH_TABLE_HEADER #include <map> #include <iostream> #include <c7a/common/logger.hpp> #include <string> #include <vector> #include <stdexcept> #include <array> #include <deque> #include "c7a/api/function_traits.hpp" #include "c7a/data/data_manager.hpp" namespace c7a { namespace core { template <typename KeyExtractor, typename ReduceFunction, typename EmitterFunction> class ReducePreTable { static const bool debug = false; using key_t = typename FunctionTraits<KeyExtractor>::result_type; using value_t = typename FunctionTraits<ReduceFunction>::result_type; protected: struct hash_result { //! which partition number the item belongs to. size_t partition_id; //! index within the partition's sub-hashtable of this item size_t partition_offset; //! index within the whole hashtable size_t global_index; hash_result(key_t v, const ReducePreTable& ht) { size_t hashed = std::hash<key_t>() (v); // partition idx partition_offset = hashed % ht.num_buckets_per_partition_; // partition id partition_id = hashed % ht.num_partitions_; // global idx global_index = partition_id * ht.num_buckets_per_partition_ + partition_offset; } }; struct bucket_block { std::deque<std::pair<key_t, value_t>> items; bucket_block *next = NULL; }; public: ReducePreTable(size_t num_partitions, size_t num_buckets_init_scale, size_t num_buckets_resize_scale, size_t max_num_items_per_bucket, size_t max_num_items_table, KeyExtractor key_extractor, ReduceFunction reduce_function, std::vector<EmitterFunction> emit) : num_partitions_(num_partitions), num_buckets_init_scale_(num_buckets_init_scale), num_buckets_resize_scale_(num_buckets_resize_scale), max_num_items_per_bucket_(max_num_items_per_bucket), max_num_items_table_(max_num_items_table), key_extractor_(key_extractor), reduce_function_(reduce_function), emit_(emit) { init(); } ReducePreTable(size_t partition_size, KeyExtractor key_extractor, ReduceFunction reduce_function, std::vector<EmitterFunction> emit) : num_partitions_(partition_size), key_extractor_(key_extractor), reduce_function_(reduce_function), emit_(emit) { init(); } ~ReducePreTable() { } void init() { num_buckets_ = num_partitions_ * num_buckets_init_scale_; if (num_partitions_ > num_buckets_ && num_buckets_ % num_partitions_ != 0) { throw std::invalid_argument("partition_size must be less than or equal to num_buckets " "AND partition_size a divider of num_buckets"); } num_buckets_per_partition_ = num_buckets_ / num_partitions_; vector_.resize(num_buckets_, NULL); items_per_partition_.resize(num_partitions_, 0); } /*! * Inserts a key/value pair. * * Optionally, this may be reduce using the reduce function * in case the key already exists. */ void Insert(const value_t& p) { key_t key = key_extractor_(p); hash_result h(key, *this); LOG << "key: " << key << " to bucket id: " << h.global_index; long num_items_bucket = 0; bucket_block* current_bucket_block = vector_[h.global_index]; while(current_bucket_block != NULL) { for(auto &bucket_item : current_bucket_block->items) { // if item and key equals // then reduce if (key == bucket_item.first) { LOG << "match of key: " << key << " and " << bucket_item.first << " ... reducing..."; bucket_item.second = reduce_function_(bucket_item.second, p); LOG << "...finished reduce!"; return; } // increase num items in bucket for visited item num_items_bucket++; } if (current_bucket_block->next == NULL) { break; } current_bucket_block = current_bucket_block->next; } if (current_bucket_block == NULL) { current_bucket_block = vector_[h.global_index] = new bucket_block(); // TODO: ensure new struct gets cleaned up } else if (current_bucket_block->items.size() == bucket_block_size_) { current_bucket_block = current_bucket_block->next = new bucket_block(); // TODO: ensure new struct gets cleaned up } // insert new item in current bucket block current_bucket_block->items.push_back(std::pair<key_t, value_t>(key, p)); // increase counter for partition items_per_partition_[h.partition_id]++; // increase total counter table_size_++; // increase num items in bucket for inserted item num_items_bucket++; if (table_size_ > max_num_items_table_) { LOG << "spilling in progress"; FlushLargestPartition(); } if (num_items_bucket > max_num_items_per_bucket_) { ResizeUp(); }; } /*! * Flushes all items. */ void Flush() { LOG << "Flushing all items"; // retrieve items for (size_t i = 0; i < num_partitions_; i++) { FlushPartition(i); } LOG << "Flushed all items"; } /*! * Retrieves all items belonging to the partition * having the most items. Retrieved items are then forward * to the provided emitter. */ void FlushLargestPartition() { LOG << "Flushing items of largest partition"; // get partition with max size size_t p_size_max = 0; size_t p_idx = 0; for (size_t i = 0; i < num_partitions_; i++) { if (items_per_partition_[i] > p_size_max) { p_size_max = items_per_partition_[i]; p_idx = i; } } LOG << "currMax: " << p_size_max << " currentIdx: " << p_idx << " currentIdx*p_size: " << p_idx * num_buckets_per_partition_ << " CurrentIdx*p_size+p_size-1 " << p_idx * num_buckets_per_partition_ + num_buckets_per_partition_ - 1; LOG << "Largest patition id: " << p_idx; FlushPartition(p_idx); LOG << "Flushed items of largest partition"; } /*! * Flushes all items of a partition. */ void FlushPartition(size_t partition_id) { LOG << "Flushing items of partition with id: " << partition_id; for (size_t i = partition_id * num_buckets_per_partition_; i <= partition_id * num_buckets_per_partition_ + num_buckets_per_partition_ - 1; i++) { bucket_block* current_bucket_block = vector_[i]; while (current_bucket_block != NULL) { for (std::pair<key_t, value_t> &bucket_item : current_bucket_block->items) { emit_[partition_id](bucket_item.second); } current_bucket_block = current_bucket_block->next; } vector_[i] = NULL; } // reset total counter table_size_ -= items_per_partition_[partition_id]; // reset partition specific counter items_per_partition_[partition_id] = 0; LOG << "Flushed items of partition with id: " << partition_id; } /*! * Returns the total num of items. */ size_t Size() { return table_size_; } /*! * Returns the total num of items. */ size_t NumBuckets() { return num_buckets_; } /*! * Sets the maximum size of the hash table. We don't want to push 2vt elements before flush happens. */ void SetMaxSize(size_t size) { max_num_items_table_ = size; } /*! * Resizes the table by increasing the number of buckets using some * resize scale factor. All items are rehashed as part of the operation. */ void ResizeUp() { LOG << "Resizing"; num_buckets_ *= num_buckets_resize_scale_; num_buckets_per_partition_ = num_buckets_ / num_partitions_; // init new array std::vector<bucket_block*> vector_old = vector_; std::vector<bucket_block*> vector_new; vector_new.resize(num_buckets_, NULL); vector_ = vector_new; // rehash all items in old array for(bucket_block* b_block : vector_old) { bucket_block* current_bucket_block = b_block; while (current_bucket_block != NULL) { for (std::pair<key_t, value_t> &bucket_item : current_bucket_block->items) { Insert(bucket_item.second); } current_bucket_block = current_bucket_block->next; } } LOG << "Resized"; } /*! * Removes all items in the table, but NOT flushing them. */ void Clear() { LOG << "Clearing"; std::fill(vector_.begin(), vector_.end(), NULL); std::fill(items_per_partition_.begin(), items_per_partition_.end(), 0); table_size_ = 0; LOG << "Cleared"; } /*! * Removes all items in the table, but NOT flushing them. */ void Reset() { LOG << "Resetting"; num_buckets_ = num_partitions_ * num_buckets_init_scale_; num_buckets_per_partition_ = num_buckets_ / num_partitions_; vector_.resize(num_buckets_, NULL); std::fill(items_per_partition_.begin(), items_per_partition_.end(), 0); table_size_ = 0; LOG << "Resetted"; } /*! * Prints content of hash table. */ void Print() { LOG << "Printing"; for (int i = 0; i < num_buckets_; i++) { if (vector_[i] == NULL) { LOG << "bucket id: " << i << " empty"; } else { std::string log = ""; bucket_block* current_bucket_block = vector_[i]; while (current_bucket_block != NULL) { log += "block: "; for (std::pair<key_t, value_t> bucket_item : current_bucket_block->items) { if (&bucket_item != NULL) { log += "("; log += bucket_item.first; log += ", "; //log += bucket_item.second; // TODO: How to convert value_t to a string? log += ") "; } } current_bucket_block = current_bucket_block->next; } LOG << "bucket id: " << i << " " << log; } } return; } private: size_t num_partitions_; // partition size size_t num_buckets_; // num buckets size_t num_buckets_per_partition_; // num buckets per partition size_t num_buckets_init_scale_ = 65536; // set number of buckets per partition based on num_partitions // multiplied with some scaling factor, must be equal to or greater than 1 size_t num_buckets_resize_scale_ = 2; // resize scale on max_num_items_per_bucket_ size_t bucket_block_size_ = 32; // size of bucket blocks size_t max_num_items_per_bucket_ = 256; // max num of items per bucket before resize std::vector<size_t> items_per_partition_; // num items per partition size_t table_size_ = 0; // total number of items size_t max_num_items_table_ = 1048576; // max num of items before spilling of largest partition KeyExtractor key_extractor_; ReduceFunction reduce_function_; std::vector<EmitterFunction> emit_; std::vector<bucket_block*> vector_; }; } } #endif // !C7A_CORE_HASH_TABLE_HEADER /******************************************************************************/ <commit_msg>some minor optimization<commit_after>/****************************************************************************** * c7a/core/hash_table.hpp * * Hash table with support for reduce and partitions. * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_CORE_HASH_TABLE_HEADER #define C7A_CORE_HASH_TABLE_HEADER #include <map> #include <iostream> #include <c7a/common/logger.hpp> #include <string> #include <vector> #include <stdexcept> #include <array> #include <deque> #include "c7a/api/function_traits.hpp" #include "c7a/data/data_manager.hpp" namespace c7a { namespace core { template <typename KeyExtractor, typename ReduceFunction, typename EmitterFunction> class ReducePreTable { static const bool debug = false; using key_t = typename FunctionTraits<KeyExtractor>::result_type; using value_t = typename FunctionTraits<ReduceFunction>::result_type; protected: struct hash_result { //! which partition number the item belongs to. size_t partition_id; //! index within the partition's sub-hashtable of this item size_t partition_offset; //! index within the whole hashtable size_t global_index; hash_result(key_t v, const ReducePreTable& ht) { size_t hashed = std::hash<key_t>() (v); // partition idx partition_offset = hashed % ht.num_buckets_per_partition_; // partition id partition_id = hashed % ht.num_partitions_; // global idx global_index = partition_id * ht.num_buckets_per_partition_ + partition_offset; } }; struct bucket_block { std::vector<std::pair<key_t, value_t>> items; bucket_block *next = NULL; bucket_block(const ReducePreTable &ht) { items.reserve(ht.bucket_block_size_); } }; public: ReducePreTable(size_t num_partitions, size_t num_buckets_init_scale, size_t num_buckets_resize_scale, size_t max_num_items_per_bucket, size_t max_num_items_table, KeyExtractor key_extractor, ReduceFunction reduce_function, std::vector<EmitterFunction> emit) : num_partitions_(num_partitions), num_buckets_init_scale_(num_buckets_init_scale), num_buckets_resize_scale_(num_buckets_resize_scale), max_num_items_per_bucket_(max_num_items_per_bucket), max_num_items_table_(max_num_items_table), key_extractor_(key_extractor), reduce_function_(reduce_function), emit_(emit) { init(); } ReducePreTable(size_t partition_size, KeyExtractor key_extractor, ReduceFunction reduce_function, std::vector<EmitterFunction> emit) : num_partitions_(partition_size), key_extractor_(key_extractor), reduce_function_(reduce_function), emit_(emit) { init(); } ~ReducePreTable() { } void init() { num_buckets_ = num_partitions_ * num_buckets_init_scale_; if (num_partitions_ > num_buckets_ && num_buckets_ % num_partitions_ != 0) { throw std::invalid_argument("partition_size must be less than or equal to num_buckets " "AND partition_size a divider of num_buckets"); } num_buckets_per_partition_ = num_buckets_ / num_partitions_; vector_.resize(num_buckets_, NULL); items_per_partition_.resize(num_partitions_, 0); } /*! * Inserts a key/value pair. * * Optionally, this may be reduce using the reduce function * in case the key already exists. */ void Insert(const value_t& p) { key_t key = key_extractor_(p); hash_result h(key, *this); LOG << "key: " << key << " to bucket id: " << h.global_index; long num_items_bucket = 0; bucket_block* current_bucket_block = vector_[h.global_index]; while(current_bucket_block != NULL) { for(auto &bucket_item : current_bucket_block->items) { // if item and key equals // then reduce if (key == bucket_item.first) { LOG << "match of key: " << key << " and " << bucket_item.first << " ... reducing..."; bucket_item.second = reduce_function_(bucket_item.second, p); LOG << "...finished reduce!"; return; } // increase num items in bucket for visited item num_items_bucket++; } if (current_bucket_block->next == NULL) { break; } current_bucket_block = current_bucket_block->next; } if (current_bucket_block == NULL) { current_bucket_block = vector_[h.global_index] = new bucket_block(*this); // TODO: ensure new struct gets deleted } else if (current_bucket_block->items.size() == bucket_block_size_) { current_bucket_block = current_bucket_block->next = new bucket_block(*this); // TODO: ensure new struct gets deleted } // insert new item in current bucket block current_bucket_block->items.push_back(std::pair<key_t, value_t>(key, p)); // increase counter for partition items_per_partition_[h.partition_id]++; // increase total counter table_size_++; // increase num items in bucket for inserted item num_items_bucket++; if (table_size_ > max_num_items_table_) { LOG << "spilling in progress"; FlushLargestPartition(); } if (num_items_bucket > max_num_items_per_bucket_) { ResizeUp(); }; } /*! * Flushes all items. */ void Flush() { LOG << "Flushing all items"; // retrieve items for (size_t i = 0; i < num_partitions_; i++) { FlushPartition(i); } LOG << "Flushed all items"; } /*! * Retrieves all items belonging to the partition * having the most items. Retrieved items are then forward * to the provided emitter. */ void FlushLargestPartition() { LOG << "Flushing items of largest partition"; // get partition with max size size_t p_size_max = 0; size_t p_idx = 0; for (size_t i = 0; i < num_partitions_; i++) { if (items_per_partition_[i] > p_size_max) { p_size_max = items_per_partition_[i]; p_idx = i; } } LOG << "currMax: " << p_size_max << " currentIdx: " << p_idx << " currentIdx*p_size: " << p_idx * num_buckets_per_partition_ << " CurrentIdx*p_size+p_size-1 " << p_idx * num_buckets_per_partition_ + num_buckets_per_partition_ - 1; LOG << "Largest patition id: " << p_idx; FlushPartition(p_idx); LOG << "Flushed items of largest partition"; } /*! * Flushes all items of a partition. */ void FlushPartition(size_t partition_id) { LOG << "Flushing items of partition with id: " << partition_id; for (size_t i = partition_id * num_buckets_per_partition_; i <= partition_id * num_buckets_per_partition_ + num_buckets_per_partition_ - 1; i++) { bucket_block* current_bucket_block = vector_[i]; while (current_bucket_block != NULL) { for (std::pair<key_t, value_t> &bucket_item : current_bucket_block->items) { emit_[partition_id](bucket_item.second); } current_bucket_block = current_bucket_block->next; } vector_[i] = NULL; } // reset total counter table_size_ -= items_per_partition_[partition_id]; // reset partition specific counter items_per_partition_[partition_id] = 0; LOG << "Flushed items of partition with id: " << partition_id; } /*! * Returns the total num of items. */ size_t Size() { return table_size_; } /*! * Returns the total num of items. */ size_t NumBuckets() { return num_buckets_; } /*! * Sets the maximum size of the hash table. We don't want to push 2vt elements before flush happens. */ void SetMaxSize(size_t size) { max_num_items_table_ = size; } /*! * Resizes the table by increasing the number of buckets using some * resize scale factor. All items are rehashed as part of the operation. */ void ResizeUp() { LOG << "Resizing"; num_buckets_ *= num_buckets_resize_scale_; num_buckets_per_partition_ = num_buckets_ / num_partitions_; // init new array std::vector<bucket_block*> vector_old = vector_; std::vector<bucket_block*> vector_new; vector_new.resize(num_buckets_, NULL); vector_ = vector_new; // rehash all items in old array for(bucket_block* b_block : vector_old) { bucket_block* current_bucket_block = b_block; while (current_bucket_block != NULL) { for (std::pair<key_t, value_t> &bucket_item : current_bucket_block->items) { Insert(bucket_item.second); } current_bucket_block = current_bucket_block->next; } } LOG << "Resized"; } /*! * Removes all items in the table, but NOT flushing them. */ void Clear() { LOG << "Clearing"; std::fill(vector_.begin(), vector_.end(), NULL); std::fill(items_per_partition_.begin(), items_per_partition_.end(), 0); table_size_ = 0; LOG << "Cleared"; } /*! * Removes all items in the table, but NOT flushing them. */ void Reset() { LOG << "Resetting"; num_buckets_ = num_partitions_ * num_buckets_init_scale_; num_buckets_per_partition_ = num_buckets_ / num_partitions_; vector_.resize(num_buckets_, NULL); std::fill(items_per_partition_.begin(), items_per_partition_.end(), 0); table_size_ = 0; LOG << "Resetted"; } /*! * Prints content of hash table. */ void Print() { LOG << "Printing"; for (int i = 0; i < num_buckets_; i++) { if (vector_[i] == NULL) { LOG << "bucket id: " << i << " empty"; } else { std::string log = ""; bucket_block* current_bucket_block = vector_[i]; while (current_bucket_block != NULL) { log += "block: "; for (std::pair<key_t, value_t> bucket_item : current_bucket_block->items) { if (&bucket_item != NULL) { log += "("; log += bucket_item.first; log += ", "; //log += bucket_item.second; // TODO: How to convert value_t to a string? log += ") "; } } current_bucket_block = current_bucket_block->next; } LOG << "bucket id: " << i << " " << log; } } return; } private: size_t num_partitions_; // partition size size_t num_buckets_; // num buckets size_t num_buckets_per_partition_; // num buckets per partition size_t num_buckets_init_scale_ = 65536; // set number of buckets per partition based on num_partitions // multiplied with some scaling factor, must be equal to or greater than 1 size_t num_buckets_resize_scale_ = 2; // resize scale on max_num_items_per_bucket_ size_t bucket_block_size_ = 32; // size of bucket blocks size_t max_num_items_per_bucket_ = 256; // max num of items per bucket before resize std::vector<size_t> items_per_partition_; // num items per partition size_t table_size_ = 0; // total number of items size_t max_num_items_table_ = 1048576; // max num of items before spilling of largest partition KeyExtractor key_extractor_; ReduceFunction reduce_function_; std::vector<EmitterFunction> emit_; std::vector<bucket_block*> vector_; }; } } #endif // !C7A_CORE_HASH_TABLE_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg & Daniel Wallin 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/pch.hpp" #include "libtorrent/time.hpp" // for total_seconds #include <libtorrent/kademlia/traversal_algorithm.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include <libtorrent/kademlia/node.hpp> #include <libtorrent/session_status.hpp> #include "libtorrent/broadcast_socket.hpp" // for cidr_distance #include <boost/bind.hpp> namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DEFINE_LOG(traversal) #endif observer_ptr traversal_algorithm::new_observer(void* ptr , udp::endpoint const& ep, node_id const& id) { observer_ptr o(new (ptr) null_observer(boost::intrusive_ptr<traversal_algorithm>(this), ep, id)); #if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS o->m_in_constructor = false; #endif return o; } traversal_algorithm::traversal_algorithm( node_impl& node , node_id target) : m_ref_count(0) , m_node(node) , m_target(target) , m_invoke_count(0) , m_branch_factor(3) , m_responses(0) , m_timeouts(0) , m_num_target_nodes(m_node.m_table.bucket_size() * 2) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << "] new traversal process. Target: " << target; #endif } // returns true of lhs and rhs are too close to each other to appear // in the same DHT search under different node IDs bool compare_ip_cidr(observer_ptr const& lhs, observer_ptr const& rhs) { if (lhs->target_addr().is_v4() != rhs->target_addr().is_v4()) return false; // the number of bits in the IPs that may match. If // more bits that this matches, something suspicious is // going on and we shouldn't add the second one to our // routing table int cutoff = rhs->target_addr().is_v4() ? 4 : 64; int dist = cidr_distance(lhs->target_addr(), rhs->target_addr()); return dist <= cutoff; } void traversal_algorithm::add_entry(node_id const& id, udp::endpoint addr, unsigned char flags) { TORRENT_ASSERT(m_node.m_rpc.allocation_size() >= sizeof(find_data_observer)); void* ptr = m_node.m_rpc.allocate_observer(); if (ptr == 0) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "[" << this << ":" << name() << "] failed to allocate memory for observer. aborting!"; #endif done(); return; } observer_ptr o = new_observer(ptr, addr, id); if (id.is_all_zeros()) { o->set_id(generate_random_id()); o->flags |= observer::flag_no_id; } o->flags |= flags; std::vector<observer_ptr>::iterator i = std::lower_bound( m_results.begin() , m_results.end() , o , boost::bind( compare_ref , boost::bind(&observer::id, _1) , boost::bind(&observer::id, _2) , m_target ) ); if (i == m_results.end() || (*i)->id() != id) { if (m_node.settings().restrict_search_ips) { // don't allow multiple entries from IPs very close to each other std::vector<observer_ptr>::iterator j = std::find_if( m_results.begin(), m_results.end(), boost::bind(&compare_ip_cidr, _1, o)); if (j != m_results.end()) { // we already have a node in this search with an IP very // close to this one. We know that it's not the same, because // it claims a different node-ID. Ignore this to avoid attacks #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "ignoring DHT search entry: " << o->id() << " " << o->target_addr() << " existing node: " << (*j)->id() << " " << (*j)->target_addr(); #endif return; } } TORRENT_ASSERT(std::find_if(m_results.begin(), m_results.end() , boost::bind(&observer::id, _1) == id) == m_results.end()); #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "[" << this << ":" << name() << "] adding result: " << id << " " << addr; #endif i = m_results.insert(i, o); } if (m_results.size() > 100) { #ifdef TORRENT_DEBUG for (int i = 100; i < m_results.size(); ++i) m_results[i]->m_was_abandoned = true; #endif m_results.resize(100); } } void traversal_algorithm::start() { // in case the routing table is empty, use the // router nodes in the table if (m_results.empty()) add_router_entries(); init(); add_requests(); } void* traversal_algorithm::allocate_observer() { return m_node.m_rpc.allocate_observer(); } void traversal_algorithm::free_observer(void* ptr) { m_node.m_rpc.free_observer(ptr); } void traversal_algorithm::traverse(node_id const& id, udp::endpoint addr) { #ifdef TORRENT_DHT_VERBOSE_LOGGING if (id.is_all_zeros()) TORRENT_LOG(traversal) << time_now_string() << "[" << this << ":" << name() << "] WARNING: node returned a list which included a node with id 0"; #endif add_entry(id, addr, 0); } void traversal_algorithm::finished(observer_ptr o) { #ifdef TORRENT_DEBUG std::vector<observer_ptr>::iterator i = std::find( m_results.begin(), m_results.end(), o); TORRENT_ASSERT(i != m_results.end() || m_results.size() == 100); #endif // if this flag is set, it means we increased the // branch factor for it, and we should restore it if (o->flags & observer::flag_short_timeout) --m_branch_factor; TORRENT_ASSERT(o->flags & observer::flag_queried); o->flags |= observer::flag_alive; ++m_responses; --m_invoke_count; TORRENT_ASSERT(m_invoke_count >= 0); add_requests(); if (m_invoke_count == 0) done(); } // prevent request means that the total number of requests has // overflown. This query failed because it was the oldest one. // So, if this is true, don't make another request void traversal_algorithm::failed(observer_ptr o, int flags) { TORRENT_ASSERT(m_invoke_count >= 0); if (m_results.empty()) return; TORRENT_ASSERT(o->flags & observer::flag_queried); if (flags & short_timeout) { // short timeout means that it has been more than // two seconds since we sent the request, and that // we'll most likely not get a response. But, in case // we do get a late response, keep the handler // around for some more, but open up the slot // by increasing the branch factor if ((o->flags & observer::flag_short_timeout) == 0) ++m_branch_factor; o->flags |= observer::flag_short_timeout; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << ":" << name() << "] first chance timeout: " << o->id() << " " << o->target_ep() << " branch-factor: " << m_branch_factor << " invoke-count: " << m_invoke_count; #endif } else { o->flags |= observer::flag_failed; // if this flag is set, it means we increased the // branch factor for it, and we should restore it if (o->flags & observer::flag_short_timeout) --m_branch_factor; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << ":" << name() << "] failed: " << o->id() << " " << o->target_ep() << " branch-factor: " << m_branch_factor << " invoke-count: " << m_invoke_count; #endif // don't tell the routing table about // node ids that we just generated ourself if ((o->flags & observer::flag_no_id) == 0) m_node.m_table.node_failed(o->id(), o->target_ep()); ++m_timeouts; --m_invoke_count; TORRENT_ASSERT(m_invoke_count >= 0); } if (flags & prevent_request) { --m_branch_factor; if (m_branch_factor <= 0) m_branch_factor = 1; } add_requests(); if (m_invoke_count == 0) done(); } void traversal_algorithm::done() { // delete all our references to the observer objects so // they will in turn release the traversal algorithm m_results.clear(); } void traversal_algorithm::add_requests() { int results_target = m_num_target_nodes; // Find the first node that hasn't already been queried. for (std::vector<observer_ptr>::iterator i = m_results.begin() , end(m_results.end()); i != end && results_target > 0 && m_invoke_count < m_branch_factor; ++i) { if ((*i)->flags & observer::flag_alive) --results_target; if ((*i)->flags & observer::flag_queried) continue; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << ":" << name() << "]" << " nodes-left: " << (m_results.end() - i) << " invoke-count: " << m_invoke_count << " branch-factor: " << m_branch_factor; #endif if (invoke(*i)) { TORRENT_ASSERT(m_invoke_count >= 0); ++m_invoke_count; (*i)->flags |= observer::flag_queried; } } } void traversal_algorithm::add_router_entries() { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " using router nodes to initiate traversal algorithm. " << std::distance(m_node.m_table.router_begin(), m_node.m_table.router_end()) << " routers"; #endif for (routing_table::router_iterator i = m_node.m_table.router_begin() , end(m_node.m_table.router_end()); i != end; ++i) { add_entry(node_id(0), *i, observer::flag_initial); } } void traversal_algorithm::init() { // update the last activity of this bucket m_node.m_table.touch_bucket(m_target); m_branch_factor = m_node.branch_factor(); m_node.add_traversal_algorithm(this); } traversal_algorithm::~traversal_algorithm() { m_node.remove_traversal_algorithm(this); } void traversal_algorithm::status(dht_lookup& l) { l.timeouts = m_timeouts; l.responses = m_responses; l.outstanding_requests = m_invoke_count; l.branch_factor = m_branch_factor; l.type = name(); l.nodes_left = 0; l.first_timeout = 0; int last_sent = INT_MAX; ptime now = time_now(); for (std::vector<observer_ptr>::iterator i = m_results.begin() , end(m_results.end()); i != end; ++i) { observer& o = **i; if (o.flags & observer::flag_queried) { last_sent = (std::min)(last_sent, total_seconds(now - o.sent())); if (o.has_short_timeout()) ++l.first_timeout; continue; } ++l.nodes_left; } l.last_sent = last_sent; } } } // namespace libtorrent::dht <commit_msg>release asserts fix<commit_after>/* Copyright (c) 2006, Arvid Norberg & Daniel Wallin 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/pch.hpp" #include "libtorrent/time.hpp" // for total_seconds #include <libtorrent/kademlia/traversal_algorithm.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include <libtorrent/kademlia/node.hpp> #include <libtorrent/session_status.hpp> #include "libtorrent/broadcast_socket.hpp" // for cidr_distance #include <boost/bind.hpp> namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DEFINE_LOG(traversal) #endif observer_ptr traversal_algorithm::new_observer(void* ptr , udp::endpoint const& ep, node_id const& id) { observer_ptr o(new (ptr) null_observer(boost::intrusive_ptr<traversal_algorithm>(this), ep, id)); #if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS o->m_in_constructor = false; #endif return o; } traversal_algorithm::traversal_algorithm( node_impl& node , node_id target) : m_ref_count(0) , m_node(node) , m_target(target) , m_invoke_count(0) , m_branch_factor(3) , m_responses(0) , m_timeouts(0) , m_num_target_nodes(m_node.m_table.bucket_size() * 2) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << "] new traversal process. Target: " << target; #endif } // returns true of lhs and rhs are too close to each other to appear // in the same DHT search under different node IDs bool compare_ip_cidr(observer_ptr const& lhs, observer_ptr const& rhs) { if (lhs->target_addr().is_v4() != rhs->target_addr().is_v4()) return false; // the number of bits in the IPs that may match. If // more bits that this matches, something suspicious is // going on and we shouldn't add the second one to our // routing table int cutoff = rhs->target_addr().is_v4() ? 4 : 64; int dist = cidr_distance(lhs->target_addr(), rhs->target_addr()); return dist <= cutoff; } void traversal_algorithm::add_entry(node_id const& id, udp::endpoint addr, unsigned char flags) { TORRENT_ASSERT(m_node.m_rpc.allocation_size() >= sizeof(find_data_observer)); void* ptr = m_node.m_rpc.allocate_observer(); if (ptr == 0) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "[" << this << ":" << name() << "] failed to allocate memory for observer. aborting!"; #endif done(); return; } observer_ptr o = new_observer(ptr, addr, id); if (id.is_all_zeros()) { o->set_id(generate_random_id()); o->flags |= observer::flag_no_id; } o->flags |= flags; std::vector<observer_ptr>::iterator i = std::lower_bound( m_results.begin() , m_results.end() , o , boost::bind( compare_ref , boost::bind(&observer::id, _1) , boost::bind(&observer::id, _2) , m_target ) ); if (i == m_results.end() || (*i)->id() != id) { if (m_node.settings().restrict_search_ips) { // don't allow multiple entries from IPs very close to each other std::vector<observer_ptr>::iterator j = std::find_if( m_results.begin(), m_results.end(), boost::bind(&compare_ip_cidr, _1, o)); if (j != m_results.end()) { // we already have a node in this search with an IP very // close to this one. We know that it's not the same, because // it claims a different node-ID. Ignore this to avoid attacks #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "ignoring DHT search entry: " << o->id() << " " << o->target_addr() << " existing node: " << (*j)->id() << " " << (*j)->target_addr(); #endif return; } } TORRENT_ASSERT(std::find_if(m_results.begin(), m_results.end() , boost::bind(&observer::id, _1) == id) == m_results.end()); #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "[" << this << ":" << name() << "] adding result: " << id << " " << addr; #endif i = m_results.insert(i, o); } if (m_results.size() > 100) { #if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS for (int i = 100; i < m_results.size(); ++i) m_results[i]->m_was_abandoned = true; #endif m_results.resize(100); } } void traversal_algorithm::start() { // in case the routing table is empty, use the // router nodes in the table if (m_results.empty()) add_router_entries(); init(); add_requests(); } void* traversal_algorithm::allocate_observer() { return m_node.m_rpc.allocate_observer(); } void traversal_algorithm::free_observer(void* ptr) { m_node.m_rpc.free_observer(ptr); } void traversal_algorithm::traverse(node_id const& id, udp::endpoint addr) { #ifdef TORRENT_DHT_VERBOSE_LOGGING if (id.is_all_zeros()) TORRENT_LOG(traversal) << time_now_string() << "[" << this << ":" << name() << "] WARNING: node returned a list which included a node with id 0"; #endif add_entry(id, addr, 0); } void traversal_algorithm::finished(observer_ptr o) { #ifdef TORRENT_DEBUG std::vector<observer_ptr>::iterator i = std::find( m_results.begin(), m_results.end(), o); TORRENT_ASSERT(i != m_results.end() || m_results.size() == 100); #endif // if this flag is set, it means we increased the // branch factor for it, and we should restore it if (o->flags & observer::flag_short_timeout) --m_branch_factor; TORRENT_ASSERT(o->flags & observer::flag_queried); o->flags |= observer::flag_alive; ++m_responses; --m_invoke_count; TORRENT_ASSERT(m_invoke_count >= 0); add_requests(); if (m_invoke_count == 0) done(); } // prevent request means that the total number of requests has // overflown. This query failed because it was the oldest one. // So, if this is true, don't make another request void traversal_algorithm::failed(observer_ptr o, int flags) { TORRENT_ASSERT(m_invoke_count >= 0); if (m_results.empty()) return; TORRENT_ASSERT(o->flags & observer::flag_queried); if (flags & short_timeout) { // short timeout means that it has been more than // two seconds since we sent the request, and that // we'll most likely not get a response. But, in case // we do get a late response, keep the handler // around for some more, but open up the slot // by increasing the branch factor if ((o->flags & observer::flag_short_timeout) == 0) ++m_branch_factor; o->flags |= observer::flag_short_timeout; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << ":" << name() << "] first chance timeout: " << o->id() << " " << o->target_ep() << " branch-factor: " << m_branch_factor << " invoke-count: " << m_invoke_count; #endif } else { o->flags |= observer::flag_failed; // if this flag is set, it means we increased the // branch factor for it, and we should restore it if (o->flags & observer::flag_short_timeout) --m_branch_factor; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << ":" << name() << "] failed: " << o->id() << " " << o->target_ep() << " branch-factor: " << m_branch_factor << " invoke-count: " << m_invoke_count; #endif // don't tell the routing table about // node ids that we just generated ourself if ((o->flags & observer::flag_no_id) == 0) m_node.m_table.node_failed(o->id(), o->target_ep()); ++m_timeouts; --m_invoke_count; TORRENT_ASSERT(m_invoke_count >= 0); } if (flags & prevent_request) { --m_branch_factor; if (m_branch_factor <= 0) m_branch_factor = 1; } add_requests(); if (m_invoke_count == 0) done(); } void traversal_algorithm::done() { // delete all our references to the observer objects so // they will in turn release the traversal algorithm m_results.clear(); } void traversal_algorithm::add_requests() { int results_target = m_num_target_nodes; // Find the first node that hasn't already been queried. for (std::vector<observer_ptr>::iterator i = m_results.begin() , end(m_results.end()); i != end && results_target > 0 && m_invoke_count < m_branch_factor; ++i) { if ((*i)->flags & observer::flag_alive) --results_target; if ((*i)->flags & observer::flag_queried) continue; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << ":" << name() << "]" << " nodes-left: " << (m_results.end() - i) << " invoke-count: " << m_invoke_count << " branch-factor: " << m_branch_factor; #endif if (invoke(*i)) { TORRENT_ASSERT(m_invoke_count >= 0); ++m_invoke_count; (*i)->flags |= observer::flag_queried; } } } void traversal_algorithm::add_router_entries() { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " using router nodes to initiate traversal algorithm. " << std::distance(m_node.m_table.router_begin(), m_node.m_table.router_end()) << " routers"; #endif for (routing_table::router_iterator i = m_node.m_table.router_begin() , end(m_node.m_table.router_end()); i != end; ++i) { add_entry(node_id(0), *i, observer::flag_initial); } } void traversal_algorithm::init() { // update the last activity of this bucket m_node.m_table.touch_bucket(m_target); m_branch_factor = m_node.branch_factor(); m_node.add_traversal_algorithm(this); } traversal_algorithm::~traversal_algorithm() { m_node.remove_traversal_algorithm(this); } void traversal_algorithm::status(dht_lookup& l) { l.timeouts = m_timeouts; l.responses = m_responses; l.outstanding_requests = m_invoke_count; l.branch_factor = m_branch_factor; l.type = name(); l.nodes_left = 0; l.first_timeout = 0; int last_sent = INT_MAX; ptime now = time_now(); for (std::vector<observer_ptr>::iterator i = m_results.begin() , end(m_results.end()); i != end; ++i) { observer& o = **i; if (o.flags & observer::flag_queried) { last_sent = (std::min)(last_sent, total_seconds(now - o.sent())); if (o.has_short_timeout()) ++l.first_timeout; continue; } ++l.nodes_left; } l.last_sent = last_sent; } } } // namespace libtorrent::dht <|endoftext|>
<commit_before>/**********************************************************************************/ /* Pika: Phase field snow micro-structure model */ /* */ /* (C) 2014 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 */ /**********************************************************************************/ #include "DoubleWellPotentialMMS.h" registerMooseObject("PikaApp", DoubleWellPotentialMMS); template<> InputParameters validParams<DoubleWellPotentialMMS>() { InputParameters params = validParams<Kernel>(); return params; } DoubleWellPotentialMMS::DoubleWellPotentialMMS(const InputParameters & parameters) : Kernel(parameters) { } Real DoubleWellPotentialMMS::computeQpResidual() { Real t = _t; Real x = _q_point[_qp](0); Real y = _q_point[_qp](1); Real f = -t*(pow(x - 0.5, 2) + pow(y - 0.5, 2) - 0.125) + pow(t*(pow(x - 0.5, 2) + pow(y - 0.5, 2) - 0.125), 3.0); return -_test[_i][_qp] * f; } <commit_msg>Continue to register DoubleWellPotential in Pika.<commit_after>/**********************************************************************************/ /* Pika: Phase field snow micro-structure model */ /* */ /* (C) 2014 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 */ /**********************************************************************************/ #include "DoubleWellPotentialMMS.h" #include "DoubleWellPotential.h" registerMooseObject("PikaApp", DoubleWellPotentialMMS); // FIXME: DoubleWellPotential is in the phase_field module and should be // registered there instead. registerMooseObject("PikaApp", DoubleWellPotential); template<> InputParameters validParams<DoubleWellPotentialMMS>() { InputParameters params = validParams<Kernel>(); return params; } DoubleWellPotentialMMS::DoubleWellPotentialMMS(const InputParameters & parameters) : Kernel(parameters) { } Real DoubleWellPotentialMMS::computeQpResidual() { Real t = _t; Real x = _q_point[_qp](0); Real y = _q_point[_qp](1); Real f = -t*(pow(x - 0.5, 2) + pow(y - 0.5, 2) - 0.125) + pow(t*(pow(x - 0.5, 2) + pow(y - 0.5, 2) - 0.125), 3.0); return -_test[_i][_qp] * f; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: countermain.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2004-03-17 11:51:35 $ * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright (c) 2003 by Sun Microsystems, 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Sun Microsystems, 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. * *************************************************************************/ /*************************************************************************************************** *************************************************************************************************** * * simple client application registering and using the counter component. * *************************************************************************************************** **************************************************************************************************/ #include <stdio.h> #include <rtl/ustring.hxx> #include <osl/diagnose.h> #include <cppuhelper/bootstrap.hxx> // generated c++ interfaces #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/registry/XImplementationRegistration.hpp> #include <foo/XCountable.hpp> using namespace foo; using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::registry; using namespace ::rtl; //================================================================================================== int SAL_CALL main(int argc, char **argv) { Reference< XSimpleRegistry > xReg = createSimpleRegistry(); OSL_ENSURE( xReg.is(), "### cannot get service instance of \"com.sun.star.regiystry.SimpleRegistry\"!" ); xReg->open(OUString::createFromAscii("counter.uno.rdb"), sal_False, sal_False); OSL_ENSURE( xReg->isValid(), "### cannot open test registry \"counter.uno.rdb\"!" ); Reference< XComponentContext > xContext = bootstrap_InitialComponentContext(xReg); OSL_ENSURE( xContext.is(), "### cannot creage intial component context!" ); Reference< XMultiComponentFactory > xMgr = xContext->getServiceManager(); OSL_ENSURE( xMgr.is(), "### cannot get initial service manager!" ); // register my counter component Reference< XImplementationRegistration > xImplReg( xMgr->createInstanceWithContext(OUString::createFromAscii("com.sun.star.registry.ImplementationRegistration"), xContext), UNO_QUERY); OSL_ENSURE( xImplReg.is(), "### cannot get service instance of \"com.sun.star.registry.ImplementationRegistration\"!" ); if (xImplReg.is()) { xImplReg->registerImplementation( OUString::createFromAscii("com.sun.star.loader.SharedLibrary"), // loader for component #ifdef UNX #ifdef MACOSX OUString::createFromAscii("counter.uno.dylib"), // component location #else OUString::createFromAscii("counter.uno.so"), // component location #endif #else OUString::createFromAscii("counter.uno.dll"), // component location #endif Reference< XSimpleRegistry >() // registry omitted, // defaulting to service manager registry used ); // get a counter instance Reference< XInterface > xx ; xx = xMgr->createInstanceWithContext(OUString::createFromAscii("foo.Counter"), xContext); Reference< XCountable > xCount( xx, UNO_QUERY ); OSL_ENSURE( xCount.is(), "### cannot get service instance of \"foo.Counter\"!" ); if (xCount.is()) { xCount->setCount( 42 ); fprintf( stdout , "%d," , xCount->getCount() ); fprintf( stdout , "%d," , xCount->increment() ); fprintf( stdout , "%d\n" , xCount->decrement() ); } } Reference< XComponent >::query( xContext )->dispose(); return 0; } <commit_msg>INTEGRATION: CWS pchfix02 (1.6.152); FILE MERGED 2006/09/01 17:32:27 kaib 1.6.152.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * $RCSfile: countermain.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-17 00:16:42 $ * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright (c) 2003 by Sun Microsystems, 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Sun Microsystems, 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. * *************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_odk.hxx" /*************************************************************************************************** *************************************************************************************************** * * simple client application registering and using the counter component. * *************************************************************************************************** **************************************************************************************************/ #include <stdio.h> #include <rtl/ustring.hxx> #include <osl/diagnose.h> #include <cppuhelper/bootstrap.hxx> // generated c++ interfaces #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/registry/XImplementationRegistration.hpp> #include <foo/XCountable.hpp> using namespace foo; using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::registry; using namespace ::rtl; //================================================================================================== int SAL_CALL main(int argc, char **argv) { Reference< XSimpleRegistry > xReg = createSimpleRegistry(); OSL_ENSURE( xReg.is(), "### cannot get service instance of \"com.sun.star.regiystry.SimpleRegistry\"!" ); xReg->open(OUString::createFromAscii("counter.uno.rdb"), sal_False, sal_False); OSL_ENSURE( xReg->isValid(), "### cannot open test registry \"counter.uno.rdb\"!" ); Reference< XComponentContext > xContext = bootstrap_InitialComponentContext(xReg); OSL_ENSURE( xContext.is(), "### cannot creage intial component context!" ); Reference< XMultiComponentFactory > xMgr = xContext->getServiceManager(); OSL_ENSURE( xMgr.is(), "### cannot get initial service manager!" ); // register my counter component Reference< XImplementationRegistration > xImplReg( xMgr->createInstanceWithContext(OUString::createFromAscii("com.sun.star.registry.ImplementationRegistration"), xContext), UNO_QUERY); OSL_ENSURE( xImplReg.is(), "### cannot get service instance of \"com.sun.star.registry.ImplementationRegistration\"!" ); if (xImplReg.is()) { xImplReg->registerImplementation( OUString::createFromAscii("com.sun.star.loader.SharedLibrary"), // loader for component #ifdef UNX #ifdef MACOSX OUString::createFromAscii("counter.uno.dylib"), // component location #else OUString::createFromAscii("counter.uno.so"), // component location #endif #else OUString::createFromAscii("counter.uno.dll"), // component location #endif Reference< XSimpleRegistry >() // registry omitted, // defaulting to service manager registry used ); // get a counter instance Reference< XInterface > xx ; xx = xMgr->createInstanceWithContext(OUString::createFromAscii("foo.Counter"), xContext); Reference< XCountable > xCount( xx, UNO_QUERY ); OSL_ENSURE( xCount.is(), "### cannot get service instance of \"foo.Counter\"!" ); if (xCount.is()) { xCount->setCount( 42 ); fprintf( stdout , "%d," , xCount->getCount() ); fprintf( stdout , "%d," , xCount->increment() ); fprintf( stdout , "%d\n" , xCount->decrement() ); } } Reference< XComponent >::query( xContext )->dispose(); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2014 by Philip N. Garner * * See the file COPYING for the licence associated with this software. * * Author(s): * Phil Garner, December 2014 */ /* * Take care here; there is a boost thing called path. In this sense, there is * the possibility that one could be confused as the other. Of course, it * boils down to being careful with namespaces. */ #include "lube/path.h" #include "boost/filesystem/operations.hpp" namespace fs = boost::filesystem; namespace libube { /** Concrete implementation of path module */ class Path : public path { public: Path(var iArg); var dir(bool iVal); var rdir(bool iVal); var tree(); private: fs::path mPath; var tree(fs::path iPath); }; /** Factory function to create a class */ void factory(Module** oModule, var iArg) { *oModule = new Path(iArg); } }; using namespace libube; Path::Path(var iArg) { mPath = iArg ? iArg.str() : fs::initial_path(); } var Path::dir(bool iVal) { if (!exists(mPath)) throw error("dir: path doesn't exist"); var dir; fs::directory_iterator end; for (fs::directory_iterator it(mPath); it != end; it++) dir[it->path().c_str()] = iVal ? it->path().stem().c_str() : nil; return dir; } var Path::rdir(bool iVal) { if (!exists(mPath)) throw error("rdir: path doesn't exist"); var dir; fs::recursive_directory_iterator end; for (fs::recursive_directory_iterator it(mPath); it != end; it++) dir[it->path().c_str()] = iVal ? it->path().stem().c_str() : nil; return dir; } var Path::tree() { return tree(mPath); } var Path::tree(boost::filesystem::path iPath) { if (!exists(iPath)) throw error("tree: path doesn't exist"); var dir; fs::directory_iterator end; for (fs::directory_iterator it(iPath); it != end; it++) if (fs::is_directory(*it)) dir[it->path().filename().c_str()] = tree(*it); else dir[it->path().filename().c_str()] = nil; return dir; } <commit_msg>Have dir() and rdir() return the component parts of the path in an array<commit_after>/* * Copyright 2014 by Philip N. Garner * * See the file COPYING for the licence associated with this software. * * Author(s): * Phil Garner, December 2014 */ /* * Take care here; there is a boost thing called path. In this sense, there is * the possibility that one could be confused as the other. Of course, it * boils down to being careful with namespaces. */ #include "lube/path.h" #include "boost/filesystem/operations.hpp" namespace fs = boost::filesystem; namespace libube { /** Concrete implementation of path module */ class Path : public path { public: Path(var iArg); var dir(bool iVal); var rdir(bool iVal); var tree(); private: fs::path mPath; var tree(fs::path iPath); }; /** Factory function to create a class */ void factory(Module** oModule, var iArg) { *oModule = new Path(iArg); } }; using namespace libube; Path::Path(var iArg) { mPath = iArg ? iArg.str() : fs::initial_path(); } var Path::dir(bool iVal) { if (!exists(mPath)) throw error("dir: path doesn't exist"); var dir; fs::directory_iterator end; for (fs::directory_iterator it(mPath); it != end; it++) { var val; // = nil if (iVal) { val[2] = it->path().extension().c_str(); val[1] = it->path().stem().c_str(); val[0] = it->path().parent_path().c_str(); } dir[it->path().c_str()] = val; } return dir; } var Path::rdir(bool iVal) { if (!exists(mPath)) throw error("rdir: path doesn't exist"); var dir; fs::recursive_directory_iterator end; for (fs::recursive_directory_iterator it(mPath); it != end; it++) { var val; // = nil if (iVal) { val[2] = it->path().extension().c_str(); val[1] = it->path().stem().c_str(); val[0] = it->path().parent_path().c_str(); } dir[it->path().c_str()] = val; } return dir; } var Path::tree() { return tree(mPath); } var Path::tree(boost::filesystem::path iPath) { if (!exists(iPath)) throw error("tree: path doesn't exist"); var dir; fs::directory_iterator end; for (fs::directory_iterator it(iPath); it != end; it++) if (fs::is_directory(*it)) dir[it->path().filename().c_str()] = tree(*it); else dir[it->path().filename().c_str()] = nil; return dir; } <|endoftext|>
<commit_before>#include "graphicitemblock.h" #include <QBrush> #include <QColor> #include <QFontMetrics> #include <QDebug> bd::GraphicItemBlock::GraphicItemBlock(Block *block, QGraphicsItem *parent) : QGraphicsItem(parent) { this->block = block; this->currentBoundingRect = QRectF(); this->giBlockHead = Q_NULLPTR; this->giParamsPublic = QList<GraphicItemTextBox *>(); this->updateBlockData(); } QRectF bd::GraphicItemBlock::boundingRect() const { return this->currentBoundingRect; } void bd::GraphicItemBlock::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); Q_UNUSED(painter); painter->setPen(Qt::red); painter->drawLine(-200, 0, 200, 0); painter->drawLine(0, -200, 0, 200); } void bd::GraphicItemBlock::updateBlockData() { qreal widthMaximum = 0; qreal widthInputs = 0; qreal widthOutputs = 0; qreal heightMaximum = 0; GraphicItemTextBox *gitb; // ------------------------------------------------------------------------ // Create Sub GraphicItems // ------------------------------------------------------------------------ // create new header if (this->giBlockHead != Q_NULLPTR) { delete this->giBlockHead; } this->giBlockHead = new GraphicItemBlockHeader(this->block, this); if (this->giBlockHead->getUsedWidth() > widthMaximum) widthMaximum = this->giBlockHead->getUsedWidth(); heightMaximum += this->giBlockHead->getUsedHeight(); this->giBlockHead->setY(this->giBlockHead->getUsedHeight()/2.0); // clear private parameters while (this->giParamsPrivate.size() > 0) delete this->giParamsPrivate.takeLast(); // create public parameters for (int i=0; i < this->block->getParameters().size(); ++i) { // create new list Parameter *param = this->block->getParameters().at(i); if (!param->isPublic()) { gitb = new GraphicItemTextBox(this); gitb->bgColor = this->backgroundParameter; this->giParamsPrivate.append(gitb); // update gitb->setText(param->name(), GraphicItemTextBox::Align::Center); // update height gitb->setY(gitb->y() + gitb->getUsedHeight()/2.0); gitb->setY(gitb->y() + heightMaximum); heightMaximum += gitb->getUsedHeight(); // update maximum width if (gitb->getUsedWidth() > widthMaximum) widthMaximum = gitb->getUsedWidth(); } } // clear inputs and outputs while (this->giInputs.size() > 0) delete this->giInputs.takeLast(); while (this->giOutputs.size() > 0) delete this->giOutputs.takeLast(); for (int i = 0; i < this->block->getInputs().size() || i < this->block->getOutputs().size(); ++i) { Input *inp = Q_NULLPTR; Output *outp = Q_NULLPTR; GraphicItemTextBox *giInp = Q_NULLPTR; GraphicItemTextBox *giOutp = Q_NULLPTR; // inputs if (i < this->block->getInputs().size()) { inp = this->block->getInputs().at(i); giInp = new GraphicItemTextBox(this); giInp->bgColor = this->backgroundInputs; this->giInputs.append(giInp); // update giInp->setText(inp->name(), GraphicItemTextBox::Align::Left); // update height giInp->setY(giInp->y() + giInp->getUsedHeight()/2.0); giInp->setY(giInp->y() + heightMaximum); // update width if (giInp->getUsedWidth() > widthInputs) widthInputs = giInp->getUsedWidth(); } // outputs if (i < this->block->getOutputs().size()) { outp = this->block->getOutputs().at(i); giOutp = new GraphicItemTextBox(this); giOutp->bgColor = this->backgroundOutputs; this->giOutputs.append(giOutp); // update giOutp->setText(outp->name(), GraphicItemTextBox::Align::Right); // update height giOutp->setY(giOutp->y() + giOutp->getUsedHeight()/2.0); giOutp->setY(giOutp->y() + heightMaximum); // update width if (giOutp->getUsedWidth() > widthOutputs) widthOutputs = giOutp->getUsedWidth(); } // set new height int h = 0; if (giOutp != Q_NULLPTR && giOutp->getUsedHeight() > h) h = giOutp->getUsedHeight(); if (giInp != Q_NULLPTR && giInp->getUsedHeight() > h) h = giInp->getUsedHeight(); heightMaximum += h; // set new width if ((widthInputs + widthOutputs) > widthMaximum) widthMaximum = widthInputs + widthOutputs; } // clear public parameters while (this->giParamsPublic.size() > 0) delete this->giParamsPublic.takeLast(); // create public parameters for (int i=0; i < this->block->getParameters().size(); ++i) { // create new list Parameter *param = this->block->getParameters().at(i); if (param->isPublic()) { gitb = new GraphicItemTextBox(this); gitb->bgColor = this->backgroundParameter; this->giParamsPublic.append(gitb); // update gitb->setText(param->name(), GraphicItemTextBox::Align::Center); // update height gitb->setY(gitb->y() + gitb->getUsedHeight()/2.0); gitb->setY(gitb->y() + heightMaximum); heightMaximum += gitb->getUsedHeight(); // update maximum width if (gitb->getUsedWidth() > widthMaximum) widthMaximum = gitb->getUsedWidth(); } } // ------------------------------------------------------------------------ // Update Positon // ------------------------------------------------------------------------ // update header this->giBlockHead->setY(this->giBlockHead->y() - heightMaximum/2.0); this->giBlockHead->minWidth = widthMaximum; // update private parameters for (int i=0; i < this->giParamsPrivate.size(); ++i) { gitb = this->giParamsPrivate.at(i); gitb->minWidth = widthMaximum; gitb->setY(gitb->y() - heightMaximum/2.0); } // stretch i/o width if ((widthInputs + widthOutputs) < widthMaximum) { int w = widthMaximum - widthInputs - widthOutputs; widthInputs += w/2.0; widthOutputs += w/2.0; } // update inputs for (int i=0; i < this->giInputs.size(); ++i) { gitb = this->giInputs.at(i); gitb->minWidth = widthInputs; gitb->setY(gitb->y() - heightMaximum/2.0); gitb->setX((widthInputs - widthMaximum) / 2.0); } // update outputs for (int i=0; i < this->giOutputs.size(); ++i) { gitb = this->giOutputs.at(i); gitb->minWidth = widthOutputs; gitb->setY(gitb->y() - heightMaximum/2.0); gitb->setX((widthMaximum - widthOutputs) / 2.0); } // update public parameters for (int i=0; i < this->giParamsPublic.size(); ++i) { gitb = this->giParamsPublic.at(i); gitb->minWidth = widthMaximum; gitb->setY(gitb->y() - heightMaximum/2.0); } } <commit_msg>same amount of input and output textboxes<commit_after>#include "graphicitemblock.h" #include <QBrush> #include <QColor> #include <QFontMetrics> #include <QDebug> bd::GraphicItemBlock::GraphicItemBlock(Block *block, QGraphicsItem *parent) : QGraphicsItem(parent) { this->block = block; this->currentBoundingRect = QRectF(); this->giBlockHead = Q_NULLPTR; this->giParamsPublic = QList<GraphicItemTextBox *>(); this->updateBlockData(); } QRectF bd::GraphicItemBlock::boundingRect() const { return this->currentBoundingRect; } void bd::GraphicItemBlock::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); Q_UNUSED(painter); painter->setPen(Qt::red); painter->drawLine(-200, 0, 200, 0); painter->drawLine(0, -200, 0, 200); } void bd::GraphicItemBlock::updateBlockData() { qreal widthMaximum = 0; qreal widthInputs = 0; qreal widthOutputs = 0; qreal heightMaximum = 0; GraphicItemTextBox *gitb; // ------------------------------------------------------------------------ // Create Sub GraphicItems // ------------------------------------------------------------------------ // create new header if (this->giBlockHead != Q_NULLPTR) { delete this->giBlockHead; } this->giBlockHead = new GraphicItemBlockHeader(this->block, this); if (this->giBlockHead->getUsedWidth() > widthMaximum) widthMaximum = this->giBlockHead->getUsedWidth(); heightMaximum += this->giBlockHead->getUsedHeight(); this->giBlockHead->setY(this->giBlockHead->getUsedHeight()/2.0); // clear private parameters while (this->giParamsPrivate.size() > 0) delete this->giParamsPrivate.takeLast(); // create public parameters for (int i=0; i < this->block->getParameters().size(); ++i) { // create new list Parameter *param = this->block->getParameters().at(i); if (!param->isPublic()) { gitb = new GraphicItemTextBox(this); gitb->bgColor = this->backgroundParameter; this->giParamsPrivate.append(gitb); // update gitb->setText(param->name(), GraphicItemTextBox::Align::Center); // update height gitb->setY(gitb->y() + gitb->getUsedHeight()/2.0); gitb->setY(gitb->y() + heightMaximum); heightMaximum += gitb->getUsedHeight(); // update maximum width if (gitb->getUsedWidth() > widthMaximum) widthMaximum = gitb->getUsedWidth(); } } // clear inputs and outputs while (this->giInputs.size() > 0) delete this->giInputs.takeLast(); while (this->giOutputs.size() > 0) delete this->giOutputs.takeLast(); for (int i = 0; i < this->block->getInputs().size() || i < this->block->getOutputs().size(); ++i) { Input *inp = Q_NULLPTR; Output *outp = Q_NULLPTR; GraphicItemTextBox *giInp = Q_NULLPTR; GraphicItemTextBox *giOutp = Q_NULLPTR; // input - create new textbox giInp = new GraphicItemTextBox(this); giInp->bgColor = this->backgroundInputs; this->giInputs.append(giInp); // input - write text into textbox if (i < this->block->getInputs().size()) { inp = this->block->getInputs().at(i); giInp->setText(inp->name(), GraphicItemTextBox::Align::Left); } // input update height, width giInp->setY(giInp->y() + giInp->getUsedHeight()/2.0); giInp->setY(giInp->y() + heightMaximum); if (giInp->getUsedWidth() > widthInputs) widthInputs = giInp->getUsedWidth(); // output - create new textbox giOutp = new GraphicItemTextBox(this); giOutp->bgColor = this->backgroundOutputs; this->giOutputs.append(giOutp); // output - write text into textbox if (i < this->block->getOutputs().size()) { outp = this->block->getOutputs().at(i); giOutp->setText(outp->name(), GraphicItemTextBox::Align::Right); } // output - update height, width giOutp->setY(giOutp->y() + giOutp->getUsedHeight()/2.0); giOutp->setY(giOutp->y() + heightMaximum); if (giOutp->getUsedWidth() > widthOutputs) widthOutputs = giOutp->getUsedWidth(); // set new height int h = 0; if (giOutp->getUsedHeight() > h) h = giOutp->getUsedHeight(); if (giInp->getUsedHeight() > h) h = giInp->getUsedHeight(); heightMaximum += h; // set new width if ((widthInputs + widthOutputs) > widthMaximum) widthMaximum = widthInputs + widthOutputs; } // clear public parameters while (this->giParamsPublic.size() > 0) delete this->giParamsPublic.takeLast(); // create public parameters for (int i=0; i < this->block->getParameters().size(); ++i) { // create new list Parameter *param = this->block->getParameters().at(i); if (param->isPublic()) { gitb = new GraphicItemTextBox(this); gitb->bgColor = this->backgroundParameter; this->giParamsPublic.append(gitb); // update gitb->setText(param->name(), GraphicItemTextBox::Align::Center); // update height gitb->setY(gitb->y() + gitb->getUsedHeight()/2.0); gitb->setY(gitb->y() + heightMaximum); heightMaximum += gitb->getUsedHeight(); // update maximum width if (gitb->getUsedWidth() > widthMaximum) widthMaximum = gitb->getUsedWidth(); } } // ------------------------------------------------------------------------ // Update Positon // ------------------------------------------------------------------------ // update header this->giBlockHead->setY(this->giBlockHead->y() - heightMaximum/2.0); this->giBlockHead->minWidth = widthMaximum; // update private parameters for (int i=0; i < this->giParamsPrivate.size(); ++i) { gitb = this->giParamsPrivate.at(i); gitb->minWidth = widthMaximum; gitb->setY(gitb->y() - heightMaximum/2.0); } // stretch i/o width if ((widthInputs + widthOutputs) < widthMaximum) { int w = widthMaximum - widthInputs - widthOutputs; widthInputs += w/2.0; widthOutputs += w/2.0; } // update inputs for (int i=0; i < this->giInputs.size(); ++i) { gitb = this->giInputs.at(i); gitb->minWidth = widthInputs; gitb->setY(gitb->y() - heightMaximum/2.0); gitb->setX((widthInputs - widthMaximum) / 2.0); } // update outputs for (int i=0; i < this->giOutputs.size(); ++i) { gitb = this->giOutputs.at(i); gitb->minWidth = widthOutputs; gitb->setY(gitb->y() - heightMaximum/2.0); gitb->setX((widthMaximum - widthOutputs) / 2.0); } // update public parameters for (int i=0; i < this->giParamsPublic.size(); ++i) { gitb = this->giParamsPublic.at(i); gitb->minWidth = widthMaximum; gitb->setY(gitb->y() - heightMaximum/2.0); } } <|endoftext|>
<commit_before>//===------- LowerHopToExecutor.cpp - Lower hop_to_executor on actors -----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "insert-hop-to-executor" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/Dominance.h" #include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "llvm/ADT/ScopedHashTable.h" using namespace swift; namespace { /// Lower hop_to_executor instructions with actor operands. /// /// While the language centers actors as the core concept, the runtime /// is largely expressed in terms of executors, which intentionally are /// an independent concept. Every actor has an executor; actors can /// customize their executor, subject to three restrictions: /// /// - Any given actor must report the same executor every time its /// executor is derived. An actor can be lazy about creating its /// executor, but it can't have multiple executors, even at different /// points in its lifetime. /// /// - Keeping the actor reference alive must keep the executor alive. /// /// - Derivations of the executor may be freely removed, combined, /// or sunk by the compiler. (Whether they should also be hoistable /// is more contentious.) /// /// To facilitate full optimization of hops, SILGen emits hops to actors /// with a hop_to_executor with an actor operand. (Among other benefits, /// this means that OptimizeHopToExecutor will eliminate the derivation /// operation associated with the hop.) This pass then comes along and /// inserts the derivations, turning those hops into hops to executors. /// IRGen expects hops to be to executors before it runs. class LowerHopToActor { SILFunction *F; SILBuilder B; DominanceInfo *Dominance; /// A map from an actor value to the executor we've derived for it. llvm::ScopedHashTable<SILValue, SILValue> ExecutorForActor; bool processHop(HopToExecutorInst *hop); bool processExtract(ExtractExecutorInst *extract); SILValue emitGetExecutor(SILLocation loc, SILValue actor, bool makeOptional); public: LowerHopToActor(SILFunction *f, DominanceInfo *dominance) : F(f), B(*F), Dominance(dominance) { } /// The entry point to the transformation. bool run(); }; bool LowerHopToActor::run() { bool changed = false; auto runOnBlock = [&](SILBasicBlock *block) { for (auto ii = block->begin(), ie = block->end(); ii != ie; ) { SILInstruction *inst = &*ii++; if (auto *hop = dyn_cast<HopToExecutorInst>(inst)) { changed |= processHop(hop); } else if (auto *extract = dyn_cast<ExtractExecutorInst>(inst)) { changed |= processExtract(extract); } } }; runInDominanceOrderWithScopes(Dominance, runOnBlock, ExecutorForActor); return changed; } static bool isOptionalBuiltinExecutor(SILType type) { if (auto objectType = type.getOptionalObjectType()) return objectType.is<BuiltinExecutorType>(); return false; } /// Search for hop_to_executor instructions with actor-typed operands. bool LowerHopToActor::processHop(HopToExecutorInst *hop) { auto actor = hop->getTargetExecutor(); // Ignore hops that are already to Optional<Builtin.Executor>. if (isOptionalBuiltinExecutor(actor->getType())) return false; B.setInsertionPoint(hop); B.setCurrentDebugScope(hop->getDebugScope()); // Get the dominating executor value for this actor, if available, // or else emit code to derive it. SILValue executor = emitGetExecutor(hop->getLoc(), actor, /*optional*/true); B.createHopToExecutor(hop->getLoc(), executor, /*mandatory*/ false); hop->eraseFromParent(); return true; } bool LowerHopToActor::processExtract(ExtractExecutorInst *extract) { // Dig out the executor. auto executor = extract->getExpectedExecutor(); if (!isOptionalBuiltinExecutor(executor->getType())) { B.setInsertionPoint(extract); B.setCurrentDebugScope(extract->getDebugScope()); executor = emitGetExecutor(extract->getLoc(), executor, /*optional*/false); } // Unconditionally replace the extract with the executor. extract->replaceAllUsesWith(executor); extract->eraseFromParent(); return true; } static bool isDefaultActorType(CanType actorType, ModuleDecl *M, ResilienceExpansion expansion) { if (auto cls = actorType.getClassOrBoundGenericClass()) return cls->isDefaultActor(M, expansion); return false; } static AccessorDecl *getUnownedExecutorGetter(ASTContext &ctx, ProtocolDecl *actorProtocol) { for (auto member: actorProtocol->getAllMembers()) { if (auto var = dyn_cast<VarDecl>(member)) { if (var->getName() == ctx.Id_unownedExecutor) return var->getAccessor(AccessorKind::Get); } } return nullptr; } SILValue LowerHopToActor::emitGetExecutor(SILLocation loc, SILValue actor, bool makeOptional) { // Get the dominating executor value for this actor, if available, // or else emit code to derive it. SILValue executor = ExecutorForActor.lookup(actor); if (executor) { if (makeOptional) executor = B.createOptionalSome(loc, executor, SILType::getOptionalType(executor->getType())); return executor; } // This is okay because actor types have to be classes and so never // have multiple abstraction patterns. CanType actorType = actor->getType().getASTType(); auto &ctx = F->getASTContext(); auto resultType = SILType::getPrimitiveObjectType(ctx.TheExecutorType); // If the actor type is a default actor, go ahead and devirtualize here. auto module = F->getModule().getSwiftModule(); SILValue unmarkedExecutor; if (isDefaultActorType(actorType, module, F->getResilienceExpansion())) { auto builtinName = ctx.getIdentifier( getBuiltinName(BuiltinValueKind::BuildDefaultActorExecutorRef)); auto builtinDecl = cast<FuncDecl>(getBuiltinValueDecl(ctx, builtinName)); auto subs = SubstitutionMap::get(builtinDecl->getGenericSignature(), {actorType}, {}); unmarkedExecutor = B.createBuiltin(loc, builtinName, resultType, subs, {actor}); // Otherwise, go through Actor.unownedExecutor. } else { auto actorProtocol = ctx.getProtocol(KnownProtocolKind::Actor); auto req = getUnownedExecutorGetter(ctx, actorProtocol); assert(req && "Concurrency library broken"); SILDeclRef fn(req, SILDeclRef::Kind::Func); auto actorConf = module->lookupConformance(actorType, actorProtocol); assert(actorConf && "hop_to_executor with actor that doesn't conform to Actor"); auto subs = SubstitutionMap::get(req->getGenericSignature(), {actorType}, {actorConf}); auto fnType = F->getModule().Types.getConstantFunctionType(*F, fn); auto witness = B.createWitnessMethod(loc, actorType, actorConf, fn, SILType::getPrimitiveObjectType(fnType)); auto witnessCall = B.createApply(loc, witness, subs, {actor}); // The protocol requirement returns an UnownedSerialExecutor; extract // the Builtin.Executor from it. auto executorDecl = ctx.getUnownedSerialExecutorDecl(); auto executorProps = executorDecl->getStoredProperties(); assert(executorProps.size() == 1); unmarkedExecutor = B.createStructExtract(loc, witnessCall, executorProps[0]); } // Mark the dependence of the resulting value on the actor value to // force the actor to stay alive. executor = B.createMarkDependence(loc, unmarkedExecutor, actor); // Cache the non-optional result for later. ExecutorForActor.insert(actor, executor); // Inject the result into an optional if requested. if (makeOptional) executor = B.createOptionalSome(loc, executor, SILType::getOptionalType(executor->getType())); return executor; } class LowerHopToActorPass : public SILFunctionTransform { /// The entry point to the transformation. void run() override { auto fn = getFunction(); auto domTree = getAnalysis<DominanceAnalysis>()->get(fn); LowerHopToActor pass(getFunction(), domTree); if (pass.run()) invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions); } }; } // end anonymous namespace SILTransform *swift::createLowerHopToActor() { return new LowerHopToActorPass(); } <commit_msg>Handle Builtin.Executor types in lowering<commit_after>//===------- LowerHopToExecutor.cpp - Lower hop_to_executor on actors -----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "insert-hop-to-executor" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/Dominance.h" #include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "llvm/ADT/ScopedHashTable.h" using namespace swift; namespace { /// Lower hop_to_executor instructions with actor operands. /// /// While the language centers actors as the core concept, the runtime /// is largely expressed in terms of executors, which intentionally are /// an independent concept. Every actor has an executor; actors can /// customize their executor, subject to three restrictions: /// /// - Any given actor must report the same executor every time its /// executor is derived. An actor can be lazy about creating its /// executor, but it can't have multiple executors, even at different /// points in its lifetime. /// /// - Keeping the actor reference alive must keep the executor alive. /// /// - Derivations of the executor may be freely removed, combined, /// or sunk by the compiler. (Whether they should also be hoistable /// is more contentious.) /// /// To facilitate full optimization of hops, SILGen emits hops to actors /// with a hop_to_executor with an actor operand. (Among other benefits, /// this means that OptimizeHopToExecutor will eliminate the derivation /// operation associated with the hop.) This pass then comes along and /// inserts the derivations, turning those hops into hops to executors. /// IRGen expects hops to be to executors before it runs. class LowerHopToActor { SILFunction *F; SILBuilder B; DominanceInfo *Dominance; /// A map from an actor value to the executor we've derived for it. llvm::ScopedHashTable<SILValue, SILValue> ExecutorForActor; bool processHop(HopToExecutorInst *hop); bool processExtract(ExtractExecutorInst *extract); SILValue emitGetExecutor(SILLocation loc, SILValue actor, bool makeOptional); public: LowerHopToActor(SILFunction *f, DominanceInfo *dominance) : F(f), B(*F), Dominance(dominance) { } /// The entry point to the transformation. bool run(); }; bool LowerHopToActor::run() { bool changed = false; auto runOnBlock = [&](SILBasicBlock *block) { for (auto ii = block->begin(), ie = block->end(); ii != ie; ) { SILInstruction *inst = &*ii++; if (auto *hop = dyn_cast<HopToExecutorInst>(inst)) { changed |= processHop(hop); } else if (auto *extract = dyn_cast<ExtractExecutorInst>(inst)) { changed |= processExtract(extract); } } }; runInDominanceOrderWithScopes(Dominance, runOnBlock, ExecutorForActor); return changed; } static bool isOptionalBuiltinExecutor(SILType type) { if (auto objectType = type.getOptionalObjectType()) return objectType.is<BuiltinExecutorType>(); return false; } /// Search for hop_to_executor instructions with actor-typed operands. bool LowerHopToActor::processHop(HopToExecutorInst *hop) { auto actor = hop->getTargetExecutor(); // Ignore hops that are already to Optional<Builtin.Executor>. if (isOptionalBuiltinExecutor(actor->getType())) return false; B.setInsertionPoint(hop); B.setCurrentDebugScope(hop->getDebugScope()); SILValue executor; if (actor->getType().is<BuiltinExecutorType>()) { // IRGen expects an optional Builtin.Executor, not a Builtin.Executor // but we can wrap it nicely executor = B.createOptionalSome( hop->getLoc(), actor, SILType::getOptionalType(actor->getType())); } else { // Get the dominating executor value for this actor, if available, // or else emit code to derive it. executor = emitGetExecutor(hop->getLoc(), actor, /*optional*/true); } assert(executor && "executor not set"); B.createHopToExecutor(hop->getLoc(), executor, /*mandatory*/ false); hop->eraseFromParent(); return true; } bool LowerHopToActor::processExtract(ExtractExecutorInst *extract) { // Dig out the executor. auto executor = extract->getExpectedExecutor(); if (!isOptionalBuiltinExecutor(executor->getType())) { B.setInsertionPoint(extract); B.setCurrentDebugScope(extract->getDebugScope()); executor = emitGetExecutor(extract->getLoc(), executor, /*optional*/false); } // Unconditionally replace the extract with the executor. extract->replaceAllUsesWith(executor); extract->eraseFromParent(); return true; } static bool isDefaultActorType(CanType actorType, ModuleDecl *M, ResilienceExpansion expansion) { if (auto cls = actorType.getClassOrBoundGenericClass()) return cls->isDefaultActor(M, expansion); return false; } static AccessorDecl *getUnownedExecutorGetter(ASTContext &ctx, ProtocolDecl *actorProtocol) { for (auto member: actorProtocol->getAllMembers()) { if (auto var = dyn_cast<VarDecl>(member)) { if (var->getName() == ctx.Id_unownedExecutor) return var->getAccessor(AccessorKind::Get); } } return nullptr; } SILValue LowerHopToActor::emitGetExecutor(SILLocation loc, SILValue actor, bool makeOptional) { // Get the dominating executor value for this actor, if available, // or else emit code to derive it. SILValue executor = ExecutorForActor.lookup(actor); if (executor) { if (makeOptional) executor = B.createOptionalSome(loc, executor, SILType::getOptionalType(executor->getType())); return executor; } // This is okay because actor types have to be classes and so never // have multiple abstraction patterns. CanType actorType = actor->getType().getASTType(); auto &ctx = F->getASTContext(); auto resultType = SILType::getPrimitiveObjectType(ctx.TheExecutorType); // If the actor type is a default actor, go ahead and devirtualize here. auto module = F->getModule().getSwiftModule(); SILValue unmarkedExecutor; if (isDefaultActorType(actorType, module, F->getResilienceExpansion())) { auto builtinName = ctx.getIdentifier( getBuiltinName(BuiltinValueKind::BuildDefaultActorExecutorRef)); auto builtinDecl = cast<FuncDecl>(getBuiltinValueDecl(ctx, builtinName)); auto subs = SubstitutionMap::get(builtinDecl->getGenericSignature(), {actorType}, {}); unmarkedExecutor = B.createBuiltin(loc, builtinName, resultType, subs, {actor}); // Otherwise, go through Actor.unownedExecutor. } else { auto actorProtocol = ctx.getProtocol(KnownProtocolKind::Actor); auto req = getUnownedExecutorGetter(ctx, actorProtocol); assert(req && "Concurrency library broken"); SILDeclRef fn(req, SILDeclRef::Kind::Func); auto actorConf = module->lookupConformance(actorType, actorProtocol); assert(actorConf && "hop_to_executor with actor that doesn't conform to Actor"); auto subs = SubstitutionMap::get(req->getGenericSignature(), {actorType}, {actorConf}); auto fnType = F->getModule().Types.getConstantFunctionType(*F, fn); auto witness = B.createWitnessMethod(loc, actorType, actorConf, fn, SILType::getPrimitiveObjectType(fnType)); auto witnessCall = B.createApply(loc, witness, subs, {actor}); // The protocol requirement returns an UnownedSerialExecutor; extract // the Builtin.Executor from it. auto executorDecl = ctx.getUnownedSerialExecutorDecl(); auto executorProps = executorDecl->getStoredProperties(); assert(executorProps.size() == 1); unmarkedExecutor = B.createStructExtract(loc, witnessCall, executorProps[0]); } // Mark the dependence of the resulting value on the actor value to // force the actor to stay alive. executor = B.createMarkDependence(loc, unmarkedExecutor, actor); // Cache the non-optional result for later. ExecutorForActor.insert(actor, executor); // Inject the result into an optional if requested. if (makeOptional) executor = B.createOptionalSome(loc, executor, SILType::getOptionalType(executor->getType())); return executor; } class LowerHopToActorPass : public SILFunctionTransform { /// The entry point to the transformation. void run() override { auto fn = getFunction(); auto domTree = getAnalysis<DominanceAnalysis>()->get(fn); LowerHopToActor pass(getFunction(), domTree); if (pass.run()) invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions); } }; } // end anonymous namespace SILTransform *swift::createLowerHopToActor() { return new LowerHopToActorPass(); } <|endoftext|>
<commit_before>#include "../ClipperUtils.hpp" #include "../PolylineCollection.hpp" #include "../Surface.hpp" #include "FillPlanePath.hpp" namespace Slic3r { void FillPlanePath::_fill_surface_single( const FillParams &params, unsigned int thickness_layers, const std::pair<float, Point> &direction, ExPolygon &expolygon, Polylines &polylines_out) { expolygon.rotate(- direction.first); coord_t distance_between_lines = scale_(this->spacing) / params.density; // align infill across layers using the object's bounding box // Rotated bounding box of the whole object. BoundingBox bounding_box = this->bounding_box.rotated(- direction.first); Point shift = this->_centered() ? bounding_box.center() : bounding_box.min; expolygon.translate(-shift(0), -shift(1)); bounding_box.translate(-shift(0), -shift(1)); Pointfs pts = _generate( coord_t(ceil(coordf_t(bounding_box.min(0)) / distance_between_lines)), coord_t(ceil(coordf_t(bounding_box.min(1)) / distance_between_lines)), coord_t(ceil(coordf_t(bounding_box.max(0)) / distance_between_lines)), coord_t(ceil(coordf_t(bounding_box.max(1)) / distance_between_lines))); Polylines polylines; if (pts.size() >= 2) { // Convert points to a polyline, upscale. polylines.push_back(Polyline()); Polyline &polyline = polylines.back(); polyline.points.reserve(pts.size()); for (Pointfs::iterator it = pts.begin(); it != pts.end(); ++ it) polyline.points.push_back(Point( coord_t(floor((*it)(0) * distance_between_lines + 0.5)), coord_t(floor((*it)(1) * distance_between_lines + 0.5)))); // intersection(polylines_src, offset((Polygons)expolygon, scale_(0.02)), &polylines); polylines = intersection_pl(polylines, to_polygons(expolygon)); /* if (1) { require "Slic3r/SVG.pm"; print "Writing fill.svg\n"; Slic3r::SVG::output("fill.svg", no_arrows => 1, polygons => \@$expolygon, green_polygons => [ $bounding_box->polygon ], polylines => [ $polyline ], red_polylines => \@paths, ); } */ // paths must be repositioned and rotated back for (Polylines::iterator it = polylines.begin(); it != polylines.end(); ++ it) { it->translate(shift(0), shift(1)); it->rotate(direction.first); } } // Move the polylines to the output, avoid a deep copy. size_t j = polylines_out.size(); polylines_out.resize(j + polylines.size(), Polyline()); for (size_t i = 0; i < polylines.size(); ++ i) std::swap(polylines_out[j ++], polylines[i]); } // Follow an Archimedean spiral, in polar coordinates: r=a+b\theta Pointfs FillArchimedeanChords::_generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y) { // Radius to achieve. coordf_t rmax = std::sqrt(coordf_t(max_x)*coordf_t(max_x)+coordf_t(max_y)*coordf_t(max_y)) * std::sqrt(2.) + 1.5; // Now unwind the spiral. coordf_t a = 1.; coordf_t b = 1./(2.*M_PI); coordf_t theta = 0.; coordf_t r = 1; Pointfs out; //FIXME Vojtech: If used as a solid infill, there is a gap left at the center. out.push_back(Vec2d(0, 0)); out.push_back(Vec2d(1, 0)); while (r < rmax) { theta += 1. / r; r = a + b * theta; out.push_back(Vec2d(r * cos(theta), r * sin(theta))); } return out; } // Adapted from // http://cpansearch.perl.org/src/KRYDE/Math-PlanePath-122/lib/Math/PlanePath/HilbertCurve.pm // // state=0 3--2 plain // | // 0--1 // // state=4 1--2 transpose // | | // 0 3 // // state=8 // // state=12 3 0 rot180 + transpose // | | // 2--1 // static inline Point hilbert_n_to_xy(const size_t n) { static const int next_state[16] = { 4,0,0,12, 0,4,4,8, 12,8,8,4, 8,12,12,0 }; static const int digit_to_x[16] = { 0,1,1,0, 0,0,1,1, 1,0,0,1, 1,1,0,0 }; static const int digit_to_y[16] = { 0,0,1,1, 0,1,1,0, 1,1,0,0, 1,0,0,1 }; // Number of 2 bit digits. size_t ndigits = 0; { size_t nc = n; while(nc > 0) { nc >>= 2; ++ ndigits; } } int state = (ndigits & 1) ? 4 : 0; int dirstate = (ndigits & 1) ? 0 : 4; coord_t x = 0; coord_t y = 0; for (int i = (int)ndigits - 1; i >= 0; -- i) { int digit = (n >> (i * 2)) & 3; state += digit; if (digit != 3) dirstate = state; // lowest non-3 digit x |= digit_to_x[state] << i; y |= digit_to_y[state] << i; state = next_state[state]; } return Point(x, y); } Pointfs FillHilbertCurve::_generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y) { // Minimum power of two square to fit the domain. size_t sz = 2; size_t pw = 1; { size_t sz0 = std::max(max_x + 1 - min_x, max_y + 1 - min_y); while (sz < sz0) { sz = sz << 1; ++ pw; } } size_t sz2 = sz * sz; Pointfs line; line.reserve(sz2); for (size_t i = 0; i < sz2; ++ i) { Point p = hilbert_n_to_xy(i); line.push_back(Vec2d(p(0) + min_x, p(1) + min_y)); } return line; } Pointfs FillOctagramSpiral::_generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y) { // Radius to achieve. coordf_t rmax = std::sqrt(coordf_t(max_x)*coordf_t(max_x)+coordf_t(max_y)*coordf_t(max_y)) * std::sqrt(2.) + 1.5; // Now unwind the spiral. coordf_t r = 0; coordf_t r_inc = sqrt(2.); Pointfs out; out.push_back(Vec2d(0, 0)); while (r < rmax) { r += r_inc; coordf_t rx = r / sqrt(2.); coordf_t r2 = r + rx; out.push_back(Vec2d( r, 0.)); out.push_back(Vec2d( r2, rx)); out.push_back(Vec2d( rx, rx)); out.push_back(Vec2d( rx, r2)); out.push_back(Vec2d(0., r)); out.push_back(Vec2d(-rx, r2)); out.push_back(Vec2d(-rx, rx)); out.push_back(Vec2d(-r2, rx)); out.push_back(Vec2d(-r, 0.)); out.push_back(Vec2d(-r2, -rx)); out.push_back(Vec2d(-rx, -rx)); out.push_back(Vec2d(-rx, -r2)); out.push_back(Vec2d(0., -r)); out.push_back(Vec2d( rx, -r2)); out.push_back(Vec2d( rx, -rx)); out.push_back(Vec2d( r2+r_inc, -rx)); } return out; } } // namespace Slic3r <commit_msg>Reworked discretization step of Archimedean Chords infill to lower slicing time and memory requirements. Fixes "Infill pattern Archimedean causing total freeze at Infilling patterns" #1871<commit_after>#include "../ClipperUtils.hpp" #include "../PolylineCollection.hpp" #include "../Surface.hpp" #include "FillPlanePath.hpp" namespace Slic3r { void FillPlanePath::_fill_surface_single( const FillParams &params, unsigned int thickness_layers, const std::pair<float, Point> &direction, ExPolygon &expolygon, Polylines &polylines_out) { expolygon.rotate(- direction.first); coord_t distance_between_lines = coord_t(scale_(this->spacing) / params.density); // align infill across layers using the object's bounding box // Rotated bounding box of the whole object. BoundingBox bounding_box = this->bounding_box.rotated(- direction.first); Point shift = this->_centered() ? bounding_box.center() : bounding_box.min; expolygon.translate(-shift(0), -shift(1)); bounding_box.translate(-shift(0), -shift(1)); Pointfs pts = _generate( coord_t(ceil(coordf_t(bounding_box.min(0)) / distance_between_lines)), coord_t(ceil(coordf_t(bounding_box.min(1)) / distance_between_lines)), coord_t(ceil(coordf_t(bounding_box.max(0)) / distance_between_lines)), coord_t(ceil(coordf_t(bounding_box.max(1)) / distance_between_lines))); Polylines polylines; if (pts.size() >= 2) { // Convert points to a polyline, upscale. polylines.push_back(Polyline()); Polyline &polyline = polylines.back(); polyline.points.reserve(pts.size()); for (Pointfs::iterator it = pts.begin(); it != pts.end(); ++ it) polyline.points.push_back(Point( coord_t(floor((*it)(0) * distance_between_lines + 0.5)), coord_t(floor((*it)(1) * distance_between_lines + 0.5)))); // intersection(polylines_src, offset((Polygons)expolygon, scale_(0.02)), &polylines); polylines = intersection_pl(polylines, to_polygons(expolygon)); /* if (1) { require "Slic3r/SVG.pm"; print "Writing fill.svg\n"; Slic3r::SVG::output("fill.svg", no_arrows => 1, polygons => \@$expolygon, green_polygons => [ $bounding_box->polygon ], polylines => [ $polyline ], red_polylines => \@paths, ); } */ // paths must be repositioned and rotated back for (Polylines::iterator it = polylines.begin(); it != polylines.end(); ++ it) { it->translate(shift(0), shift(1)); it->rotate(direction.first); } } // Move the polylines to the output, avoid a deep copy. size_t j = polylines_out.size(); polylines_out.resize(j + polylines.size(), Polyline()); for (size_t i = 0; i < polylines.size(); ++ i) std::swap(polylines_out[j ++], polylines[i]); } // Follow an Archimedean spiral, in polar coordinates: r=a+b\theta Pointfs FillArchimedeanChords::_generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y) { // Radius to achieve. coordf_t rmax = std::sqrt(coordf_t(max_x)*coordf_t(max_x)+coordf_t(max_y)*coordf_t(max_y)) * std::sqrt(2.) + 1.5; // Now unwind the spiral. coordf_t a = 1.; coordf_t b = 1./(2.*M_PI); coordf_t theta = 0.; coordf_t r = 1; Pointfs out; //FIXME Vojtech: If used as a solid infill, there is a gap left at the center. out.push_back(Vec2d(0, 0)); out.push_back(Vec2d(1, 0)); while (r < rmax) { // Discretization angle to achieve a discretization error lower than RESOLUTION. theta += 2. * acos(1. - RESOLUTION / r); r = a + b * theta; out.push_back(Vec2d(r * cos(theta), r * sin(theta))); } return out; } // Adapted from // http://cpansearch.perl.org/src/KRYDE/Math-PlanePath-122/lib/Math/PlanePath/HilbertCurve.pm // // state=0 3--2 plain // | // 0--1 // // state=4 1--2 transpose // | | // 0 3 // // state=8 // // state=12 3 0 rot180 + transpose // | | // 2--1 // static inline Point hilbert_n_to_xy(const size_t n) { static const int next_state[16] = { 4,0,0,12, 0,4,4,8, 12,8,8,4, 8,12,12,0 }; static const int digit_to_x[16] = { 0,1,1,0, 0,0,1,1, 1,0,0,1, 1,1,0,0 }; static const int digit_to_y[16] = { 0,0,1,1, 0,1,1,0, 1,1,0,0, 1,0,0,1 }; // Number of 2 bit digits. size_t ndigits = 0; { size_t nc = n; while(nc > 0) { nc >>= 2; ++ ndigits; } } int state = (ndigits & 1) ? 4 : 0; int dirstate = (ndigits & 1) ? 0 : 4; coord_t x = 0; coord_t y = 0; for (int i = (int)ndigits - 1; i >= 0; -- i) { int digit = (n >> (i * 2)) & 3; state += digit; if (digit != 3) dirstate = state; // lowest non-3 digit x |= digit_to_x[state] << i; y |= digit_to_y[state] << i; state = next_state[state]; } return Point(x, y); } Pointfs FillHilbertCurve::_generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y) { // Minimum power of two square to fit the domain. size_t sz = 2; size_t pw = 1; { size_t sz0 = std::max(max_x + 1 - min_x, max_y + 1 - min_y); while (sz < sz0) { sz = sz << 1; ++ pw; } } size_t sz2 = sz * sz; Pointfs line; line.reserve(sz2); for (size_t i = 0; i < sz2; ++ i) { Point p = hilbert_n_to_xy(i); line.push_back(Vec2d(p(0) + min_x, p(1) + min_y)); } return line; } Pointfs FillOctagramSpiral::_generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y) { // Radius to achieve. coordf_t rmax = std::sqrt(coordf_t(max_x)*coordf_t(max_x)+coordf_t(max_y)*coordf_t(max_y)) * std::sqrt(2.) + 1.5; // Now unwind the spiral. coordf_t r = 0; coordf_t r_inc = sqrt(2.); Pointfs out; out.push_back(Vec2d(0, 0)); while (r < rmax) { r += r_inc; coordf_t rx = r / sqrt(2.); coordf_t r2 = r + rx; out.push_back(Vec2d( r, 0.)); out.push_back(Vec2d( r2, rx)); out.push_back(Vec2d( rx, rx)); out.push_back(Vec2d( rx, r2)); out.push_back(Vec2d(0., r)); out.push_back(Vec2d(-rx, r2)); out.push_back(Vec2d(-rx, rx)); out.push_back(Vec2d(-r2, rx)); out.push_back(Vec2d(-r, 0.)); out.push_back(Vec2d(-r2, -rx)); out.push_back(Vec2d(-rx, -rx)); out.push_back(Vec2d(-rx, -r2)); out.push_back(Vec2d(0., -r)); out.push_back(Vec2d( rx, -r2)); out.push_back(Vec2d( rx, -rx)); out.push_back(Vec2d( r2+r_inc, -rx)); } return out; } } // namespace Slic3r <|endoftext|>
<commit_before>#include "RoleBase.h" #include "Creature.h" #include "interface.h" #include "Action.h" #include "Utils.h" #include "NavigationFinder.h" #include "Engine.h" #include "World.h" #include "Object.h" #include "Avatar.h" CRoleBase::CRoleBase(void) { m_pCreature = NULL; m_pActionComplete = NULL; m_nOrceDirection = 0; m_nMoveing = 0; m_fMoveSpeed = 6.0f; m_nMoveToType = 0; m_nUpdateMove = 1; } CRoleBase::~CRoleBase(void) { SAFE_DELETE(m_pActionComplete); SAFE_DELETE(m_pCreature); SAFE_DELETE(m_pPathFind); }<commit_msg>初始化角色<commit_after>#include "RoleBase.h" #include "Creature.h" #include "interface.h" #include "Action.h" #include "Utils.h" #include "NavigationFinder.h" #include "Engine.h" #include "World.h" #include "Object.h" #include "Avatar.h" CRoleBase::CRoleBase(void) { m_pCreature = NULL; m_pActionComplete = NULL; m_nOrceDirection = 0; m_nMoveing = 0; m_fMoveSpeed = 6.0f; m_nMoveToType = 0; m_nUpdateMove = 1; } CRoleBase::~CRoleBase(void) { SAFE_DELETE(m_pActionComplete); SAFE_DELETE(m_pCreature); SAFE_DELETE(m_pPathFind); } //ʼɫ int CRoleBase::Init(int nRoleID, const char* strCharFile) { if (m_pCreature)return 1; }<|endoftext|>
<commit_before>// -*- C++ -*- // The MIT License (MIT) // // Copyright (c) 2021 Alexander Samoilov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <gtest/gtest.h> #include "math.hpp" #include "ChebyshevDifferentiate.hpp" #include "PoissonProblem.hpp" #include "FastCosineTransform.hpp" template<size_t N> void sysslv(double a[N][N], double b[N]) { constexpr size_t n = N; double biga,save; int i,j,k,imax; for (j=0;j<n;j++) { biga=0.0; for(i=j;i<n;i++) if (std::fabs(biga) < std::fabs(a[i][j])) { biga=a[i][j]; imax=i; } if (std::fabs(biga) == 0.0) { throw std::logic_error("Very singular matrix..."); } for (k=j;k<n;k++) { save=a[imax][k]; a[imax][k]=a[j][k]; a[j][k]=save/biga; } save=b[imax]; b[imax]=b[j]; b[j]=save/biga; for (i=j+1;i<n;i++) { for(k=j+1;k<n;k++) a[i][k] -= a[i][j]*a[j][k]; b[i] -= b[j]*a[i][j]; } } for (k=n-2;k>=0;k--) for(j=n-1;j>k;j--) b[k] -= a[k][j]*b[j]; } TEST(cftSuite, test_cosfft1) { constexpr size_t M = 2; RowVectorXd x(M + 1), x_inv(M + 1); x << 1., 2., 3.; x_inv << 6., -2., 2.; FCT::cosfft1(M, x); EXPECT_DOUBLE_EQ((x - x_inv).norm(), 0.0); } TEST(cftSuite, test_cosfft12) { constexpr size_t M = 32; auto y = [](double x) {return x*x*x*x - 1;}; /// \f$y = x^4 - 1\f$ double x_min = -1., x_max = 1.; double xa = 0.5*(x_min-x_max); double xb = 0.5*(x_min+x_max); RowVectorXd x_grid(M + 1), f_vals1(M + 1), f_vals2(M + 1); for (size_t i = 0; i <= M; i++) { x_grid[i] = xa*std::cos(M_PI*i/(double)M)+xb; } for (size_t i = 0; i <= M; i++) { f_vals2[i] = f_vals1[i] = y(x_grid[i]); } FCT::cosfft1(M, f_vals1); FCT::cosfft1(M, f_vals1, FCT::TransformType::Inverse); // EXPECT_DOUBLE_EQ((f_vals1 - f_vals2).norm(), 0.0); constexpr double EPS = 1e-14; EXPECT_NEAR((f_vals1 - f_vals2).norm(), 0.0, EPS); } /// check that `.transpose()` and `.transposeInPlace()` /// surely work with non-square matrices TEST(eigenSuite, test_transpose) { constexpr size_t M = 2; constexpr size_t N = 3; RowMatrixXd ma(M, N), maT; ma << 1., 2., 3., 4., 5., 6.; maT = ma.transpose(); // std::cout << ma << std::endl; // std::cout << maT << std::endl; EXPECT_EQ(ma.rows(), maT.cols()); EXPECT_EQ(maT.rows(), ma.cols()); ma.transposeInPlace(); EXPECT_EQ(ma.rows(), maT.rows()); EXPECT_EQ(ma.cols(), maT.cols()); // assertion failure if use // `Eigen::Ref<RowMatrixXd>` instead of plain `RowMatrixXd&` auto transpose = [](RowMatrixXd& ma) { ma.transposeInPlace(); }; transpose(ma); EXPECT_EQ(ma.rows(), maT.cols()); EXPECT_EQ(maT.rows(), ma.cols()); } TEST(eigenSuite, test_unity) { constexpr size_t M = 2; constexpr size_t N = 3; RowMatrixXd ma; ma = Eigen::MatrixXd::Identity(M + 1, N + 1); // std::cout << "ma:\n" << ma << std::endl; EXPECT_EQ(ma.rows(), M + 1); EXPECT_EQ(ma.cols(), N + 1); ma.transposeInPlace(); EXPECT_EQ(ma.rows(), N + 1); EXPECT_EQ(ma.cols(), M + 1); EXPECT_EQ(ma(0, 0), 1.0); EXPECT_EQ(ma(1, 1), 1.0); EXPECT_EQ(ma(2, 2), 1.0); EXPECT_EQ(ma(1, 2), 0.0); EXPECT_EQ(ma(2, 1), 0.0); } TEST(cftSuite, test_cf2) { constexpr size_t M = 2; constexpr size_t N = 4; RowMatrixXd m(M + 1, N + 1), m_inv(M + 1, N + 1), m1; m << 1., 2., 3., 1., 2., 4., 5., 6., 4., 5., 7., 8., 9., 7., 8.; m_inv << 72., -0.87867965644035673, 9., -5.1213203435596428, 18., -30., -4.4408920985006262e-16, -6., 4.4408920985006262e-16, -6., 24., -0.29289321881345254, 3., -1.7071067811865479, 6.; m1 = m; FCT::cft2(M, N, m); FCT::cft2_with_transpose(M, N, m1); // std::cout << std::setprecision(17) << m << std::endl; constexpr double EPS = 1e-14; EXPECT_NEAR((m - m_inv).norm(), 0.0, EPS); EXPECT_NEAR((m - m1).norm(), 0.0, EPS); } TEST(bsSuite, test_gauss_elim) { constexpr double EPS = 1e-12; constexpr size_t M = 4; // https://mxncalc.com/gaussian-elimination-calculator double A[M][M] = {{1., 2., 3., 4.}, {5., 6., 8., 5.}, {4., 15., 2., 12.}, {3., 2., 5., 6.},}; double b[M] = {11., 12., 3., 7.,}; double x[M] = { -7.127'853'881'278'5, 1.237'442'922'374'4, 4.858'447'488'584'5, 0.269'406'392'694'06, }; Eigen::Vector4d bb(b), xx(x); Eigen::Matrix4d AA(reinterpret_cast<double*>(A)); AA.transposeInPlace(); // std::cout << "AA: " << AA << std::endl; sysslv(A, b); Eigen::Vector4d b2(b); //EXPECT_DOUBLE_EQ((b2 - xx).norm(), 0.0); // Expected equality of these values: // (b2 - xx).norm() // Which is: 5.3413613165043815e-14 // 0.0 // Which is: 0 EXPECT_NEAR((b2 - xx).norm(), 0.0, EPS); Eigen::Vector4d x2 = AA.lu().solve(bb); // std::cout << "x2: " << x2 << std::endl; // std::cout << "xx: " << xx << std::endl; EXPECT_NEAR((x2 - xx).norm(), 0.0, EPS); } TEST(ChebyshevDifferentiate, test_deriv1) { constexpr size_t M = 32; auto y = [](double x) {return x*x*x*x + sin(x);}; /// \f$y = x^4 + \sin x\f$ auto y_deriv1 = [](double x) {return 4*x*x*x + cos(x);}; /// \f$y = 4x^3 + \cos x\f$ RowVectorXd x_grid(M + 1), f_vals(M + 1), f_deriv_vals(M + 1); double x_min = -1., x_max = 1.; double xa = 0.5*(x_max-x_min); double xb = 0.5*(x_min+x_max); // std::cout << "xa: " << xa << " xb: " << xb << std::endl; for (size_t i = 0; i <= M; i++) { x_grid[i] = xa*std::cos(M_PI*i/(double)M)+xb; } // std::cout << "x_grid: " << x_grid << std::endl; for (size_t i = 0; i <= M; i++) { f_vals[i] = y (x_grid[i]); f_deriv_vals[i] = y_deriv1 (x_grid[i]); } // std::cout << "f_vals: [" << f_vals << "]\n"; // std::cout << "f_deriv_vals: [" << f_deriv_vals << "]\n"; FCT::cosfft1(M, f_vals, FCT::TransformType::Inverse); CS::spectral_differentiate(M, f_vals, f_vals, 2.0 / (x_max - x_min)); FCT::cosfft1(M, f_vals); // std::cout << "f_vals: [" << f_vals << "]\n"; // std::cout << "f_vals - f_deriv_vals: [" << f_vals - f_deriv_vals << "]\n"; //EXPECT_DOUBLE_EQ((f_vals - f_deriv_vals).norm(), 0.0); constexpr double EPS = 1e-10; EXPECT_NEAR((f_vals - f_deriv_vals).norm(), 0.0, EPS); } TEST(PoissonProblem, test_homogeneous_boundary) { auto sums_evens_odds = [](auto const& begin, auto const& end, size_t stride = 1) -> std::pair<double, double> { double evens = 0.0, odds = 0.0; size_t counter = 0; for (auto it = begin; ;std::advance(it, stride)) { if (detail::is_even(counter++)) { evens += *it; } else { odds += *it; } if (it == end) break; } return {evens, odds}; }; auto check_evens_odds = [sums_evens_odds](auto const& ma, size_t row1, size_t col1, size_t row2, size_t col2, size_t stride = 1) { auto [evens, odds] = sums_evens_odds(&ma(row1, col1), &ma(row2, col2), stride); EXPECT_EQ(evens, 0); EXPECT_EQ(odds, 0); }; constexpr size_t M = 4; double A[M + 1][M + 1] = { {1., 2., 3., 4., 8.,}, {5., 6., 8., 5., 7.,}, {3., 5., 7., 2., 1.,}, {4., 15., 2., 12., 11.,}, {3., 2., 5., 6., 5.,}, }; RowMatrixXd AA(M + 1, M + 1), BB = RowMatrixXd::Zero(M + 1, M + 1); for (size_t i = 0; i <= M; ++i) { for (size_t j = 0; j <= M; ++j) { AA(i, j) = A[i][j]; } } // std::cout << "AA: [\n" << AA << "]\n"; CS::homogeneous_boundary(M, M, AA, BB); // std::cout << "BB: [\n" << BB << "]\n"; // std::cout << "AA: [\n" << AA << "]\n"; CS::homogeneous_boundary(M, M, AA, AA); // std::cout << "AA: [\n" << AA << "]\n"; EXPECT_DOUBLE_EQ((AA - BB).norm(), 0.0); constexpr size_t N = 2*M; RowMatrixXd CC(M + 1, N + 1); for (size_t i = 0; i <= M; ++i) { for (size_t j = 0; j <= N; ++j) { CC(i, j) = A[i][j % 2]; } } // std::cout << "CC: [\n" << CC << "]\n"; CS::homogeneous_boundary(M, N, CC, CC); // std::cout << "CC: [\n" << CC << "]\n"; for (size_t I = 0; I <= M; ++I) check_evens_odds(CC, I, 0, I, N, 1); for (size_t J = 0; J <= N; ++J) check_evens_odds(CC, 0, J, M, J, N + 1); } <commit_msg>cosmetic: reformat<commit_after>// -*- C++ -*- // The MIT License (MIT) // // Copyright (c) 2021 Alexander Samoilov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <gtest/gtest.h> #include "math.hpp" #include "ChebyshevDifferentiate.hpp" #include "PoissonProblem.hpp" #include "FastCosineTransform.hpp" template<size_t N> void sysslv(double a[N][N], double b[N]) { constexpr size_t n = N; double biga,save; int i,j,k,imax; for (j=0;j<n;j++) { biga=0.0; for(i=j;i<n;i++) if (std::fabs(biga) < std::fabs(a[i][j])) { biga=a[i][j]; imax=i; } if (std::fabs(biga) == 0.0) { throw std::logic_error("Very singular matrix..."); } for (k=j;k<n;k++) { save=a[imax][k]; a[imax][k]=a[j][k]; a[j][k]=save/biga; } save=b[imax]; b[imax]=b[j]; b[j]=save/biga; for (i=j+1;i<n;i++) { for(k=j+1;k<n;k++) a[i][k] -= a[i][j]*a[j][k]; b[i] -= b[j]*a[i][j]; } } for (k=n-2;k>=0;k--) for(j=n-1;j>k;j--) b[k] -= a[k][j]*b[j]; } TEST(cftSuite, test_cosfft1) { constexpr size_t M = 2; RowVectorXd x(M + 1), x_inv(M + 1); x << 1., 2., 3.; x_inv << 6., -2., 2.; FCT::cosfft1(M, x); EXPECT_DOUBLE_EQ((x - x_inv).norm(), 0.0); } TEST(cftSuite, test_cosfft12) { constexpr size_t M = 32; auto y = [](double x) {return x*x*x*x - 1;}; /// \f$y = x^4 - 1\f$ double x_min = -1., x_max = 1.; double xa = 0.5*(x_min-x_max); double xb = 0.5*(x_min+x_max); RowVectorXd x_grid(M + 1), f_vals1(M + 1), f_vals2(M + 1); for (size_t i = 0; i <= M; i++) { x_grid[i] = xa*std::cos(M_PI*i/(double)M)+xb; } for (size_t i = 0; i <= M; i++) { f_vals2[i] = f_vals1[i] = y(x_grid[i]); } FCT::cosfft1(M, f_vals1); FCT::cosfft1(M, f_vals1, FCT::TransformType::Inverse); // EXPECT_DOUBLE_EQ((f_vals1 - f_vals2).norm(), 0.0); constexpr double EPS = 1e-14; EXPECT_NEAR((f_vals1 - f_vals2).norm(), 0.0, EPS); } /// check that `.transpose()` and `.transposeInPlace()` /// surely work with non-square matrices TEST(eigenSuite, test_transpose) { constexpr size_t M = 2; constexpr size_t N = 3; RowMatrixXd ma(M, N), maT; ma << 1., 2., 3., 4., 5., 6.; maT = ma.transpose(); // std::cout << ma << std::endl; // std::cout << maT << std::endl; EXPECT_EQ(ma.rows(), maT.cols()); EXPECT_EQ(maT.rows(), ma.cols()); ma.transposeInPlace(); EXPECT_EQ(ma.rows(), maT.rows()); EXPECT_EQ(ma.cols(), maT.cols()); // assertion failure if use // `Eigen::Ref<RowMatrixXd>` instead of plain `RowMatrixXd&` auto transpose = [](RowMatrixXd& ma) { ma.transposeInPlace(); }; transpose(ma); EXPECT_EQ(ma.rows(), maT.cols()); EXPECT_EQ(maT.rows(), ma.cols()); } TEST(eigenSuite, test_unity) { constexpr size_t M = 2; constexpr size_t N = 3; RowMatrixXd ma; ma = Eigen::MatrixXd::Identity(M + 1, N + 1); // std::cout << "ma:\n" << ma << std::endl; EXPECT_EQ(ma.rows(), M + 1); EXPECT_EQ(ma.cols(), N + 1); ma.transposeInPlace(); EXPECT_EQ(ma.rows(), N + 1); EXPECT_EQ(ma.cols(), M + 1); EXPECT_EQ(ma(0, 0), 1.0); EXPECT_EQ(ma(1, 1), 1.0); EXPECT_EQ(ma(2, 2), 1.0); EXPECT_EQ(ma(1, 2), 0.0); EXPECT_EQ(ma(2, 1), 0.0); } TEST(cftSuite, test_cf2) { constexpr size_t M = 2; constexpr size_t N = 4; RowMatrixXd m(M + 1, N + 1), m_inv(M + 1, N + 1), m1; m << 1., 2., 3., 1., 2., 4., 5., 6., 4., 5., 7., 8., 9., 7., 8.; m_inv << 72., -0.87867965644035673, 9., -5.1213203435596428, 18., -30., -4.4408920985006262e-16, -6., 4.4408920985006262e-16, -6., 24., -0.29289321881345254, 3., -1.7071067811865479, 6.; m1 = m; FCT::cft2(M, N, m); FCT::cft2_with_transpose(M, N, m1); // std::cout << std::setprecision(17) << m << std::endl; constexpr double EPS = 1e-14; EXPECT_NEAR((m - m_inv).norm(), 0.0, EPS); EXPECT_NEAR((m - m1).norm(), 0.0, EPS); } TEST(bsSuite, test_gauss_elim) { constexpr double EPS = 1e-12; constexpr size_t M = 4; // https://mxncalc.com/gaussian-elimination-calculator double A[M][M] = {{1., 2., 3., 4.}, {5., 6., 8., 5.}, {4., 15., 2., 12.}, {3., 2., 5., 6.},}; double b[M] = {11., 12., 3., 7.,}; double x[M] = { -7.127'853'881'278'5, 1.237'442'922'374'4, 4.858'447'488'584'5, 0.269'406'392'694'06, }; Eigen::Vector4d bb(b), xx(x); Eigen::Matrix4d AA(reinterpret_cast<double*>(A)); AA.transposeInPlace(); // std::cout << "AA: " << AA << std::endl; sysslv(A, b); Eigen::Vector4d b2(b); //EXPECT_DOUBLE_EQ((b2 - xx).norm(), 0.0); // Expected equality of these values: // (b2 - xx).norm() // Which is: 5.3413613165043815e-14 // 0.0 // Which is: 0 EXPECT_NEAR((b2 - xx).norm(), 0.0, EPS); Eigen::Vector4d x2 = AA.lu().solve(bb); // std::cout << "x2: " << x2 << std::endl; // std::cout << "xx: " << xx << std::endl; EXPECT_NEAR((x2 - xx).norm(), 0.0, EPS); } TEST(ChebyshevDifferentiate, test_deriv1) { constexpr size_t M = 32; auto y = [](double x) {return x*x*x*x + sin(x);}; /// \f$y = x^4 + \sin x\f$ auto y_deriv1 = [](double x) {return 4*x*x*x + cos(x);}; /// \f$y = 4x^3 + \cos x\f$ RowVectorXd x_grid(M + 1), f_vals(M + 1), f_deriv_vals(M + 1); double x_min = -1., x_max = 1.; double xa = 0.5*(x_max-x_min); double xb = 0.5*(x_min+x_max); // std::cout << "xa: " << xa << " xb: " << xb << std::endl; for (size_t i = 0; i <= M; i++) { x_grid[i] = xa*std::cos(M_PI*i/(double)M)+xb; } // std::cout << "x_grid: " << x_grid << std::endl; for (size_t i = 0; i <= M; i++) { f_vals[i] = y (x_grid[i]); f_deriv_vals[i] = y_deriv1 (x_grid[i]); } // std::cout << "f_vals: [" << f_vals << "]\n"; // std::cout << "f_deriv_vals: [" << f_deriv_vals << "]\n"; FCT::cosfft1(M, f_vals, FCT::TransformType::Inverse); CS::spectral_differentiate(M, f_vals, f_vals, 2.0 / (x_max - x_min)); FCT::cosfft1(M, f_vals); // std::cout << "f_vals: [" << f_vals << "]\n"; // std::cout << "f_vals - f_deriv_vals: [" << f_vals - f_deriv_vals << "]\n"; //EXPECT_DOUBLE_EQ((f_vals - f_deriv_vals).norm(), 0.0); constexpr double EPS = 1e-10; EXPECT_NEAR((f_vals - f_deriv_vals).norm(), 0.0, EPS); } TEST(PoissonProblem, test_homogeneous_boundary) { auto sums_evens_odds = [](auto const& begin, auto const& end, size_t stride = 1) -> std::pair<double, double> { double evens = 0.0, odds = 0.0; size_t counter = 0; for (auto it = begin; ;std::advance(it, stride)) { if (detail::is_even(counter++)) { evens += *it; } else { odds += *it; } if (it == end) break; } return {evens, odds}; }; auto check_evens_odds = [sums_evens_odds] (auto const& ma, size_t row1, size_t col1, size_t row2, size_t col2, size_t stride = 1) { auto [evens, odds] = sums_evens_odds(&ma(row1, col1), &ma(row2, col2), stride); EXPECT_EQ(evens, 0); EXPECT_EQ(odds, 0); }; constexpr size_t M = 4; double A[M + 1][M + 1] = { {1., 2., 3., 4., 8.,}, {5., 6., 8., 5., 7.,}, {3., 5., 7., 2., 1.,}, {4., 15., 2., 12., 11.,}, {3., 2., 5., 6., 5.,}, }; RowMatrixXd AA(M + 1, M + 1), BB = RowMatrixXd::Zero(M + 1, M + 1); for (size_t i = 0; i <= M; ++i) { for (size_t j = 0; j <= M; ++j) { AA(i, j) = A[i][j]; } } // std::cout << "AA: [\n" << AA << "]\n"; CS::homogeneous_boundary(M, M, AA, BB); // std::cout << "BB: [\n" << BB << "]\n"; // std::cout << "AA: [\n" << AA << "]\n"; CS::homogeneous_boundary(M, M, AA, AA); // std::cout << "AA: [\n" << AA << "]\n"; EXPECT_DOUBLE_EQ((AA - BB).norm(), 0.0); constexpr size_t N = 2*M; RowMatrixXd CC(M + 1, N + 1); for (size_t i = 0; i <= M; ++i) { for (size_t j = 0; j <= N; ++j) { CC(i, j) = A[i][j % 2]; } } // std::cout << "CC: [\n" << CC << "]\n"; CS::homogeneous_boundary(M, N, CC, CC); // std::cout << "CC: [\n" << CC << "]\n"; for (size_t I = 0; I <= M; ++I) check_evens_odds(CC, I, 0, I, N, 1); for (size_t J = 0; J <= N; ++J) check_evens_odds(CC, 0, J, M, J, N + 1); } <|endoftext|>
<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 <cassert> #include <numeric> #include <chrono> #include <bh_component.hpp> #include <bh_extmethod.hpp> #include <bh_util.hpp> #include <bh_opcode.h> #include <jitk/fuser.hpp> #include <jitk/block.hpp> #include <jitk/instruction.hpp> #include <jitk/graph.hpp> #include <jitk/transformer.hpp> #include <jitk/fuser_cache.hpp> #include <jitk/codegen_util.hpp> #include <jitk/statistics.hpp> #include <jitk/dtype.hpp> #include <jitk/apply_fusion.hpp> #include "engine_openmp.hpp" using namespace bohrium; using namespace jitk; using namespace component; using namespace std; namespace { class Impl : public ComponentImpl { private: //Allocated base arrays set<bh_base*> _allocated_bases; public: // Some statistics Statistics stat; // The OpenMP engine EngineOpenMP engine; // Known extension methods map<bh_opcode, extmethod::ExtmethodFace> extmethods; Impl(int stack_level) : ComponentImpl(stack_level), stat(config), engine(config, stat) {} ~Impl(); void execute(BhIR *bhir); void extmethod(const string &name, bh_opcode opcode) { // ExtmethodFace does not have a default or copy constructor thus // we have to use its move constructor. extmethods.insert(make_pair(opcode, extmethod::ExtmethodFace(config, name))); } // Handle messages from parent string message(const string &msg) { stringstream ss; if (msg == "statistic_enable_and_reset") { stat = Statistics(true, config); } else if (msg == "statistic") { stat.write("OpenMP", "", ss); return ss.str(); } else if (msg == "info") { ss << engine.info(); } return ss.str(); } // Handle memory pointer retrieval void* getMemoryPointer(bh_base &base, bool copy2host, bool force_alloc, bool nullify) { if (not copy2host) { throw runtime_error("OpenMP - getMemoryPointer(): `copy2host` is not True"); } if (force_alloc) { bh_data_malloc(&base); } void *ret = base.data; if (nullify) { base.data = NULL; } return ret; } // Handle memory pointer obtainment void setMemoryPointer(bh_base *base, bool host_ptr, void *mem) { if (not host_ptr) { throw runtime_error("OpenMP - setMemoryPointer(): `host_ptr` is not True"); } if (base->data != nullptr) { throw runtime_error("OpenMP - setMemoryPointer(): `base->data` is not NULL"); } base->data = mem; } // We have no context so returning NULL void* getDeviceContext() { return nullptr; }; // We have no context so doing nothing void setDeviceContext(void* device_context) {}; }; } extern "C" ComponentImpl* create(int stack_level) { return new Impl(stack_level); } extern "C" void destroy(ComponentImpl* self) { delete self; } Impl::~Impl() { if (stat.print_on_exit) { stat.write("OpenMP", config.defaultGet<std::string>("prof_filename", ""), cout); } } void Impl::execute(BhIR *bhir) { bh_base *cond = bhir->getRepeatCondition(); for (uint64_t i = 0; i < bhir->getNRepeats(); ++i) { // Let's handle extension methods engine.handleExtmethod(*this, bhir); // And then the regular instructions engine.handleExecution(bhir); // Check condition if (cond != nullptr and cond->data != nullptr and not ((bool*) cond->data)[0]) { break; } // Slide offsets std::vector<bh_instruction> new_instr_list; std::vector<bh_view> new_views; // Iterate through all instructions and slide the relevant views for (bh_instruction instr : bhir->instr_list) { bh_instruction new_instr = instr; for (bh_view view : instr.operand) { if (not view.slide_strides.empty()) { // The relevant dimension in the view is updated by the given stride for (size_t i = 0; i < view.slide_strides.size(); i++) { size_t off_dim = view.slide_dimensions.at(i); size_t off_stride = view.slide_strides.at(i); view.start += view.stride[off_dim] * off_stride; } } new_views.push_back(view); } instr.operand = new_views; new_views.clear(); new_instr_list.push_back(instr); } // Update the instruction list bhir->instr_list = new_instr_list; } } <commit_msg>Changed from copying to editing in place<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 <cassert> #include <numeric> #include <chrono> #include <bh_component.hpp> #include <bh_extmethod.hpp> #include <bh_util.hpp> #include <bh_opcode.h> #include <jitk/fuser.hpp> #include <jitk/block.hpp> #include <jitk/instruction.hpp> #include <jitk/graph.hpp> #include <jitk/transformer.hpp> #include <jitk/fuser_cache.hpp> #include <jitk/codegen_util.hpp> #include <jitk/statistics.hpp> #include <jitk/dtype.hpp> #include <jitk/apply_fusion.hpp> #include "engine_openmp.hpp" using namespace bohrium; using namespace jitk; using namespace component; using namespace std; namespace { class Impl : public ComponentImpl { private: //Allocated base arrays set<bh_base*> _allocated_bases; public: // Some statistics Statistics stat; // The OpenMP engine EngineOpenMP engine; // Known extension methods map<bh_opcode, extmethod::ExtmethodFace> extmethods; Impl(int stack_level) : ComponentImpl(stack_level), stat(config), engine(config, stat) {} ~Impl(); void execute(BhIR *bhir); void extmethod(const string &name, bh_opcode opcode) { // ExtmethodFace does not have a default or copy constructor thus // we have to use its move constructor. extmethods.insert(make_pair(opcode, extmethod::ExtmethodFace(config, name))); } // Handle messages from parent string message(const string &msg) { stringstream ss; if (msg == "statistic_enable_and_reset") { stat = Statistics(true, config); } else if (msg == "statistic") { stat.write("OpenMP", "", ss); return ss.str(); } else if (msg == "info") { ss << engine.info(); } return ss.str(); } // Handle memory pointer retrieval void* getMemoryPointer(bh_base &base, bool copy2host, bool force_alloc, bool nullify) { if (not copy2host) { throw runtime_error("OpenMP - getMemoryPointer(): `copy2host` is not True"); } if (force_alloc) { bh_data_malloc(&base); } void *ret = base.data; if (nullify) { base.data = NULL; } return ret; } // Handle memory pointer obtainment void setMemoryPointer(bh_base *base, bool host_ptr, void *mem) { if (not host_ptr) { throw runtime_error("OpenMP - setMemoryPointer(): `host_ptr` is not True"); } if (base->data != nullptr) { throw runtime_error("OpenMP - setMemoryPointer(): `base->data` is not NULL"); } base->data = mem; } // We have no context so returning NULL void* getDeviceContext() { return nullptr; }; // We have no context so doing nothing void setDeviceContext(void* device_context) {}; }; } extern "C" ComponentImpl* create(int stack_level) { return new Impl(stack_level); } extern "C" void destroy(ComponentImpl* self) { delete self; } Impl::~Impl() { if (stat.print_on_exit) { stat.write("OpenMP", config.defaultGet<std::string>("prof_filename", ""), cout); } } void Impl::execute(BhIR *bhir) { bh_base *cond = bhir->getRepeatCondition(); for (uint64_t i = 0; i < bhir->getNRepeats(); ++i) { // Let's handle extension methods engine.handleExtmethod(*this, bhir); // And then the regular instructions engine.handleExecution(bhir); // Check condition if (cond != nullptr and cond->data != nullptr and not ((bool*) cond->data)[0]) { break; } // Iterate through all instructions and slide the relevant views for (bh_instruction &instr : bhir->instr_list) { for (bh_view &view : instr.operand) { if (not view.slide_strides.empty()) { // The relevant dimension in the view is updated by the given stride for (size_t i = 0; i < view.slide_strides.size(); i++) { size_t off_dim = view.slide_dimensions.at(i); size_t off_stride = view.slide_strides.at(i); view.start += view.stride[off_dim] * off_stride; } } } } } } <|endoftext|>
<commit_before>//===- SubtargetEmitter.cpp - Generate subtarget enumerations -------------===// // // The LLVM Compiler Infrastructure // // This file was developed by James M. Laskey and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend emits subtarget enumerations. // //===----------------------------------------------------------------------===// #include "SubtargetEmitter.h" #include "CodeGenTarget.h" #include "Record.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Debug.h" #include <algorithm> #include <set> using namespace llvm; // Convenience types typedef std::vector<Record*> RecordList; typedef std::vector<Record*>::iterator RecordListIter; // SubtargetEmitter::run - Main subtarget enumeration emitter. // void SubtargetEmitter::run(std::ostream &OS) { EmitSourceFileHeader("Subtarget Enumeration Source Fragment", OS); RecordList Features = Records.getAllDerivedDefinitions("SubtargetFeature"); RecordList Processors = Records.getAllDerivedDefinitions("Processor"); OS << "namespace llvm {\n\n"; { // Feature enumeration int i = 0; OS << "enum {\n"; for (RecordListIter RI = Features.begin(), E = Features.end(); RI != E;){ Record *R = *RI++; std::string Instance = R->getName(); OS << " " << Instance << " = " << " 1 << " << i++ << ((RI != E) ? ",\n" : "\n"); } OS << "};\n"; } { // Feature key values OS << "\n\n" << "/// Sorted (by key) array of values for CPU features.\n" << "static SubtargetFeatureKV FeatureKV[] = {\n"; for (RecordListIter RI = Features.begin(), E = Features.end(); RI != E;) { Record *R = *RI++; std::string Instance = R->getName(); std::string Name = R->getValueAsString("Name"); std::string Desc = R->getValueAsString("Desc"); OS << " { " << "\"" << Name << "\", " << "\"" << Desc << "\", " << Instance << ((RI != E) ? " },\n" : " }\n"); } OS << "};\n"; } { // Feature key values OS << "\n\n" << "/// Sorted (by key) array of values for CPU subtype.\n" << "static const SubtargetFeatureKV SubTypeKV[] = {\n"; for (RecordListIter RI = Processors.begin(), E = Processors.end(); RI != E;) { Record *R = *RI++; std::string Name = R->getValueAsString("Name"); Record *ProcItin = R->getValueAsDef("ProcItin"); ListInit *Features = R->getValueAsListInit("Features"); unsigned N = Features->getSize(); OS << " { " << "\"" << Name << "\", " << "\"Select the " << Name << " processor\", "; if (N == 0) { OS << "0"; } else { for (unsigned i = 0; i < N; ) { if (DefInit *DI = dynamic_cast<DefInit*>(Features->getElement(i++))) { Record *Feature = DI->getDef(); std::string Name = Feature->getName(); OS << Name; if (i != N) OS << " | "; } else { throw "Feature: " + Name + " expected feature in processor feature list!"; } } } OS << ((RI != E) ? " },\n" : " }\n"); } OS << "};\n"; } OS << "\n} // End llvm namespace \n"; } <commit_msg>Sort the features and processor lists for the sake of search (and maintainers.)<commit_after>//===- SubtargetEmitter.cpp - Generate subtarget enumerations -------------===// // // The LLVM Compiler Infrastructure // // This file was developed by James M. Laskey and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend emits subtarget enumerations. // //===----------------------------------------------------------------------===// #include "SubtargetEmitter.h" #include "CodeGenTarget.h" #include "Record.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Debug.h" #include <algorithm> #include <set> using namespace llvm; // // Convenience types. // typedef std::vector<Record*> RecordList; typedef std::vector<Record*>::iterator RecordListIter; // // Record sort by name function. // struct LessRecord { bool operator()(const Record *Rec1, const Record *Rec2) const { return Rec1->getName() < Rec2->getName(); } }; // // Record sort by field "Name" function. // struct LessRecordFieldName { bool operator()(const Record *Rec1, const Record *Rec2) const { return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name"); } }; // // SubtargetEmitter::run - Main subtarget enumeration emitter. // void SubtargetEmitter::run(std::ostream &OS) { EmitSourceFileHeader("Subtarget Enumeration Source Fragment", OS); RecordList Features = Records.getAllDerivedDefinitions("SubtargetFeature"); sort(Features.begin(), Features.end(), LessRecord()); RecordList Processors = Records.getAllDerivedDefinitions("Processor"); sort(Processors.begin(), Processors.end(), LessRecordFieldName()); OS << "namespace llvm {\n\n"; { // Feature enumeration int i = 0; OS << "enum {\n"; for (RecordListIter RI = Features.begin(), E = Features.end(); RI != E;){ Record *R = *RI++; std::string Instance = R->getName(); OS << " " << Instance << " = " << " 1 << " << i++ << ((RI != E) ? ",\n" : "\n"); } OS << "};\n"; } { // Feature key values OS << "\n\n" << "/// Sorted (by key) array of values for CPU features.\n" << "static SubtargetFeatureKV FeatureKV[] = {\n"; for (RecordListIter RI = Features.begin(), E = Features.end(); RI != E;) { Record *R = *RI++; std::string Instance = R->getName(); std::string Name = R->getValueAsString("Name"); std::string Desc = R->getValueAsString("Desc"); OS << " { " << "\"" << Name << "\", " << "\"" << Desc << "\", " << Instance << ((RI != E) ? " },\n" : " }\n"); } OS << "};\n"; } { // CPU key values OS << "\n\n" << "/// Sorted (by key) array of values for CPU subtype.\n" << "static const SubtargetFeatureKV SubTypeKV[] = {\n"; for (RecordListIter RI = Processors.begin(), E = Processors.end(); RI != E;) { Record *R = *RI++; std::string Name = R->getValueAsString("Name"); Record *ProcItin = R->getValueAsDef("ProcItin"); ListInit *Features = R->getValueAsListInit("Features"); unsigned N = Features->getSize(); OS << " { " << "\"" << Name << "\", " << "\"Select the " << Name << " processor\", "; if (N == 0) { OS << "0"; } else { for (unsigned i = 0; i < N; ) { if (DefInit *DI = dynamic_cast<DefInit*>(Features->getElement(i++))) { Record *Feature = DI->getDef(); std::string Name = Feature->getName(); OS << Name; if (i != N) OS << " | "; } else { throw "Feature: " + Name + " expected feature in processor feature list!"; } } } OS << ((RI != E) ? " },\n" : " }\n"); } OS << "};\n"; } OS << "\n} // End llvm namespace \n"; } <|endoftext|>
<commit_before>#include <SDL2/SDL.h> #include "PageView.h" // global declaration #define TRUE 1 #define FALSE 0 int cur_mode; int running; static const int screen_w = 1024; static const int screen_h = 1024; enum LR_MODES { LR_DEFAULT, LR_LINKS, LR_URL }; enum KEYS { LR_L, LR_J, LR_K, LR_F, LR_G, LR_Q, LR_ESC, LR_SPACE, LR_RETURN, LR_UP, LR_DOWN }; void render_links_tab() { } void shift_down() { } void shift_up() { } void page_down() { } void page_up() { } void show_url_bar() { } void links_up() { } void links_down() { } void navigate() { } /* * * By the time this gets called, mode switching already happened. * */ void handle_keypress(int key) { if((key == LR_L) && (cur_mode == LR_LINKS)){ render_links_tab(); } else if((key == LR_J) && (cur_mode == LR_DEFAULT)){ shift_down(); } else if((key == LR_K) && (cur_mode == LR_DEFAULT)){ shift_up(); } else if((key == LR_F) && (cur_mode == LR_DEFAULT)){ page_down(); } else if((key == LR_G) && (cur_mode == LR_DEFAULT)){ page_up(); } else if((key == LR_SPACE) && (cur_mode == LR_URL)){ show_url_bar(); } else if((key == LR_UP) && (cur_mode == LR_LINKS)){ links_up(); } else if((key == LR_DOWN) && (cur_mode == LR_LINKS)){ links_down(); } else if((key == LR_RETURN && (cur_mode == LR_LINKS))){ navigate(); } else{ SDL_Log("Invalid key combination: %d\n" , key); } } // updates the mode from cur_mode to mode or throws an error if the request is invalid void update_mode( const int mode ) { if((cur_mode == LR_DEFAULT) && (mode == LR_LINKS)){ cur_mode = LR_LINKS; SDL_Log("Mode Switch from DEFAULT to LINKS\n"); } else if((cur_mode == LR_DEFAULT) && (mode == LR_URL)){ cur_mode = LR_URL; SDL_Log("Mode Switch from DEFAULT to URL\n"); } else if((cur_mode == LR_LINKS) && (mode == LR_DEFAULT)){ cur_mode = LR_DEFAULT; SDL_Log("Mode Switch from LINKS to DEFAULT\n"); } else if((cur_mode == LR_URL) && (mode == LR_DEFAULT)){ cur_mode = LR_DEFAULT; SDL_Log("Mode Switch from URL to DEFAULT\n"); } else{ SDL_Log("Invalid Mode Switch Attempt, cur mode: %d\n" , cur_mode); } } void input_controller() { SDL_Event event; while( SDL_PollEvent(&event) ){ if( event.type == SDL_QUIT){ running = FALSE; break; } else if( event.type == SDL_KEYDOWN ){ switch( event.key.keysym.sym ){ case SDLK_l: SDL_Log("L key pressed\n"); update_mode(LR_LINKS); handle_keypress(LR_L); break; case SDLK_j: SDL_Log("J key pressed\n"); handle_keypress(LR_J); break; case SDLK_k: SDL_Log("K key pressed\n"); handle_keypress(LR_K); break; case SDLK_f: SDL_Log("F key pressed\n"); handle_keypress(LR_F); break; case SDLK_g: SDL_Log("G key pressed\n"); handle_keypress(LR_G); break; case SDLK_SPACE: SDL_Log("Space key pressed"); update_mode(LR_URL); handle_keypress(LR_SPACE); break; case SDLK_q: SDL_Log("Q key pressed\n"); update_mode(LR_DEFAULT); break; case SDLK_ESCAPE: running = FALSE; break; case SDLK_UP: SDL_Log("Up key pressed\n"); handle_keypress(LR_UP); break; case SDLK_DOWN: SDL_Log("Down key pressed\n"); handle_keypress(LR_DOWN); break; case SDLK_RETURN: SDL_Log("Return key pressed\n"); handle_keypress(LR_RETURN); break; } } } } //TODO void render(SDL_Renderer *renderer) { SDL_RenderClear(renderer); } int main( int argc, char **argv ) { SDL_Window *window; SDL_Renderer *renderer; SDL_Texture *texture; PageView *pv; SDL_Init(SDL_INIT_VIDEO); SDL_Log( "SDL Initialized\n"); window = SDL_CreateWindow("Key Press Test", SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED, screen_w, screen_h, SDL_WINDOW_OPENGL ); if( window == NULL ){ SDL_LogCritical(SDL_LOG_CATEGORY_ERROR, "Failed to create window: %s\n" , SDL_GetError()); } Uint32 render_flags = (SDL_BLENDMODE_BLEND | SDL_RENDERER_TARGETTEXTURE | SDL_RENDERER_PRESENTVSYNC); renderer = SDL_CreateRenderer(window, -1, render_flags); if( renderer == NULL ){ SDL_LogCritical(SDL_LOG_CATEGORY_ERROR, "Failed to create renderer %s\n" , SDL_GetError()); } //SDL_SetRenderDrawBlendMode(renderer,-1, render_flags); texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, screen_w, screen_h ); pv = new PageView(texture, screen_w, screen_h); running = TRUE; cur_mode = LR_DEFAULT; // program main loop while(running){ // SDL_SetRenderTarget(renderer, texture); // SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00); SDL_RenderClear(renderer); input_controller(); } SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); SDL_Quit(); printf("Process Complete, exiting \n"); return 0; } <commit_msg>adding rendering stuff<commit_after>#include <SDL2/SDL.h> #include "PageView.h" // global declaration #define TRUE 1 #define FALSE 0 int cur_mode; int running; static const int screen_w = 1024; static const int screen_h = 1024; enum LR_MODES { LR_DEFAULT, LR_LINKS, LR_URL }; enum KEYS { LR_L, LR_J, LR_K, LR_F, LR_G, LR_Q, LR_ESC, LR_SPACE, LR_RETURN, LR_UP, LR_DOWN }; void render_links_tab() { } void shift_down() { } void shift_up() { } void page_down() { } void page_up() { } void show_url_bar() { } void links_up() { } void links_down() { } void navigate() { } /* * * By the time this gets called, mode switching already happened. * */ void handle_keypress(int key) { if((key == LR_L) && (cur_mode == LR_LINKS)){ render_links_tab(); } else if((key == LR_J) && (cur_mode == LR_DEFAULT)){ shift_down(); } else if((key == LR_K) && (cur_mode == LR_DEFAULT)){ shift_up(); } else if((key == LR_F) && (cur_mode == LR_DEFAULT)){ page_down(); } else if((key == LR_G) && (cur_mode == LR_DEFAULT)){ page_up(); } else if((key == LR_SPACE) && (cur_mode == LR_URL)){ show_url_bar(); } else if((key == LR_UP) && (cur_mode == LR_LINKS)){ links_up(); } else if((key == LR_DOWN) && (cur_mode == LR_LINKS)){ links_down(); } else if((key == LR_RETURN && (cur_mode == LR_LINKS))){ navigate(); } else{ SDL_Log("Invalid key combination: %d\n" , key); } } // updates the mode from cur_mode to mode or throws an error if the request is invalid void update_mode( const int mode ) { if((cur_mode == LR_DEFAULT) && (mode == LR_LINKS)){ cur_mode = LR_LINKS; SDL_Log("Mode Switch from DEFAULT to LINKS\n"); } else if((cur_mode == LR_DEFAULT) && (mode == LR_URL)){ cur_mode = LR_URL; SDL_Log("Mode Switch from DEFAULT to URL\n"); } else if((cur_mode == LR_LINKS) && (mode == LR_DEFAULT)){ cur_mode = LR_DEFAULT; SDL_Log("Mode Switch from LINKS to DEFAULT\n"); } else if((cur_mode == LR_URL) && (mode == LR_DEFAULT)){ cur_mode = LR_DEFAULT; SDL_Log("Mode Switch from URL to DEFAULT\n"); } else{ SDL_Log("Invalid Mode Switch Attempt, cur mode: %d\n" , cur_mode); } } void input_controller() { SDL_Event event; while( SDL_PollEvent(&event) ){ if( event.type == SDL_QUIT){ running = FALSE; break; } else if( event.type == SDL_KEYDOWN ){ switch( event.key.keysym.sym ){ case SDLK_l: SDL_Log("L key pressed\n"); update_mode(LR_LINKS); handle_keypress(LR_L); break; case SDLK_j: SDL_Log("J key pressed\n"); handle_keypress(LR_J); break; case SDLK_k: SDL_Log("K key pressed\n"); handle_keypress(LR_K); break; case SDLK_f: SDL_Log("F key pressed\n"); handle_keypress(LR_F); break; case SDLK_g: SDL_Log("G key pressed\n"); handle_keypress(LR_G); break; case SDLK_SPACE: SDL_Log("Space key pressed"); update_mode(LR_URL); handle_keypress(LR_SPACE); break; case SDLK_q: SDL_Log("Q key pressed\n"); update_mode(LR_DEFAULT); break; case SDLK_ESCAPE: running = FALSE; break; case SDLK_UP: SDL_Log("Up key pressed\n"); handle_keypress(LR_UP); break; case SDLK_DOWN: SDL_Log("Down key pressed\n"); handle_keypress(LR_DOWN); break; case SDLK_RETURN: SDL_Log("Return key pressed\n"); handle_keypress(LR_RETURN); break; } } } } //TODO void render(SDL_Renderer *renderer) { SDL_RenderClear(renderer); } int main( int argc, char **argv ) { SDL_Window *window; SDL_Renderer *renderer; SDL_Texture *texture; PageView *pv; SDL_Init(SDL_INIT_VIDEO); SDL_Log( "SDL Initialized\n"); window = SDL_CreateWindow("Key Press Test", SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED, screen_w, screen_h, SDL_WINDOW_OPENGL ); if( window == NULL ){ SDL_LogCritical(SDL_LOG_CATEGORY_ERROR, "Failed to create window: %s\n" , SDL_GetError()); } Uint32 render_flags = (SDL_BLENDMODE_BLEND | SDL_RENDERER_TARGETTEXTURE | SDL_RENDERER_PRESENTVSYNC); renderer = SDL_CreateRenderer(window, -1, render_flags); if( renderer == NULL ){ SDL_LogCritical(SDL_LOG_CATEGORY_ERROR, "Failed to create renderer %s\n" , SDL_GetError()); } //SDL_SetRenderDrawBlendMode(renderer,-1, render_flags); texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, screen_w, screen_h ); pv = new PageView(texture, screen_w, screen_h); running = TRUE; cur_mode = LR_DEFAULT; // program main loop while(running){ SDL_SetRenderTarget(renderer, texture); SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00); SDL_RenderClear(renderer); input_controller(); SDL_SetRenderTarget(renderer, NULL); SDL_RenderCopy(renderer, texture, NULL, NULL); } SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); SDL_Quit(); printf("Process Complete, exiting \n"); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) DataStax, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "connection_pool_connector.hpp" #include "connection_pool_manager.hpp" #include "event_loop.hpp" #include "memory.hpp" #include "metrics.hpp" namespace cass { ConnectionPoolConnector::ConnectionPoolConnector(ConnectionPoolManager* manager, const Address& address, const Callback& callback) : pool_(Memory::allocate<ConnectionPool>(manager, address)) , callback_(callback) , remaining_(0) { } void ConnectionPoolConnector::connect() { inc_ref(); const size_t num_connections_per_host = pool_->manager()->settings().num_connections_per_host; remaining_ = num_connections_per_host; for (size_t i = 0; i < num_connections_per_host; ++i) { PooledConnector::Ptr connector( Memory::allocate<PooledConnector>(pool_.get(), bind_callback(&ConnectionPoolConnector::on_connect, this))); pending_connections_.push_back(connector); connector->connect(); } } void ConnectionPoolConnector::cancel() { if (pool_) pool_->close(); for (PooledConnector::Vec::iterator it = pending_connections_.begin(), end = pending_connections_.end(); it != end; ++it) { (*it)->cancel(); } } ConnectionPool::Ptr ConnectionPoolConnector::release_pool() { ConnectionPool::Ptr temp = pool_; pool_.reset(); return temp; } Connector::ConnectionError ConnectionPoolConnector::error_code() const { return critical_error_connector_ ? critical_error_connector_->error_code() : Connector::CONNECTION_OK; } String ConnectionPoolConnector::error_message() const { return critical_error_connector_ ? critical_error_connector_->error_message() : ""; } bool ConnectionPoolConnector::is_ok() const { return !is_critical_error(); } bool ConnectionPoolConnector::is_critical_error() const { return critical_error_connector_; } bool ConnectionPoolConnector::is_keyspace_error() const { if (critical_error_connector_) { return critical_error_connector_->is_keyspace_error(); } return false; } void ConnectionPoolConnector::on_connect(PooledConnector* connector) { pending_connections_.erase(std::remove(pending_connections_.begin(), pending_connections_.end(), connector), pending_connections_.end()); if (connector->is_ok()) { pool_->add_connection(connector->release_connection(), ConnectionPool::Protected()); } else if (!connector->is_canceled()){ LOG_ERROR("Connection pool was unable to connect to host %s because of the following error: %s", pool_->address().to_string().c_str(), connector->error_message().c_str()); if (connector->is_critical_error()) { if (!critical_error_connector_) { critical_error_connector_.reset(connector); pool_->close(); for (PooledConnector::Vec::iterator it = pending_connections_.begin(), end = pending_connections_.end(); it != end; ++it) { (*it)->cancel(); } } } else { pool_->schedule_reconnect(ConnectionPool::Protected()); } } if (--remaining_ == 0) { ConnectionPool::Ptr temp = pool_; callback_(this); // Notify listener after the callback if (!critical_error_connector_) { temp->notify_up_or_down(ConnectionPool::Protected()); } else { temp->notify_critical_error(critical_error_connector_->error_code(), critical_error_connector_->error_message(), ConnectionPool::Protected()); } // If the pool hasn't been released then close it. if (pool_) pool_->close(); dec_ref(); } } } // namespace cass <commit_msg>CPP-627 - Ensuring ConnectionPoolManager is available for notifications<commit_after>/* Copyright (c) DataStax, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "connection_pool_connector.hpp" #include "connection_pool_manager.hpp" #include "event_loop.hpp" #include "memory.hpp" #include "metrics.hpp" namespace cass { ConnectionPoolConnector::ConnectionPoolConnector(ConnectionPoolManager* manager, const Address& address, const Callback& callback) : pool_(Memory::allocate<ConnectionPool>(manager, address)) , callback_(callback) , remaining_(0) { } void ConnectionPoolConnector::connect() { inc_ref(); const size_t num_connections_per_host = pool_->manager()->settings().num_connections_per_host; remaining_ = num_connections_per_host; for (size_t i = 0; i < num_connections_per_host; ++i) { PooledConnector::Ptr connector( Memory::allocate<PooledConnector>(pool_.get(), bind_callback(&ConnectionPoolConnector::on_connect, this))); pending_connections_.push_back(connector); connector->connect(); } } void ConnectionPoolConnector::cancel() { if (pool_) pool_->close(); for (PooledConnector::Vec::iterator it = pending_connections_.begin(), end = pending_connections_.end(); it != end; ++it) { (*it)->cancel(); } } ConnectionPool::Ptr ConnectionPoolConnector::release_pool() { ConnectionPool::Ptr temp = pool_; pool_.reset(); return temp; } Connector::ConnectionError ConnectionPoolConnector::error_code() const { return critical_error_connector_ ? critical_error_connector_->error_code() : Connector::CONNECTION_OK; } String ConnectionPoolConnector::error_message() const { return critical_error_connector_ ? critical_error_connector_->error_message() : ""; } bool ConnectionPoolConnector::is_ok() const { return !is_critical_error(); } bool ConnectionPoolConnector::is_critical_error() const { return critical_error_connector_; } bool ConnectionPoolConnector::is_keyspace_error() const { if (critical_error_connector_) { return critical_error_connector_->is_keyspace_error(); } return false; } void ConnectionPoolConnector::on_connect(PooledConnector* connector) { pending_connections_.erase(std::remove(pending_connections_.begin(), pending_connections_.end(), connector), pending_connections_.end()); if (connector->is_ok()) { pool_->add_connection(connector->release_connection(), ConnectionPool::Protected()); } else if (!connector->is_canceled()){ LOG_ERROR("Connection pool was unable to connect to host %s because of the following error: %s", pool_->address().to_string().c_str(), connector->error_message().c_str()); if (connector->is_critical_error()) { if (!critical_error_connector_) { critical_error_connector_.reset(connector); pool_->close(); for (PooledConnector::Vec::iterator it = pending_connections_.begin(), end = pending_connections_.end(); it != end; ++it) { (*it)->cancel(); } } } else { pool_->schedule_reconnect(ConnectionPool::Protected()); } } if (--remaining_ == 0) { if (!critical_error_connector_) { pool_->notify_up_or_down(ConnectionPool::Protected()); } else { pool_->notify_critical_error(critical_error_connector_->error_code(), critical_error_connector_->error_message(), ConnectionPool::Protected()); } callback_(this); // If the pool hasn't been released then close it. if (pool_) pool_->close(); dec_ref(); } } } // namespace cass <|endoftext|>
<commit_before>#include <pddl/detail/parsing/Predicate.h> #include <pddl/AST.h> #include <pddl/Exception.h> #include <pddl/detail/SignatureMatching.h> #include <pddl/detail/parsing/Constant.h> #include <pddl/detail/parsing/Variable.h> #include <pddl/detail/parsing/VariableDeclaration.h> namespace pddl { namespace detail { //////////////////////////////////////////////////////////////////////////////////////////////////// // // Predicate // //////////////////////////////////////////////////////////////////////////////////////////////////// std::experimental::optional<ast::PredicatePointer> parsePredicate(Context &context, ASTContext &astContext, VariableStack &variableStack) { auto &tokenizer = context.tokenizer; tokenizer.skipWhiteSpace(); const auto previousPosition = tokenizer.position(); if (!tokenizer.testAndSkip<std::string>("(")) { tokenizer.seek(previousPosition); return std::experimental::nullopt; } const auto name = tokenizer.getIdentifier(); ast::Predicate::Arguments arguments; tokenizer.skipWhiteSpace(); // Parse arguments while (tokenizer.currentCharacter() != ')') { // Parse argument if it is a variable auto variable = testParsingVariable(context, variableStack); if (variable) { arguments.emplace_back(std::move(variable.value())); tokenizer.skipWhiteSpace(); continue; } // Parse argument if it is a constant auto constant = testParsingConstant(context, astContext); if (constant) { arguments.emplace_back(std::move(constant.value())); tokenizer.skipWhiteSpace(); continue; } // If argument is neither variable nor constant, this is not a valid predicate tokenizer.seek(previousPosition); return std::experimental::nullopt; } const auto &predicates = astContext.domain->predicates; const auto matchingPredicateDeclaration = std::find_if(predicates.cbegin(), predicates.cend(), [&](const auto &predicateDeclaration) { return matches(name, arguments, *predicateDeclaration); }); if (matchingPredicateDeclaration == predicates.cend()) { // TODO: enumerate candidates and why they are incompatible tokenizer.seek(previousPosition); throw ParserException(tokenizer.location(), "no matching declaration found for predicate “" + name + "”"); } auto *declaration = matchingPredicateDeclaration->get(); tokenizer.expect<std::string>(")"); return std::make_unique<ast::Predicate>(std::move(arguments), declaration); } //////////////////////////////////////////////////////////////////////////////////////////////////// } } <commit_msg>Refactoring to reuse term parsing code.<commit_after>#include <pddl/detail/parsing/Predicate.h> #include <pddl/AST.h> #include <pddl/Exception.h> #include <pddl/detail/SignatureMatching.h> #include <pddl/detail/parsing/Term.h> namespace pddl { namespace detail { //////////////////////////////////////////////////////////////////////////////////////////////////// // // Predicate // //////////////////////////////////////////////////////////////////////////////////////////////////// std::experimental::optional<ast::PredicatePointer> parsePredicate(Context &context, ASTContext &astContext, VariableStack &variableStack) { auto &tokenizer = context.tokenizer; tokenizer.skipWhiteSpace(); const auto previousPosition = tokenizer.position(); if (!tokenizer.testAndSkip<std::string>("(")) { tokenizer.seek(previousPosition); return std::experimental::nullopt; } const auto name = tokenizer.getIdentifier(); ast::Predicate::Arguments arguments; tokenizer.skipWhiteSpace(); // Parse arguments while (tokenizer.currentCharacter() != ')') { auto term = parseTerm(context, astContext, variableStack); if (term) { arguments.emplace_back(std::move(term.value())); tokenizer.skipWhiteSpace(); continue; } // If the term couldn’t be parsed, this is not a valid predicate tokenizer.seek(previousPosition); return std::experimental::nullopt; } const auto &predicates = astContext.domain->predicates; const auto matchingPredicateDeclaration = std::find_if(predicates.cbegin(), predicates.cend(), [&](const auto &predicateDeclaration) { return matches(name, arguments, *predicateDeclaration); }); if (matchingPredicateDeclaration == predicates.cend()) { // TODO: enumerate candidates and why they are incompatible tokenizer.seek(previousPosition); throw ParserException(tokenizer.location(), "no matching declaration found for predicate “" + name + "”"); } auto *declaration = matchingPredicateDeclaration->get(); tokenizer.expect<std::string>(")"); return std::make_unique<ast::Predicate>(std::move(arguments), declaration); } //////////////////////////////////////////////////////////////////////////////////////////////////// } } <|endoftext|>
<commit_before>#include "H-qoi.h" // Here we define the functions to compute the QoI (side_qoi) // and supply the right hand side for the associated adjoint problem (side_qoi_derivative) using namespace libMesh; void CoupledSystemQoI::init_qoi( std::vector<Number>& sys_qoi) { //Only 1 qoi to worry about sys_qoi.resize(1); return; } // This function supplies the right hand side for the adjoint problem // We only have one QoI, so we don't bother checking the qois argument // to see if it was requested from us void CoupledSystemQoI::side_qoi_derivative (DiffContext &context, const QoISet & /* qois */) { FEMContext &c = libmesh_cast_ref<FEMContext&>(context); // Element Jacobian * quadrature weights for interior integration const std::vector<Real> &JxW = c.side_fe_var[0]->get_JxW(); // Get velocity basis functions phi const std::vector<std::vector<Real> > &phi = c.side_fe_var[0]->get_phi(); const std::vector<Point > &q_point = c.side_fe_var[0]->get_xyz(); // The number of local degrees of freedom in each variable const unsigned int n_u_dofs = c.dof_indices_var[1].size(); DenseSubVector<Number> &Qu = *c.elem_qoi_subderivatives[0][0]; DenseSubVector<Number> &QC = *c.elem_qoi_subderivatives[0][3]; // Now we will build the element Jacobian and residual. // Constructing the residual requires the solution and its // gradient from the previous timestep. This must be // calculated at each quadrature point by summing the // solution degree-of-freedom values by the appropriate // weight functions. unsigned int n_qpoints = c.side_qrule->n_points(); Number u = 0. ; Number C = 0. ; // // If side is on outlet if(c.has_side_boundary_id(2)) { // Loop over all the qps on this side for (unsigned int qp=0; qp != n_qpoints; qp++) { Real x = q_point[qp](0); // If side is on left outlet if(x < 0.) { // Get u at the qp u = c.side_value(0,qp); C = c.side_value(3,qp); // Add the contribution from each basis function for (unsigned int i=0; i != n_u_dofs; i++) { Qu(i) += JxW[qp] * -phi[i][qp] * C; QC(i) += JxW[qp] * phi[i][qp] * -u; } } // end if } // end quadrature loop } // end if on outlet } // This function computes the actual QoI void CoupledSystemQoI::side_qoi(DiffContext &context, const QoISet & /* qois */) { FEMContext &c = libmesh_cast_ref<FEMContext&>(context); // First we get some references to cell-specific data that // will be used to assemble the linear system. // Element Jacobian * quadrature weights for interior integration const std::vector<Real> &JxW = c.side_fe_var[0]->get_JxW(); const std::vector<Point > &q_point = c.side_fe_var[0]->get_xyz(); // Loop over qp's, compute the function at each qp and add // to get the QoI unsigned int n_qpoints = c.side_qrule->n_points(); Real dQoI_0 = 0. ; Number u = 0. ; Number C = 0. ; // If side is on the left outlet if(c.has_side_boundary_id(2)) { //Loop over all the qps on this side for (unsigned int qp=0; qp != n_qpoints; qp++) { Real x = q_point[qp](0); if(x < 0.) { // Get u and C at the qp u = c.side_value(0,qp); C = c.side_value(3,qp); dQoI_0 += JxW[qp] * -u * C; } // end if } // end quadrature loop } // end if on bdry c.elem_qoi[0] += dQoI_0; } <commit_msg>Another --enable-complex fix for adjoints ex3<commit_after>#include "H-qoi.h" // Here we define the functions to compute the QoI (side_qoi) // and supply the right hand side for the associated adjoint problem (side_qoi_derivative) using namespace libMesh; void CoupledSystemQoI::init_qoi( std::vector<Number>& sys_qoi) { //Only 1 qoi to worry about sys_qoi.resize(1); return; } // This function supplies the right hand side for the adjoint problem // We only have one QoI, so we don't bother checking the qois argument // to see if it was requested from us void CoupledSystemQoI::side_qoi_derivative (DiffContext &context, const QoISet & /* qois */) { FEMContext &c = libmesh_cast_ref<FEMContext&>(context); // Element Jacobian * quadrature weights for interior integration const std::vector<Real> &JxW = c.side_fe_var[0]->get_JxW(); // Get velocity basis functions phi const std::vector<std::vector<Real> > &phi = c.side_fe_var[0]->get_phi(); const std::vector<Point > &q_point = c.side_fe_var[0]->get_xyz(); // The number of local degrees of freedom in each variable const unsigned int n_u_dofs = c.dof_indices_var[1].size(); DenseSubVector<Number> &Qu = *c.elem_qoi_subderivatives[0][0]; DenseSubVector<Number> &QC = *c.elem_qoi_subderivatives[0][3]; // Now we will build the element Jacobian and residual. // Constructing the residual requires the solution and its // gradient from the previous timestep. This must be // calculated at each quadrature point by summing the // solution degree-of-freedom values by the appropriate // weight functions. unsigned int n_qpoints = c.side_qrule->n_points(); Number u = 0. ; Number C = 0. ; // // If side is on outlet if(c.has_side_boundary_id(2)) { // Loop over all the qps on this side for (unsigned int qp=0; qp != n_qpoints; qp++) { Real x = q_point[qp](0); // If side is on left outlet if(x < 0.) { // Get u at the qp u = c.side_value(0,qp); C = c.side_value(3,qp); // Add the contribution from each basis function for (unsigned int i=0; i != n_u_dofs; i++) { Qu(i) += JxW[qp] * -phi[i][qp] * C; QC(i) += JxW[qp] * phi[i][qp] * -u; } } // end if } // end quadrature loop } // end if on outlet } // This function computes the actual QoI void CoupledSystemQoI::side_qoi(DiffContext &context, const QoISet & /* qois */) { FEMContext &c = libmesh_cast_ref<FEMContext&>(context); // First we get some references to cell-specific data that // will be used to assemble the linear system. // Element Jacobian * quadrature weights for interior integration const std::vector<Real> &JxW = c.side_fe_var[0]->get_JxW(); const std::vector<Point > &q_point = c.side_fe_var[0]->get_xyz(); // Loop over qp's, compute the function at each qp and add // to get the QoI unsigned int n_qpoints = c.side_qrule->n_points(); Number dQoI_0 = 0. ; Number u = 0. ; Number C = 0. ; // If side is on the left outlet if(c.has_side_boundary_id(2)) { //Loop over all the qps on this side for (unsigned int qp=0; qp != n_qpoints; qp++) { Real x = q_point[qp](0); if(x < 0.) { // Get u and C at the qp u = c.side_value(0,qp); C = c.side_value(3,qp); dQoI_0 += JxW[qp] * -u * C; } // end if } // end quadrature loop } // end if on bdry c.elem_qoi[0] += dQoI_0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2017, Respective Authors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <eos/chain/global_property_object.hpp> #include <eos/chain/node_property_object.hpp> #include <eos/chain/fork_database.hpp> #include <eos/chain/block_database.hpp> #include <eos/chain/genesis_state.hpp> #include <chainbase/chainbase.hpp> #include <fc/scoped_exit.hpp> #include <fc/signals.hpp> #include <eos/chain/protocol/protocol.hpp> #include <fc/log/logger.hpp> #include <map> namespace eos { namespace chain { /** * @class database * @brief tracks the blockchain state in an extensible manner */ class database : public chainbase::database { public: database(); ~database(); enum validation_steps { skip_nothing = 0, skip_producer_signature = 1 << 0, ///< used while reindexing skip_transaction_signatures = 1 << 1, ///< used by non-producer nodes skip_transaction_dupe_check = 1 << 2, ///< used while reindexing skip_fork_db = 1 << 3, ///< used while reindexing skip_block_size_check = 1 << 4, ///< used when applying locally generated transactions skip_tapos_check = 1 << 5, ///< used while reindexing -- note this skips expiration check as well skip_authority_check = 1 << 6, ///< used while reindexing -- disables any checking of authority on transactions skip_merkle_check = 1 << 7, ///< used while reindexing skip_assert_evaluation = 1 << 8, ///< used while reindexing skip_undo_history_check = 1 << 9, ///< used while reindexing skip_producer_schedule_check= 1 << 10, ///< used while reindexing skip_validate = 1 << 11 ///< used prior to checkpoint, skips validate() call on transaction }; /** * @brief Open a database, creating a new one if necessary * * Opens a database in the specified directory. If no initialized database is found, genesis_loader is called * and its return value is used as the genesis state when initializing the new database * * genesis_loader will not be called if an existing database is found. * * @param data_dir Path to open or create database in * @param shared_file_size Size of the database memory mapped file * @param genesis_loader A callable object which returns the genesis state to initialize new databases on */ void open(const fc::path& data_dir, uint64_t shared_file_size, std::function<genesis_state_type()> genesis_loader ); /** * @brief Rebuild object graph from block history and open detabase * * This method may be called after or instead of @ref database::open, and will rebuild the object graph by * replaying blockchain history. When this method exits successfully, the database will be open. */ void reindex(fc::path data_dir, uint64_t shared_file_size, const genesis_state_type& initial_allocation = genesis_state_type()); /** * @brief wipe Delete database from disk, and potentially the raw chain as well. * @param include_blocks If true, delete the raw chain as well as the database. * * Will close the database before wiping. Database will be closed when this function returns. */ void wipe(const fc::path& data_dir, bool include_blocks); void close(); /** * @return true if the block is in our fork DB or saved to disk as * part of the official chain, otherwise return false */ bool is_known_block( const block_id_type& id )const; bool is_known_transaction( const transaction_id_type& id )const; block_id_type get_block_id_for_num( uint32_t block_num )const; optional<signed_block> fetch_block_by_id( const block_id_type& id )const; optional<signed_block> fetch_block_by_number( uint32_t num )const; const signed_transaction& get_recent_transaction( const transaction_id_type& trx_id )const; std::vector<block_id_type> get_block_ids_on_fork(block_id_type head_of_fork) const; /** * Calculate the percent of block production slots that were missed in the * past 128 blocks, not including the current block. */ uint32_t producer_participation_rate()const; void add_checkpoints(const flat_map<uint32_t,block_id_type>& checkpts); const flat_map<uint32_t,block_id_type> get_checkpoints()const { return _checkpoints; } bool before_last_checkpoint()const; bool push_block( const signed_block& b, uint32_t skip = skip_nothing ); void push_transaction( const signed_transaction& trx, uint32_t skip = skip_nothing ); bool _push_block( const signed_block& b ); void _push_transaction( const signed_transaction& trx ); signed_block generate_block( const fc::time_point_sec when, producer_id_type producer, const fc::ecc::private_key& block_signing_private_key, uint32_t skip ); signed_block _generate_block( const fc::time_point_sec when, producer_id_type producer, const fc::ecc::private_key& block_signing_private_key ); template<typename Function> auto with_skip_flags( uint64_t flags, Function&& f ) -> decltype((*((Function*)nullptr))()) { auto old_flags = _skip_flags; auto on_exit = fc::make_scoped_exit( [&](){ _skip_flags = old_flags; } ); _skip_flags = flags; return f(); } template<typename Function> auto with_producing( Function&& f ) -> decltype((*((Function*)nullptr))()) { auto old_producing = _producing; auto on_exit = fc::make_scoped_exit( [&](){ _producing = old_producing; } ); _producing = true; return f(); } template<typename Function> auto without_pending_transactions( Function&& f ) -> decltype((*((Function*)nullptr))()) { auto old_pending = std::move( _pending_transactions ); _pending_tx_session.reset(); auto on_exit = fc::make_scoped_exit( [&](){ for( const auto& t : old_pending ) { try { push_transaction( t ); } catch ( ... ){} } }); return f(); } void pop_block(); void clear_pending(); /** * This signal is emitted after all operations and virtual operation for a * block have been applied but before the get_applied_operations() are cleared. * * You may not yield from this callback because the blockchain is holding * the write lock and may be in an "inconstant state" until after it is * released. */ fc::signal<void(const signed_block&)> applied_block; /** * This signal is emitted any time a new transaction is added to the pending * block state. */ fc::signal<void(const signed_transaction&)> on_pending_transaction; /** * @brief Get the producer scheduled for block production in a slot. * * slot_num always corresponds to a time in the future. * * If slot_num == 1, returns the next scheduled producer. * If slot_num == 2, returns the next scheduled producer after * 1 block gap. * * Use the get_slot_time() and get_slot_at_time() functions * to convert between slot_num and timestamp. * * Passing slot_num == 0 returns EOS_NULL_PRODUCER */ producer_id_type get_scheduled_producer(uint32_t slot_num)const; /** * Get the time at which the given slot occurs. * * If slot_num == 0, return time_point_sec(). * * If slot_num == N for N > 0, return the Nth next * block-interval-aligned time greater than head_block_time(). */ fc::time_point_sec get_slot_time(uint32_t slot_num)const; /** * Get the last slot which occurs AT or BEFORE the given time. * * The return value is the greatest value N such that * get_slot_time( N ) <= when. * * If no such N exists, return 0. */ uint32_t get_slot_at_time(fc::time_point_sec when)const; void update_producer_schedule(); const chain_id_type& get_chain_id()const; const global_property_object& get_global_properties()const; const dynamic_global_property_object& get_dynamic_global_properties()const; const node_property_object& get_node_properties()const; time_point_sec head_block_time()const; uint32_t head_block_num()const; block_id_type head_block_id()const; producer_id_type head_block_producer()const; uint32_t block_interval( )const { return EOS_BLOCK_INTERVAL_SEC; } node_property_object& node_properties(); uint32_t last_irreversible_block_num() const; /// Reset the object graph in-memory void initialize_indexes(); void init_genesis(const genesis_state_type& genesis_state = genesis_state_type()); void debug_dump(); void apply_debug_updates(); void debug_update(const fc::variant_object& update); /** * This method validates transactions without adding it to the pending state. * @return true if the transaction would validate */ void validate_transaction(const signed_transaction& trx); private: optional<session> _pending_tx_session; public: // these were formerly private, but they have a fairly well-defined API, so let's make them public void apply_block(const signed_block& next_block, uint32_t skip = skip_nothing); void apply_transaction(const signed_transaction& trx, uint32_t skip = skip_nothing); private: void _apply_block(const signed_block& next_block); void _apply_transaction(const signed_transaction& trx); ///Steps involved in applying a new block ///@{ const producer_object& validate_block_header(uint32_t skip, const signed_block& next_block)const; const producer_object& _validate_block_header(const signed_block& next_block)const; void create_block_summary(const signed_block& next_block); void update_global_dynamic_data(const signed_block& b); void update_signing_producer(const producer_object& signing_producer, const signed_block& new_block); void update_last_irreversible_block(); void clear_expired_transactions(); deque< signed_transaction > _pending_transactions; fork_database _fork_db; /** * Note: we can probably store blocks by block num rather than * block id because after the undo window is past the block ID * is no longer relevant and its number is irreversible. * * During the "fork window" we can cache blocks in memory * until the fork is resolved. This should make maintaining * the fork tree relatively simple. */ block_database _block_id_to_block; bool _producing = false; uint64_t _skip_flags = 0; flat_map<uint32_t,block_id_type> _checkpoints; node_property_object _node_property_object; }; } } <commit_msg>define a means to register handlers for actions on particular contracts<commit_after>/* * Copyright (c) 2017, Respective Authors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <eos/chain/global_property_object.hpp> #include <eos/chain/node_property_object.hpp> #include <eos/chain/fork_database.hpp> #include <eos/chain/block_database.hpp> #include <eos/chain/genesis_state.hpp> #include <chainbase/chainbase.hpp> #include <fc/scoped_exit.hpp> #include <fc/signals.hpp> #include <eos/chain/protocol/protocol.hpp> #include <fc/log/logger.hpp> #include <map> namespace eos { namespace chain { class database; class message_validate_context { public: message_validate_context( const transaction& t, const message& m ) :trx(t),msg(m){} const transaction& trx; const message& msg; }; class state_validate_context : public message_validate_context { public: state_validate_context( const database& d, const transaction& t, const message& m ) :message_validate_context(t,m),db(d){} const database& db; }; class apply_context : public state_validate_context { public: apply_context( database& d, const transaction& t, const message& m ) :state_validate_context(d,t,m),mutable_db(d){} database& mutable_db; }; typedef std::function<void( message_validate_context& )> message_validate_handler; typedef std::function<void( state_validate_context& )> state_validate_handler; typedef std::function<void( apply_context& )> apply_handler; typedef string action_type; /** * @class database * @brief tracks the blockchain state in an extensible manner */ class database : public chainbase::database { map< account_name, map<action_type, message_validate_handler> > message_validate_handlers; map< account_name, map<action_type, state_validate_handler> > state_validate_handlers; map< account_name, map<action_type, apply_handler> > apply_handlers; public: database(); ~database(); /** * The database can override any script handler with native code. */ ///@{ void set_validate_handler( const account_name& contract, const action_type& action, message_validate_handler v ) { message_validate_handlers[contract][action] = v; } void set_state_validate_handler( const account_name& contract, const action_type& action, state_validate_handler v ) { state_validate_handlers[contract][action] = v; } void set_apply_handler( const account_name& contract, const action_type& action, apply_handler v ) { apply_handlers[contract][action] = v; } //@} enum validation_steps { skip_nothing = 0, skip_producer_signature = 1 << 0, ///< used while reindexing skip_transaction_signatures = 1 << 1, ///< used by non-producer nodes skip_transaction_dupe_check = 1 << 2, ///< used while reindexing skip_fork_db = 1 << 3, ///< used while reindexing skip_block_size_check = 1 << 4, ///< used when applying locally generated transactions skip_tapos_check = 1 << 5, ///< used while reindexing -- note this skips expiration check as well skip_authority_check = 1 << 6, ///< used while reindexing -- disables any checking of authority on transactions skip_merkle_check = 1 << 7, ///< used while reindexing skip_assert_evaluation = 1 << 8, ///< used while reindexing skip_undo_history_check = 1 << 9, ///< used while reindexing skip_producer_schedule_check= 1 << 10, ///< used while reindexing skip_validate = 1 << 11 ///< used prior to checkpoint, skips validate() call on transaction }; /** * @brief Open a database, creating a new one if necessary * * Opens a database in the specified directory. If no initialized database is found, genesis_loader is called * and its return value is used as the genesis state when initializing the new database * * genesis_loader will not be called if an existing database is found. * * @param data_dir Path to open or create database in * @param shared_file_size Size of the database memory mapped file * @param genesis_loader A callable object which returns the genesis state to initialize new databases on */ void open(const fc::path& data_dir, uint64_t shared_file_size, std::function<genesis_state_type()> genesis_loader ); /** * @brief Rebuild object graph from block history and open detabase * * This method may be called after or instead of @ref database::open, and will rebuild the object graph by * replaying blockchain history. When this method exits successfully, the database will be open. */ void reindex(fc::path data_dir, uint64_t shared_file_size, const genesis_state_type& initial_allocation = genesis_state_type()); /** * @brief wipe Delete database from disk, and potentially the raw chain as well. * @param include_blocks If true, delete the raw chain as well as the database. * * Will close the database before wiping. Database will be closed when this function returns. */ void wipe(const fc::path& data_dir, bool include_blocks); void close(); /** * @return true if the block is in our fork DB or saved to disk as * part of the official chain, otherwise return false */ bool is_known_block( const block_id_type& id )const; bool is_known_transaction( const transaction_id_type& id )const; block_id_type get_block_id_for_num( uint32_t block_num )const; optional<signed_block> fetch_block_by_id( const block_id_type& id )const; optional<signed_block> fetch_block_by_number( uint32_t num )const; const signed_transaction& get_recent_transaction( const transaction_id_type& trx_id )const; std::vector<block_id_type> get_block_ids_on_fork(block_id_type head_of_fork) const; /** * Calculate the percent of block production slots that were missed in the * past 128 blocks, not including the current block. */ uint32_t producer_participation_rate()const; void add_checkpoints(const flat_map<uint32_t,block_id_type>& checkpts); const flat_map<uint32_t,block_id_type> get_checkpoints()const { return _checkpoints; } bool before_last_checkpoint()const; bool push_block( const signed_block& b, uint32_t skip = skip_nothing ); void push_transaction( const signed_transaction& trx, uint32_t skip = skip_nothing ); bool _push_block( const signed_block& b ); void _push_transaction( const signed_transaction& trx ); signed_block generate_block( const fc::time_point_sec when, producer_id_type producer, const fc::ecc::private_key& block_signing_private_key, uint32_t skip ); signed_block _generate_block( const fc::time_point_sec when, producer_id_type producer, const fc::ecc::private_key& block_signing_private_key ); template<typename Function> auto with_skip_flags( uint64_t flags, Function&& f ) -> decltype((*((Function*)nullptr))()) { auto old_flags = _skip_flags; auto on_exit = fc::make_scoped_exit( [&](){ _skip_flags = old_flags; } ); _skip_flags = flags; return f(); } template<typename Function> auto with_producing( Function&& f ) -> decltype((*((Function*)nullptr))()) { auto old_producing = _producing; auto on_exit = fc::make_scoped_exit( [&](){ _producing = old_producing; } ); _producing = true; return f(); } template<typename Function> auto without_pending_transactions( Function&& f ) -> decltype((*((Function*)nullptr))()) { auto old_pending = std::move( _pending_transactions ); _pending_tx_session.reset(); auto on_exit = fc::make_scoped_exit( [&](){ for( const auto& t : old_pending ) { try { push_transaction( t ); } catch ( ... ){} } }); return f(); } void pop_block(); void clear_pending(); /** * This signal is emitted after all operations and virtual operation for a * block have been applied but before the get_applied_operations() are cleared. * * You may not yield from this callback because the blockchain is holding * the write lock and may be in an "inconstant state" until after it is * released. */ fc::signal<void(const signed_block&)> applied_block; /** * This signal is emitted any time a new transaction is added to the pending * block state. */ fc::signal<void(const signed_transaction&)> on_pending_transaction; /** * @brief Get the producer scheduled for block production in a slot. * * slot_num always corresponds to a time in the future. * * If slot_num == 1, returns the next scheduled producer. * If slot_num == 2, returns the next scheduled producer after * 1 block gap. * * Use the get_slot_time() and get_slot_at_time() functions * to convert between slot_num and timestamp. * * Passing slot_num == 0 returns EOS_NULL_PRODUCER */ producer_id_type get_scheduled_producer(uint32_t slot_num)const; /** * Get the time at which the given slot occurs. * * If slot_num == 0, return time_point_sec(). * * If slot_num == N for N > 0, return the Nth next * block-interval-aligned time greater than head_block_time(). */ fc::time_point_sec get_slot_time(uint32_t slot_num)const; /** * Get the last slot which occurs AT or BEFORE the given time. * * The return value is the greatest value N such that * get_slot_time( N ) <= when. * * If no such N exists, return 0. */ uint32_t get_slot_at_time(fc::time_point_sec when)const; void update_producer_schedule(); const chain_id_type& get_chain_id()const; const global_property_object& get_global_properties()const; const dynamic_global_property_object& get_dynamic_global_properties()const; const node_property_object& get_node_properties()const; time_point_sec head_block_time()const; uint32_t head_block_num()const; block_id_type head_block_id()const; producer_id_type head_block_producer()const; uint32_t block_interval( )const { return EOS_BLOCK_INTERVAL_SEC; } node_property_object& node_properties(); uint32_t last_irreversible_block_num() const; /// Reset the object graph in-memory void initialize_indexes(); void init_genesis(const genesis_state_type& genesis_state = genesis_state_type()); void debug_dump(); void apply_debug_updates(); void debug_update(const fc::variant_object& update); /** * This method validates transactions without adding it to the pending state. * @return true if the transaction would validate */ void validate_transaction(const signed_transaction& trx); private: optional<session> _pending_tx_session; public: // these were formerly private, but they have a fairly well-defined API, so let's make them public void apply_block(const signed_block& next_block, uint32_t skip = skip_nothing); void apply_transaction(const signed_transaction& trx, uint32_t skip = skip_nothing); private: void _apply_block(const signed_block& next_block); void _apply_transaction(const signed_transaction& trx); ///Steps involved in applying a new block ///@{ const producer_object& validate_block_header(uint32_t skip, const signed_block& next_block)const; const producer_object& _validate_block_header(const signed_block& next_block)const; void create_block_summary(const signed_block& next_block); void update_global_dynamic_data(const signed_block& b); void update_signing_producer(const producer_object& signing_producer, const signed_block& new_block); void update_last_irreversible_block(); void clear_expired_transactions(); deque< signed_transaction > _pending_transactions; fork_database _fork_db; /** * Note: we can probably store blocks by block num rather than * block id because after the undo window is past the block ID * is no longer relevant and its number is irreversible. * * During the "fork window" we can cache blocks in memory * until the fork is resolved. This should make maintaining * the fork tree relatively simple. */ block_database _block_id_to_block; bool _producing = false; uint64_t _skip_flags = 0; flat_map<uint32_t,block_id_type> _checkpoints; node_property_object _node_property_object; }; } } <|endoftext|>
<commit_before>//=========================================================================== // // File: benchmarkLRSurfaceRefinement.C // // Created: Wed Nov 22 2012 // // Author: Sverre Briseid <Sverre.Briseid@sintef.no> // // Revision: // // Description: Read a LRSplineSurface, benchmark the refinement function. // We compare the one-at-a-time approach vs all at once. // //=========================================================================== #include "GoTools/lrsplines2D/LRSplineSurface.h" #include "GoTools/lrsplines2D/Mesh2D.h" #include "GoTools/lrsplines2D/Direction2D.h" #include "GoTools/lrsplines2D/LRBenchmarkUtils.h" #include "GoTools/lrsplines2D/LRSplinePlotUtils.h" //#include "GoTools/lrsplines2D/Element.h" // sbr/trd version (based on trondheim version). #include "GoTools/geometry/ObjectHeader.h" #include "GoTools/geometry/SplineSurface.h" #include "GoTools/geometry/GeometryTools.h" #include "GoTools/utils/config.h" #include <iostream> #include <assert.h> #include <fstream> #include <string> #include "string.h" //using LRSpline; using namespace Go; using std::vector; bool my_equal_function (double i, double j) { double tol = 1e-10;//14; return (fabs(i - j) < tol); } int main(int argc, char *argv[]) { if (argc != 4) { std::cout << "Usage: spline_sf.g2 num_ref num_iter" << std::endl; return -1; } char* filein_char = argv[1]; std::ifstream filein(argv[1]); // Input lr spline. // If input surface is not fine enough we refine. int min_num_each_dir = atoi(argv[2]); int num_iter = atoi(argv[3]); if (num_iter != 1) MESSAGE("Not using num_iter yet."); shared_ptr<Go::SplineSurface> spline_sf; // shared_ptr<Go::SplineSurface> lr_spline_sf_go; shared_ptr<LRSplineSurface> lr_spline_sf, lr_spline_sf_single_refs; int order_u, order_v, num_coefs_u, num_coefs_v, dim, num_bases=-1; if (strcasestr(filein_char, ".g2")) { spline_sf = shared_ptr<Go::SplineSurface>(new Go::SplineSurface()); puts("Reading the Go::SplineSurface."); Go::ObjectHeader header; // header.read(filein); filein >> header; // We check that a lr spline was read. if (header.classType() != Class_SplineSurface) { puts("The input g2-file was not of type Class_SplineSurface"); return -1; } // We read using the GO:LRSplineSurface routine. filein >> *spline_sf; assert(!spline_sf->rational()); order_u = spline_sf->order_u(); order_v = spline_sf->order_v(); num_coefs_u = spline_sf->numCoefs_u(); num_coefs_v = spline_sf->numCoefs_v(); dim = spline_sf->dimension(); // We may refine the input surface. if ((num_coefs_u < min_num_each_dir) || (num_coefs_v < min_num_each_dir)) { // We want to insert knots so that they are as evenly as // possible distributed. Or not far from it at least. MESSAGE("Refining the surface!"); int num_new_knots_u = min_num_each_dir - num_coefs_u; if (num_new_knots_u > 0) { BsplineBasis bas_u = spline_sf->basis_u(); GeometryTools::insertKnotsEvenly(bas_u, num_new_knots_u); std::cout << "spline_sf bas_u size: " << spline_sf->basis_u().numCoefs() << ", bas_u size: " << bas_u.numCoefs() << std::endl; vector<double> new_knots_u; set_symmetric_difference(spline_sf->basis_u().begin(), spline_sf->basis_u().end(), bas_u.begin(), bas_u.end(), back_inserter(new_knots_u)); spline_sf->insertKnot_u(new_knots_u); } int num_new_knots_v = min_num_each_dir - num_coefs_v; if (num_new_knots_v > 0) { BsplineBasis bas_v = spline_sf->basis_v(); GeometryTools::insertKnotsEvenly(bas_v, num_new_knots_v); vector<double> new_knots_v; set_symmetric_difference(spline_sf->basis_v().begin(), spline_sf->basis_v().end(), bas_v.begin(), bas_v.end(), back_inserter(new_knots_v)); spline_sf->insertKnot_v(new_knots_v); } } #if 0 #endif puts("Done reading the Go::SplineSurface."); } else { MESSAGE("Input was not a g2-file!"); return -1; } // order_u = spline_sf->order_u(); // order_v = spline_sf->order_v(); num_coefs_u = spline_sf->numCoefs_u(); num_coefs_v = spline_sf->numCoefs_v(); // We must count the number of segments. We do this the easiest way // by looking at the number of different knots in each direction, // (and subtract one). vector<double> all_knots_u(spline_sf->basis_u().begin(), spline_sf->basis_u().end()); vector<double> all_knots_v(spline_sf->basis_v().begin(), spline_sf->basis_v().end()); vector<double>::iterator last_uniq_u = unique(all_knots_u.begin(), all_knots_u.end(), my_equal_function); vector<double>::iterator last_uniq_v = unique(all_knots_v.begin(), all_knots_v.end(), my_equal_function); vector<double> unique_knots_u(all_knots_u.begin(), last_uniq_u); vector<double> unique_knots_v(all_knots_v.begin(), last_uniq_v); int num_segs_u = unique_knots_u.size() - 1; int num_segs_v = unique_knots_v.size() - 1; std::cout << "num_segs_u: " << num_segs_u << ", num_segs_v: " << num_segs_v << std::endl; // We create the refinement vectors. // First segments with a constant u parameter. vector<LRSplineSurface::Refinement2D> refs_u, refs_v; int mult = 1; Direction2D dir = XFIXED; for (size_t ki = 0; ki < num_segs_u - 1; ++ki) { // We bisect the interval. double wgt = 0.4; // Value in the range [0.0, 1.0]. double const_par = wgt*unique_knots_u[ki] + (1.0 - wgt)*unique_knots_u[ki+1]; // We insert line segments which cover order_v - 1 intervals. for (size_t kj = order_v - 1; kj < num_segs_v; kj += order_v) { // To avoid a too regular pattern we alter start // values. Maybe we should use a random function ... double tmin = (ki%2 == 1) ? unique_knots_v[kj - order_v + 1] : unique_knots_v[kj - order_v + 2]; double tmax = (ki%2 == 1) ? unique_knots_v[kj] : unique_knots_v[kj + 1]; LRSplineSurface::Refinement2D ref; ref.kval = const_par; ref.start = tmin; ref.end = tmax; ref.d = dir; ref.multiplicity = mult; refs_u.push_back(ref); } } dir = YFIXED; for (size_t ki = 0; ki < num_segs_v - 1; ++ki) { // We bisect the interval. double wgt = 0.4; double const_par = wgt*unique_knots_v[ki] + (1.0 - wgt)*unique_knots_v[ki+1]; // We insert line segments which cover order_u - 1 intervals. for (size_t kj = order_u - 1; kj < num_segs_u; kj += order_u) { // To avoid a too regular pattern we alter start // values. Maybe we should use a random function ... double tmin = (ki%2 == 1) ? unique_knots_u[kj - order_u + 1] : unique_knots_u[kj - order_u + 2]; double tmax = (ki%2 == 1) ? unique_knots_u[kj] : unique_knots_u[kj + 1]; LRSplineSurface::Refinement2D ref; ref.kval = const_par; ref.start = tmin; ref.end = tmax; ref.d = dir; ref.multiplicity = mult; refs_v.push_back(ref); } } vector<LRSplineSurface::Refinement2D> all_refs(refs_u.begin(), refs_u.end()); all_refs.insert(all_refs.end(), refs_v.begin(), refs_v.end()); std::cout << "num_refs_to_insert: " << all_refs.size() << std::endl; // We then create and refine the LRSplineSurface. lr_spline_sf = shared_ptr<LRSplineSurface> // (new LRSpline<vector<double>::const_iterator, vector<double>::const_iterator> > (new LRSplineSurface(order_u - 1, order_v - 1, num_coefs_u, num_coefs_v, dim, spline_sf->basis_u().begin(), spline_sf->basis_v().begin(), spline_sf->coefs_begin())); lr_spline_sf_single_refs = shared_ptr<LRSplineSurface> // (new LRSpline<vector<double>::const_iterator, vector<double>::const_iterator> > (new LRSplineSurface(order_u - 1, order_v - 1, num_coefs_u, num_coefs_v, dim, spline_sf->basis_u().begin(), spline_sf->basis_v().begin(), spline_sf->coefs_begin())); double time_lrspline_lr_ref = benchmarkSfRefinement(*lr_spline_sf, all_refs); std::cout << "Time lr refinement: " << time_lrspline_lr_ref << std::endl; double time_lrspline_lr_ref_single = benchmarkSfRefinement(*lr_spline_sf_single_refs, all_refs, true); std::cout << "Time lr refinement single refs: " << time_lrspline_lr_ref_single << std::endl; // We write to screen the number of basis functions for both // versions. int num_elem = lr_spline_sf->numElements(); int num_basis_funcs = lr_spline_sf->numBasisFunctions(); std::cout << "num_elem: " << num_elem << ", num_basis_funcs: " << num_basis_funcs << std::endl; int num_elem_single = lr_spline_sf_single_refs->numElements(); int num_basis_funcs_single = lr_spline_sf_single_refs->numBasisFunctions(); std::cout << "num_elem_single_refs: " << num_elem_single << ", num_basis_funcs_single_refs: " << num_basis_funcs_single << std::endl; int num_samples_u = min_num_each_dir + 29; // Rather random number. int num_samples_v = min_num_each_dir + 37; // Rather random number. double umin = spline_sf->startparam_u(); double umax = spline_sf->endparam_u(); double ustep = (umax - umin)/(num_samples_u - 1); double vmin = spline_sf->startparam_v(); double vmax = spline_sf->endparam_v(); double vstep = (vmax - vmin)/(num_samples_v - 1); double max_dist = -1.0, max_dist_single = -1.0; Point pt_go; Point pt_lr, pt_lr_single; for (size_t kj = 0; kj < num_samples_v; ++kj) { double vpar = vmin + kj*vstep; for (size_t ki = 0; ki < num_samples_u; ++ki) { double upar = umin + ki*ustep; spline_sf->point(pt_go, upar, vpar); pt_lr = (*lr_spline_sf)(upar, vpar); pt_lr_single = (*lr_spline_sf_single_refs)(upar, vpar); double dist = 0.0; double dist_single = 0.0; for (int kk = 0; kk < dim; ++kk) { dist += (pt_go[kk] - pt_lr[kk])*(pt_go[kk] - pt_lr[kk]); dist_single += (pt_go[kk] - pt_lr_single[kk])*(pt_go[kk] - pt_lr_single[kk]); } dist = sqrt(dist); dist_single = sqrt(dist_single); if (dist > max_dist) { max_dist = dist; } if (dist_single > max_dist_single) { max_dist_single = dist_single; } } } std::cout << "max_dist: " << max_dist << std::endl; std::cout << "max_dist_single_refs: " << max_dist_single << std::endl; // MESSAGE("Missing writing refined surface grid to file!"); std::ofstream lrsf_grid_ps("tmp/lrsf_grid.ps"); // writePostscriptMesh(*lrsf); writePostscriptMesh(*lr_spline_sf, lrsf_grid_ps); } <commit_msg>More benchmark analysis.<commit_after>//=========================================================================== // // File: benchmarkLRSurfaceRefinement.C // // Created: Wed Nov 22 2012 // // Author: Sverre Briseid <Sverre.Briseid@sintef.no> // // Revision: // // Description: Read a LRSplineSurface, benchmark the refinement function. // We compare the one-at-a-time approach vs all at once. // //=========================================================================== #include "GoTools/lrsplines2D/LRSplineSurface.h" #include "GoTools/lrsplines2D/Mesh2D.h" #include "GoTools/lrsplines2D/Direction2D.h" #include "GoTools/lrsplines2D/LRBenchmarkUtils.h" #include "GoTools/lrsplines2D/LRSplinePlotUtils.h" //#include "GoTools/lrsplines2D/Element.h" // sbr/trd version (based on trondheim version). #include "GoTools/geometry/ObjectHeader.h" #include "GoTools/geometry/SplineSurface.h" #include "GoTools/geometry/GeometryTools.h" #include "GoTools/utils/config.h" #include <iostream> #include <assert.h> #include <fstream> #include <string> #include "string.h" //using LRSpline; using namespace Go; using std::vector; bool my_equal_function (double i, double j) { double tol = 1e-10;//14; return (fabs(i - j) < tol); } int main(int argc, char *argv[]) { if (argc != 4) { std::cout << "Usage: spline_sf.g2 num_ref num_iter" << std::endl; return -1; } char* filein_char = argv[1]; std::ifstream filein(argv[1]); // Input lr spline. // If input surface is not fine enough we refine. int min_num_each_dir = atoi(argv[2]); int num_iter = atoi(argv[3]); if (num_iter != 1) puts("Not using num_iter yet."); shared_ptr<Go::SplineSurface> spline_sf; // shared_ptr<Go::SplineSurface> lr_spline_sf_go; shared_ptr<LRSplineSurface> lr_spline_sf, lr_spline_sf_single_refs; int order_u, order_v, num_coefs_u, num_coefs_v, dim, num_bases=-1; if (strcasestr(filein_char, ".g2")) { spline_sf = shared_ptr<Go::SplineSurface>(new Go::SplineSurface()); puts("Reading the Go::SplineSurface."); Go::ObjectHeader header; // header.read(filein); filein >> header; // We check that a lr spline was read. if (header.classType() != Class_SplineSurface) { puts("The input g2-file was not of type Class_SplineSurface"); return -1; } // We read using the GO:LRSplineSurface routine. filein >> *spline_sf; assert(!spline_sf->rational()); order_u = spline_sf->order_u(); order_v = spline_sf->order_v(); num_coefs_u = spline_sf->numCoefs_u(); num_coefs_v = spline_sf->numCoefs_v(); dim = spline_sf->dimension(); // We may refine the input surface. if ((num_coefs_u < min_num_each_dir) || (num_coefs_v < min_num_each_dir)) { // We want to insert knots so that they are as evenly as // possible distributed. Or not far from it at least. MESSAGE("Refining the surface!"); int num_new_knots_u = min_num_each_dir - num_coefs_u; if (num_new_knots_u > 0) { BsplineBasis bas_u = spline_sf->basis_u(); GeometryTools::insertKnotsEvenly(bas_u, num_new_knots_u); std::cout << "spline_sf bas_u size: " << spline_sf->basis_u().numCoefs() << ", bas_u size: " << bas_u.numCoefs() << std::endl; vector<double> new_knots_u; set_symmetric_difference(spline_sf->basis_u().begin(), spline_sf->basis_u().end(), bas_u.begin(), bas_u.end(), back_inserter(new_knots_u)); spline_sf->insertKnot_u(new_knots_u); } int num_new_knots_v = min_num_each_dir - num_coefs_v; if (num_new_knots_v > 0) { BsplineBasis bas_v = spline_sf->basis_v(); GeometryTools::insertKnotsEvenly(bas_v, num_new_knots_v); vector<double> new_knots_v; set_symmetric_difference(spline_sf->basis_v().begin(), spline_sf->basis_v().end(), bas_v.begin(), bas_v.end(), back_inserter(new_knots_v)); spline_sf->insertKnot_v(new_knots_v); } } } else { MESSAGE("Input was not a g2-file!"); return -1; } // order_u = spline_sf->order_u(); // order_v = spline_sf->order_v(); num_coefs_u = spline_sf->numCoefs_u(); num_coefs_v = spline_sf->numCoefs_v(); // We must count the number of segments. We do this the easiest way // by looking at the number of different knots in each direction, // (and subtract one). vector<double> all_knots_u(spline_sf->basis_u().begin(), spline_sf->basis_u().end()); vector<double> all_knots_v(spline_sf->basis_v().begin(), spline_sf->basis_v().end()); vector<double>::iterator last_uniq_u = unique(all_knots_u.begin(), all_knots_u.end(), my_equal_function); vector<double>::iterator last_uniq_v = unique(all_knots_v.begin(), all_knots_v.end(), my_equal_function); vector<double> unique_knots_u(all_knots_u.begin(), last_uniq_u); vector<double> unique_knots_v(all_knots_v.begin(), last_uniq_v); int num_segs_u = unique_knots_u.size() - 1; int num_segs_v = unique_knots_v.size() - 1; std::cout << "num_segs_u: " << num_segs_u << ", num_segs_v: " << num_segs_v << std::endl; // We create the refinement vectors. // First segments with a constant u parameter. vector<LRSplineSurface::Refinement2D> refs_u, refs_v; int mult = 1; Direction2D dir = XFIXED; for (size_t ki = 0; ki < num_segs_u - 1; ++ki) { // We bisect the interval. double wgt = 0.4; // Value in the range [0.0, 1.0]. double const_par = wgt*unique_knots_u[ki] + (1.0 - wgt)*unique_knots_u[ki+1]; // We insert line segments which cover order_v - 1 intervals. for (size_t kj = order_v - 1; kj < num_segs_v; kj += order_v) { // To avoid a too regular pattern we alter start // values. Maybe we should use a random function ... double tmin = (ki%2 == 1) ? unique_knots_v[kj - order_v + 1] : unique_knots_v[kj - order_v + 2]; double tmax = (ki%2 == 1) ? unique_knots_v[kj] : unique_knots_v[kj + 1]; LRSplineSurface::Refinement2D ref; ref.kval = const_par; ref.start = tmin; ref.end = tmax; ref.d = dir; ref.multiplicity = mult; refs_u.push_back(ref); } } dir = YFIXED; for (size_t ki = 0; ki < num_segs_v - 1; ++ki) { // We bisect the interval. double wgt = 0.4; double const_par = wgt*unique_knots_v[ki] + (1.0 - wgt)*unique_knots_v[ki+1]; // We insert line segments which cover order_u - 1 intervals. for (size_t kj = order_u - 1; kj < num_segs_u; kj += order_u) { // To avoid a too regular pattern we alter start // values. Maybe we should use a random function ... double tmin = (ki%2 == 1) ? unique_knots_u[kj - order_u + 1] : unique_knots_u[kj - order_u + 2]; double tmax = (ki%2 == 1) ? unique_knots_u[kj] : unique_knots_u[kj + 1]; LRSplineSurface::Refinement2D ref; ref.kval = const_par; ref.start = tmin; ref.end = tmax; ref.d = dir; ref.multiplicity = mult; refs_v.push_back(ref); } } vector<LRSplineSurface::Refinement2D> all_refs(refs_u.begin(), refs_u.end()); all_refs.insert(all_refs.end(), refs_v.begin(), refs_v.end()); std::cout << "num_refs_to_insert: " << all_refs.size() << std::endl; // We then create and refine the LRSplineSurface. lr_spline_sf = shared_ptr<LRSplineSurface> // (new LRSpline<vector<double>::const_iterator, vector<double>::const_iterator> > (new LRSplineSurface(order_u - 1, order_v - 1, num_coefs_u, num_coefs_v, dim, spline_sf->basis_u().begin(), spline_sf->basis_v().begin(), spline_sf->coefs_begin())); lr_spline_sf_single_refs = shared_ptr<LRSplineSurface> // (new LRSpline<vector<double>::const_iterator, vector<double>::const_iterator> > (new LRSplineSurface(order_u - 1, order_v - 1, num_coefs_u, num_coefs_v, dim, spline_sf->basis_u().begin(), spline_sf->basis_v().begin(), spline_sf->coefs_begin())); double time_lrspline_lr_ref = benchmarkSfRefinement(*lr_spline_sf, all_refs); std::cout << "Time lr refinement: " << time_lrspline_lr_ref << std::endl; double time_lrspline_lr_ref_single = benchmarkSfRefinement(*lr_spline_sf_single_refs, all_refs, true); std::cout << "Time lr refinement single refs: " << time_lrspline_lr_ref_single << std::endl; // We write to screen the number of basis functions for both // versions. int num_elem = lr_spline_sf->numElements(); int num_basis_funcs = lr_spline_sf->numBasisFunctions(); std::cout << "num_elem: " << num_elem << ", num_basis_funcs: " << num_basis_funcs << std::endl; int num_elem_single = lr_spline_sf_single_refs->numElements(); int num_basis_funcs_single = lr_spline_sf_single_refs->numBasisFunctions(); std::cout << "num_elem_single_refs: " << num_elem_single << ", num_basis_funcs_single_refs: " << num_basis_funcs_single << std::endl; int num_samples_u = min_num_each_dir + 29; // Rather random number. int num_samples_v = min_num_each_dir + 37; // Rather random number. double umin = spline_sf->startparam_u(); double umax = spline_sf->endparam_u(); double ustep = (umax - umin)/(num_samples_u - 1); double vmin = spline_sf->startparam_v(); double vmax = spline_sf->endparam_v(); double vstep = (vmax - vmin)/(num_samples_v - 1); double max_dist = -1.0, max_dist_single = -1.0; Point pt_go; Point pt_lr, pt_lr_single; for (size_t kj = 0; kj < num_samples_v; ++kj) { double vpar = vmin + kj*vstep; for (size_t ki = 0; ki < num_samples_u; ++ki) { double upar = umin + ki*ustep; spline_sf->point(pt_go, upar, vpar); pt_lr = (*lr_spline_sf)(upar, vpar); pt_lr_single = (*lr_spline_sf_single_refs)(upar, vpar); double dist = 0.0; double dist_single = 0.0; for (int kk = 0; kk < dim; ++kk) { dist += (pt_go[kk] - pt_lr[kk])*(pt_go[kk] - pt_lr[kk]); dist_single += (pt_go[kk] - pt_lr_single[kk])*(pt_go[kk] - pt_lr_single[kk]); } dist = sqrt(dist); dist_single = sqrt(dist_single); if (dist > max_dist) { max_dist = dist; } if (dist_single > max_dist_single) { max_dist_single = dist_single; } } } std::cout << "max_dist: " << max_dist << std::endl; std::cout << "max_dist_single_refs: " << max_dist_single << std::endl; // MESSAGE("Missing writing refined surface grid to file!"); std::ofstream lrsf_grid_ps("tmp/lrsf_grid.ps"); // writePostscriptMesh(*lrsf); writePostscriptMesh(*lr_spline_sf, lrsf_grid_ps); } <|endoftext|>
<commit_before>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef MFEM_ELASTICITY_KERNEL_HELPERS_HPP #define MFEM_ELASTICITY_KERNEL_HELPERS_HPP #include "general/forall.hpp" #include "linalg/tensor.hpp" using mfem::internal::tensor; namespace mfem { namespace KernelHelpers { // MFEM_SHARED_3D_BLOCK_TENSOR definition // Should be moved in backends/cuda/hip header files. #if defined(__CUDA_ARCH__) #define MFEM_SHARED_3D_BLOCK_TENSOR(name,T,bx,by,bz,...)\ MFEM_SHARED tensor<T,bx,by,bz,__VA_ARGS__> name;\ name(threadIdx.x, threadIdx.y, threadIdx.z) = tensor<T,__VA_ARGS__> {}; #else #define MFEM_SHARED_3D_BLOCK_TENSOR(name,...) tensor<__VA_ARGS__> name {}; #endif // Kernel helper functions /** * @brief Runtime check for memory restrictions that are determined at compile * time. * * @param d1d Number of degrees of freedom in 1D. * @param q1d Number of quadrature points in 1D. */ inline void CheckMemoryRestriction(int d1d, int q1d) { MFEM_VERIFY(d1d <= q1d, "There should be more or equal quadrature points " "as there are dofs"); MFEM_VERIFY(d1d <= MAX_D1D, "Maximum number of degrees of freedom in 1D reached." "This number can be increased globally in general/forall.hpp if " "device memory allows."); MFEM_VERIFY(q1d <= MAX_Q1D, "Maximum quadrature points 1D reached." "This number can be increased globally in " "general/forall.hpp if device memory allows."); } /** * @brief Multi-component gradient evaluation from DOFs to quadrature points in * reference coordinates. * * The implementation exploits sum factorization. * * @note DeviceTensor<2> means RANK=2 * * @tparam dim Dimension. * @tparam d1d Number of degrees of freedom in 1D. * @tparam q1d er of quadrature points in 1D. * @param B Basis functions evaluated at quadrature points in column-major * layout q1d x d1d. * @param G Gradients of basis functions evaluated at quadrature points in * column major layout q1d x d1d. * @param smem Block of shared memory for scratch space. Size needed is 2 x 3 x * q1d x q1d x q1d. * @param U Input vector d1d x d1d x d1d x dim. * @param dUdxi Gradient of the input vector wrt to reference coordinates. Size * needed q1d x q1d x q1d x dim x dim. */ template <int dim, int d1d, int q1d> static inline MFEM_HOST_DEVICE void CalcGrad(const tensor<double, q1d, d1d> &B, const tensor<double, q1d, d1d> &G, tensor<double,2,3,q1d,q1d,q1d> &smem, const DeviceTensor<4, const double> &U, tensor<double, q1d, q1d, q1d, dim, dim> &dUdxi) { for (int c = 0; c < dim; ++c) { MFEM_FOREACH_THREAD(dz,z,d1d) { MFEM_FOREACH_THREAD(dy,y,d1d) { MFEM_FOREACH_THREAD(dx,x,d1d) { smem(0,0,dx,dy,dz) = U(dx,dy,dz,c); } } } MFEM_SYNC_THREAD; MFEM_FOREACH_THREAD(dz,z,d1d) { MFEM_FOREACH_THREAD(dy,y,d1d) { MFEM_FOREACH_THREAD(qx,x,q1d) { double u = 0.0; double v = 0.0; for (int dx = 0; dx < d1d; ++dx) { const double input = smem(0,0,dx,dy,dz); u += input * B(qx,dx); v += input * G(qx,dx); } smem(0,1,dz,dy,qx) = u; smem(0,2,dz,dy,qx) = v; } } } MFEM_SYNC_THREAD; MFEM_FOREACH_THREAD(dz,z,d1d) { MFEM_FOREACH_THREAD(qy,y,q1d) { MFEM_FOREACH_THREAD(qx,x,q1d) { double u = 0.0; double v = 0.0; double w = 0.0; for (int dy = 0; dy < d1d; ++dy) { u += smem(0,2,dz,dy,qx) * B(qy,dy); v += smem(0,1,dz,dy,qx) * G(qy,dy); w += smem(0,1,dz,dy,qx) * B(qy,dy); } smem(1,0,dz,qy,qx) = u; smem(1,1,dz,qy,qx) = v; smem(1,2,dz,qy,qx) = w; } } } MFEM_SYNC_THREAD; MFEM_FOREACH_THREAD(qz,z,q1d) { MFEM_FOREACH_THREAD(qy,y,q1d) { MFEM_FOREACH_THREAD(qx,x,q1d) { double u = 0.0; double v = 0.0; double w = 0.0; for (int dz = 0; dz < d1d; ++dz) { u += smem(1,0,dz,qy,qx) * B(qz,dz); v += smem(1,1,dz,qy,qx) * B(qz,dz); w += smem(1,2,dz,qy,qx) * G(qz,dz); } dUdxi(qz,qy,qx,c,0) += u; dUdxi(qz,qy,qx,c,1) += v; dUdxi(qz,qy,qx,c,2) += w; } } } MFEM_SYNC_THREAD; } // vdim } /** * @brief Multi-component transpose gradient evaluation from DOFs to quadrature * points in reference coordinates with contraction of the D vector. * * @tparam dim Dimension. * @tparam d1d Number of degrees of freedom in 1D. * @tparam q1d er of quadrature points in 1D. * @param B Basis functions evaluated at quadrature points in column-major * layout q1d x d1d. * @param G Gradients of basis functions evaluated at quadrature points in * column major layout q1d x d1d. * @param smem Block of shared memory for scratch space. Size needed is 2 x 3 x * q1d x q1d x q1d. * @param U Input vector q1d x q1d x q1d x dim. * @param F Output vector that applied the gradient evaluation from DOFs to * quadrature points in reference coordinates with contraction of the D operator * on the input vectro. Size is d1d x d1d x d1d x dim. */ template <int dim, int d1d, int q1d> static inline MFEM_HOST_DEVICE void CalcGradTSum(const tensor<double, q1d, d1d> &B, const tensor<double, q1d, d1d> &G, tensor<double, 2, 3, q1d, q1d, q1d> &smem, const tensor<double, q1d, q1d, q1d, dim, dim> &U, DeviceTensor<4, double> &F) { for (int c = 0; c < dim; ++c) { MFEM_FOREACH_THREAD(qz, z, q1d) { MFEM_FOREACH_THREAD(qy, y, q1d) { MFEM_FOREACH_THREAD(dx, x, d1d) { double u = 0.0, v = 0.0, w = 0.0; for (int qx = 0; qx < q1d; ++qx) { u += U(qx, qy, qz, 0, c) * G(qx, dx); v += U(qx, qy, qz, 1, c) * B(qx, dx); w += U(qx, qy, qz, 2, c) * B(qx, dx); } smem(0, 0, qz, qy, dx) = u; smem(0, 1, qz, qy, dx) = v; smem(0, 2, qz, qy, dx) = w; } } } MFEM_SYNC_THREAD; MFEM_FOREACH_THREAD(qz, z, q1d) { MFEM_FOREACH_THREAD(dy, y, d1d) { MFEM_FOREACH_THREAD(dx, x, d1d) { double u = 0.0, v = 0.0, w = 0.0; for (int qy = 0; qy < q1d; ++qy) { u += smem(0, 0, qz, qy, dx) * B(qy, dy); v += smem(0, 1, qz, qy, dx) * G(qy, dy); w += smem(0, 2, qz, qy, dx) * B(qy, dy); } smem(1, 0, qz, dy, dx) = u; smem(1, 1, qz, dy, dx) = v; smem(1, 2, qz, dy, dx) = w; } } } MFEM_SYNC_THREAD; MFEM_FOREACH_THREAD(dz, z, d1d) { MFEM_FOREACH_THREAD(dy, y, d1d) { MFEM_FOREACH_THREAD(dx, x, d1d) { double u = 0.0, v = 0.0, w = 0.0; for (int qz = 0; qz < q1d; ++qz) { u += smem(1, 0, qz, dy, dx) * B(qz, dz); v += smem(1, 1, qz, dy, dx) * B(qz, dz); w += smem(1, 2, qz, dy, dx) * G(qz, dz); } const double sum = u + v + w; F(dx, dy, dz, c) += sum; } } } MFEM_SYNC_THREAD; } } /** * @brief Compute the gradient of all shape functions. * * @note TODO: Does not make use of shared memory on the GPU. * * @tparam dim Dimension. * @tparam d1d Number of degrees of freedom in 1D. * @tparam q1d er of quadrature points in 1D. * @param qx Quadrature point x index. * @param qy Quadrature point y index. * @param qz Quadrature point z index. * @param B Basis functions evaluated at quadrature points in column-major * layout q1d x d1d. * @param G Gradients of basis functions evaluated at quadrature points in * column major layout q1d x d1d. * @param invJ Inverse of the Jacobian at the quadrature point. Size is dim x * dim. * * @return Gradient of all shape functions at the quadrature point. Size is d1d * x d1d x d1d x dim. */ template <int dim, int d1d, int q1d> static inline MFEM_HOST_DEVICE tensor<double, d1d, d1d, d1d, dim> GradAllShapeFunctions(int qx, int qy, int qz, const tensor<double, q1d, d1d> &B, const tensor<double, q1d, d1d> &G, const tensor<double, dim, dim> &invJ) { tensor<double, d1d, d1d, d1d, dim> dphi_dx; // G (x) B (x) B // B (x) G (x) B // B (x) B (x) G for (int dx = 0; dx < d1d; dx++) { for (int dy = 0; dy < d1d; dy++) { for (int dz = 0; dz < d1d; dz++) { dphi_dx(dx,dy,dz) = transpose(invJ) * tensor<double, dim> {G(qx, dx) * B(qy, dy) * B(qz, dz), B(qx, dx) * G(qy, dy) * B(qz, dz), B(qx, dx) * B(qy, dy) * G(qz, dz) }; } } } return dphi_dx; } } // namespace KernelHelpers } // namespace mfem #endif <commit_msg>Update miniapps/elasticity/kernels/kernel_helpers.hpp<commit_after>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef MFEM_ELASTICITY_KERNEL_HELPERS_HPP #define MFEM_ELASTICITY_KERNEL_HELPERS_HPP #include "general/forall.hpp" #include "linalg/tensor.hpp" using mfem::internal::tensor; namespace mfem { namespace KernelHelpers { // MFEM_SHARED_3D_BLOCK_TENSOR definition // Should be moved in backends/cuda/hip header files. #if defined(__CUDA_ARCH__) #define MFEM_SHARED_3D_BLOCK_TENSOR(name,T,bx,by,bz,...)\ MFEM_SHARED tensor<T,bx,by,bz,__VA_ARGS__> name;\ name(threadIdx.x, threadIdx.y, threadIdx.z) = tensor<T,__VA_ARGS__> {}; #else #define MFEM_SHARED_3D_BLOCK_TENSOR(name,...) tensor<__VA_ARGS__> name {}; #endif // Kernel helper functions /** * @brief Runtime check for memory restrictions that are determined at compile * time. * * @param d1d Number of degrees of freedom in 1D. * @param q1d Number of quadrature points in 1D. */ inline void CheckMemoryRestriction(int d1d, int q1d) { MFEM_VERIFY(d1d <= q1d, "There should be more or equal quadrature points " "as there are dofs"); MFEM_VERIFY(d1d <= MAX_D1D, "Maximum number of degrees of freedom in 1D reached." "This number can be increased globally in general/forall.hpp if " "device memory allows."); MFEM_VERIFY(q1d <= MAX_Q1D, "Maximum quadrature points 1D reached." "This number can be increased globally in " "general/forall.hpp if device memory allows."); } /** * @brief Multi-component gradient evaluation from DOFs to quadrature points in * reference coordinates. * * The implementation exploits sum factorization. * * @note DeviceTensor<2> means RANK=2 * * @tparam dim Dimension. * @tparam d1d Number of degrees of freedom in 1D. * @tparam q1d er of quadrature points in 1D. * @param B Basis functions evaluated at quadrature points in column-major * layout q1d x d1d. * @param G Gradients of basis functions evaluated at quadrature points in * column major layout q1d x d1d. * @param smem Block of shared memory for scratch space. Size needed is 2 x 3 x * q1d x q1d x q1d. * @param U Input vector d1d x d1d x d1d x dim. * @param dUdxi Gradient of the input vector wrt to reference coordinates. Size * needed q1d x q1d x q1d x dim x dim. */ template <int dim, int d1d, int q1d> static inline MFEM_HOST_DEVICE void CalcGrad(const tensor<double, q1d, d1d> &B, const tensor<double, q1d, d1d> &G, tensor<double,2,3,q1d,q1d,q1d> &smem, const DeviceTensor<4, const double> &U, tensor<double, q1d, q1d, q1d, dim, dim> &dUdxi) { for (int c = 0; c < dim; ++c) { MFEM_FOREACH_THREAD(dz,z,d1d) { MFEM_FOREACH_THREAD(dy,y,d1d) { MFEM_FOREACH_THREAD(dx,x,d1d) { smem(0,0,dx,dy,dz) = U(dx,dy,dz,c); } } } MFEM_SYNC_THREAD; MFEM_FOREACH_THREAD(dz,z,d1d) { MFEM_FOREACH_THREAD(dy,y,d1d) { MFEM_FOREACH_THREAD(qx,x,q1d) { double u = 0.0; double v = 0.0; for (int dx = 0; dx < d1d; ++dx) { const double input = smem(0,0,dx,dy,dz); u += input * B(qx,dx); v += input * G(qx,dx); } smem(0,1,dz,dy,qx) = u; smem(0,2,dz,dy,qx) = v; } } } MFEM_SYNC_THREAD; MFEM_FOREACH_THREAD(dz,z,d1d) { MFEM_FOREACH_THREAD(qy,y,q1d) { MFEM_FOREACH_THREAD(qx,x,q1d) { double u = 0.0; double v = 0.0; double w = 0.0; for (int dy = 0; dy < d1d; ++dy) { u += smem(0,2,dz,dy,qx) * B(qy,dy); v += smem(0,1,dz,dy,qx) * G(qy,dy); w += smem(0,1,dz,dy,qx) * B(qy,dy); } smem(1,0,dz,qy,qx) = u; smem(1,1,dz,qy,qx) = v; smem(1,2,dz,qy,qx) = w; } } } MFEM_SYNC_THREAD; MFEM_FOREACH_THREAD(qz,z,q1d) { MFEM_FOREACH_THREAD(qy,y,q1d) { MFEM_FOREACH_THREAD(qx,x,q1d) { double u = 0.0; double v = 0.0; double w = 0.0; for (int dz = 0; dz < d1d; ++dz) { u += smem(1,0,dz,qy,qx) * B(qz,dz); v += smem(1,1,dz,qy,qx) * B(qz,dz); w += smem(1,2,dz,qy,qx) * G(qz,dz); } dUdxi(qz,qy,qx,c,0) += u; dUdxi(qz,qy,qx,c,1) += v; dUdxi(qz,qy,qx,c,2) += w; } } } MFEM_SYNC_THREAD; } // vdim } /** * @brief Multi-component transpose gradient evaluation from DOFs to quadrature * points in reference coordinates with contraction of the D vector. * * @tparam dim Dimension. * @tparam d1d Number of degrees of freedom in 1D. * @tparam q1d er of quadrature points in 1D. * @param B Basis functions evaluated at quadrature points in column-major * layout q1d x d1d. * @param G Gradients of basis functions evaluated at quadrature points in * column major layout q1d x d1d. * @param smem Block of shared memory for scratch space. Size needed is 2 x 3 x * q1d x q1d x q1d. * @param U Input vector q1d x q1d x q1d x dim. * @param F Output vector that applied the gradient evaluation from DOFs to * quadrature points in reference coordinates with contraction of the D operator * on the input vector. Size is d1d x d1d x d1d x dim. */ template <int dim, int d1d, int q1d> static inline MFEM_HOST_DEVICE void CalcGradTSum(const tensor<double, q1d, d1d> &B, const tensor<double, q1d, d1d> &G, tensor<double, 2, 3, q1d, q1d, q1d> &smem, const tensor<double, q1d, q1d, q1d, dim, dim> &U, DeviceTensor<4, double> &F) { for (int c = 0; c < dim; ++c) { MFEM_FOREACH_THREAD(qz, z, q1d) { MFEM_FOREACH_THREAD(qy, y, q1d) { MFEM_FOREACH_THREAD(dx, x, d1d) { double u = 0.0, v = 0.0, w = 0.0; for (int qx = 0; qx < q1d; ++qx) { u += U(qx, qy, qz, 0, c) * G(qx, dx); v += U(qx, qy, qz, 1, c) * B(qx, dx); w += U(qx, qy, qz, 2, c) * B(qx, dx); } smem(0, 0, qz, qy, dx) = u; smem(0, 1, qz, qy, dx) = v; smem(0, 2, qz, qy, dx) = w; } } } MFEM_SYNC_THREAD; MFEM_FOREACH_THREAD(qz, z, q1d) { MFEM_FOREACH_THREAD(dy, y, d1d) { MFEM_FOREACH_THREAD(dx, x, d1d) { double u = 0.0, v = 0.0, w = 0.0; for (int qy = 0; qy < q1d; ++qy) { u += smem(0, 0, qz, qy, dx) * B(qy, dy); v += smem(0, 1, qz, qy, dx) * G(qy, dy); w += smem(0, 2, qz, qy, dx) * B(qy, dy); } smem(1, 0, qz, dy, dx) = u; smem(1, 1, qz, dy, dx) = v; smem(1, 2, qz, dy, dx) = w; } } } MFEM_SYNC_THREAD; MFEM_FOREACH_THREAD(dz, z, d1d) { MFEM_FOREACH_THREAD(dy, y, d1d) { MFEM_FOREACH_THREAD(dx, x, d1d) { double u = 0.0, v = 0.0, w = 0.0; for (int qz = 0; qz < q1d; ++qz) { u += smem(1, 0, qz, dy, dx) * B(qz, dz); v += smem(1, 1, qz, dy, dx) * B(qz, dz); w += smem(1, 2, qz, dy, dx) * G(qz, dz); } const double sum = u + v + w; F(dx, dy, dz, c) += sum; } } } MFEM_SYNC_THREAD; } } /** * @brief Compute the gradient of all shape functions. * * @note TODO: Does not make use of shared memory on the GPU. * * @tparam dim Dimension. * @tparam d1d Number of degrees of freedom in 1D. * @tparam q1d er of quadrature points in 1D. * @param qx Quadrature point x index. * @param qy Quadrature point y index. * @param qz Quadrature point z index. * @param B Basis functions evaluated at quadrature points in column-major * layout q1d x d1d. * @param G Gradients of basis functions evaluated at quadrature points in * column major layout q1d x d1d. * @param invJ Inverse of the Jacobian at the quadrature point. Size is dim x * dim. * * @return Gradient of all shape functions at the quadrature point. Size is d1d * x d1d x d1d x dim. */ template <int dim, int d1d, int q1d> static inline MFEM_HOST_DEVICE tensor<double, d1d, d1d, d1d, dim> GradAllShapeFunctions(int qx, int qy, int qz, const tensor<double, q1d, d1d> &B, const tensor<double, q1d, d1d> &G, const tensor<double, dim, dim> &invJ) { tensor<double, d1d, d1d, d1d, dim> dphi_dx; // G (x) B (x) B // B (x) G (x) B // B (x) B (x) G for (int dx = 0; dx < d1d; dx++) { for (int dy = 0; dy < d1d; dy++) { for (int dz = 0; dz < d1d; dz++) { dphi_dx(dx,dy,dz) = transpose(invJ) * tensor<double, dim> {G(qx, dx) * B(qy, dy) * B(qz, dz), B(qx, dx) * G(qy, dy) * B(qz, dz), B(qx, dx) * B(qy, dy) * G(qz, dz) }; } } } return dphi_dx; } } // namespace KernelHelpers } // namespace mfem #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/audio_device/android/single_rw_fifo.h" #if !defined(__ARMEL__) // ARM specific due to the implementation of MemoryBarrier. #error trying to compile ARM code for non-ARM target #endif static int UpdatePos(int pos, int capacity) { return (pos + 1) % capacity; } namespace webrtc { namespace subtle { // From http://src.chromium.org/viewvc/chrome/trunk/src/base/atomicops_internals_arm_gcc.h // Note that it is only the MemoryBarrier function that makes this class arm // specific. Borrowing other MemoryBarrier implementations, this class could // be extended to more platforms. inline void MemoryBarrier() { // Note: This is a function call, which is also an implicit compiler // barrier. typedef void (*KernelMemoryBarrierFunc)(); ((KernelMemoryBarrierFunc)0xffff0fa0)(); } } // namespace subtle SingleRwFifo::SingleRwFifo(int capacity) : capacity_(capacity), size_(0), read_pos_(0), write_pos_(0) { queue_.reset(new int8_t*[capacity_]); } SingleRwFifo::~SingleRwFifo() { } void SingleRwFifo::Push(int8_t* mem) { assert(mem); // Ensure that there is space for the new data in the FIFO. // Note there is only one writer meaning that the other thread is guaranteed // only to decrease the size. const int free_slots = capacity() - size(); if (free_slots <= 0) { // Size can be queried outside of the Push function. The caller is assumed // to ensure that Push will be successful before calling it. assert(false); return; } queue_[write_pos_] = mem; // Memory barrier ensures that |size_| is updated after the size has changed. subtle::MemoryBarrier(); ++size_; write_pos_ = UpdatePos(write_pos_, capacity()); } int8_t* SingleRwFifo::Pop() { int8_t* ret_val = NULL; if (size() <= 0) { // Size can be queried outside of the Pop function. The caller is assumed // to ensure that Pop will be successfull before calling it. assert(false); return ret_val; } ret_val = queue_[read_pos_]; // Memory barrier ensures that |size_| is updated after the size has changed. subtle::MemoryBarrier(); --size_; read_pos_ = UpdatePos(read_pos_, capacity()); return ret_val; } } // namespace webrtc <commit_msg>Fix broken build on x86 Android BUG=2545 R=fischman@webrtc.org, henrike@webrtc.org<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/audio_device/android/single_rw_fifo.h" static int UpdatePos(int pos, int capacity) { return (pos + 1) % capacity; } namespace webrtc { namespace subtle { #if defined(__ARMEL__) // From http://src.chromium.org/viewvc/chrome/trunk/src/base/atomicops_internals_arm_gcc.h // Note that it is only the MemoryBarrier function that makes this class arm // specific. Borrowing other MemoryBarrier implementations, this class could // be extended to more platforms. inline void MemoryBarrier() { // Note: This is a function call, which is also an implicit compiler // barrier. typedef void (*KernelMemoryBarrierFunc)(); ((KernelMemoryBarrierFunc)0xffff0fa0)(); } #elif defined(__x86_64__) || defined (__i386__) // From http://src.chromium.org/viewvc/chrome/trunk/src/base/atomicops_internals_x86_gcc.h // mfence exists on x64 and x86 platforms containing SSE2. // x86 platforms that don't have SSE2 will crash with SIGILL. // If this code needs to run on such platforms in the future, // add runtime CPU detection here. inline void MemoryBarrier() { __asm__ __volatile__("mfence" : : : "memory"); } #else #error Add an implementation of MemoryBarrier() for this platform! #endif } // namespace subtle SingleRwFifo::SingleRwFifo(int capacity) : capacity_(capacity), size_(0), read_pos_(0), write_pos_(0) { queue_.reset(new int8_t*[capacity_]); } SingleRwFifo::~SingleRwFifo() { } void SingleRwFifo::Push(int8_t* mem) { assert(mem); // Ensure that there is space for the new data in the FIFO. // Note there is only one writer meaning that the other thread is guaranteed // only to decrease the size. const int free_slots = capacity() - size(); if (free_slots <= 0) { // Size can be queried outside of the Push function. The caller is assumed // to ensure that Push will be successful before calling it. assert(false); return; } queue_[write_pos_] = mem; // Memory barrier ensures that |size_| is updated after the size has changed. subtle::MemoryBarrier(); ++size_; write_pos_ = UpdatePos(write_pos_, capacity()); } int8_t* SingleRwFifo::Pop() { int8_t* ret_val = NULL; if (size() <= 0) { // Size can be queried outside of the Pop function. The caller is assumed // to ensure that Pop will be successfull before calling it. assert(false); return ret_val; } ret_val = queue_[read_pos_]; // Memory barrier ensures that |size_| is updated after the size has changed. subtle::MemoryBarrier(); --size_; read_pos_ = UpdatePos(read_pos_, capacity()); return ret_val; } } // namespace webrtc <|endoftext|>
<commit_before>// This program re-calculates _struct_conn.pdbx_dist_value values // and prints message if it differs by more than 0.002A from the value in file. #include <gemmi/util.hpp> // for giends_with #include <gemmi/gz.hpp> // for MaybeGzipped #include <gemmi/cif.hpp> #include <gemmi/numb.hpp> // for as_number #include <gemmi/mmcif.hpp> #include <gemmi/dirwalk.hpp> // for CifWalk #include <cstdio> #include <map> using namespace gemmi; int verbose = false; void check_struct_conn(gemmi::cif::Block& block) { cif::Table struct_conn = block.find("_struct_conn.", {"id", "conn_type_id", "ptnr2_symmetry", "pdbx_dist_value" }); Structure st = read_atoms_from_block(block); for (Connection& con : st.models[0].connections) { const Atom* atom[2] = {nullptr, nullptr}; for (int n : {0, 1}) { if (con.res[n]) atom[n] = con.res[n]->find_by_name_altloc(con.atom[n], con.altloc[n]); if (!atom[n]) std::printf("%s: %s atom not found in %s\n", block.name.c_str(), con.name.c_str(), con.res[n]->ident().c_str()); } if (!atom[0] || !atom[1]) continue; NearbyImage im = st.cell.find_nearest_image(atom[0]->pos, atom[1]->pos, con.image); double dist = std::sqrt(im.dist_sq); cif::Table::Row row = struct_conn.find_row(con.name); if (!starts_with(con.name, row.str(1))) std::printf("%s: Unexpected connection name: %s for %s\n", block.name.c_str(), con.name.c_str(), row.str(1).c_str()); std::string ref_sym = row.str(2); double ref_dist = cif::as_number(row[3]); bool differs = std::abs(dist - ref_dist) > 0.002; if (verbose || differs) { std::printf("%s %s im:%s %.3f %c= %.3f (%s)%s\n", block.name.c_str(), con.name.c_str(), im.pdb_symbol(true).c_str(), dist, (differs ? '!' : '='), ref_dist, ref_sym.c_str(), st.cell.explicit_matrices ? " {fract}" : ""); } } for (cif::Table::Row row : struct_conn) if (st.models[0].find_connection_by_name(row.str(0)) == nullptr) std::printf("%s: connection not read: %s\n", block.name.c_str(), row.str(0).c_str()); } int main(int argc, char* argv[]) { if (argc == 3 && argv[1] == std::string("-v")) verbose = true; else if (argc != 2) return 1; int counter = 0; try { for (const char* path : CifWalk(argv[argc-1])) { cif::Document doc = cif::read(gemmi::MaybeGzipped(path)); check_struct_conn(doc.sole_block()); if (++counter % 1000 == 0) { std::printf("[progress: %d files]\n", counter); std::fflush(stdout); } } } catch (std::runtime_error& err) { std::fprintf(stderr, "Error: %s\n", err.what()); return 1; } return 0; } <commit_msg>check_conn: list connections >5A<commit_after>// This program re-calculates _struct_conn.pdbx_dist_value values // and prints message if it differs by more than 0.002A from the value in file. #include <gemmi/util.hpp> // for giends_with #include <gemmi/gz.hpp> // for MaybeGzipped #include <gemmi/cif.hpp> #include <gemmi/numb.hpp> // for as_number #include <gemmi/mmcif.hpp> #include <gemmi/dirwalk.hpp> // for CifWalk #include <cstdio> #include <map> using namespace gemmi; int verbose = false; void check_struct_conn(gemmi::cif::Block& block) { cif::Table struct_conn = block.find("_struct_conn.", {"id", "conn_type_id", "ptnr2_symmetry", "pdbx_dist_value" }); Structure st = read_atoms_from_block(block); for (Connection& con : st.models[0].connections) { const Atom* atom[2] = {nullptr, nullptr}; for (int n : {0, 1}) { if (con.res[n]) atom[n] = con.res[n]->find_by_name_altloc(con.atom[n], con.altloc[n]); if (!atom[n]) std::printf("%s: %s atom not found in %s\n", block.name.c_str(), con.name.c_str(), con.res[n]->ident().c_str()); } if (!atom[0] || !atom[1]) continue; NearbyImage im = st.cell.find_nearest_image(atom[0]->pos, atom[1]->pos, con.image); double dist = std::sqrt(im.dist_sq); cif::Table::Row row = struct_conn.find_row(con.name); if (!starts_with(con.name, row.str(1))) std::printf("%s: Unexpected connection name: %s for %s\n", block.name.c_str(), con.name.c_str(), row.str(1).c_str()); if (dist > 5) std::printf("%s: Long connection %s: %g\n", block.name.c_str(), con.name.c_str(), dist); std::string ref_sym = row.str(2); double ref_dist = cif::as_number(row[3]); bool differs = std::abs(dist - ref_dist) > 0.002; if (verbose || differs) { std::printf("%s %s im:%s %.3f %c= %.3f (%s)%s\n", block.name.c_str(), con.name.c_str(), im.pdb_symbol(true).c_str(), dist, (differs ? '!' : '='), ref_dist, ref_sym.c_str(), st.cell.explicit_matrices ? " {fract}" : ""); } } for (cif::Table::Row row : struct_conn) if (st.models[0].find_connection_by_name(row.str(0)) == nullptr) std::printf("%s: connection not read: %s\n", block.name.c_str(), row.str(0).c_str()); } int main(int argc, char* argv[]) { if (argc == 3 && argv[1] == std::string("-v")) verbose = true; else if (argc != 2) return 1; int counter = 0; try { for (const char* path : CifWalk(argv[argc-1])) { cif::Document doc = cif::read(gemmi::MaybeGzipped(path)); check_struct_conn(doc.sole_block()); if (++counter % 1000 == 0) { std::printf("[progress: %d files]\n", counter); std::fflush(stdout); } } } catch (std::runtime_error& err) { std::fprintf(stderr, "Error: %s\n", err.what()); return 1; } return 0; } <|endoftext|>
<commit_before>/* This file is part of KMail. Copyright (c) 2003 Andreas Gungl <a.gungl@gmx.de> KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. KMail is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "config.h" #include "filterlogdlg.h" #include "filterlog.h" #include <kdebug.h> #include <kdeversion.h> #include <kfiledialog.h> #include <klocale.h> #include <kmessagebox.h> #include <kvbox.h> #include <QCheckBox> #include <QLabel> #include <QSpinBox> #include <QStringList> #include <q3textedit.h> #include <q3groupbox.h> #include <errno.h> using namespace KMail; FilterLogDialog::FilterLogDialog( QWidget * parent ) : KDialog( parent ) { setCaption( i18n( "Filter Log Viewer" ) ); setButtons( User1|User2|Close ); setObjectName( "FilterLogDlg" ); setModal( false ); setDefaultButton( Close ); setButtonGuiItem( User1, KStdGuiItem::clear() ); setButtonGuiItem( User2, KStdGuiItem::saveAs() ); setAttribute( Qt::WA_DeleteOnClose ); QFrame *page = new KVBox( this ); setMainWidget( page ); mTextEdit = new Q3TextEdit( page ); mTextEdit->setReadOnly( true ); mTextEdit->setWordWrap( Q3TextEdit::NoWrap ); mTextEdit->setTextFormat( Qt::LogText ); QStringList logEntries = FilterLog::instance()->getLogEntries(); for ( QStringList::Iterator it = logEntries.begin(); it != logEntries.end(); ++it ) { mTextEdit->append( *it ); } mLogActiveBox = new QCheckBox( i18n("&Log filter activities"), page ); mLogActiveBox->setChecked( FilterLog::instance()->isLogging() ); connect( mLogActiveBox, SIGNAL(clicked()), this, SLOT(slotSwitchLogState(void)) ); mLogActiveBox->setWhatsThis( i18n( "You can turn logging of filter activities on and off here. " "Of course, log data is collected and shown only when logging " "is turned on. " ) ); mLogDetailsBox = new Q3GroupBox(1, Qt::Horizontal, i18n( "Logging Details" ), page ); mLogDetailsBox->setEnabled( mLogActiveBox->isChecked() ); connect( mLogActiveBox, SIGNAL( toggled( bool ) ), mLogDetailsBox, SLOT( setEnabled( bool ) ) ); mLogPatternDescBox = new QCheckBox( i18n("Log pattern description"), mLogDetailsBox ); mLogPatternDescBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::patternDesc ) ); connect( mLogPatternDescBox, SIGNAL(clicked()), this, SLOT(slotChangeLogDetail(void)) ); // TODO //QWhatsThis::add( mLogPatternDescBox, // i18n( "" ) ); mLogRuleEvaluationBox = new QCheckBox( i18n("Log filter &rule evaluation"), mLogDetailsBox ); mLogRuleEvaluationBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::ruleResult ) ); connect( mLogRuleEvaluationBox, SIGNAL(clicked()), this, SLOT(slotChangeLogDetail(void)) ); mLogRuleEvaluationBox->setWhatsThis( i18n( "You can control the feedback in the log concerning the " "evaluation of the filter rules of applied filters: " "having this option checked will give detailed feedback " "for each single filter rule; alternatively, only " "feedback about the result of the evaluation of all rules " "of a single filter will be given." ) ); mLogPatternResultBox = new QCheckBox( i18n("Log filter pattern evaluation"), mLogDetailsBox ); mLogPatternResultBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::patternResult ) ); connect( mLogPatternResultBox, SIGNAL(clicked()), this, SLOT(slotChangeLogDetail(void)) ); // TODO //QWhatsThis::add( mLogPatternResultBox, // i18n( "" ) ); mLogFilterActionBox = new QCheckBox( i18n("Log filter actions"), mLogDetailsBox ); mLogFilterActionBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::appliedAction ) ); connect( mLogFilterActionBox, SIGNAL(clicked()), this, SLOT(slotChangeLogDetail(void)) ); // TODO //QWhatsThis::add( mLogFilterActionBox, // i18n( "" ) ); KHBox * hbox = new KHBox( page ); new QLabel( i18n("Log size limit:"), hbox ); mLogMemLimitSpin = new QSpinBox( hbox ); mLogMemLimitSpin->setMinimum( 1 ); mLogMemLimitSpin->setMaximum( 1024 * 256 ); // 256 MB // value in the QSpinBox is in KB while it's in Byte in the FilterLog mLogMemLimitSpin->setValue( FilterLog::instance()->getMaxLogSize() / 1024 ); mLogMemLimitSpin->setSuffix( " KB" ); mLogMemLimitSpin->setSpecialValueText( i18n("unlimited") ); connect( mLogMemLimitSpin, SIGNAL(valueChanged(int)), this, SLOT(slotChangeLogMemLimit(int)) ); mLogMemLimitSpin->setWhatsThis( i18n( "Collecting log data uses memory to temporarily store the " "log data; here you can limit the maximum amount of memory " "to be used: if the size of the collected log data exceeds " "this limit then the oldest data will be discarded until " "the limit is no longer exceeded. " ) ); connect(FilterLog::instance(), SIGNAL(logEntryAdded(QString)), this, SLOT(slotLogEntryAdded(QString))); connect(FilterLog::instance(), SIGNAL(logShrinked(void)), this, SLOT(slotLogShrinked(void))); connect(FilterLog::instance(), SIGNAL(logStateChanged(void)), this, SLOT(slotLogStateChanged(void))); setInitialSize( QSize( 500, 500 ) ); } void FilterLogDialog::slotLogEntryAdded( QString logEntry ) { mTextEdit->append( logEntry ); } void FilterLogDialog::slotLogShrinked() { // limit the size of the shown log lines as soon as // the log has reached it's memory limit if ( mTextEdit->maxLogLines() == -1 ) mTextEdit->setMaxLogLines( mTextEdit->lines() ); } void FilterLogDialog::slotLogStateChanged() { mLogActiveBox->setChecked( FilterLog::instance()->isLogging() ); mLogPatternDescBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::patternDesc ) ); mLogRuleEvaluationBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::ruleResult ) ); mLogPatternResultBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::patternResult ) ); mLogFilterActionBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::appliedAction ) ); // value in the QSpinBox is in KB while it's in Byte in the FilterLog int newLogSize = FilterLog::instance()->getMaxLogSize() / 1024; if ( mLogMemLimitSpin->value() != newLogSize ) mLogMemLimitSpin->setValue( newLogSize ); } void FilterLogDialog::slotChangeLogDetail() { if ( mLogPatternDescBox->isChecked() != FilterLog::instance()->isContentTypeEnabled( FilterLog::patternDesc ) ) FilterLog::instance()->setContentTypeEnabled( FilterLog::patternDesc, mLogPatternDescBox->isChecked() ); if ( mLogRuleEvaluationBox->isChecked() != FilterLog::instance()->isContentTypeEnabled( FilterLog::ruleResult ) ) FilterLog::instance()->setContentTypeEnabled( FilterLog::ruleResult, mLogRuleEvaluationBox->isChecked() ); if ( mLogPatternResultBox->isChecked() != FilterLog::instance()->isContentTypeEnabled( FilterLog::patternResult ) ) FilterLog::instance()->setContentTypeEnabled( FilterLog::patternResult, mLogPatternResultBox->isChecked() ); if ( mLogFilterActionBox->isChecked() != FilterLog::instance()->isContentTypeEnabled( FilterLog::appliedAction ) ) FilterLog::instance()->setContentTypeEnabled( FilterLog::appliedAction, mLogFilterActionBox->isChecked() ); } void FilterLogDialog::slotSwitchLogState() { FilterLog::instance()->setLogging( mLogActiveBox->isChecked() ); } void FilterLogDialog::slotChangeLogMemLimit( int value ) { FilterLog::instance()->setMaxLogSize( value * 1024 ); } void FilterLogDialog::slotUser1() { FilterLog::instance()->clear(); mTextEdit->clear(); } void FilterLogDialog::slotUser2() { QString fileName; KFileDialog fdlg( QString::null, QString::null, this); fdlg.setMode( KFile::File ); fdlg.setSelection( "kmail-filter.log" ); fdlg.setOperationMode( KFileDialog::Saving ); if ( fdlg.exec() ) { fileName = fdlg.selectedFile(); if ( !FilterLog::instance()->saveToFile( fileName ) ) { KMessageBox::error( this, i18n( "Could not write the file %1:\n" "\"%2\" is the detailed error description.", fileName, QString::fromLocal8Bit( strerror( errno ) ) ), i18n( "KMail Error" ) ); } } } #include "filterlogdlg.moc" <commit_msg>using KUrl in first argument of KFileDialog<commit_after>/* This file is part of KMail. Copyright (c) 2003 Andreas Gungl <a.gungl@gmx.de> KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. KMail is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "config.h" #include "filterlogdlg.h" #include "filterlog.h" #include <kdebug.h> #include <kdeversion.h> #include <kfiledialog.h> #include <klocale.h> #include <kmessagebox.h> #include <kvbox.h> #include <QCheckBox> #include <QLabel> #include <QSpinBox> #include <QStringList> #include <q3textedit.h> #include <q3groupbox.h> #include <errno.h> using namespace KMail; FilterLogDialog::FilterLogDialog( QWidget * parent ) : KDialog( parent ) { setCaption( i18n( "Filter Log Viewer" ) ); setButtons( User1|User2|Close ); setObjectName( "FilterLogDlg" ); setModal( false ); setDefaultButton( Close ); setButtonGuiItem( User1, KStdGuiItem::clear() ); setButtonGuiItem( User2, KStdGuiItem::saveAs() ); setAttribute( Qt::WA_DeleteOnClose ); QFrame *page = new KVBox( this ); setMainWidget( page ); mTextEdit = new Q3TextEdit( page ); mTextEdit->setReadOnly( true ); mTextEdit->setWordWrap( Q3TextEdit::NoWrap ); mTextEdit->setTextFormat( Qt::LogText ); QStringList logEntries = FilterLog::instance()->getLogEntries(); for ( QStringList::Iterator it = logEntries.begin(); it != logEntries.end(); ++it ) { mTextEdit->append( *it ); } mLogActiveBox = new QCheckBox( i18n("&Log filter activities"), page ); mLogActiveBox->setChecked( FilterLog::instance()->isLogging() ); connect( mLogActiveBox, SIGNAL(clicked()), this, SLOT(slotSwitchLogState(void)) ); mLogActiveBox->setWhatsThis( i18n( "You can turn logging of filter activities on and off here. " "Of course, log data is collected and shown only when logging " "is turned on. " ) ); mLogDetailsBox = new Q3GroupBox(1, Qt::Horizontal, i18n( "Logging Details" ), page ); mLogDetailsBox->setEnabled( mLogActiveBox->isChecked() ); connect( mLogActiveBox, SIGNAL( toggled( bool ) ), mLogDetailsBox, SLOT( setEnabled( bool ) ) ); mLogPatternDescBox = new QCheckBox( i18n("Log pattern description"), mLogDetailsBox ); mLogPatternDescBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::patternDesc ) ); connect( mLogPatternDescBox, SIGNAL(clicked()), this, SLOT(slotChangeLogDetail(void)) ); // TODO //QWhatsThis::add( mLogPatternDescBox, // i18n( "" ) ); mLogRuleEvaluationBox = new QCheckBox( i18n("Log filter &rule evaluation"), mLogDetailsBox ); mLogRuleEvaluationBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::ruleResult ) ); connect( mLogRuleEvaluationBox, SIGNAL(clicked()), this, SLOT(slotChangeLogDetail(void)) ); mLogRuleEvaluationBox->setWhatsThis( i18n( "You can control the feedback in the log concerning the " "evaluation of the filter rules of applied filters: " "having this option checked will give detailed feedback " "for each single filter rule; alternatively, only " "feedback about the result of the evaluation of all rules " "of a single filter will be given." ) ); mLogPatternResultBox = new QCheckBox( i18n("Log filter pattern evaluation"), mLogDetailsBox ); mLogPatternResultBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::patternResult ) ); connect( mLogPatternResultBox, SIGNAL(clicked()), this, SLOT(slotChangeLogDetail(void)) ); // TODO //QWhatsThis::add( mLogPatternResultBox, // i18n( "" ) ); mLogFilterActionBox = new QCheckBox( i18n("Log filter actions"), mLogDetailsBox ); mLogFilterActionBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::appliedAction ) ); connect( mLogFilterActionBox, SIGNAL(clicked()), this, SLOT(slotChangeLogDetail(void)) ); // TODO //QWhatsThis::add( mLogFilterActionBox, // i18n( "" ) ); KHBox * hbox = new KHBox( page ); new QLabel( i18n("Log size limit:"), hbox ); mLogMemLimitSpin = new QSpinBox( hbox ); mLogMemLimitSpin->setMinimum( 1 ); mLogMemLimitSpin->setMaximum( 1024 * 256 ); // 256 MB // value in the QSpinBox is in KB while it's in Byte in the FilterLog mLogMemLimitSpin->setValue( FilterLog::instance()->getMaxLogSize() / 1024 ); mLogMemLimitSpin->setSuffix( " KB" ); mLogMemLimitSpin->setSpecialValueText( i18n("unlimited") ); connect( mLogMemLimitSpin, SIGNAL(valueChanged(int)), this, SLOT(slotChangeLogMemLimit(int)) ); mLogMemLimitSpin->setWhatsThis( i18n( "Collecting log data uses memory to temporarily store the " "log data; here you can limit the maximum amount of memory " "to be used: if the size of the collected log data exceeds " "this limit then the oldest data will be discarded until " "the limit is no longer exceeded. " ) ); connect(FilterLog::instance(), SIGNAL(logEntryAdded(QString)), this, SLOT(slotLogEntryAdded(QString))); connect(FilterLog::instance(), SIGNAL(logShrinked(void)), this, SLOT(slotLogShrinked(void))); connect(FilterLog::instance(), SIGNAL(logStateChanged(void)), this, SLOT(slotLogStateChanged(void))); setInitialSize( QSize( 500, 500 ) ); } void FilterLogDialog::slotLogEntryAdded( QString logEntry ) { mTextEdit->append( logEntry ); } void FilterLogDialog::slotLogShrinked() { // limit the size of the shown log lines as soon as // the log has reached it's memory limit if ( mTextEdit->maxLogLines() == -1 ) mTextEdit->setMaxLogLines( mTextEdit->lines() ); } void FilterLogDialog::slotLogStateChanged() { mLogActiveBox->setChecked( FilterLog::instance()->isLogging() ); mLogPatternDescBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::patternDesc ) ); mLogRuleEvaluationBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::ruleResult ) ); mLogPatternResultBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::patternResult ) ); mLogFilterActionBox->setChecked( FilterLog::instance()->isContentTypeEnabled( FilterLog::appliedAction ) ); // value in the QSpinBox is in KB while it's in Byte in the FilterLog int newLogSize = FilterLog::instance()->getMaxLogSize() / 1024; if ( mLogMemLimitSpin->value() != newLogSize ) mLogMemLimitSpin->setValue( newLogSize ); } void FilterLogDialog::slotChangeLogDetail() { if ( mLogPatternDescBox->isChecked() != FilterLog::instance()->isContentTypeEnabled( FilterLog::patternDesc ) ) FilterLog::instance()->setContentTypeEnabled( FilterLog::patternDesc, mLogPatternDescBox->isChecked() ); if ( mLogRuleEvaluationBox->isChecked() != FilterLog::instance()->isContentTypeEnabled( FilterLog::ruleResult ) ) FilterLog::instance()->setContentTypeEnabled( FilterLog::ruleResult, mLogRuleEvaluationBox->isChecked() ); if ( mLogPatternResultBox->isChecked() != FilterLog::instance()->isContentTypeEnabled( FilterLog::patternResult ) ) FilterLog::instance()->setContentTypeEnabled( FilterLog::patternResult, mLogPatternResultBox->isChecked() ); if ( mLogFilterActionBox->isChecked() != FilterLog::instance()->isContentTypeEnabled( FilterLog::appliedAction ) ) FilterLog::instance()->setContentTypeEnabled( FilterLog::appliedAction, mLogFilterActionBox->isChecked() ); } void FilterLogDialog::slotSwitchLogState() { FilterLog::instance()->setLogging( mLogActiveBox->isChecked() ); } void FilterLogDialog::slotChangeLogMemLimit( int value ) { FilterLog::instance()->setMaxLogSize( value * 1024 ); } void FilterLogDialog::slotUser1() { FilterLog::instance()->clear(); mTextEdit->clear(); } void FilterLogDialog::slotUser2() { QString fileName; KFileDialog fdlg( KUrl(), QString::null, this); fdlg.setMode( KFile::File ); fdlg.setSelection( "kmail-filter.log" ); fdlg.setOperationMode( KFileDialog::Saving ); if ( fdlg.exec() ) { fileName = fdlg.selectedFile(); if ( !FilterLog::instance()->saveToFile( fileName ) ) { KMessageBox::error( this, i18n( "Could not write the file %1:\n" "\"%2\" is the detailed error description.", fileName, QString::fromLocal8Bit( strerror( errno ) ) ), i18n( "KMail Error" ) ); } } } #include "filterlogdlg.moc" <|endoftext|>
<commit_before>/** * Copyright (c) 2004 David Faure <faure@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; version 2 of the License * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "jobscheduler.h" #include "kmfolder.h" #include "folderstorage.h" #include "kmfoldermgr.h" #include <kdebug.h> using namespace KMail; JobScheduler::JobScheduler( QObject* parent, const char* name ) : QObject( parent, name ), mTimer( this ), mCurrentTask( 0 ), mCurrentJob( 0 ), mIgnoreOpenNotify( false ) { connect( &mTimer, SIGNAL( timeout() ), SLOT( slotRunNextJob() ) ); // No need to start the internal timer yet, we wait for a task to be scheduled } JobScheduler::~JobScheduler() { // delete tasks in tasklist (no autodelete for QValueList) for( QValueList<ScheduledTask *>::Iterator it = mTaskList.begin(); it != mTaskList.end(); ++it ) { delete (*it); } delete mCurrentTask; delete mCurrentJob; } void JobScheduler::registerTask( ScheduledTask* task ) { int typeId = task->taskTypeId(); if ( typeId ) { KMFolder* folder = task->folder(); // Search for an identical task already scheduled for( QValueList<ScheduledTask *>::ConstIterator it = mTaskList.begin(); it != mTaskList.end(); ++it ) { if ( (*it)->taskTypeId() == typeId && (*it)->folder() == folder ) { #ifdef DEBUG_SCHEDULER kdDebug(5006) << "JobScheduler: already having task type " << typeId << " for folder " << folder->label() << endl; #endif delete task; return; } } // Note that scheduling an identical task as the one currently running is allowed. } #ifdef DEBUG_SCHEDULER kdDebug(5006) << "JobScheduler: adding task " << task << " (type " << task->taskTypeId() << ") for folder " << task->folder() << " " << task->folder()->label() << endl; #endif mTaskList.append( task ); if ( !mTimer.isActive() ) restartTimer(); } void JobScheduler::notifyOpeningFolder( KMFolder* folder ) { if ( mCurrentTask && mCurrentTask->folder() == folder ) { if ( mIgnoreOpenNotify ) { // set when starting a job for this folder #ifdef DEBUG_SCHEDULER kdDebug(5006) << "JobScheduler: got the opening-notification for " << folder->label() << " as expected." << endl; #endif mIgnoreOpenNotify = false; } else { // Jobs scheduled from here should always be cancellable. // One exception though, is when ExpireJob does its final KMMoveCommand. // Then that command shouldn't kill its own parent job just because it opens a folder... if ( mCurrentJob->isCancellable() ) interruptCurrentTask(); } } } void JobScheduler::interruptCurrentTask() { Q_ASSERT( mCurrentTask ); #ifdef DEBUG_SCHEDULER kdDebug(5006) << "JobScheduler: interrupting job " << mCurrentJob << " for folder " << mCurrentTask->folder()->label() << endl; #endif // File it again. This will either delete it or put it in mTaskList. registerTask( mCurrentTask ); mCurrentTask = 0; mCurrentJob->kill(); // This deletes the job and calls slotJobFinished! } void JobScheduler::slotRunNextJob() { #ifdef DEBUG_SCHEDULER kdDebug(5006) << "JobScheduler: slotRunNextJob" << endl; #endif Q_ASSERT( mCurrentTask == 0 ); ScheduledTask* task = 0; // Find a task suitable for being run for( QValueList<ScheduledTask *>::Iterator it = mTaskList.begin(); it != mTaskList.end(); ++it ) { // Remove if folder died if ( (*it)->folder() == 0 ) { #ifdef DEBUG_SCHEDULER kdDebug(5006) << " folder for task " << (*it) << " was deleted" << endl; #endif mTaskList.remove( it ); if ( !mTaskList.isEmpty() ) slotRunNextJob(); // to avoid the mess with invalid iterators :) else mTimer.stop(); return; } // The condition is that the folder must be unused (not open) // But first we ask search folders to release their access to it kmkernel->searchFolderMgr()->tryReleasingFolder( (*it)->folder() ); #ifdef DEBUG_SCHEDULER kdDebug(5006) << " looking at folder " << (*it)->folder()->label() << " " << (*it)->folder()->location() << " isOpened=" << (*it)->folder()->isOpened() << endl; #endif if ( !(*it)->folder()->isOpened() ) { task = *it; mTaskList.remove( it ); break; } } if ( !task ) // found nothing to run, i.e. folder was opened return; // Timer keeps running, i.e. try again in 1 minute runTaskNow( task ); if ( !mCurrentJob ) // nothing to do for that task slotRunNextJob(); // find another one } void JobScheduler::restartTimer() { #ifdef DEBUG_SCHEDULER mTimer.start( 10000 ); // 10 seconds #else mTimer.start( 1 * 60000 ); // 1 minute #endif } void JobScheduler::runTaskNow( ScheduledTask* task ) { if ( mCurrentTask ) { interruptCurrentTask(); } mCurrentTask = task; mTimer.stop(); mCurrentJob = mCurrentTask->run(); #ifdef DEBUG_SCHEDULER kdDebug(5006) << "JobScheduler: task " << mCurrentTask << " for folder " << mCurrentTask->folder()->label() << " returned job " << mCurrentJob << " " << ( mCurrentJob?mCurrentJob->className():0 ) << endl; #endif if ( !mCurrentJob ) { // nothing to do, e.g. folder deleted delete mCurrentTask; mCurrentTask = 0; if ( !mTaskList.isEmpty() ) restartTimer(); return; } // Register the job in the folder. This makes it autodeleted if the folder is deleted. mCurrentTask->folder()->storage()->addJob( mCurrentJob ); connect( mCurrentJob, SIGNAL( finished() ), this, SLOT( slotJobFinished() ) ); mIgnoreOpenNotify = true; // Obviously we'll have to open the folder ourselves mCurrentJob->start(); mIgnoreOpenNotify = false; } void JobScheduler::slotJobFinished() { // Do we need to test for mCurrentJob->error()? What do we do then? #ifdef DEBUG_SCHEDULER kdDebug(5006) << "JobScheduler: slotJobFinished" << endl; #endif delete mCurrentTask; mCurrentTask = 0; mCurrentJob = 0; if ( !mTaskList.isEmpty() ) restartTimer(); } #include "jobscheduler.moc" <commit_msg>CVS_SILENT debug<commit_after>/** * Copyright (c) 2004 David Faure <faure@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; version 2 of the License * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "jobscheduler.h" #include "kmfolder.h" #include "folderstorage.h" #include "kmfoldermgr.h" #include <kdebug.h> using namespace KMail; JobScheduler::JobScheduler( QObject* parent, const char* name ) : QObject( parent, name ), mTimer( this ), mCurrentTask( 0 ), mCurrentJob( 0 ), mIgnoreOpenNotify( false ) { connect( &mTimer, SIGNAL( timeout() ), SLOT( slotRunNextJob() ) ); // No need to start the internal timer yet, we wait for a task to be scheduled } JobScheduler::~JobScheduler() { // delete tasks in tasklist (no autodelete for QValueList) for( QValueList<ScheduledTask *>::Iterator it = mTaskList.begin(); it != mTaskList.end(); ++it ) { delete (*it); } delete mCurrentTask; delete mCurrentJob; } void JobScheduler::registerTask( ScheduledTask* task ) { int typeId = task->taskTypeId(); if ( typeId ) { KMFolder* folder = task->folder(); // Search for an identical task already scheduled for( QValueList<ScheduledTask *>::ConstIterator it = mTaskList.begin(); it != mTaskList.end(); ++it ) { if ( (*it)->taskTypeId() == typeId && (*it)->folder() == folder ) { #ifdef DEBUG_SCHEDULER kdDebug(5006) << "JobScheduler: already having task type " << typeId << " for folder " << folder->label() << endl; #endif delete task; return; } } // Note that scheduling an identical task as the one currently running is allowed. } #ifdef DEBUG_SCHEDULER kdDebug(5006) << "JobScheduler: adding task " << task << " (type " << task->taskTypeId() << ") for folder " << task->folder() << " " << task->folder()->label() << endl; #endif mTaskList.append( task ); if ( !mTimer.isActive() ) restartTimer(); } void JobScheduler::notifyOpeningFolder( KMFolder* folder ) { if ( mCurrentTask && mCurrentTask->folder() == folder ) { if ( mIgnoreOpenNotify ) { // set when starting a job for this folder #ifdef DEBUG_SCHEDULER kdDebug(5006) << "JobScheduler: got the opening-notification for " << folder->label() << " as expected." << endl; #endif mIgnoreOpenNotify = false; } else { // Jobs scheduled from here should always be cancellable. // One exception though, is when ExpireJob does its final KMMoveCommand. // Then that command shouldn't kill its own parent job just because it opens a folder... if ( mCurrentJob->isCancellable() ) interruptCurrentTask(); } } } void JobScheduler::interruptCurrentTask() { Q_ASSERT( mCurrentTask ); #ifdef DEBUG_SCHEDULER kdDebug(5006) << "JobScheduler: interrupting job " << mCurrentJob << " for folder " << mCurrentTask->folder()->label() << endl; #endif // File it again. This will either delete it or put it in mTaskList. registerTask( mCurrentTask ); mCurrentTask = 0; mCurrentJob->kill(); // This deletes the job and calls slotJobFinished! } void JobScheduler::slotRunNextJob() { #ifdef DEBUG_SCHEDULER kdDebug(5006) << "JobScheduler: slotRunNextJob" << endl; #endif Q_ASSERT( mCurrentTask == 0 ); ScheduledTask* task = 0; // Find a task suitable for being run for( QValueList<ScheduledTask *>::Iterator it = mTaskList.begin(); it != mTaskList.end(); ++it ) { // Remove if folder died if ( (*it)->folder() == 0 ) { #ifdef DEBUG_SCHEDULER kdDebug(5006) << " folder for task " << (*it) << " was deleted" << endl; #endif mTaskList.remove( it ); if ( !mTaskList.isEmpty() ) slotRunNextJob(); // to avoid the mess with invalid iterators :) else mTimer.stop(); return; } // The condition is that the folder must be unused (not open) // But first we ask search folders to release their access to it kmkernel->searchFolderMgr()->tryReleasingFolder( (*it)->folder() ); #ifdef DEBUG_SCHEDULER kdDebug(5006) << " looking at folder " << (*it)->folder()->label() << " " << (*it)->folder()->location() << " isOpened=" << (*it)->folder()->isOpened() << endl; #endif if ( !(*it)->folder()->isOpened() ) { task = *it; mTaskList.remove( it ); break; } } if ( !task ) // found nothing to run, i.e. folder was opened return; // Timer keeps running, i.e. try again in 1 minute runTaskNow( task ); if ( !mCurrentJob ) // nothing to do for that task slotRunNextJob(); // find another one } void JobScheduler::restartTimer() { #ifdef DEBUG_SCHEDULER mTimer.start( 10000 ); // 10 seconds #else mTimer.start( 1 * 60000 ); // 1 minute #endif } void JobScheduler::runTaskNow( ScheduledTask* task ) { if ( mCurrentTask ) { interruptCurrentTask(); } mCurrentTask = task; mTimer.stop(); mCurrentJob = mCurrentTask->run(); #ifdef DEBUG_SCHEDULER kdDebug(5006) << "JobScheduler: task " << mCurrentTask << " (type " << mCurrentTask->taskTypeId() << ")" << " for folder " << mCurrentTask->folder()->label() << " returned job " << mCurrentJob << " " << ( mCurrentJob?mCurrentJob->className():0 ) << endl; #endif if ( !mCurrentJob ) { // nothing to do, e.g. folder deleted delete mCurrentTask; mCurrentTask = 0; if ( !mTaskList.isEmpty() ) restartTimer(); return; } // Register the job in the folder. This makes it autodeleted if the folder is deleted. mCurrentTask->folder()->storage()->addJob( mCurrentJob ); connect( mCurrentJob, SIGNAL( finished() ), this, SLOT( slotJobFinished() ) ); mIgnoreOpenNotify = true; // Obviously we'll have to open the folder ourselves mCurrentJob->start(); mIgnoreOpenNotify = false; } void JobScheduler::slotJobFinished() { // Do we need to test for mCurrentJob->error()? What do we do then? #ifdef DEBUG_SCHEDULER kdDebug(5006) << "JobScheduler: slotJobFinished" << endl; #endif delete mCurrentTask; mCurrentTask = 0; mCurrentJob = 0; if ( !mTaskList.isEmpty() ) restartTimer(); } #include "jobscheduler.moc" <|endoftext|>
<commit_before>/* knserverinfo.cpp KNode, the KDE newsreader Copyright (c) 1999-2001 the KNode authors. See file AUTHORS for details 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US */ #include "knserverinfo.h" #include "utilities.h" #include <kmessagebox.h> #include <kconfig.h> #include <klocale.h> #include <kdebug.h> #include <kwallet.h> using namespace KWallet; KNServerInfo::KNServerInfo() : t_ype(STnntp), i_d(-1), p_ort(119), h_old(300), t_imeout(60), n_eedsLogon(false) { } KNServerInfo::~KNServerInfo() { } void KNServerInfo::readConf(KConfig *conf) { s_erver=conf->readEntry("server", "localhost"); if(t_ype==STnntp) p_ort=conf->readNumEntry("port", 119); else p_ort=conf->readNumEntry("port", 25); h_old=conf->readNumEntry("holdTime", 300); if(h_old < 0) h_old=0; t_imeout=conf->readNumEntry("timeout", 60); if(t_imeout < 15) t_imeout=15; if(t_ype==STnntp) { i_d=conf->readNumEntry("id", -1); n_eedsLogon=conf->readBoolEntry("needsLogon",false); u_ser=conf->readEntry("user"); Wallet* wallet = openWallet(); if ( !wallet || wallet->readPassword( s_erver, p_ass ) ) { p_ass = KNHelper::decryptStr(conf->readEntry("pass")); conf->deleteEntry("pass"); //Save the pass in wallet as this might be the first time it's used if ( wallet ) wallet->writePassword( s_erver, p_ass ); } } } Wallet* KNServerInfo::openWallet() { QString networkWallet = Wallet::NetworkWallet(); Wallet* wallet = Wallet::openWallet(networkWallet); if ( !wallet->hasFolder("knode") ) wallet->createFolder("knode"); wallet->setFolder("knode"); return wallet; } void KNServerInfo::saveConf(KConfig *conf) { conf->writeEntry("server", s_erver); conf->writeEntry("port", p_ort); conf->writeEntry("holdTime", h_old); conf->writeEntry("timeout", t_imeout); if (t_ype==STnntp) { conf->writeEntry("id", i_d); conf->writeEntry("needsLogon", n_eedsLogon); conf->writeEntry("user", u_ser); Wallet* wallet = openWallet(); if ( wallet->writePassword( s_erver, p_ass ) ) { KMessageBox::information( 0, i18n( "KWallet isn't running. We strongly recommend using " "KWallet for managing your password" ) ); conf->writeEntry("pass", KNHelper::encryptStr(p_ass)); } } } bool KNServerInfo::operator==(const KNServerInfo &s) { return ( (t_ype==s.t_ype) && (s_erver==s.s_erver) && (p_ort==s.p_ort) && (h_old==s.h_old) && (t_imeout==s.t_imeout) && (n_eedsLogon==s.n_eedsLogon) && (u_ser==s.u_ser) && (p_ass==s.p_ass) ); } <commit_msg>Don't crash. Remember to remind George that it shouldn't be failing silently :)<commit_after>/* knserverinfo.cpp KNode, the KDE newsreader Copyright (c) 1999-2001 the KNode authors. See file AUTHORS for details 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US */ #include "knserverinfo.h" #include "utilities.h" #include <kmessagebox.h> #include <kconfig.h> #include <klocale.h> #include <kdebug.h> #include <kwallet.h> using namespace KWallet; KNServerInfo::KNServerInfo() : t_ype(STnntp), i_d(-1), p_ort(119), h_old(300), t_imeout(60), n_eedsLogon(false) { } KNServerInfo::~KNServerInfo() { } void KNServerInfo::readConf(KConfig *conf) { s_erver=conf->readEntry("server", "localhost"); if(t_ype==STnntp) p_ort=conf->readNumEntry("port", 119); else p_ort=conf->readNumEntry("port", 25); h_old=conf->readNumEntry("holdTime", 300); if(h_old < 0) h_old=0; t_imeout=conf->readNumEntry("timeout", 60); if(t_imeout < 15) t_imeout=15; if(t_ype==STnntp) { i_d=conf->readNumEntry("id", -1); n_eedsLogon=conf->readBoolEntry("needsLogon",false); u_ser=conf->readEntry("user"); Wallet* wallet = openWallet(); if ( !wallet || wallet->readPassword( s_erver, p_ass ) ) { p_ass = KNHelper::decryptStr(conf->readEntry("pass")); conf->deleteEntry("pass"); //Save the pass in wallet as this might be the first time it's used if ( wallet ) wallet->writePassword( s_erver, p_ass ); } } } Wallet* KNServerInfo::openWallet() { QString networkWallet = Wallet::NetworkWallet(); Wallet* wallet = Wallet::openWallet(networkWallet); if ( !wallet ) { KMessageBox::error( 0, i18n("The wallet couldn't be opened " "This error is most probably caused " "by providing a wrong password.") ); return 0; } if ( wallet && !wallet->hasFolder("knode") ) wallet->createFolder("knode"); wallet->setFolder("knode"); return wallet; } void KNServerInfo::saveConf(KConfig *conf) { conf->writeEntry("server", s_erver); conf->writeEntry("port", p_ort); conf->writeEntry("holdTime", h_old); conf->writeEntry("timeout", t_imeout); if (t_ype==STnntp) { conf->writeEntry("id", i_d); conf->writeEntry("needsLogon", n_eedsLogon); conf->writeEntry("user", u_ser); Wallet* wallet = openWallet(); if ( !wallet || wallet->writePassword( s_erver, p_ass ) ) { KMessageBox::information( 0, i18n( "KWallet isn't running. We strongly recommend using " "KWallet for managing your password" ) ); conf->writeEntry("pass", KNHelper::encryptStr(p_ass)); } } } bool KNServerInfo::operator==(const KNServerInfo &s) { return ( (t_ype==s.t_ype) && (s_erver==s.s_erver) && (p_ort==s.p_ort) && (h_old==s.h_old) && (t_imeout==s.t_imeout) && (n_eedsLogon==s.n_eedsLogon) && (u_ser==s.u_ser) && (p_ass==s.p_ass) ); } <|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/views/bookmark_bubble_view.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/keyboard_codes.h" #include "base/string_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/bookmarks/bookmark_editor.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/bookmarks/bookmark_utils.h" #include "chrome/browser/metrics/user_metrics.h" #include "chrome/browser/profile.h" #include "chrome/browser/views/info_bubble.h" #include "chrome/common/notification_service.h" #include "gfx/canvas.h" #include "gfx/color_utils.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "views/event.h" #include "views/standard_layout.h" #include "views/controls/button/native_button.h" #include "views/controls/textfield/textfield.h" #include "views/focus/focus_manager.h" #include "views/window/client_view.h" #include "views/window/window.h" using views::Combobox; using views::ColumnSet; using views::GridLayout; using views::Label; using views::Link; using views::NativeButton; using views::View; // Padding between "Title:" and the actual title. static const int kTitlePadding = 4; // Minimum width for the fields - they will push out the size of the bubble if // necessary. This should be big enough so that the field pushes the right side // of the bubble far enough so that the edit button's left edge is to the right // of the field's left edge. static const int kMinimumFieldSize = 180; // Bubble close image. static SkBitmap* kCloseImage = NULL; // Declared in browser_dialogs.h so callers don't have to depend on our header. namespace browser { void ShowBookmarkBubbleView(views::Window* parent, const gfx::Rect& bounds, InfoBubbleDelegate* delegate, Profile* profile, const GURL& url, bool newly_bookmarked) { BookmarkBubbleView::Show(parent, bounds, delegate, profile, url, newly_bookmarked); } void HideBookmarkBubbleView() { BookmarkBubbleView::Hide(); } bool IsBookmarkBubbleViewShowing() { return BookmarkBubbleView::IsShowing(); } } // namespace browser // BookmarkBubbleView --------------------------------------------------------- BookmarkBubbleView* BookmarkBubbleView::bubble_ = NULL; // static void BookmarkBubbleView::Show(views::Window* parent, const gfx::Rect& bounds, InfoBubbleDelegate* delegate, Profile* profile, const GURL& url, bool newly_bookmarked) { if (IsShowing()) return; bubble_ = new BookmarkBubbleView(delegate, profile, url, newly_bookmarked); InfoBubble* info_bubble = InfoBubble::Show(parent->GetClientView()->GetWidget(), bounds, BubbleBorder::TOP_LEFT, bubble_, bubble_); bubble_->set_info_bubble(info_bubble); GURL url_ptr(url); NotificationService::current()->Notify( NotificationType::BOOKMARK_BUBBLE_SHOWN, Source<Profile>(profile->GetOriginalProfile()), Details<GURL>(&url_ptr)); bubble_->BubbleShown(); } // static bool BookmarkBubbleView::IsShowing() { return bubble_ != NULL; } void BookmarkBubbleView::Hide() { if (IsShowing()) bubble_->Close(); } BookmarkBubbleView::~BookmarkBubbleView() { if (apply_edits_) { ApplyEdits(); } else if (remove_bookmark_) { BookmarkModel* model = profile_->GetBookmarkModel(); const BookmarkNode* node = model->GetMostRecentlyAddedNodeForURL(url_); if (node) model->Remove(node->GetParent(), node->GetParent()->IndexOfChild(node)); } } void BookmarkBubbleView::DidChangeBounds(const gfx::Rect& previous, const gfx::Rect& current) { Layout(); } void BookmarkBubbleView::BubbleShown() { DCHECK(GetWidget()); GetFocusManager()->RegisterAccelerator( views::Accelerator(base::VKEY_RETURN, false, false, false), this); title_tf_->RequestFocus(); title_tf_->SelectAll(); } bool BookmarkBubbleView::AcceleratorPressed( const views::Accelerator& accelerator) { if (accelerator.GetKeyCode() != base::VKEY_RETURN) return false; if (edit_button_->HasFocus()) HandleButtonPressed(edit_button_); else HandleButtonPressed(close_button_); return true; } void BookmarkBubbleView::ViewHierarchyChanged(bool is_add, View* parent, View* child) { if (is_add && child == this) Init(); } BookmarkBubbleView::BookmarkBubbleView(InfoBubbleDelegate* delegate, Profile* profile, const GURL& url, bool newly_bookmarked) : delegate_(delegate), profile_(profile), url_(url), newly_bookmarked_(newly_bookmarked), parent_model_( profile_->GetBookmarkModel(), profile_->GetBookmarkModel()->GetMostRecentlyAddedNodeForURL(url)), remove_bookmark_(false), apply_edits_(true) { } void BookmarkBubbleView::Init() { static SkColor kTitleColor; static bool initialized = false; if (!initialized) { kTitleColor = color_utils::GetReadableColor(SkColorSetRGB(6, 45, 117), InfoBubble::kBackgroundColor); kCloseImage = ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_INFO_BUBBLE_CLOSE); initialized = true; } remove_link_ = new Link(l10n_util::GetString( IDS_BOOMARK_BUBBLE_REMOVE_BOOKMARK)); remove_link_->SetController(this); edit_button_ = new NativeButton( this, l10n_util::GetString(IDS_BOOMARK_BUBBLE_OPTIONS)); close_button_ = new NativeButton(this, l10n_util::GetString(IDS_DONE)); close_button_->SetIsDefault(true); Label* combobox_label = new Label( l10n_util::GetString(IDS_BOOMARK_BUBBLE_FOLDER_TEXT)); parent_combobox_ = new Combobox(&parent_model_); parent_combobox_->SetSelectedItem(parent_model_.node_parent_index()); parent_combobox_->set_listener(this); parent_combobox_->SetAccessibleName(combobox_label->GetText()); Label* title_label = new Label(l10n_util::GetString( newly_bookmarked_ ? IDS_BOOMARK_BUBBLE_PAGE_BOOKMARKED : IDS_BOOMARK_BUBBLE_PAGE_BOOKMARK)); title_label->SetFont( ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::MediumFont)); title_label->SetColor(kTitleColor); GridLayout* layout = new GridLayout(this); SetLayoutManager(layout); ColumnSet* cs = layout->AddColumnSet(0); // Top (title) row. cs->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); cs->AddPaddingColumn(1, kUnrelatedControlHorizontalSpacing); cs->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); // Middle (input field) rows. cs = layout->AddColumnSet(2); cs->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); cs->AddPaddingColumn(0, kRelatedControlHorizontalSpacing); cs->AddColumn(GridLayout::FILL, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, kMinimumFieldSize); // Bottom (buttons) row. cs = layout->AddColumnSet(3); cs->AddPaddingColumn(1, kRelatedControlHorizontalSpacing); cs->AddColumn(GridLayout::LEADING, GridLayout::TRAILING, 0, GridLayout::USE_PREF, 0, 0); // We subtract 2 to account for the natural button padding, and // to bring the separation visually in line with the row separation // height. cs->AddPaddingColumn(0, kRelatedButtonHSpacing - 2); cs->AddColumn(GridLayout::LEADING, GridLayout::TRAILING, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, 0); layout->AddView(title_label); layout->AddView(remove_link_); layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing); layout->StartRow(0, 2); layout->AddView( new Label(l10n_util::GetString(IDS_BOOMARK_BUBBLE_TITLE_TEXT))); title_tf_ = new views::Textfield(); title_tf_->SetText(WideToUTF16(GetTitle())); layout->AddView(title_tf_); layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing); layout->StartRow(0, 2); layout->AddView(combobox_label); layout->AddView(parent_combobox_); layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing); layout->StartRow(0, 3); layout->AddView(edit_button_); layout->AddView(close_button_); } std::wstring BookmarkBubbleView::GetTitle() { BookmarkModel* bookmark_model= profile_->GetBookmarkModel(); const BookmarkNode* node = bookmark_model->GetMostRecentlyAddedNodeForURL(url_); if (node) return node->GetTitle(); else NOTREACHED(); return std::wstring(); } void BookmarkBubbleView::ButtonPressed( views::Button* sender, const views::Event& event) { HandleButtonPressed(sender); } void BookmarkBubbleView::LinkActivated(Link* source, int event_flags) { DCHECK(source == remove_link_); UserMetrics::RecordAction(UserMetricsAction("BookmarkBubble_Unstar"), profile_); // Set this so we remove the bookmark after the window closes. remove_bookmark_ = true; apply_edits_ = false; info_bubble_->set_fade_away_on_close(true); Close(); } void BookmarkBubbleView::ItemChanged(Combobox* combobox, int prev_index, int new_index) { if (new_index + 1 == parent_model_.GetItemCount()) { UserMetrics::RecordAction( UserMetricsAction("BookmarkBubble_EditFromCombobox"), profile_); ShowEditor(); return; } } void BookmarkBubbleView::InfoBubbleClosing(InfoBubble* info_bubble, bool closed_by_escape) { if (closed_by_escape) { remove_bookmark_ = newly_bookmarked_; apply_edits_ = false; } // We have to reset |bubble_| here, not in our destructor, because we'll be // destroyed asynchronously and the shown state will be checked before then. DCHECK(bubble_ == this); bubble_ = NULL; if (delegate_) delegate_->InfoBubbleClosing(info_bubble, closed_by_escape); NotificationService::current()->Notify( NotificationType::BOOKMARK_BUBBLE_HIDDEN, Source<Profile>(profile_->GetOriginalProfile()), NotificationService::NoDetails()); } bool BookmarkBubbleView::CloseOnEscape() { return delegate_ ? delegate_->CloseOnEscape() : true; } std::wstring BookmarkBubbleView::accessible_name() { return l10n_util::GetString(IDS_BOOMARK_BUBBLE_ADD_BOOKMARK); } void BookmarkBubbleView::Close() { static_cast<InfoBubble*>(GetWidget())->Close(); } void BookmarkBubbleView::HandleButtonPressed(views::Button* sender) { if (sender == edit_button_) { UserMetrics::RecordAction(UserMetricsAction("BookmarkBubble_Edit"), profile_); info_bubble_->set_fade_away_on_close(true); ShowEditor(); } else { DCHECK(sender == close_button_); info_bubble_->set_fade_away_on_close(true); Close(); } // WARNING: we've most likely been deleted when CloseWindow returns. } void BookmarkBubbleView::ShowEditor() { const BookmarkNode* node = profile_->GetBookmarkModel()->GetMostRecentlyAddedNodeForURL(url_); // Commit any edits now. ApplyEdits(); #if defined(OS_WIN) // Parent the editor to our root ancestor (not the root we're in, as that // is the info bubble and will close shortly). HWND parent = GetAncestor(GetWidget()->GetNativeView(), GA_ROOTOWNER); // We're about to show the bookmark editor. When the bookmark editor closes // we want the browser to become active. WidgetWin::Hide() does a hide in // a such way that activation isn't changed, which means when we close // Windows gets confused as to who it should give active status to. We // explicitly hide the bookmark bubble window in such a way that activation // status changes. That way, when the editor closes, activation is properly // restored to the browser. ShowWindow(GetWidget()->GetNativeView(), SW_HIDE); #else gfx::NativeWindow parent = GTK_WINDOW( static_cast<views::WidgetGtk*>(GetWidget())->GetTransientParent()); #endif // Even though we just hid the window, we need to invoke Close to schedule // the delete and all that. Close(); if (node) { BookmarkEditor::Show(parent, profile_, NULL, BookmarkEditor::EditDetails(node), BookmarkEditor::SHOW_TREE); } } void BookmarkBubbleView::ApplyEdits() { // Set this to make sure we don't attempt to apply edits again. apply_edits_ = false; BookmarkModel* model = profile_->GetBookmarkModel(); const BookmarkNode* node = model->GetMostRecentlyAddedNodeForURL(url_); if (node) { const std::wstring new_title = UTF16ToWide(title_tf_->text()); if (new_title != node->GetTitle()) { model->SetTitle(node, new_title); UserMetrics::RecordAction( UserMetricsAction("BookmarkBubble_ChangeTitleInBubble"), profile_); } // Last index means 'Choose another folder...' if (parent_combobox_->selected_item() < parent_model_.GetItemCount() - 1) { const BookmarkNode* new_parent = parent_model_.GetNodeAt(parent_combobox_->selected_item()); if (new_parent != node->GetParent()) { UserMetrics::RecordAction( UserMetricsAction("BookmarkBubble_ChangeParent"), profile_); model->Move(node, new_parent, new_parent->GetChildCount()); } } } } <commit_msg>Makes the bookmark bubble right aligned.<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/views/bookmark_bubble_view.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/keyboard_codes.h" #include "base/string_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/bookmarks/bookmark_editor.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/bookmarks/bookmark_utils.h" #include "chrome/browser/metrics/user_metrics.h" #include "chrome/browser/profile.h" #include "chrome/browser/views/info_bubble.h" #include "chrome/common/notification_service.h" #include "gfx/canvas.h" #include "gfx/color_utils.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "views/event.h" #include "views/standard_layout.h" #include "views/controls/button/native_button.h" #include "views/controls/textfield/textfield.h" #include "views/focus/focus_manager.h" #include "views/window/client_view.h" #include "views/window/window.h" using views::Combobox; using views::ColumnSet; using views::GridLayout; using views::Label; using views::Link; using views::NativeButton; using views::View; // Padding between "Title:" and the actual title. static const int kTitlePadding = 4; // Minimum width for the fields - they will push out the size of the bubble if // necessary. This should be big enough so that the field pushes the right side // of the bubble far enough so that the edit button's left edge is to the right // of the field's left edge. static const int kMinimumFieldSize = 180; // Bubble close image. static SkBitmap* kCloseImage = NULL; // Declared in browser_dialogs.h so callers don't have to depend on our header. namespace browser { void ShowBookmarkBubbleView(views::Window* parent, const gfx::Rect& bounds, InfoBubbleDelegate* delegate, Profile* profile, const GURL& url, bool newly_bookmarked) { BookmarkBubbleView::Show(parent, bounds, delegate, profile, url, newly_bookmarked); } void HideBookmarkBubbleView() { BookmarkBubbleView::Hide(); } bool IsBookmarkBubbleViewShowing() { return BookmarkBubbleView::IsShowing(); } } // namespace browser // BookmarkBubbleView --------------------------------------------------------- BookmarkBubbleView* BookmarkBubbleView::bubble_ = NULL; // static void BookmarkBubbleView::Show(views::Window* parent, const gfx::Rect& bounds, InfoBubbleDelegate* delegate, Profile* profile, const GURL& url, bool newly_bookmarked) { if (IsShowing()) return; bubble_ = new BookmarkBubbleView(delegate, profile, url, newly_bookmarked); InfoBubble* info_bubble = InfoBubble::Show(parent->GetClientView()->GetWidget(), bounds, BubbleBorder::TOP_RIGHT, bubble_, bubble_); bubble_->set_info_bubble(info_bubble); GURL url_ptr(url); NotificationService::current()->Notify( NotificationType::BOOKMARK_BUBBLE_SHOWN, Source<Profile>(profile->GetOriginalProfile()), Details<GURL>(&url_ptr)); bubble_->BubbleShown(); } // static bool BookmarkBubbleView::IsShowing() { return bubble_ != NULL; } void BookmarkBubbleView::Hide() { if (IsShowing()) bubble_->Close(); } BookmarkBubbleView::~BookmarkBubbleView() { if (apply_edits_) { ApplyEdits(); } else if (remove_bookmark_) { BookmarkModel* model = profile_->GetBookmarkModel(); const BookmarkNode* node = model->GetMostRecentlyAddedNodeForURL(url_); if (node) model->Remove(node->GetParent(), node->GetParent()->IndexOfChild(node)); } } void BookmarkBubbleView::DidChangeBounds(const gfx::Rect& previous, const gfx::Rect& current) { Layout(); } void BookmarkBubbleView::BubbleShown() { DCHECK(GetWidget()); GetFocusManager()->RegisterAccelerator( views::Accelerator(base::VKEY_RETURN, false, false, false), this); title_tf_->RequestFocus(); title_tf_->SelectAll(); } bool BookmarkBubbleView::AcceleratorPressed( const views::Accelerator& accelerator) { if (accelerator.GetKeyCode() != base::VKEY_RETURN) return false; if (edit_button_->HasFocus()) HandleButtonPressed(edit_button_); else HandleButtonPressed(close_button_); return true; } void BookmarkBubbleView::ViewHierarchyChanged(bool is_add, View* parent, View* child) { if (is_add && child == this) Init(); } BookmarkBubbleView::BookmarkBubbleView(InfoBubbleDelegate* delegate, Profile* profile, const GURL& url, bool newly_bookmarked) : delegate_(delegate), profile_(profile), url_(url), newly_bookmarked_(newly_bookmarked), parent_model_( profile_->GetBookmarkModel(), profile_->GetBookmarkModel()->GetMostRecentlyAddedNodeForURL(url)), remove_bookmark_(false), apply_edits_(true) { } void BookmarkBubbleView::Init() { static SkColor kTitleColor; static bool initialized = false; if (!initialized) { kTitleColor = color_utils::GetReadableColor(SkColorSetRGB(6, 45, 117), InfoBubble::kBackgroundColor); kCloseImage = ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_INFO_BUBBLE_CLOSE); initialized = true; } remove_link_ = new Link(l10n_util::GetString( IDS_BOOMARK_BUBBLE_REMOVE_BOOKMARK)); remove_link_->SetController(this); edit_button_ = new NativeButton( this, l10n_util::GetString(IDS_BOOMARK_BUBBLE_OPTIONS)); close_button_ = new NativeButton(this, l10n_util::GetString(IDS_DONE)); close_button_->SetIsDefault(true); Label* combobox_label = new Label( l10n_util::GetString(IDS_BOOMARK_BUBBLE_FOLDER_TEXT)); parent_combobox_ = new Combobox(&parent_model_); parent_combobox_->SetSelectedItem(parent_model_.node_parent_index()); parent_combobox_->set_listener(this); parent_combobox_->SetAccessibleName(combobox_label->GetText()); Label* title_label = new Label(l10n_util::GetString( newly_bookmarked_ ? IDS_BOOMARK_BUBBLE_PAGE_BOOKMARKED : IDS_BOOMARK_BUBBLE_PAGE_BOOKMARK)); title_label->SetFont( ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::MediumFont)); title_label->SetColor(kTitleColor); GridLayout* layout = new GridLayout(this); SetLayoutManager(layout); ColumnSet* cs = layout->AddColumnSet(0); // Top (title) row. cs->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); cs->AddPaddingColumn(1, kUnrelatedControlHorizontalSpacing); cs->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); // Middle (input field) rows. cs = layout->AddColumnSet(2); cs->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); cs->AddPaddingColumn(0, kRelatedControlHorizontalSpacing); cs->AddColumn(GridLayout::FILL, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, kMinimumFieldSize); // Bottom (buttons) row. cs = layout->AddColumnSet(3); cs->AddPaddingColumn(1, kRelatedControlHorizontalSpacing); cs->AddColumn(GridLayout::LEADING, GridLayout::TRAILING, 0, GridLayout::USE_PREF, 0, 0); // We subtract 2 to account for the natural button padding, and // to bring the separation visually in line with the row separation // height. cs->AddPaddingColumn(0, kRelatedButtonHSpacing - 2); cs->AddColumn(GridLayout::LEADING, GridLayout::TRAILING, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, 0); layout->AddView(title_label); layout->AddView(remove_link_); layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing); layout->StartRow(0, 2); layout->AddView( new Label(l10n_util::GetString(IDS_BOOMARK_BUBBLE_TITLE_TEXT))); title_tf_ = new views::Textfield(); title_tf_->SetText(WideToUTF16(GetTitle())); layout->AddView(title_tf_); layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing); layout->StartRow(0, 2); layout->AddView(combobox_label); layout->AddView(parent_combobox_); layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing); layout->StartRow(0, 3); layout->AddView(edit_button_); layout->AddView(close_button_); } std::wstring BookmarkBubbleView::GetTitle() { BookmarkModel* bookmark_model= profile_->GetBookmarkModel(); const BookmarkNode* node = bookmark_model->GetMostRecentlyAddedNodeForURL(url_); if (node) return node->GetTitle(); else NOTREACHED(); return std::wstring(); } void BookmarkBubbleView::ButtonPressed( views::Button* sender, const views::Event& event) { HandleButtonPressed(sender); } void BookmarkBubbleView::LinkActivated(Link* source, int event_flags) { DCHECK(source == remove_link_); UserMetrics::RecordAction(UserMetricsAction("BookmarkBubble_Unstar"), profile_); // Set this so we remove the bookmark after the window closes. remove_bookmark_ = true; apply_edits_ = false; info_bubble_->set_fade_away_on_close(true); Close(); } void BookmarkBubbleView::ItemChanged(Combobox* combobox, int prev_index, int new_index) { if (new_index + 1 == parent_model_.GetItemCount()) { UserMetrics::RecordAction( UserMetricsAction("BookmarkBubble_EditFromCombobox"), profile_); ShowEditor(); return; } } void BookmarkBubbleView::InfoBubbleClosing(InfoBubble* info_bubble, bool closed_by_escape) { if (closed_by_escape) { remove_bookmark_ = newly_bookmarked_; apply_edits_ = false; } // We have to reset |bubble_| here, not in our destructor, because we'll be // destroyed asynchronously and the shown state will be checked before then. DCHECK(bubble_ == this); bubble_ = NULL; if (delegate_) delegate_->InfoBubbleClosing(info_bubble, closed_by_escape); NotificationService::current()->Notify( NotificationType::BOOKMARK_BUBBLE_HIDDEN, Source<Profile>(profile_->GetOriginalProfile()), NotificationService::NoDetails()); } bool BookmarkBubbleView::CloseOnEscape() { return delegate_ ? delegate_->CloseOnEscape() : true; } std::wstring BookmarkBubbleView::accessible_name() { return l10n_util::GetString(IDS_BOOMARK_BUBBLE_ADD_BOOKMARK); } void BookmarkBubbleView::Close() { static_cast<InfoBubble*>(GetWidget())->Close(); } void BookmarkBubbleView::HandleButtonPressed(views::Button* sender) { if (sender == edit_button_) { UserMetrics::RecordAction(UserMetricsAction("BookmarkBubble_Edit"), profile_); info_bubble_->set_fade_away_on_close(true); ShowEditor(); } else { DCHECK(sender == close_button_); info_bubble_->set_fade_away_on_close(true); Close(); } // WARNING: we've most likely been deleted when CloseWindow returns. } void BookmarkBubbleView::ShowEditor() { const BookmarkNode* node = profile_->GetBookmarkModel()->GetMostRecentlyAddedNodeForURL(url_); // Commit any edits now. ApplyEdits(); #if defined(OS_WIN) // Parent the editor to our root ancestor (not the root we're in, as that // is the info bubble and will close shortly). HWND parent = GetAncestor(GetWidget()->GetNativeView(), GA_ROOTOWNER); // We're about to show the bookmark editor. When the bookmark editor closes // we want the browser to become active. WidgetWin::Hide() does a hide in // a such way that activation isn't changed, which means when we close // Windows gets confused as to who it should give active status to. We // explicitly hide the bookmark bubble window in such a way that activation // status changes. That way, when the editor closes, activation is properly // restored to the browser. ShowWindow(GetWidget()->GetNativeView(), SW_HIDE); #else gfx::NativeWindow parent = GTK_WINDOW( static_cast<views::WidgetGtk*>(GetWidget())->GetTransientParent()); #endif // Even though we just hid the window, we need to invoke Close to schedule // the delete and all that. Close(); if (node) { BookmarkEditor::Show(parent, profile_, NULL, BookmarkEditor::EditDetails(node), BookmarkEditor::SHOW_TREE); } } void BookmarkBubbleView::ApplyEdits() { // Set this to make sure we don't attempt to apply edits again. apply_edits_ = false; BookmarkModel* model = profile_->GetBookmarkModel(); const BookmarkNode* node = model->GetMostRecentlyAddedNodeForURL(url_); if (node) { const std::wstring new_title = UTF16ToWide(title_tf_->text()); if (new_title != node->GetTitle()) { model->SetTitle(node, new_title); UserMetrics::RecordAction( UserMetricsAction("BookmarkBubble_ChangeTitleInBubble"), profile_); } // Last index means 'Choose another folder...' if (parent_combobox_->selected_item() < parent_model_.GetItemCount() - 1) { const BookmarkNode* new_parent = parent_model_.GetNodeAt(parent_combobox_->selected_item()); if (new_parent != node->GetParent()) { UserMetrics::RecordAction( UserMetricsAction("BookmarkBubble_ChangeParent"), profile_); model->Move(node, new_parent, new_parent->GetChildCount()); } } } } <|endoftext|>
<commit_before>// ------------------------------------------------------------------- /// \file DstWriter.cxx /// \brief /// /// \author <justo.martin-albo@physics.ox.ac.uk> /// \date Creation: 11 Aug 2016 // ------------------------------------------------------------------- #include "DstWriter.h" #include <Ntuple/NtpMCEventRecord.h> #include <TTree.h> #include <TFile.h> #include <TBranch.h> DstWriter::DstWriter(): file_(0), tree_(0) { } DstWriter::~DstWriter() { CloseFile(); delete file_; } void DstWriter::OpenFile(const std::string& filename, const std::string& option) { // Close any previously opened file CloseFile(); // Create a new ROOT file returning false if something goes wrong file_ = new TFile(filename.c_str(), option.c_str()); // Create a tree and all its branches tree_ = new TTree("NdtfDst", "DUNE ND-TF GArTPC DST"); tree_->Branch("gmcrec", "genie::NtpMCEventRecord", &(entry_.gmcrec)); tree_->Branch("RunID", &(entry_.RunID), "RunID/I"); tree_->Branch("EventID", &(entry_.EventID), "EventID/I"); tree_->Branch("Sample", &(entry_.Sample), "Sample/I"); // tree_->Branch("Ev_reco", &Ev_reco, "Ev_reco/D"); // tree_->Branch("Ev", &Ev, "Ev/D"); // tree_->Branch("Y", &Y, "Y/D"); // tree_->Branch("Y_reco", &Y_reco, "Y_reco/D"); // tree_->Branch("VertexPosition", VertexPosition, "VertexPosition[4]/D"); // tree_->Branch("NGeantTracks", &NGeantTracks, "NGeantTracks/I"); // tree_->Branch("TrackID", TrackID, "TrackID[NGeantTracks]/I"); // tree_->Branch("Momentum", Momentum, "Momentum[NGeantTracks]/D"); // tree_->Branch("TotalEDep", TotalEDep, "TotalEDep[NGeantTracks]/D"); // tree_->Branch("Pdg", Pdg, "Pdg[NGeantTracks]/I"); // tree_->Branch("dEdx", dEdx, "dEdx[NGeantTracks]/D"); // tree_->Branch("NGeantHits", NGeantHits, "NGeantHits[NGeantTracks]/I"); //tree_->SetWeight(3.75E15); } void DstWriter::CloseFile() { if (this->IsFileOpen()) { file_->Write(); file_->Close(); } } void DstWriter::Write(DstEntry& entry) { entry_ = entry; tree_->Fill(); } bool DstWriter::IsFileOpen() const { if (!file_) return false; else return file_->IsOpen(); } <commit_msg>DstWriter: added branches.<commit_after>// ------------------------------------------------------------------- /// \file DstWriter.cxx /// \brief /// /// \author <justo.martin-albo@physics.ox.ac.uk> /// \date Creation: 11 Aug 2016 // ------------------------------------------------------------------- #include "DstWriter.h" #include <Ntuple/NtpMCEventRecord.h> #include <TTree.h> #include <TFile.h> #include <TBranch.h> DstWriter::DstWriter(): file_(0), tree_(0) { } DstWriter::~DstWriter() { CloseFile(); delete file_; } void DstWriter::OpenFile(const std::string& filename, const std::string& option) { // Close any previously opened file CloseFile(); // Create a new ROOT file returning false if something goes wrong file_ = new TFile(filename.c_str(), option.c_str()); // Create a tree and all its branches tree_ = new TTree("NdtfDst", "DUNE ND-TF GArTPC DST"); tree_->Branch("gmcrec", "genie::NtpMCEventRecord", &(entry_.gmcrec)); tree_->Branch("RunID", &(entry_.RunID), "RunID/I"); tree_->Branch("EventID", &(entry_.EventID), "EventID/I"); tree_->Branch("Sample", &(entry_.Sample), "Sample/I"); tree_->Branch("Ev", &(entry_.Ev), "Ev/D"); tree_->Branch("Ev_reco", &(entry_.Ev_reco), "Ev_reco/D"); tree_->Branch("Y", &(entry_.Y), "Y/D"); tree_->Branch("Y_reco", &(entry_.Y_reco), "Y_reco/D"); tree_->Branch("VertexPosition", entry_.VertexPosition, "VertexPosition[4]/D"); tree_->Branch("NTracks", &(entry_.NTracks), "NTracks/I"); // tree_->Branch("TrackID", TrackID, "TrackID[NGeantTracks]/I"); // tree_->Branch("Momentum", Momentum, "Momentum[NGeantTracks]/D"); // tree_->Branch("TotalEDep", TotalEDep, "TotalEDep[NGeantTracks]/D"); // tree_->Branch("Pdg", Pdg, "Pdg[NGeantTracks]/I"); // tree_->Branch("dEdx", dEdx, "dEdx[NGeantTracks]/D"); // tree_->Branch("NGeantHits", NGeantHits, "NGeantHits[NGeantTracks]/I"); //tree_->SetWeight(3.75E15); } void DstWriter::CloseFile() { if (this->IsFileOpen()) { file_->Write(); file_->Close(); } } void DstWriter::Write(DstEntry& entry) { entry_ = entry; tree_->Fill(); } bool DstWriter::IsFileOpen() const { if (!file_) return false; else return file_->IsOpen(); } <|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/test/logging/win/log_file_printer.h" #include <windows.h> #include <objbase.h> #include <ios> #include <iomanip> #include <ostream> #include <sstream> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/debug/trace_event.h" #include "base/logging.h" #include "base/string_number_conversions.h" #include "base/string_piece.h" #include "base/time.h" #include "chrome/test/logging/win/log_file_reader.h" namespace { // TODO(grt) This duplicates private behavior in base/logging.cc's // LogMessage::Init. That behavior should be exposed and used here (possibly // by moving this function to logging.cc, making it use log_severity_names, and // publishing it in logging.h with BASE_EXPORT). void WriteSeverityToStream(logging::LogSeverity severity, std::ostream* out) { switch (severity) { case logging::LOG_INFO: *out << "INFO"; break; case logging::LOG_WARNING: *out << "WARNING"; break; case logging::LOG_ERROR: *out << "ERROR"; break; case logging::LOG_ERROR_REPORT: *out << "ERROR_REPORT"; break; case logging::LOG_FATAL: *out << "FATAL"; break; default: if (severity < 0) *out << "VERBOSE" << -severity; else NOTREACHED(); break; } } // TODO(grt) This duplicates private behavior in base/logging.cc's // LogMessage::Init. That behavior should be exposed and used here (possibly // by moving this function to logging.cc and publishing it in logging.h with // BASE_EXPORT). void WriteLocationToStream(const base::StringPiece& file, int line, std::ostream* out) { base::StringPiece filename(file); size_t last_slash_pos = filename.find_last_of("\\/"); if (last_slash_pos != base::StringPiece::npos) filename.remove_prefix(last_slash_pos + 1); *out << filename << '(' << line << ')'; } // Returns a pretty string for the trace event types that appear in ETW logs. const char* GetTraceTypeString(char event_type) { switch (event_type) { case TRACE_EVENT_PHASE_BEGIN: return "BEGIN"; break; case TRACE_EVENT_PHASE_END: return "END"; break; case TRACE_EVENT_PHASE_INSTANT: return "INSTANT"; break; default: NOTREACHED(); return ""; break; } } class EventPrinter : public logging_win::LogFileDelegate { public: explicit EventPrinter(std::ostream* out); virtual ~EventPrinter(); virtual void OnUnknownEvent(const EVENT_TRACE* event) OVERRIDE; virtual void OnUnparsableEvent(const EVENT_TRACE* event) OVERRIDE; virtual void OnFileHeader(const EVENT_TRACE* event, const TRACE_LOGFILE_HEADER* header) OVERRIDE; virtual void OnLogMessage(const EVENT_TRACE* event, logging::LogSeverity severity, const base::StringPiece& message) OVERRIDE; virtual void OnLogMessageFull(const EVENT_TRACE* event, logging::LogSeverity severity, DWORD stack_depth, const intptr_t* backtrace, int line, const base::StringPiece& file, const base::StringPiece& message) OVERRIDE; virtual void OnTraceEvent(const EVENT_TRACE* event, const base::StringPiece& name, char type, intptr_t id, const base::StringPiece& extra, DWORD stack_depth, const intptr_t* backtrace) OVERRIDE; private: void PrintTimeStamp(LARGE_INTEGER time_stamp); void PrintEventContext(const EVENT_TRACE* event, const base::StringPiece& level, const base::StringPiece& context); void PrintBadEvent(const EVENT_TRACE* event, const base::StringPiece& error); std::ostream* out_; DISALLOW_COPY_AND_ASSIGN(EventPrinter); }; EventPrinter::EventPrinter(std::ostream* out) : out_(out) { } EventPrinter::~EventPrinter() { } void EventPrinter::PrintTimeStamp(LARGE_INTEGER time_stamp) { FILETIME event_time = {}; base::Time::Exploded time_exploded = {}; event_time.dwLowDateTime = time_stamp.LowPart; event_time.dwHighDateTime = time_stamp.HighPart; base::Time::FromFileTime(event_time).LocalExplode(&time_exploded); *out_ << std::setfill('0') << std::setw(2) << time_exploded.month << std::setw(2) << time_exploded.day_of_month << '/' << std::setw(2) << time_exploded.hour << std::setw(2) << time_exploded.minute << std::setw(2) << time_exploded.second << '.' << std::setw(3) << time_exploded.millisecond; } // Prints the context info at the start of each line: pid, tid, time, etc. void EventPrinter::PrintEventContext(const EVENT_TRACE* event, const base::StringPiece& level, const base::StringPiece& context) { *out_ << '[' << event->Header.ProcessId << ':' << event->Header.ThreadId << ':'; PrintTimeStamp(event->Header.TimeStamp); if (!level.empty()) *out_ << ':' << level; if (!context.empty()) *out_ << ':' << context; *out_ << "] "; } // Prints a useful message for events that can't be otherwise printed. void EventPrinter::PrintBadEvent(const EVENT_TRACE* event, const base::StringPiece& error) { wchar_t guid[64]; StringFromGUID2(event->Header.Guid, &guid[0], arraysize(guid)); *out_ << error << " (class=" << guid << ", type=" << static_cast<int>(event->Header.Class.Type) << ")"; } void EventPrinter::OnUnknownEvent(const EVENT_TRACE* event) { base::StringPiece empty; PrintEventContext(event, empty, empty); PrintBadEvent(event, "unsupported event"); } void EventPrinter::OnUnparsableEvent(const EVENT_TRACE* event) { base::StringPiece empty; PrintEventContext(event, empty, empty); PrintBadEvent(event, "parse error"); } void EventPrinter::OnFileHeader(const EVENT_TRACE* event, const TRACE_LOGFILE_HEADER* header) { base::StringPiece empty; PrintEventContext(event, empty, empty); *out_ << "Log captured from Windows " << static_cast<int>(header->VersionDetail.MajorVersion) << '.' << static_cast<int>(header->VersionDetail.MinorVersion) << '.' << static_cast<int>(header->VersionDetail.SubVersion) << '.' << static_cast<int>(header->VersionDetail.SubMinorVersion) << ". " << header->EventsLost << " events lost, " << header->BuffersLost << " buffers lost." << std::endl; } void EventPrinter::OnLogMessage(const EVENT_TRACE* event, logging::LogSeverity severity, const base::StringPiece& message) { std::ostringstream level_stream; WriteSeverityToStream(severity, &level_stream); PrintEventContext(event, level_stream.str(), base::StringPiece()); *out_ << message << std::endl; } void EventPrinter::OnLogMessageFull(const EVENT_TRACE* event, logging::LogSeverity severity, DWORD stack_depth, const intptr_t* backtrace, int line, const base::StringPiece& file, const base::StringPiece& message) { std::ostringstream level_stream; std::ostringstream location_stream; WriteSeverityToStream(severity, &level_stream); WriteLocationToStream(file, line, &location_stream); PrintEventContext(event, level_stream.str(), location_stream.str()); *out_ << message << std::endl; } void EventPrinter::OnTraceEvent(const EVENT_TRACE* event, const base::StringPiece& name, char type, intptr_t id, const base::StringPiece& extra, DWORD stack_depth, const intptr_t* backtrace) { PrintEventContext(event, GetTraceTypeString(type), base::StringPiece()); *out_ << name << " (id=" << std::hex << id << ") " << extra << std::endl; } } // namespace void logging_win::PrintLogFile(const FilePath& log_file, std::ostream* out) { EventPrinter printer(out); logging_win::ReadLogFile(log_file, &printer); } <commit_msg>Windows test logging: switch back to base-10 after emitting a base-16 id.<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/test/logging/win/log_file_printer.h" #include <windows.h> #include <objbase.h> #include <ios> #include <iomanip> #include <ostream> #include <sstream> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/debug/trace_event.h" #include "base/logging.h" #include "base/string_number_conversions.h" #include "base/string_piece.h" #include "base/time.h" #include "chrome/test/logging/win/log_file_reader.h" namespace { // TODO(grt) This duplicates private behavior in base/logging.cc's // LogMessage::Init. That behavior should be exposed and used here (possibly // by moving this function to logging.cc, making it use log_severity_names, and // publishing it in logging.h with BASE_EXPORT). void WriteSeverityToStream(logging::LogSeverity severity, std::ostream* out) { switch (severity) { case logging::LOG_INFO: *out << "INFO"; break; case logging::LOG_WARNING: *out << "WARNING"; break; case logging::LOG_ERROR: *out << "ERROR"; break; case logging::LOG_ERROR_REPORT: *out << "ERROR_REPORT"; break; case logging::LOG_FATAL: *out << "FATAL"; break; default: if (severity < 0) *out << "VERBOSE" << -severity; else NOTREACHED(); break; } } // TODO(grt) This duplicates private behavior in base/logging.cc's // LogMessage::Init. That behavior should be exposed and used here (possibly // by moving this function to logging.cc and publishing it in logging.h with // BASE_EXPORT). void WriteLocationToStream(const base::StringPiece& file, int line, std::ostream* out) { base::StringPiece filename(file); size_t last_slash_pos = filename.find_last_of("\\/"); if (last_slash_pos != base::StringPiece::npos) filename.remove_prefix(last_slash_pos + 1); *out << filename << '(' << line << ')'; } // Returns a pretty string for the trace event types that appear in ETW logs. const char* GetTraceTypeString(char event_type) { switch (event_type) { case TRACE_EVENT_PHASE_BEGIN: return "BEGIN"; break; case TRACE_EVENT_PHASE_END: return "END"; break; case TRACE_EVENT_PHASE_INSTANT: return "INSTANT"; break; default: NOTREACHED(); return ""; break; } } class EventPrinter : public logging_win::LogFileDelegate { public: explicit EventPrinter(std::ostream* out); virtual ~EventPrinter(); virtual void OnUnknownEvent(const EVENT_TRACE* event) OVERRIDE; virtual void OnUnparsableEvent(const EVENT_TRACE* event) OVERRIDE; virtual void OnFileHeader(const EVENT_TRACE* event, const TRACE_LOGFILE_HEADER* header) OVERRIDE; virtual void OnLogMessage(const EVENT_TRACE* event, logging::LogSeverity severity, const base::StringPiece& message) OVERRIDE; virtual void OnLogMessageFull(const EVENT_TRACE* event, logging::LogSeverity severity, DWORD stack_depth, const intptr_t* backtrace, int line, const base::StringPiece& file, const base::StringPiece& message) OVERRIDE; virtual void OnTraceEvent(const EVENT_TRACE* event, const base::StringPiece& name, char type, intptr_t id, const base::StringPiece& extra, DWORD stack_depth, const intptr_t* backtrace) OVERRIDE; private: void PrintTimeStamp(LARGE_INTEGER time_stamp); void PrintEventContext(const EVENT_TRACE* event, const base::StringPiece& level, const base::StringPiece& context); void PrintBadEvent(const EVENT_TRACE* event, const base::StringPiece& error); std::ostream* out_; DISALLOW_COPY_AND_ASSIGN(EventPrinter); }; EventPrinter::EventPrinter(std::ostream* out) : out_(out) { } EventPrinter::~EventPrinter() { } void EventPrinter::PrintTimeStamp(LARGE_INTEGER time_stamp) { FILETIME event_time = {}; base::Time::Exploded time_exploded = {}; event_time.dwLowDateTime = time_stamp.LowPart; event_time.dwHighDateTime = time_stamp.HighPart; base::Time::FromFileTime(event_time).LocalExplode(&time_exploded); *out_ << std::setfill('0') << std::setw(2) << time_exploded.month << std::setw(2) << time_exploded.day_of_month << '/' << std::setw(2) << time_exploded.hour << std::setw(2) << time_exploded.minute << std::setw(2) << time_exploded.second << '.' << std::setw(3) << time_exploded.millisecond; } // Prints the context info at the start of each line: pid, tid, time, etc. void EventPrinter::PrintEventContext(const EVENT_TRACE* event, const base::StringPiece& level, const base::StringPiece& context) { *out_ << '[' << event->Header.ProcessId << ':' << event->Header.ThreadId << ':'; PrintTimeStamp(event->Header.TimeStamp); if (!level.empty()) *out_ << ':' << level; if (!context.empty()) *out_ << ':' << context; *out_ << "] "; } // Prints a useful message for events that can't be otherwise printed. void EventPrinter::PrintBadEvent(const EVENT_TRACE* event, const base::StringPiece& error) { wchar_t guid[64]; StringFromGUID2(event->Header.Guid, &guid[0], arraysize(guid)); *out_ << error << " (class=" << guid << ", type=" << static_cast<int>(event->Header.Class.Type) << ")"; } void EventPrinter::OnUnknownEvent(const EVENT_TRACE* event) { base::StringPiece empty; PrintEventContext(event, empty, empty); PrintBadEvent(event, "unsupported event"); } void EventPrinter::OnUnparsableEvent(const EVENT_TRACE* event) { base::StringPiece empty; PrintEventContext(event, empty, empty); PrintBadEvent(event, "parse error"); } void EventPrinter::OnFileHeader(const EVENT_TRACE* event, const TRACE_LOGFILE_HEADER* header) { base::StringPiece empty; PrintEventContext(event, empty, empty); *out_ << "Log captured from Windows " << static_cast<int>(header->VersionDetail.MajorVersion) << '.' << static_cast<int>(header->VersionDetail.MinorVersion) << '.' << static_cast<int>(header->VersionDetail.SubVersion) << '.' << static_cast<int>(header->VersionDetail.SubMinorVersion) << ". " << header->EventsLost << " events lost, " << header->BuffersLost << " buffers lost." << std::endl; } void EventPrinter::OnLogMessage(const EVENT_TRACE* event, logging::LogSeverity severity, const base::StringPiece& message) { std::ostringstream level_stream; WriteSeverityToStream(severity, &level_stream); PrintEventContext(event, level_stream.str(), base::StringPiece()); *out_ << message << std::endl; } void EventPrinter::OnLogMessageFull(const EVENT_TRACE* event, logging::LogSeverity severity, DWORD stack_depth, const intptr_t* backtrace, int line, const base::StringPiece& file, const base::StringPiece& message) { std::ostringstream level_stream; std::ostringstream location_stream; WriteSeverityToStream(severity, &level_stream); WriteLocationToStream(file, line, &location_stream); PrintEventContext(event, level_stream.str(), location_stream.str()); *out_ << message << std::endl; } void EventPrinter::OnTraceEvent(const EVENT_TRACE* event, const base::StringPiece& name, char type, intptr_t id, const base::StringPiece& extra, DWORD stack_depth, const intptr_t* backtrace) { PrintEventContext(event, GetTraceTypeString(type), base::StringPiece()); *out_ << name << " (id=0x" << std::hex << id << std::dec << ") " << extra << std::endl; } } // namespace void logging_win::PrintLogFile(const FilePath& log_file, std::ostream* out) { EventPrinter printer(out); logging_win::ReadLogFile(log_file, &printer); } <|endoftext|>
<commit_before>/* Test program for Core Logger */ #include "Core.hh" #include <string> using namespace Core; int testlogstream(logstream & ls) { ///test logstream default setup /// date insertion /// default "" prefix /// default loglevel ///test logstream date insertion ls << "test"; //TODO //ls.str() == date + "test" ls << std::endl; ///test logstream custom prefix ls.resetprefix("LogTest :"); ls << "test"; //TODO //ls.str() == date + prefix + "test" ls <<std::endl; ls.resetprefix(); ///test logstream and loglevel ls.resetLevel(loglevel::INFO); ls << loglevel::DEBUG << "Debug message" << std::endl; //ignored ls << loglevel::INFO << "Info message" << std::endl; // ok ls << loglevel::WARNING << "Warning message" << std::endl; //ok ls << loglevel::ERROR << "Error message" << std::endl; //ok ls << loglevel::FATAL << "Fatal message" << std::endl; //ok ls.resetLevel(loglevel::ERROR); ls << loglevel::DEBUG << "Debug message" << std::endl; //ignored ls << loglevel::INFO << "Info message" << std::endl; //ignored ls << loglevel::WARNING << "Warning message" << std::endl; //ignored ls << loglevel::ERROR << "Error message" << std::endl; //ok ls << loglevel::FATAL << "Fatal message" << std::endl; //ok return 0; } int main(int argc, char *argv[]) { bool res = 0; clogstreambuf clsb; logstream ls(&clsb); res += testlogstream(ls); filelogstreambuf flsb("MytestLog.txt"); logstream fls(&flsb); res += testlogstream(fls); //this should not go anywhere or do anything cnull << "BLABLAALALAHAHAHA" << std::endl; return res; } <commit_msg>bool / int fix<commit_after>/* Test program for Core Logger */ #include "Core.hh" #include <string> using namespace Core; int testlogstream(logstream & ls) { ///test logstream default setup /// date insertion /// default "" prefix /// default loglevel ///test logstream date insertion ls << "test"; //TODO //ls.str() == date + "test" ls << std::endl; ///test logstream custom prefix ls.resetprefix("LogTest :"); ls << "test"; //TODO //ls.str() == date + prefix + "test" ls <<std::endl; ls.resetprefix(); ///test logstream and loglevel ls.resetLevel(loglevel::INFO); ls << loglevel::DEBUG << "Debug message" << std::endl; //ignored ls << loglevel::INFO << "Info message" << std::endl; // ok ls << loglevel::WARNING << "Warning message" << std::endl; //ok ls << loglevel::ERROR << "Error message" << std::endl; //ok ls << loglevel::FATAL << "Fatal message" << std::endl; //ok ls.resetLevel(loglevel::ERROR); ls << loglevel::DEBUG << "Debug message" << std::endl; //ignored ls << loglevel::INFO << "Info message" << std::endl; //ignored ls << loglevel::WARNING << "Warning message" << std::endl; //ignored ls << loglevel::ERROR << "Error message" << std::endl; //ok ls << loglevel::FATAL << "Fatal message" << std::endl; //ok return 0; } int main(int argc, char *argv[]) { int res = 0; clogstreambuf clsb; logstream ls(&clsb); res += testlogstream(ls); filelogstreambuf flsb("MytestLog.txt"); logstream fls(&flsb); res += testlogstream(fls); //this should not go anywhere or do anything cnull << "BLABLAALALAHAHAHA" << std::endl; return res; } <|endoftext|>
<commit_before>#include "PHNTextBox.h" PHN_TextBox::PHN_TextBox() { this->length = 0; this->selStart = 0; this->selLength = 0; this->selEnd = 0; this->invalidateStart = -1; this->invalidateEnd = -1; this->cursor_x = -1; this->cursor_y = -1; this->scrollOffset = 0; this->scrollVisible = true; this->dragStart = -1; this->setTextSize(2); this->setMaxLength(100); } void PHN_TextBox::setDimension(int rows, int columns) { // Use the known column/row/scrollbar states to calculate the bounds if (rows > 1) { // Multiple rows - vertical scrollbar setSize(columns*chr_w+chr_w+4, rows*chr_h+2); } else { // Only a single row setSize((columns*chr_w)+chr_h+6, chr_h+2); } } void PHN_TextBox::setMaxLength(int length) { if (length < this->length) { this->length = length; } textBuff.resize(length + 1); } void PHN_TextBox::setTextSize(int size) { _textSize = size; chr_w = _textSize * 6; chr_h = _textSize * 8; invalidate(); } void PHN_TextBox::setScrollbarVisible(bool visible) { // Update the scroll visible property - invalidate to refresh scrollVisible = visible; invalidate(); } void PHN_TextBox::setTextRaw(const char* text, int textLen) { length = min(textBuff.dataSize-1, textLen); memcpy(textBuff.data, text, sizeof(char) * length); textBuff.text()[length] = 0; updateScrollLimit(); setSelectionRange(length, 0); invalidate(); } bool PHN_TextBox::ensureVisible(int charPosition) { int col = 0; int row = -scrollOffset; char* text = (char*) textBuff.data; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (text[i] == '\n' || col >= cols) { row++; col = 0; } if (i == charPosition) { break; } if (text[i] != '\n') col++; } // Not found, scroll to it int newScroll = scrollOffset; if (row >= rows) { // Scroll down the required amount of rows newScroll = scrollOffset + row - rows + 1; } else if (row < 0) { // Scroll up the required amount of rows newScroll = scrollOffset + row; } scroll.setValue(newScroll); return newScroll != scrollOffset; } void PHN_TextBox::updateScrollLimit() { int row = 0; int col = 0; char* text = (char*) textBuff.data; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (text[i] == '\n' || col >= cols) { row++; col = 0; } if (text[i] != '\n') col++; } // Update scroll maximum based on the amount of rows int scrollMax = row - rows + 1; if (col == cols) scrollMax++; scroll.setRange(max(0, scrollMax), 0); } void PHN_TextBox::setSelectionRange(int position, int length) { // Protection against selection past the limit if (position >= this->length) { position = this->length; length = 0; } // If unchanged, do nothing if (position == selStart && length == selLength) { return; } int end = position + length; // Perform character invalidation (redrawing) if (!selLength && !length) { // When only the cursor changes, only redraw the cursor // This is done by re-drawing past the text length limit invalidate(this->length); } else if (length && !selLength) { // No previous selection to a selection invalidate(position, position+length); } else if (!length && selLength) { // Previous selection to no selection invalidate(selStart, selEnd); } else { // Undo edges in previous selection if (position > selStart) invalidate(selStart, position); if (end < selEnd) invalidate(end, selEnd); // Add changes of the new selection if (position > selEnd) invalidate(position, end); if (position < selStart) invalidate(position, selStart); if (end > selEnd) invalidate(selEnd, end); } // Update selection information selStart = position; selLength = length; selEnd = end; } void PHN_TextBox::setSelection(char character) { const char seltext[] = {character, 0}; setSelection(seltext); } void PHN_TextBox::backspace() { if (selLength) { const char seltext[] = {0}; setSelection(seltext); } else if (selStart) { // Shift ending one to the left char* text = (char*) textBuff.data; memmove(text+selStart-1, text+selStart, length-selStart); length -= 1; text[length] = 0; updateScrollLimit(); setSelectionRange(selStart-1, 0); invalidate(selStart); } } void PHN_TextBox::setSelection(const char* selectionText) { // Handle backspace characters here while (*selectionText == '\b') { backspace(); selectionText++; } // Now enter the actual text int len = min((int) strlen(selectionText), (int) (textBuff.dataSize-length+selLength)); char* text = textBuff.text(); bool appended = (selLength == 0 && selStart == length); // If nothing is set, do nothing if (!len && (selLength == 0)) return; // Shift everything after the selection to the right memmove(text+selStart+len, text+selEnd, length-selEnd); // Insert the text value memcpy(text+selStart, selectionText, len); // Update length length = length - selLength + len; text[length] = 0; updateScrollLimit(); // Invalidate the changed area if (len == selLength) { invalidate(selStart, selEnd); } else { invalidate(selStart); } // Update the start and length of selection setSelectionRange(selStart+len, 0); ensureVisible(selStart); // If text was appended (cursor at the end), use faster redraw invalidateAppended = appended; } void PHN_TextBox::invalidate(int startPosition) { invalidate(startPosition, length); } void PHN_TextBox::invalidate(int startPosition, int endPosition) { invalidateAppended = false; if (invalidateStart == -1 || invalidateStart > startPosition) invalidateStart = startPosition; if (invalidateEnd == -1 || invalidateEnd < endPosition) invalidateEnd = endPosition; } void PHN_TextBox::update() { // Update scrollbar layout changes if (invalidated) { // Remove scrollbar up-front removeWidget(scroll); // Update row count rows = (height-2) / chr_h; // Update width and column count, applying this to the scrollbar int scrollWidth; if (scrollVisible) { if (rows > 1) { scrollWidth = chr_h+2; } else { scrollWidth = height*2+2; } addWidget(scroll); } else { scrollWidth = 0; } textAreaWidth = (width - scrollWidth); cols = (textAreaWidth-2) / chr_w; scroll.setBounds(x+textAreaWidth, y, scrollWidth, height); } // Handle Touch selection changes char* text = (char*) textBuff.data; if (display.isTouched(x+_textSize+1, y+_textSize+1, cols*chr_w, rows*chr_h)) { PressPoint pos = display.getTouch(); int posRow = (pos.y-(this->y+_textSize+1)) / chr_h; // Go by all characters until found int x; int col = 0; int row = -scrollOffset; int pressedIdx = this->length; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (col >= cols) { row++; col = 0; } if (row == posRow) { x = this->x + _textSize + 1 + col * chr_w; if ((text[i] == '\n') || (pos.x <= x+(chr_w>>1))) { pressedIdx = i; break; } else if (col == (cols-1)) { pressedIdx = i+1; break; } } if (text[i] == '\n') { row++; col = 0; } else { col++; } } if (display.isTouchDown()) { // Drag start dragStart = pressedIdx; setSelectionRange(pressedIdx, 0); dragLastClick = millis(); } else if (dragStart != -1 && (millis() - dragLastClick) > PHN_WIDGET_TEXT_DRAGSELDELAY) { // Drag selection int start = min(dragStart, pressedIdx); int end = max(dragStart, pressedIdx); setSelectionRange(start, max(1, end-start)); } else if (dragStart != pressedIdx) { // Repositioned the character dragStart = pressedIdx; setSelectionRange(pressedIdx, 0); dragLastClick = millis(); } ensureVisible(pressedIdx); } else if (!display.isTouched()) { dragStart = -1; } // Update scrolling if (scrollOffset != scroll.value()) { scrollOffset = scroll.value(); invalidate(); } // Partial redraws if (!invalidated) { if (invalidateStart != -1) { // Redraw parts of changed text drawTextFromTo(invalidateStart, invalidateEnd, !invalidateAppended); } else if ((millis() - cursor_blinkLast) >= PHN_WIDGET_TEXT_BLINKINTERVAL) { // Blink the cursor cursor_blinkLast = millis(); drawCursor(!cursor_blinkVisible); } } invalidateStart = -1; invalidateEnd = -1; invalidateAppended = false; } void PHN_TextBox::draw() { // Draw background color and grid display.fillRect(x+1, y+1, textAreaWidth-2, height-2, color(FOREGROUND)); display.drawRect(x, y, textAreaWidth, height, color(FRAME)); // Draw text drawTextFromTo(0, this->length, false); } void PHN_TextBox::drawCursor(bool visible) { cursor_blinkVisible = visible; if (cursor_x != -1 && cursor_y != -1) { color_t clr = cursor_blinkVisible ? color(CONTENT) : color(FOREGROUND); display.fillRect(cursor_x, cursor_y, _textSize, _textSize*8, clr); } } void PHN_TextBox::drawTextFromTo(int charStart, int charEnd, bool drawBackground) { // Reset cursor blinking to draw next update cursor_blinkLast = millis() - PHN_WIDGET_TEXT_BLINKINTERVAL; // When all empty, just wipe the screen and reset if (!length) { scroll.setRange(0, 0); display.fillRect(x+1, y+1, textAreaWidth-1, height-2, color(FOREGROUND)); cursor_x = x+_textSize+1; cursor_y = y+_textSize+1; selStart = 0; selLength = 0; return; } // First hide cursor to prevent glitches if (cursor_blinkVisible) { drawCursor(false); } Viewport old = display.getViewport(); display.setViewport(x+_textSize+1, y+_textSize+1, width, height); // Draw selection highlight, cursor and text int row = -scrollOffset; int col = 0; int x, y; bool charSel; cursor_x = -1; cursor_y = -1; char* text = (char*) textBuff.data; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (col >= cols) { row++; col = 0; } if (row >= 0 && row < rows) { x = col * chr_w; y = row * chr_h; if (i == selStart && !selLength) { // Set up cursor cursor_x = display.getViewport().x + x + 1 - _textSize - (_textSize>>1); cursor_y = display.getViewport().y + y; } // Only do drawing operations in the selected range if (i >= charStart && i <= charEnd) { charSel = i >= selStart && i < (selStart+selLength); // Fill the current row and all rows below with background color if (drawBackground && charEnd >= length) { // If last character of current line, clear right of character if ((i == length) || (text[i] == '\n')) { display.fillRect(x-1, y, (cols-col)*chr_w+1, chr_h, color(FOREGROUND)); } // If last character of all text, wipe the remaining rows if (i == length) { display.fillRect(-1, y+chr_h, cols*chr_w+1, chr_h*(rows-row-1), color(FOREGROUND)); } } // Only do drawing when not a newline if (text[i] != '\n' && text[i]) { // Update text color based on selection highlight color_t bgColor = color(charSel ? HIGHLIGHT : FOREGROUND); display.setTextColor(color(CONTENT), bgColor); // Draw text with a border for highlight updates int border_s = _textSize>>1; display.drawChar(x, y, text[i], _textSize); display.fillRect(x-border_s, y, border_s, chr_h, bgColor); display.fillRect(x+chr_w-_textSize, y, border_s, chr_h, bgColor); } } } if (text[i] == '\n') { row++; col = 0; } else { col++; } } // Update scroll maximum based on the amount of rows int scrollMax = row - rows + scrollOffset + 1; if (col == cols) scrollMax++; scroll.setRange(max(0, scrollMax), 0); // Restore viewport display.setViewport(old); } <commit_msg>Fix textbox scrollbar glitch<commit_after>#include "PHNTextBox.h" PHN_TextBox::PHN_TextBox() { this->length = 0; this->selStart = 0; this->selLength = 0; this->selEnd = 0; this->invalidateStart = -1; this->invalidateEnd = -1; this->cursor_x = -1; this->cursor_y = -1; this->scrollOffset = 0; this->scrollVisible = true; this->dragStart = -1; this->setTextSize(2); this->setMaxLength(100); this->scroll.setRange(0, 0); } void PHN_TextBox::setDimension(int rows, int columns) { // Use the known column/row/scrollbar states to calculate the bounds if (rows > 1) { // Multiple rows - vertical scrollbar setSize(columns*chr_w+chr_w+4, rows*chr_h+2); } else { // Only a single row setSize((columns*chr_w)+chr_h+6, chr_h+2); } } void PHN_TextBox::setMaxLength(int length) { if (length < this->length) { this->length = length; } textBuff.resize(length + 1); } void PHN_TextBox::setTextSize(int size) { _textSize = size; chr_w = _textSize * 6; chr_h = _textSize * 8; invalidate(); } void PHN_TextBox::setScrollbarVisible(bool visible) { // Update the scroll visible property - invalidate to refresh scrollVisible = visible; invalidate(); } void PHN_TextBox::setTextRaw(const char* text, int textLen) { length = min(textBuff.dataSize-1, textLen); memcpy(textBuff.data, text, sizeof(char) * length); textBuff.text()[length] = 0; updateScrollLimit(); setSelectionRange(length, 0); invalidate(); } bool PHN_TextBox::ensureVisible(int charPosition) { int col = 0; int row = -scrollOffset; char* text = (char*) textBuff.data; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (text[i] == '\n' || col >= cols) { row++; col = 0; } if (i == charPosition) { break; } if (text[i] != '\n') col++; } // Not found, scroll to it int newScroll = scrollOffset; if (row >= rows) { // Scroll down the required amount of rows newScroll = scrollOffset + row - rows + 1; } else if (row < 0) { // Scroll up the required amount of rows newScroll = scrollOffset + row; } scroll.setValue(newScroll); return newScroll != scrollOffset; } void PHN_TextBox::updateScrollLimit() { int row = 0; int col = 0; char* text = (char*) textBuff.data; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (text[i] == '\n' || col >= cols) { row++; col = 0; } if (text[i] != '\n') col++; } // Update scroll maximum based on the amount of rows int scrollMax = row - rows + 1; if (col == cols) scrollMax++; scroll.setRange(max(0, scrollMax), 0); } void PHN_TextBox::setSelectionRange(int position, int length) { // Protection against selection past the limit if (position >= this->length) { position = this->length; length = 0; } // If unchanged, do nothing if (position == selStart && length == selLength) { return; } int end = position + length; // Perform character invalidation (redrawing) if (!selLength && !length) { // When only the cursor changes, only redraw the cursor // This is done by re-drawing past the text length limit invalidate(this->length); } else if (length && !selLength) { // No previous selection to a selection invalidate(position, position+length); } else if (!length && selLength) { // Previous selection to no selection invalidate(selStart, selEnd); } else { // Undo edges in previous selection if (position > selStart) invalidate(selStart, position); if (end < selEnd) invalidate(end, selEnd); // Add changes of the new selection if (position > selEnd) invalidate(position, end); if (position < selStart) invalidate(position, selStart); if (end > selEnd) invalidate(selEnd, end); } // Update selection information selStart = position; selLength = length; selEnd = end; } void PHN_TextBox::setSelection(char character) { const char seltext[] = {character, 0}; setSelection(seltext); } void PHN_TextBox::backspace() { if (selLength) { const char seltext[] = {0}; setSelection(seltext); } else if (selStart) { // Shift ending one to the left char* text = (char*) textBuff.data; memmove(text+selStart-1, text+selStart, length-selStart); length -= 1; text[length] = 0; updateScrollLimit(); setSelectionRange(selStart-1, 0); invalidate(selStart); } } void PHN_TextBox::setSelection(const char* selectionText) { // Handle backspace characters here while (*selectionText == '\b') { backspace(); selectionText++; } // Now enter the actual text int len = min((int) strlen(selectionText), (int) (textBuff.dataSize-length+selLength)); char* text = textBuff.text(); bool appended = (selLength == 0 && selStart == length); // If nothing is set, do nothing if (!len && (selLength == 0)) return; // Shift everything after the selection to the right memmove(text+selStart+len, text+selEnd, length-selEnd); // Insert the text value memcpy(text+selStart, selectionText, len); // Update length length = length - selLength + len; text[length] = 0; updateScrollLimit(); // Invalidate the changed area if (len == selLength) { invalidate(selStart, selEnd); } else { invalidate(selStart); } // Update the start and length of selection setSelectionRange(selStart+len, 0); ensureVisible(selStart); // If text was appended (cursor at the end), use faster redraw invalidateAppended = appended; } void PHN_TextBox::invalidate(int startPosition) { invalidate(startPosition, length); } void PHN_TextBox::invalidate(int startPosition, int endPosition) { invalidateAppended = false; if (invalidateStart == -1 || invalidateStart > startPosition) invalidateStart = startPosition; if (invalidateEnd == -1 || invalidateEnd < endPosition) invalidateEnd = endPosition; } void PHN_TextBox::update() { // Update scrollbar layout changes if (invalidated) { // Remove scrollbar up-front removeWidget(scroll); // Update row count rows = (height-2) / chr_h; // Update width and column count, applying this to the scrollbar int scrollWidth; if (scrollVisible) { if (rows > 1) { scrollWidth = chr_h+2; } else { scrollWidth = height*2+2; } addWidget(scroll); } else { scrollWidth = 0; } textAreaWidth = (width - scrollWidth); cols = (textAreaWidth-2) / chr_w; scroll.setBounds(x+textAreaWidth, y, scrollWidth, height); } // Handle Touch selection changes char* text = (char*) textBuff.data; if (display.isTouched(x+_textSize+1, y+_textSize+1, cols*chr_w, rows*chr_h)) { PressPoint pos = display.getTouch(); int posRow = (pos.y-(this->y+_textSize+1)) / chr_h; // Go by all characters until found int x; int col = 0; int row = -scrollOffset; int pressedIdx = this->length; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (col >= cols) { row++; col = 0; } if (row == posRow) { x = this->x + _textSize + 1 + col * chr_w; if ((text[i] == '\n') || (pos.x <= x+(chr_w>>1))) { pressedIdx = i; break; } else if (col == (cols-1)) { pressedIdx = i+1; break; } } if (text[i] == '\n') { row++; col = 0; } else { col++; } } if (display.isTouchDown()) { // Drag start dragStart = pressedIdx; setSelectionRange(pressedIdx, 0); dragLastClick = millis(); } else if (dragStart != -1 && (millis() - dragLastClick) > PHN_WIDGET_TEXT_DRAGSELDELAY) { // Drag selection int start = min(dragStart, pressedIdx); int end = max(dragStart, pressedIdx); setSelectionRange(start, max(1, end-start)); } else if (dragStart != pressedIdx) { // Repositioned the character dragStart = pressedIdx; setSelectionRange(pressedIdx, 0); dragLastClick = millis(); } ensureVisible(pressedIdx); } else if (!display.isTouched()) { dragStart = -1; } // Update scrolling if (scrollOffset != scroll.value()) { scrollOffset = scroll.value(); invalidate(); } // Partial redraws if (!invalidated) { if (invalidateStart != -1) { // Redraw parts of changed text drawTextFromTo(invalidateStart, invalidateEnd, !invalidateAppended); } else if ((millis() - cursor_blinkLast) >= PHN_WIDGET_TEXT_BLINKINTERVAL) { // Blink the cursor cursor_blinkLast = millis(); drawCursor(!cursor_blinkVisible); } } invalidateStart = -1; invalidateEnd = -1; invalidateAppended = false; } void PHN_TextBox::draw() { // Draw background color and grid display.fillRect(x+1, y+1, textAreaWidth-2, height-2, color(FOREGROUND)); display.drawRect(x, y, textAreaWidth, height, color(FRAME)); // Draw text drawTextFromTo(0, this->length, false); } void PHN_TextBox::drawCursor(bool visible) { cursor_blinkVisible = visible; if (cursor_x != -1 && cursor_y != -1) { color_t clr = cursor_blinkVisible ? color(CONTENT) : color(FOREGROUND); display.fillRect(cursor_x, cursor_y, _textSize, _textSize*8, clr); } } void PHN_TextBox::drawTextFromTo(int charStart, int charEnd, bool drawBackground) { // Reset cursor blinking to draw next update cursor_blinkLast = millis() - PHN_WIDGET_TEXT_BLINKINTERVAL; // When all empty, just wipe the screen and reset if (!length) { scroll.setRange(0, 0); display.fillRect(x+1, y+1, textAreaWidth-1, height-2, color(FOREGROUND)); cursor_x = x+_textSize+1; cursor_y = y+_textSize+1; selStart = 0; selLength = 0; return; } // First hide cursor to prevent glitches if (cursor_blinkVisible) { drawCursor(false); } Viewport old = display.getViewport(); display.setViewport(x+_textSize+1, y+_textSize+1, width, height); // Draw selection highlight, cursor and text int row = -scrollOffset; int col = 0; int x, y; bool charSel; cursor_x = -1; cursor_y = -1; char* text = (char*) textBuff.data; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (col >= cols) { row++; col = 0; } if (row >= 0 && row < rows) { x = col * chr_w; y = row * chr_h; if (i == selStart && !selLength) { // Set up cursor cursor_x = display.getViewport().x + x + 1 - _textSize - (_textSize>>1); cursor_y = display.getViewport().y + y; } // Only do drawing operations in the selected range if (i >= charStart && i <= charEnd) { charSel = i >= selStart && i < (selStart+selLength); // Fill the current row and all rows below with background color if (drawBackground && charEnd >= length) { // If last character of current line, clear right of character if ((i == length) || (text[i] == '\n')) { display.fillRect(x-1, y, (cols-col)*chr_w+1, chr_h, color(FOREGROUND)); } // If last character of all text, wipe the remaining rows if (i == length) { display.fillRect(-1, y+chr_h, cols*chr_w+1, chr_h*(rows-row-1), color(FOREGROUND)); } } // Only do drawing when not a newline if (text[i] != '\n' && text[i]) { // Update text color based on selection highlight color_t bgColor = color(charSel ? HIGHLIGHT : FOREGROUND); display.setTextColor(color(CONTENT), bgColor); // Draw text with a border for highlight updates int border_s = _textSize>>1; display.drawChar(x, y, text[i], _textSize); display.fillRect(x-border_s, y, border_s, chr_h, bgColor); display.fillRect(x+chr_w-_textSize, y, border_s, chr_h, bgColor); } } } if (text[i] == '\n') { row++; col = 0; } else { col++; } } // Update scroll maximum based on the amount of rows int scrollMax = row - rows + scrollOffset + 1; if (col == cols) scrollMax++; scroll.setRange(max(0, scrollMax), 0); // Restore viewport display.setViewport(old); } <|endoftext|>
<commit_before>/* * Copyright (c) 2009 Steven Noonan <steven@uplinklabs.net> * and Miah Clayton <miah@ferrousmoon.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR 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 "universal_include.h" #include "App/app.h" #include "App/preferences.h" #include "App/version.h" #include "Game/game.h" #include "Graphics/graphics.h" #include "Interface/interface.h" #include "Interface/window.h" #include "Network/net.h" #include "Sound/soundsystem.h" IO::Console *g_console; bool g_bActive = true; int iPlaying; bool bSound; void Init_App( char *apppath ); void Init_Game(); void Init_Graphics(); void Init_Interface(); void Init_Sound(); int main ( int argc, char **argv ) { int i = 0; char temp[1024]; memset ( temp, 0, sizeof(temp) ); g_console = new IO::Console ( true, true ); sprintf(temp, "%s v%s", APP_NAME, Cerberus::Version::LongVersion()); g_console->SetTitle ( temp ); #ifdef TARGET_OS_MACOSX sprintf ( temp, "%s", "../Resources/" ); #endif // first find the location of the EXE. for (i = (int)strlen(argv[0]); i > 0; i--) { if (argv[0][i] == '\\') { argv[0][i + 1] = '\x0'; strcat(temp, argv[0]); break; } } g_console->SetColour ( IO::Console::FG_GREEN | IO::Console::FG_INTENSITY ); g_console->WriteLine ( "=======================" ); g_console->WriteLine ( "= Codename Cerberus =" ); g_console->WriteLine ( "=======================" ); g_console->SetColour (); g_console->WriteLine ( "Copyright (c) 2009 Steven Noonan <steven@uplinklabs.net>" ); g_console->WriteLine ( " and Miah Clayton <miah@ferrousmoon.com>"); g_console->WriteLine ( "All rights reserved." ); g_console->WriteLine ( "Licensed under the terms of the New BSD License.\n" ); g_console->WriteLine ( "Version %s", Cerberus::Version::LongVersion() ); g_console->Write ( "Built for " ); g_console->SetColour ( IO::Console::FG_GREEN | IO::Console::FG_INTENSITY ); #if defined ( TARGET_OS_WINDOWS ) g_console->Write ( "Microsoft Windows" ); #elif defined ( TARGET_OS_MACOSX ) g_console->Write ( "Mac OS X" ); #elif defined ( TARGET_OS_LINUX ) g_console->Write ( "Linux" ); #else g_console->Write ( "Unknown OS" ); #endif g_console->SetColour (); g_console->Write ( " using " ); g_console->SetColour ( IO::Console::FG_GREEN | IO::Console::FG_INTENSITY ); #if defined ( TARGET_COMPILER_VC ) g_console->Write ( "Visual Studio" ); #if _MSC_VER >= 1500 g_console->Write ( " 2008" ); #elif _MSC_VER >= 1400 g_console->Write ( " 2005" ); #elif _MSC_VER >= 1310 g_console->Write ( " .NET 2003" ); #elif _MSC_VER >= 1300 g_console->Write ( " .NET 2002" ); #elif _MSC_VER >= 1200 g_console->Write ( " 6.0" ); #endif #elif defined ( TARGET_COMPILER_GCC ) g_console->Write ( "GNU C++ Compiler v%d.%d.%d", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__ ); #elif defined ( TARGET_COMPILER_ICC ) g_console->Write ( "Intel C++ Compiler" ); #else g_console->Write ( "Unknown Compiler" ); #endif g_console->SetColour (); g_console->WriteLine ( "\nBuilt on " __DATE__ " at " __TIME__ ); Init_App(temp); Init_Graphics(); Init_Interface(); Init_Sound(); Init_Game(); g_app->Run (); // deconstruct the classes g_console->WriteLine ( "Destroying classes..."); g_graphics->ShowCursor ( true ); // free up the allocated memory delete g_game; g_game = NULL; delete g_interface; g_interface = NULL; delete g_graphics; g_graphics = NULL; delete g_soundSystem; g_soundSystem = NULL; // notify that the exit operations were successful g_console->WriteLine ( "Program is exiting cleanly.\n"); g_prefsManager->Save(); delete g_prefsManager; g_prefsManager = NULL; delete g_app; g_app = NULL; delete g_console; g_console = NULL; // success! return 0; } void Init_App( char *apppath ) { g_app = new App(); CrbReleaseAssert ( g_app != NULL ); char preferencesPath[2048]; #ifndef TARGET_OS_WINDOWS sprintf( preferencesPath, "%s%s", g_app->GetApplicationSupportPath(), "preferences.txt" ); #else sprintf( preferencesPath, "%s%s", g_app->GetApplicationPath(), "preferences.txt" ); #endif g_prefsManager = new Preferences ( preferencesPath ); CrbReleaseAssert ( g_prefsManager != NULL ); // We save the preferences here to ensure that preferences.txt exists. // If the application prints a blackbox.txt, this file needs to be there. g_prefsManager->Save(); if ( g_prefsManager->GetInt ( "IgnoreDataFiles", 0 ) == 0 ) { char tempPath[2048]; sprintf ( tempPath, "%s%s", g_app->GetResourcePath(), "data.dat" ); g_app->m_resource->ParseArchive ( tempPath, NULL ); sprintf ( tempPath, "%s%s", g_app->GetResourcePath(), "font.dat" ); g_app->m_resource->ParseArchive ( tempPath, NULL ); sprintf ( tempPath, "%s%s", g_app->GetResourcePath(), "graphics.dat" ); g_app->m_resource->ParseArchive ( tempPath, NULL ); sprintf ( tempPath, "%s%s", g_app->GetResourcePath(), "sounds.dat" ); g_app->m_resource->ParseArchive ( tempPath, NULL ); sprintf ( tempPath, "%s%s", g_app->GetResourcePath(), "maps.dat" ); g_app->m_resource->ParseArchive ( tempPath, NULL ); } } void Init_Game() { g_game = new Game(); CrbReleaseAssert ( g_game != NULL ); } void Init_Graphics() { const char *graphicsDriver = g_prefsManager->GetString ( "Renderer", "opengl" ); int ret = -1; CrbDebugAssert ( g_graphics == NULL ); while ( !g_graphics ) { // Pick a renderer. if ( Data::Compare<const char *> ( graphicsDriver, "opengl" ) == 0 ) { // OpenGL g_console->WriteLine ( "Attempting to use OpenGLGraphics..." ); #ifdef ENABLE_OPENGL g_graphics = new OpenGLGraphics (); #else g_console->WriteLine ( "OpenGL support not enabled." ); #endif } else if ( Data::Compare<const char *> ( graphicsDriver, "direct3d" ) == 0 ) { // Direct3D g_console->WriteLine ( "Attempting to use DirectXGraphics..." ); #ifdef TARGET_OS_WINDOWS #ifdef ENABLE_DIRECT3D g_graphics = new DirectXGraphics (); #else g_console->WriteLine ( "Direct3D support not enabled." ); #endif #else g_console->WriteLine ( "Wrong platform. Attempting to use OpenGL..." ); #endif } // Try and set the window mode. if ( g_graphics ) { ret = g_graphics->SetWindowMode ( g_prefsManager->GetInt ( "ScreenWindowed", 0 ) == 1, g_prefsManager->GetInt ( "ScreenWidth", 0 ), g_prefsManager->GetInt ( "ScreenHeight", 0 ), g_prefsManager->GetInt ( "ScreenColourDepth", 32 ) ); } // Something went wrong. if ( ret ) { delete g_graphics; g_graphics = NULL; if ( Data::Compare<const char *> ( graphicsDriver, "opengl" ) == 0 ) { // You're screwed. break; } else if ( Data::Compare<const char *> ( graphicsDriver, "direct3d" ) == 0 ) { // Direct3D may not be available on this platform. graphicsDriver = "opengl"; } else { // Er, what the hell -did- they put in preferences? graphicsDriver = "opengl"; } } else { break; } } // Something's terribly wrong. if ( !g_graphics ) CrbReleaseAbort ( "Could not initialize the graphics engine." ); // Hide the OS cursor g_graphics->ShowCursor ( true ); } void Init_Interface() { g_interface = new Interface(); CrbReleaseAssert ( g_interface != NULL ); } void Init_Sound() { #if defined(USE_OPENAL) g_soundSystem = new OpenALSoundSystem(); #elif defined(USE_SDLMIXER) g_soundSystem = new SDLMixerSoundSystem(); #endif if ( !g_soundSystem ) g_soundSystem = new NullSoundSystem(); } <commit_msg>cerberus.cpp: run App::Initialise after interface is created<commit_after>/* * Copyright (c) 2009 Steven Noonan <steven@uplinklabs.net> * and Miah Clayton <miah@ferrousmoon.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR 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 "universal_include.h" #include "App/app.h" #include "App/preferences.h" #include "App/version.h" #include "Game/game.h" #include "Graphics/graphics.h" #include "Interface/interface.h" #include "Interface/window.h" #include "Network/net.h" #include "Sound/soundsystem.h" IO::Console *g_console; bool g_bActive = true; int iPlaying; bool bSound; void Init_App( char *apppath ); void Init_Game(); void Init_Graphics(); void Init_Interface(); void Init_Sound(); int main ( int argc, char **argv ) { int i = 0; char temp[1024]; memset ( temp, 0, sizeof(temp) ); g_console = new IO::Console ( true, true ); sprintf(temp, "%s v%s", APP_NAME, Cerberus::Version::LongVersion()); g_console->SetTitle ( temp ); #ifdef TARGET_OS_MACOSX sprintf ( temp, "%s", "../Resources/" ); #endif // first find the location of the EXE. for (i = (int)strlen(argv[0]); i > 0; i--) { if (argv[0][i] == '\\') { argv[0][i + 1] = '\x0'; strcat(temp, argv[0]); break; } } g_console->SetColour ( IO::Console::FG_GREEN | IO::Console::FG_INTENSITY ); g_console->WriteLine ( "=======================" ); g_console->WriteLine ( "= Codename Cerberus =" ); g_console->WriteLine ( "=======================" ); g_console->SetColour (); g_console->WriteLine ( "Copyright (c) 2009 Steven Noonan <steven@uplinklabs.net>" ); g_console->WriteLine ( " and Miah Clayton <miah@ferrousmoon.com>"); g_console->WriteLine ( "All rights reserved." ); g_console->WriteLine ( "Licensed under the terms of the New BSD License.\n" ); g_console->WriteLine ( "Version %s", Cerberus::Version::LongVersion() ); g_console->Write ( "Built for " ); g_console->SetColour ( IO::Console::FG_GREEN | IO::Console::FG_INTENSITY ); #if defined ( TARGET_OS_WINDOWS ) g_console->Write ( "Microsoft Windows" ); #elif defined ( TARGET_OS_MACOSX ) g_console->Write ( "Mac OS X" ); #elif defined ( TARGET_OS_LINUX ) g_console->Write ( "Linux" ); #else g_console->Write ( "Unknown OS" ); #endif g_console->SetColour (); g_console->Write ( " using " ); g_console->SetColour ( IO::Console::FG_GREEN | IO::Console::FG_INTENSITY ); #if defined ( TARGET_COMPILER_VC ) g_console->Write ( "Visual Studio" ); #if _MSC_VER >= 1500 g_console->Write ( " 2008" ); #elif _MSC_VER >= 1400 g_console->Write ( " 2005" ); #elif _MSC_VER >= 1310 g_console->Write ( " .NET 2003" ); #elif _MSC_VER >= 1300 g_console->Write ( " .NET 2002" ); #elif _MSC_VER >= 1200 g_console->Write ( " 6.0" ); #endif #elif defined ( TARGET_COMPILER_GCC ) g_console->Write ( "GNU C++ Compiler v%d.%d.%d", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__ ); #elif defined ( TARGET_COMPILER_ICC ) g_console->Write ( "Intel C++ Compiler" ); #else g_console->Write ( "Unknown Compiler" ); #endif g_console->SetColour (); g_console->WriteLine ( "\nBuilt on " __DATE__ " at " __TIME__ ); Init_App(temp); Init_Graphics(); Init_Interface(); Init_Sound(); Init_Game(); g_app->Run (); // deconstruct the classes g_console->WriteLine ( "Destroying classes..."); g_graphics->ShowCursor ( true ); // free up the allocated memory delete g_game; g_game = NULL; delete g_interface; g_interface = NULL; delete g_graphics; g_graphics = NULL; delete g_soundSystem; g_soundSystem = NULL; // notify that the exit operations were successful g_console->WriteLine ( "Program is exiting cleanly.\n"); g_prefsManager->Save(); delete g_prefsManager; g_prefsManager = NULL; delete g_app; g_app = NULL; delete g_console; g_console = NULL; // success! return 0; } void Init_App( char *apppath ) { g_app = new App(); CrbReleaseAssert ( g_app != NULL ); char preferencesPath[2048]; #ifndef TARGET_OS_WINDOWS sprintf( preferencesPath, "%s%s", g_app->GetApplicationSupportPath(), "preferences.txt" ); #else sprintf( preferencesPath, "%s%s", g_app->GetApplicationPath(), "preferences.txt" ); #endif g_prefsManager = new Preferences ( preferencesPath ); CrbReleaseAssert ( g_prefsManager != NULL ); // We save the preferences here to ensure that preferences.txt exists. // If the application prints a blackbox.txt, this file needs to be there. g_prefsManager->Save(); if ( g_prefsManager->GetInt ( "IgnoreDataFiles", 0 ) == 0 ) { char tempPath[2048]; sprintf ( tempPath, "%s%s", g_app->GetResourcePath(), "data.dat" ); g_app->m_resource->ParseArchive ( tempPath, NULL ); sprintf ( tempPath, "%s%s", g_app->GetResourcePath(), "font.dat" ); g_app->m_resource->ParseArchive ( tempPath, NULL ); sprintf ( tempPath, "%s%s", g_app->GetResourcePath(), "graphics.dat" ); g_app->m_resource->ParseArchive ( tempPath, NULL ); sprintf ( tempPath, "%s%s", g_app->GetResourcePath(), "sounds.dat" ); g_app->m_resource->ParseArchive ( tempPath, NULL ); sprintf ( tempPath, "%s%s", g_app->GetResourcePath(), "maps.dat" ); g_app->m_resource->ParseArchive ( tempPath, NULL ); } } void Init_Game() { g_game = new Game(); CrbReleaseAssert ( g_game != NULL ); } void Init_Graphics() { const char *graphicsDriver = g_prefsManager->GetString ( "Renderer", "opengl" ); int ret = -1; CrbDebugAssert ( g_graphics == NULL ); while ( !g_graphics ) { // Pick a renderer. if ( Data::Compare<const char *> ( graphicsDriver, "opengl" ) == 0 ) { // OpenGL g_console->WriteLine ( "Attempting to use OpenGLGraphics..." ); #ifdef ENABLE_OPENGL g_graphics = new OpenGLGraphics (); #else g_console->WriteLine ( "OpenGL support not enabled." ); #endif } else if ( Data::Compare<const char *> ( graphicsDriver, "direct3d" ) == 0 ) { // Direct3D g_console->WriteLine ( "Attempting to use DirectXGraphics..." ); #ifdef TARGET_OS_WINDOWS #ifdef ENABLE_DIRECT3D g_graphics = new DirectXGraphics (); #else g_console->WriteLine ( "Direct3D support not enabled." ); #endif #else g_console->WriteLine ( "Wrong platform. Attempting to use OpenGL..." ); #endif } // Try and set the window mode. if ( g_graphics ) { ret = g_graphics->SetWindowMode ( g_prefsManager->GetInt ( "ScreenWindowed", 0 ) == 1, g_prefsManager->GetInt ( "ScreenWidth", 0 ), g_prefsManager->GetInt ( "ScreenHeight", 0 ), g_prefsManager->GetInt ( "ScreenColourDepth", 32 ) ); } // Something went wrong. if ( ret ) { delete g_graphics; g_graphics = NULL; if ( Data::Compare<const char *> ( graphicsDriver, "opengl" ) == 0 ) { // You're screwed. break; } else if ( Data::Compare<const char *> ( graphicsDriver, "direct3d" ) == 0 ) { // Direct3D may not be available on this platform. graphicsDriver = "opengl"; } else { // Er, what the hell -did- they put in preferences? graphicsDriver = "opengl"; } } else { break; } } // Something's terribly wrong. if ( !g_graphics ) CrbReleaseAbort ( "Could not initialize the graphics engine." ); // Hide the OS cursor g_graphics->ShowCursor ( true ); } void Init_Interface() { g_interface = new Interface(); CrbReleaseAssert ( g_interface != NULL ); g_app->Initialise(); } void Init_Sound() { #if defined(USE_OPENAL) g_soundSystem = new OpenALSoundSystem(); #elif defined(USE_SDLMIXER) g_soundSystem = new SDLMixerSoundSystem(); #endif if ( !g_soundSystem ) g_soundSystem = new NullSoundSystem(); } <|endoftext|>
<commit_before>/* * Blake2b * (C) 2016 cynecx * (C) 2017 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/blake2b.h> #include <botan/exceptn.h> #include <botan/mem_ops.h> #include <botan/loadstor.h> #include <botan/rotate.h> #include <algorithm> namespace Botan { namespace { enum blake2b_constant { BLAKE2B_BLOCKBYTES = 128, BLAKE2B_IVU64COUNT = 8 }; const uint64_t blake2b_IV[BLAKE2B_IVU64COUNT] = { 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179 }; } Blake2b::Blake2b(size_t output_bits) : m_output_bits(output_bits), m_buffer(BLAKE2B_BLOCKBYTES), m_bufpos(0), m_H(BLAKE2B_IVU64COUNT) { if(output_bits == 0 || output_bits > 512 || output_bits % 8 != 0) { throw Invalid_Argument("Bad output bits size for Blake2b"); } state_init(); } void Blake2b::state_init() { copy_mem(m_H.data(), blake2b_IV, BLAKE2B_IVU64COUNT); m_H[0] ^= 0x01010000 ^ static_cast<uint8_t>(output_length()); m_T[0] = m_T[1] = 0; m_F[0] = m_F[1] = 0; } void Blake2b::compress(const uint8_t* input, size_t blocks, uint64_t increment) { for(size_t b = 0; b != blocks; ++b) { m_T[0] += increment; if(m_T[0] < increment) { m_T[1]++; } uint64_t M[16]; uint64_t v[16]; load_le(M, input, 16); input += BLAKE2B_BLOCKBYTES; for(size_t i = 0; i < 8; i++) v[i] = m_H[i]; for(size_t i = 0; i != 8; ++i) v[i + 8] = blake2b_IV[i]; v[12] ^= m_T[0]; v[13] ^= m_T[1]; v[14] ^= m_F[0]; v[15] ^= m_F[1]; #define G(a, b, c, d, M0, M1) \ do { \ a = a + b + M0; \ d = rotr<32>(d ^ a); \ c = c + d; \ b = rotr<24>(b ^ c); \ a = a + b + M1; \ d = rotr<16>(d ^ a); \ c = c + d; \ b = rotr<63>(b ^ c); \ } while(0) #define ROUND(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, iA, iB, iC, iD, iE, iF) \ do { \ G(v[ 0], v[ 4], v[ 8], v[12], M[i0], M[i1]); \ G(v[ 1], v[ 5], v[ 9], v[13], M[i2], M[i3]); \ G(v[ 2], v[ 6], v[10], v[14], M[i4], M[i5]); \ G(v[ 3], v[ 7], v[11], v[15], M[i6], M[i7]); \ G(v[ 0], v[ 5], v[10], v[15], M[i8], M[i9]); \ G(v[ 1], v[ 6], v[11], v[12], M[iA], M[iB]); \ G(v[ 2], v[ 7], v[ 8], v[13], M[iC], M[iD]); \ G(v[ 3], v[ 4], v[ 9], v[14], M[iE], M[iF]); \ } while(0) ROUND( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); ROUND(14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3); ROUND(11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4); ROUND( 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8); ROUND( 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13); ROUND( 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9); ROUND(12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11); ROUND(13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10); ROUND( 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5); ROUND(10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0); ROUND( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); ROUND(14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3); for(size_t i = 0; i < 8; i++) { m_H[i] ^= v[i] ^ v[i + 8]; } } #undef G #undef ROUND } void Blake2b::add_data(const uint8_t input[], size_t length) { if(length == 0) return; if(m_bufpos > 0) { if(m_bufpos < BLAKE2B_BLOCKBYTES) { const size_t take = std::min(BLAKE2B_BLOCKBYTES - m_bufpos, length); copy_mem(&m_buffer[m_bufpos], input, take); m_bufpos += take; length -= take; input += take; } if(m_bufpos == m_buffer.size() && length > 0) { compress(m_buffer.data(), 1, BLAKE2B_BLOCKBYTES); m_bufpos = 0; } } if(length > BLAKE2B_BLOCKBYTES) { const size_t full_blocks = ((length-1) / BLAKE2B_BLOCKBYTES); compress(input, full_blocks, BLAKE2B_BLOCKBYTES); input += full_blocks * BLAKE2B_BLOCKBYTES; length -= full_blocks * BLAKE2B_BLOCKBYTES; } if(length > 0) { copy_mem(&m_buffer[m_bufpos], input, length); m_bufpos += length; } } void Blake2b::final_result(uint8_t output[]) { if(m_bufpos != BLAKE2B_BLOCKBYTES) clear_mem(&m_buffer[m_bufpos], BLAKE2B_BLOCKBYTES - m_bufpos); m_F[0] = 0xFFFFFFFFFFFFFFFF; compress(m_buffer.data(), 1, m_bufpos); copy_out_vec_le(output, output_length(), m_H); clear(); } std::string Blake2b::name() const { return "Blake2b(" + std::to_string(m_output_bits) + ")"; } HashFunction* Blake2b::clone() const { return new Blake2b(m_output_bits); } std::unique_ptr<HashFunction> Blake2b::copy_state() const { return std::unique_ptr<HashFunction>(new Blake2b(*this)); } void Blake2b::clear() { zeroise(m_H); zeroise(m_buffer); m_bufpos = 0; state_init(); } } <commit_msg>Avoid macros in Blake2b to workaround Visual C++ 2017 infinite loop<commit_after>/* * Blake2b * (C) 2016 cynecx * (C) 2017 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/blake2b.h> #include <botan/exceptn.h> #include <botan/mem_ops.h> #include <botan/loadstor.h> #include <botan/rotate.h> #include <algorithm> namespace Botan { namespace { enum blake2b_constant { BLAKE2B_BLOCKBYTES = 128, BLAKE2B_IVU64COUNT = 8 }; const uint64_t blake2b_IV[BLAKE2B_IVU64COUNT] = { 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179 }; } Blake2b::Blake2b(size_t output_bits) : m_output_bits(output_bits), m_buffer(BLAKE2B_BLOCKBYTES), m_bufpos(0), m_H(BLAKE2B_IVU64COUNT) { if(output_bits == 0 || output_bits > 512 || output_bits % 8 != 0) { throw Invalid_Argument("Bad output bits size for Blake2b"); } state_init(); } void Blake2b::state_init() { copy_mem(m_H.data(), blake2b_IV, BLAKE2B_IVU64COUNT); m_H[0] ^= 0x01010000 ^ static_cast<uint8_t>(output_length()); m_T[0] = m_T[1] = 0; m_F[0] = m_F[1] = 0; } namespace { inline void G(uint64_t& a, uint64_t& b, uint64_t& c, uint64_t& d, uint64_t M0, uint64_t M1) { a = a + b + M0; d = rotr<32>(d ^ a); c = c + d; b = rotr<24>(b ^ c); a = a + b + M1; d = rotr<16>(d ^ a); c = c + d; b = rotr<63>(b ^ c); } template<size_t i0, size_t i1, size_t i2, size_t i3, size_t i4, size_t i5, size_t i6, size_t i7, size_t i8, size_t i9, size_t iA, size_t iB, size_t iC, size_t iD, size_t iE, size_t iF> inline void ROUND(uint64_t* v, const uint64_t* M) { G(v[ 0], v[ 4], v[ 8], v[12], M[i0], M[i1]); G(v[ 1], v[ 5], v[ 9], v[13], M[i2], M[i3]); G(v[ 2], v[ 6], v[10], v[14], M[i4], M[i5]); G(v[ 3], v[ 7], v[11], v[15], M[i6], M[i7]); G(v[ 0], v[ 5], v[10], v[15], M[i8], M[i9]); G(v[ 1], v[ 6], v[11], v[12], M[iA], M[iB]); G(v[ 2], v[ 7], v[ 8], v[13], M[iC], M[iD]); G(v[ 3], v[ 4], v[ 9], v[14], M[iE], M[iF]); } } void Blake2b::compress(const uint8_t* input, size_t blocks, uint64_t increment) { for(size_t b = 0; b != blocks; ++b) { m_T[0] += increment; if(m_T[0] < increment) { m_T[1]++; } uint64_t M[16]; uint64_t v[16]; load_le(M, input, 16); input += BLAKE2B_BLOCKBYTES; for(size_t i = 0; i < 8; i++) v[i] = m_H[i]; for(size_t i = 0; i != 8; ++i) v[i + 8] = blake2b_IV[i]; v[12] ^= m_T[0]; v[13] ^= m_T[1]; v[14] ^= m_F[0]; v[15] ^= m_F[1]; ROUND< 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15>(v, M); ROUND<14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3>(v, M); ROUND<11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4>(v, M); ROUND< 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8>(v, M); ROUND< 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13>(v, M); ROUND< 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9>(v, M); ROUND<12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11>(v, M); ROUND<13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10>(v, M); ROUND< 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5>(v, M); ROUND<10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0>(v, M); ROUND< 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15>(v, M); ROUND<14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3>(v, M); for(size_t i = 0; i < 8; i++) { m_H[i] ^= v[i] ^ v[i + 8]; } } } void Blake2b::add_data(const uint8_t input[], size_t length) { if(length == 0) return; if(m_bufpos > 0) { if(m_bufpos < BLAKE2B_BLOCKBYTES) { const size_t take = std::min(BLAKE2B_BLOCKBYTES - m_bufpos, length); copy_mem(&m_buffer[m_bufpos], input, take); m_bufpos += take; length -= take; input += take; } if(m_bufpos == m_buffer.size() && length > 0) { compress(m_buffer.data(), 1, BLAKE2B_BLOCKBYTES); m_bufpos = 0; } } if(length > BLAKE2B_BLOCKBYTES) { const size_t full_blocks = ((length-1) / BLAKE2B_BLOCKBYTES); compress(input, full_blocks, BLAKE2B_BLOCKBYTES); input += full_blocks * BLAKE2B_BLOCKBYTES; length -= full_blocks * BLAKE2B_BLOCKBYTES; } if(length > 0) { copy_mem(&m_buffer[m_bufpos], input, length); m_bufpos += length; } } void Blake2b::final_result(uint8_t output[]) { if(m_bufpos != BLAKE2B_BLOCKBYTES) clear_mem(&m_buffer[m_bufpos], BLAKE2B_BLOCKBYTES - m_bufpos); m_F[0] = 0xFFFFFFFFFFFFFFFF; compress(m_buffer.data(), 1, m_bufpos); copy_out_vec_le(output, output_length(), m_H); clear(); } std::string Blake2b::name() const { return "Blake2b(" + std::to_string(m_output_bits) + ")"; } HashFunction* Blake2b::clone() const { return new Blake2b(m_output_bits); } std::unique_ptr<HashFunction> Blake2b::copy_state() const { return std::unique_ptr<HashFunction>(new Blake2b(*this)); } void Blake2b::clear() { zeroise(m_H); zeroise(m_buffer); m_bufpos = 0; state_init(); } } <|endoftext|>
<commit_before>#include "material/velvet.h" #include "math/math.h" namespace AT_NAME { // NOTE // Production Friendly Microfacet Sheen BRDF. // http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf AT_DEVICE_MTRL_API real MicrofacetVelvet::pdf( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) { auto ret = pdf(param->roughness, normal, wi, wo); return ret; } AT_DEVICE_MTRL_API real MicrofacetVelvet::pdf( const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) const { return pdf(&m_param, normal, wi, wo, u, v); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetVelvet::sampleDirection( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, real u, real v, aten::sampler* sampler) { aten::vec3 dir = sampleDirection(param->roughness, normal, wi, sampler); return std::move(dir); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetVelvet::sampleDirection( const aten::ray& ray, const aten::vec3& normal, real u, real v, aten::sampler* sampler) const { return std::move(sampleDirection(&m_param, normal, ray.dir, u, v, sampler)); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetVelvet::bsdf( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) { auto albedo = param->baseColor; albedo *= material::sampleTexture(param->albedoMap, u, v, real(1)); real fresnel = 1; real ior = param->ior; aten::vec3 ret = bsdf(albedo, param->roughness, ior, fresnel, normal, wi, wo, u, v); return std::move(ret); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetVelvet::bsdf( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v, const aten::vec3& externalAlbedo) { auto albedo = param->baseColor; albedo *= externalAlbedo; real fresnel = 1; real ior = param->ior; aten::vec3 ret = bsdf(albedo, param->roughness, ior, fresnel, normal, wi, wo, u, v); return std::move(ret); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetVelvet::bsdf( const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) const { return std::move(bsdf(&m_param, normal, wi, wo, u, v)); } static AT_DEVICE_MTRL_API inline real sampleVelvet_D( const aten::vec3& h, const aten::vec3& n, real roughness) { real cosTheta = dot(n, h); if (cosTheta < real(0)) { return real(0); } real inv_r = real(1) / roughness; real sinTheta = aten::sqrt(aten::cmpMax(1 - cosTheta * cosTheta, real(0))); real D = ((real(2) + inv_r) * aten::pow(sinTheta, inv_r)) / (AT_MATH_PI_2); return D; } static AT_DEVICE_MTRL_API inline real interpVelvetParam(int i, real a) { // NOTE // a = (1 - r)^2 static const real p0[] = { real(25.3245), real(3.32435), real(0.16801), real(-1.27393), real(-4.85967) }; static const real p1[] = { real(21.5473), real(3.82987), real(0.19823), real(-1.97760), real(-4.32054) }; // NOTE // P = (1 − r)^2 * p0 + (1 − (1 − r)^2) * p1 // => P = a * p0 + (1 - a) * p1 real p = a * p0[i] + (1 - a) + p1[i]; return p; } static AT_DEVICE_MTRL_API inline real computeVelvet_L(real x, real roughness) { real r = roughness; real powOneMinusR = aten::pow(real(1) - r, real(2)); real a = interpVelvetParam(0, powOneMinusR); real b = interpVelvetParam(1, powOneMinusR); real c = interpVelvetParam(2, powOneMinusR); real d = interpVelvetParam(3, powOneMinusR); real e = interpVelvetParam(4, powOneMinusR); // NOTE // L(x) = a / (1 + b * x^c) + d * x + e real L = a / (1 + b * aten::pow(x, c)) + d * x + e; return L; } static AT_DEVICE_MTRL_API inline real computeVelvet_Lambda(real cosTheta, real roughness) { real r = roughness; if (cosTheta < real(0.5)) { return aten::exp(computeVelvet_L(cosTheta, r)); } return aten::exp(2 * computeVelvet_L(0.5, r) - computeVelvet_L(1 - cosTheta, r)); } static AT_DEVICE_MTRL_API inline real sampleVelvet_G(real cos_wi, real cos_wo, real r) { cos_wi = real(cos_wi <= real(0) ? 0 : 1); cos_wo = real(cos_wo <= real(0) ? 0 : 1); real G = cos_wi * cos_wo / (1 + computeVelvet_Lambda(cos_wi, r) + computeVelvet_Lambda(cos_wo, r)); return G; } AT_DEVICE_MTRL_API real MicrofacetVelvet::pdf( real roughness, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo) { // NOTE // "We found plain uniform sampling of the upper hemisphere to be more effective". // とのことで、importance sampling でなく、uniform sampling がいいらしい... aten::vec3 V = -wi; aten::vec3 N = normal; auto cosTheta = dot(V, N); if (cosTheta < real(0)) { return real(0); } return 1 / AT_MATH_PI_HALF; } AT_DEVICE_MTRL_API aten::vec3 MicrofacetVelvet::sampleDirection( real roughness, const aten::vec3& in, const aten::vec3& normal, aten::sampler* sampler) { auto n = normal; auto t = aten::getOrthoVector(n); auto b = cross(n, t); // NOTE // "We found plain uniform sampling of the upper hemisphere to be more effective". // とのことで、importance sampling でなく、uniform sampling がいいらしい... auto r1 = sampler->nextSample(); auto r2 = sampler->nextSample(); // NOTE // r2[0, 1] => phi[0, 2pi] auto phi = AT_MATH_PI_2 * r2; // NOTE // r1[0, 1] => cos_theta[0, 1] auto cosTheta = r1; auto sinTheta = aten::sqrt(1 - cosTheta * cosTheta); auto x = aten::cos(phi) * sinTheta; auto y = aten::sin(phi) * sinTheta; auto z = cosTheta; aten::vec3 dir = normalize((t * x + b * y + n * z)); return std::move(dir); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetVelvet::bsdf( const aten::vec3& albedo, const real roughness, const real ior, real& fresnel, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) { aten::vec3 V = -wi; aten::vec3 L = wo; aten::vec3 N = normal; aten::vec3 H = normalize(L + V); auto NdotL = aten::abs(dot(N, L)); auto NdotV = aten::abs(dot(N, V)); // Compute D. real D = sampleVelvet_D(H, N, roughness); // Compute G. real G = sampleVelvet_G(NdotL, NdotV, roughness); auto denom = 4 * NdotL * NdotV; auto bsdf = denom > AT_MATH_EPSILON ? albedo * G * D / denom : aten::vec3(0); fresnel = real(0); return std::move(bsdf); } AT_DEVICE_MTRL_API void MicrofacetVelvet::sample( MaterialSampling* result, const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& orgnormal, aten::sampler* sampler, real u, real v, bool isLightPath/*= false*/) { result->dir = sampleDirection(param->roughness, wi, normal, sampler); result->pdf = pdf(param->roughness, normal, wi, result->dir); auto albedo = param->baseColor; albedo *= material::sampleTexture(param->albedoMap, u, v, real(1)); real fresnel = 1; real ior = param->ior; result->bsdf = bsdf(albedo, param->roughness, ior, fresnel, normal, wi, result->dir, u, v); result->fresnel = fresnel; } AT_DEVICE_MTRL_API void MicrofacetVelvet::sample( MaterialSampling* result, const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& orgnormal, aten::sampler* sampler, real u, real v, const aten::vec3& externalAlbedo, bool isLightPath/*= false*/) { result->dir = sampleDirection(param->roughness, wi, normal, sampler); result->pdf = pdf(param->roughness, normal, wi, result->dir); auto albedo = param->baseColor; albedo *= externalAlbedo; real fresnel = 1; real ior = param->ior; result->bsdf = bsdf(albedo, param->roughness, ior, fresnel, normal, wi, result->dir, u, v); result->fresnel = fresnel; } AT_DEVICE_MTRL_API MaterialSampling MicrofacetVelvet::sample( const aten::ray& ray, const aten::vec3& normal, const aten::vec3& orgnormal, aten::sampler* sampler, real u, real v, bool isLightPath/*= false*/) const { MaterialSampling ret; sample( &ret, &m_param, normal, ray.dir, orgnormal, sampler, u, v, isLightPath); return std::move(ret); } bool MicrofacetVelvet::edit(aten::IMaterialParamEditor* editor) { auto b0 = AT_EDIT_MATERIAL_PARAM(editor, m_param, roughness); auto b1 = AT_EDIT_MATERIAL_PARAM(editor, m_param, baseColor); AT_EDIT_MATERIAL_PARAM_TEXTURE(editor, m_param, albedoMap); AT_EDIT_MATERIAL_PARAM_TEXTURE(editor, m_param, normalMap); return b0 || b1; } } <commit_msg>Fix errors due to refactoring.<commit_after>#include "material/velvet.h" #include "math/math.h" #include "material/sample_texture.h" namespace AT_NAME { // NOTE // Production Friendly Microfacet Sheen BRDF. // http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf AT_DEVICE_MTRL_API real MicrofacetVelvet::pdf( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) { auto ret = pdf(param->roughness, normal, wi, wo); return ret; } AT_DEVICE_MTRL_API real MicrofacetVelvet::pdf( const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) const { return pdf(&m_param, normal, wi, wo, u, v); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetVelvet::sampleDirection( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, real u, real v, aten::sampler* sampler) { aten::vec3 dir = sampleDirection(param->roughness, normal, wi, sampler); return std::move(dir); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetVelvet::sampleDirection( const aten::ray& ray, const aten::vec3& normal, real u, real v, aten::sampler* sampler) const { return std::move(sampleDirection(&m_param, normal, ray.dir, u, v, sampler)); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetVelvet::bsdf( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) { auto albedo = param->baseColor; albedo *= AT_NAME::sampleTexture(param->albedoMap, u, v, aten::vec3(real(1))); real fresnel = 1; real ior = param->ior; aten::vec3 ret = bsdf(albedo, param->roughness, ior, fresnel, normal, wi, wo, u, v); return std::move(ret); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetVelvet::bsdf( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v, const aten::vec3& externalAlbedo) { auto albedo = param->baseColor; albedo *= externalAlbedo; real fresnel = 1; real ior = param->ior; aten::vec3 ret = bsdf(albedo, param->roughness, ior, fresnel, normal, wi, wo, u, v); return std::move(ret); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetVelvet::bsdf( const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) const { return std::move(bsdf(&m_param, normal, wi, wo, u, v)); } static AT_DEVICE_MTRL_API inline real sampleVelvet_D( const aten::vec3& h, const aten::vec3& n, real roughness) { real cosTheta = dot(n, h); if (cosTheta < real(0)) { return real(0); } real inv_r = real(1) / roughness; real sinTheta = aten::sqrt(aten::cmpMax(1 - cosTheta * cosTheta, real(0))); real D = ((real(2) + inv_r) * aten::pow(sinTheta, inv_r)) / (AT_MATH_PI_2); return D; } static AT_DEVICE_MTRL_API inline real interpVelvetParam(int i, real a) { // NOTE // a = (1 - r)^2 static const real p0[] = { real(25.3245), real(3.32435), real(0.16801), real(-1.27393), real(-4.85967) }; static const real p1[] = { real(21.5473), real(3.82987), real(0.19823), real(-1.97760), real(-4.32054) }; // NOTE // P = (1 − r)^2 * p0 + (1 − (1 − r)^2) * p1 // => P = a * p0 + (1 - a) * p1 real p = a * p0[i] + (1 - a) + p1[i]; return p; } static AT_DEVICE_MTRL_API inline real computeVelvet_L(real x, real roughness) { real r = roughness; real powOneMinusR = aten::pow(real(1) - r, real(2)); real a = interpVelvetParam(0, powOneMinusR); real b = interpVelvetParam(1, powOneMinusR); real c = interpVelvetParam(2, powOneMinusR); real d = interpVelvetParam(3, powOneMinusR); real e = interpVelvetParam(4, powOneMinusR); // NOTE // L(x) = a / (1 + b * x^c) + d * x + e real L = a / (1 + b * aten::pow(x, c)) + d * x + e; return L; } static AT_DEVICE_MTRL_API inline real computeVelvet_Lambda(real cosTheta, real roughness) { real r = roughness; if (cosTheta < real(0.5)) { return aten::exp(computeVelvet_L(cosTheta, r)); } return aten::exp(2 * computeVelvet_L(0.5, r) - computeVelvet_L(1 - cosTheta, r)); } static AT_DEVICE_MTRL_API inline real sampleVelvet_G(real cos_wi, real cos_wo, real r) { cos_wi = real(cos_wi <= real(0) ? 0 : 1); cos_wo = real(cos_wo <= real(0) ? 0 : 1); real G = cos_wi * cos_wo / (1 + computeVelvet_Lambda(cos_wi, r) + computeVelvet_Lambda(cos_wo, r)); return G; } AT_DEVICE_MTRL_API real MicrofacetVelvet::pdf( real roughness, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo) { // NOTE // "We found plain uniform sampling of the upper hemisphere to be more effective". // とのことで、importance sampling でなく、uniform sampling がいいらしい... aten::vec3 V = -wi; aten::vec3 N = normal; auto cosTheta = dot(V, N); if (cosTheta < real(0)) { return real(0); } return 1 / AT_MATH_PI_HALF; } AT_DEVICE_MTRL_API aten::vec3 MicrofacetVelvet::sampleDirection( real roughness, const aten::vec3& in, const aten::vec3& normal, aten::sampler* sampler) { auto n = normal; auto t = aten::getOrthoVector(n); auto b = cross(n, t); // NOTE // "We found plain uniform sampling of the upper hemisphere to be more effective". // とのことで、importance sampling でなく、uniform sampling がいいらしい... auto r1 = sampler->nextSample(); auto r2 = sampler->nextSample(); // NOTE // r2[0, 1] => phi[0, 2pi] auto phi = AT_MATH_PI_2 * r2; // NOTE // r1[0, 1] => cos_theta[0, 1] auto cosTheta = r1; auto sinTheta = aten::sqrt(1 - cosTheta * cosTheta); auto x = aten::cos(phi) * sinTheta; auto y = aten::sin(phi) * sinTheta; auto z = cosTheta; aten::vec3 dir = normalize((t * x + b * y + n * z)); return std::move(dir); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetVelvet::bsdf( const aten::vec3& albedo, const real roughness, const real ior, real& fresnel, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) { aten::vec3 V = -wi; aten::vec3 L = wo; aten::vec3 N = normal; aten::vec3 H = normalize(L + V); auto NdotL = aten::abs(dot(N, L)); auto NdotV = aten::abs(dot(N, V)); // Compute D. real D = sampleVelvet_D(H, N, roughness); // Compute G. real G = sampleVelvet_G(NdotL, NdotV, roughness); auto denom = 4 * NdotL * NdotV; auto bsdf = denom > AT_MATH_EPSILON ? albedo * G * D / denom : aten::vec3(0); fresnel = real(0); return std::move(bsdf); } AT_DEVICE_MTRL_API void MicrofacetVelvet::sample( MaterialSampling* result, const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& orgnormal, aten::sampler* sampler, real u, real v, bool isLightPath/*= false*/) { result->dir = sampleDirection(param->roughness, wi, normal, sampler); result->pdf = pdf(param->roughness, normal, wi, result->dir); auto albedo = param->baseColor; albedo *= AT_NAME::sampleTexture(param->albedoMap, u, v, aten::vec3(real(1))); real fresnel = 1; real ior = param->ior; result->bsdf = bsdf(albedo, param->roughness, ior, fresnel, normal, wi, result->dir, u, v); result->fresnel = fresnel; } AT_DEVICE_MTRL_API void MicrofacetVelvet::sample( MaterialSampling* result, const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& orgnormal, aten::sampler* sampler, real u, real v, const aten::vec3& externalAlbedo, bool isLightPath/*= false*/) { result->dir = sampleDirection(param->roughness, wi, normal, sampler); result->pdf = pdf(param->roughness, normal, wi, result->dir); auto albedo = param->baseColor; albedo *= externalAlbedo; real fresnel = 1; real ior = param->ior; result->bsdf = bsdf(albedo, param->roughness, ior, fresnel, normal, wi, result->dir, u, v); result->fresnel = fresnel; } AT_DEVICE_MTRL_API MaterialSampling MicrofacetVelvet::sample( const aten::ray& ray, const aten::vec3& normal, const aten::vec3& orgnormal, aten::sampler* sampler, real u, real v, bool isLightPath/*= false*/) const { MaterialSampling ret; sample( &ret, &m_param, normal, ray.dir, orgnormal, sampler, u, v, isLightPath); return std::move(ret); } bool MicrofacetVelvet::edit(aten::IMaterialParamEditor* editor) { auto b0 = AT_EDIT_MATERIAL_PARAM(editor, m_param, roughness); auto b1 = AT_EDIT_MATERIAL_PARAM(editor, m_param, baseColor); AT_EDIT_MATERIAL_PARAM_TEXTURE(editor, m_param, albedoMap); AT_EDIT_MATERIAL_PARAM_TEXTURE(editor, m_param, normalMap); return b0 || b1; } } <|endoftext|>
<commit_before>#include "fetchgit.hh" #include "primops.hh" #include "eval-inline.hh" #include "download.hh" #include "store-api.hh" #include "pathlocks.hh" #include <sys/time.h> #include <regex> #include <nlohmann/json.hpp> using namespace std::string_literals; namespace nix { GitInfo exportGit(ref<Store> store, const std::string & uri, const std::string & ref, const std::string & rev, const std::string & name) { if (rev != "") { std::regex revRegex("^[0-9a-fA-F]{40}$"); if (!std::regex_match(rev, revRegex)) throw Error("invalid Git revision '%s'", rev); } Path cacheDir = getCacheDir() + "/nix/git"; if (!pathExists(cacheDir)) { createDirs(cacheDir); runProgram("git", true, { "init", "--bare", cacheDir }); } std::string localRef = hashString(htSHA256, fmt("%s-%s", uri, ref)).to_string(Base32, false); Path localRefFile = cacheDir + "/refs/heads/" + localRef; /* If the local ref is older than ‘tarball-ttl’ seconds, do a git fetch to update the local ref to the remote ref. */ time_t now = time(0); struct stat st; if (stat(localRefFile.c_str(), &st) != 0 || st.st_mtime < now - settings.tarballTtl) { Activity act(*logger, lvlTalkative, actUnknown, fmt("fetching Git repository '%s'", uri)); // FIXME: git stderr messes up our progress indicator, so // we're using --quiet for now. Should process its stderr. runProgram("git", true, { "-C", cacheDir, "fetch", "--quiet", "--force", "--", uri, ref + ":" + localRef }); struct timeval times[2]; times[0].tv_sec = now; times[0].tv_usec = 0; times[1].tv_sec = now; times[1].tv_usec = 0; utimes(localRefFile.c_str(), times); } // FIXME: check whether rev is an ancestor of ref. GitInfo gitInfo; gitInfo.rev = rev != "" ? rev : chomp(readFile(localRefFile)); gitInfo.shortRev = std::string(gitInfo.rev, 0, 7); printTalkative("using revision %s of repo '%s'", uri, gitInfo.rev); std::string storeLinkName = hashString(htSHA512, name + std::string("\0"s) + gitInfo.rev).to_string(Base32, false); Path storeLink = cacheDir + "/" + storeLinkName + ".link"; PathLocks storeLinkLock({storeLink}, fmt("waiting for lock on '%1%'...", storeLink)); try { // FIXME: doesn't handle empty lines auto json = nlohmann::json::parse(readFile(storeLink)); assert(json["uri"] == uri && json["name"] == name && json["rev"] == gitInfo.rev); gitInfo.storePath = json["storePath"]; if (store->isValidPath(gitInfo.storePath)) { gitInfo.revCount = json["revCount"]; return gitInfo; } } catch (SysError & e) { if (e.errNo != ENOENT) throw; } // FIXME: should pipe this, or find some better way to extract a // revision. auto tar = runProgram("git", true, { "-C", cacheDir, "archive", gitInfo.rev }); Path tmpDir = createTempDir(); AutoDelete delTmpDir(tmpDir, true); runProgram("tar", true, { "x", "-C", tmpDir }, tar); gitInfo.storePath = store->addToStore(name, tmpDir); gitInfo.revCount = std::stoull(runProgram("git", true, { "-C", cacheDir, "rev-list", "--count", gitInfo.rev })); nlohmann::json json; json["storePath"] = gitInfo.storePath; json["uri"] = uri; json["name"] = name; json["rev"] = gitInfo.rev; json["revCount"] = gitInfo.revCount; writeFile(storeLink, json.dump()); return gitInfo; } static void prim_fetchGit(EvalState & state, const Pos & pos, Value * * args, Value & v) { std::string url; std::string ref = "master"; std::string rev; std::string name = "source"; state.forceValue(*args[0]); if (args[0]->type == tAttrs) { state.forceAttrs(*args[0], pos); for (auto & attr : *args[0]->attrs) { string n(attr.name); if (n == "url") { PathSet context; url = state.coerceToString(*attr.pos, *attr.value, context, false, false); if (hasPrefix(url, "/")) url = "file://" + url; } else if (n == "ref") ref = state.forceStringNoCtx(*attr.value, *attr.pos); else if (n == "rev") rev = state.forceStringNoCtx(*attr.value, *attr.pos); else if (n == "name") name = state.forceStringNoCtx(*attr.value, *attr.pos); else throw EvalError("unsupported argument '%s' to 'fetchGit', at %s", attr.name, *attr.pos); } if (url.empty()) throw EvalError(format("'url' argument required, at %1%") % pos); } else url = state.forceStringNoCtx(*args[0], pos); // FIXME: git externals probably can be used to bypass the URI // whitelist. Ah well. state.checkURI(url); auto gitInfo = exportGit(state.store, url, ref, rev, name); state.mkAttrs(v, 8); mkString(*state.allocAttr(v, state.sOutPath), gitInfo.storePath, PathSet({gitInfo.storePath})); mkString(*state.allocAttr(v, state.symbols.create("rev")), gitInfo.rev); mkString(*state.allocAttr(v, state.symbols.create("shortRev")), gitInfo.shortRev); mkInt(*state.allocAttr(v, state.symbols.create("revCount")), gitInfo.revCount); v.attrs->sort(); } static RegisterPrimOp r("fetchGit", 1, prim_fetchGit); } <commit_msg>fetchGit: Fix broken assertion<commit_after>#include "fetchgit.hh" #include "primops.hh" #include "eval-inline.hh" #include "download.hh" #include "store-api.hh" #include "pathlocks.hh" #include <sys/time.h> #include <regex> #include <nlohmann/json.hpp> using namespace std::string_literals; namespace nix { GitInfo exportGit(ref<Store> store, const std::string & uri, const std::string & ref, const std::string & rev, const std::string & name) { if (rev != "") { std::regex revRegex("^[0-9a-fA-F]{40}$"); if (!std::regex_match(rev, revRegex)) throw Error("invalid Git revision '%s'", rev); } Path cacheDir = getCacheDir() + "/nix/git"; if (!pathExists(cacheDir)) { createDirs(cacheDir); runProgram("git", true, { "init", "--bare", cacheDir }); } std::string localRef = hashString(htSHA256, fmt("%s-%s", uri, ref)).to_string(Base32, false); Path localRefFile = cacheDir + "/refs/heads/" + localRef; /* If the local ref is older than ‘tarball-ttl’ seconds, do a git fetch to update the local ref to the remote ref. */ time_t now = time(0); struct stat st; if (stat(localRefFile.c_str(), &st) != 0 || st.st_mtime < now - settings.tarballTtl) { Activity act(*logger, lvlTalkative, actUnknown, fmt("fetching Git repository '%s'", uri)); // FIXME: git stderr messes up our progress indicator, so // we're using --quiet for now. Should process its stderr. runProgram("git", true, { "-C", cacheDir, "fetch", "--quiet", "--force", "--", uri, ref + ":" + localRef }); struct timeval times[2]; times[0].tv_sec = now; times[0].tv_usec = 0; times[1].tv_sec = now; times[1].tv_usec = 0; utimes(localRefFile.c_str(), times); } // FIXME: check whether rev is an ancestor of ref. GitInfo gitInfo; gitInfo.rev = rev != "" ? rev : chomp(readFile(localRefFile)); gitInfo.shortRev = std::string(gitInfo.rev, 0, 7); printTalkative("using revision %s of repo '%s'", uri, gitInfo.rev); std::string storeLinkName = hashString(htSHA512, name + std::string("\0"s) + gitInfo.rev).to_string(Base32, false); Path storeLink = cacheDir + "/" + storeLinkName + ".link"; PathLocks storeLinkLock({storeLink}, fmt("waiting for lock on '%1%'...", storeLink)); try { // FIXME: doesn't handle empty lines auto json = nlohmann::json::parse(readFile(storeLink)); assert(json["name"] == name && json["rev"] == gitInfo.rev); gitInfo.storePath = json["storePath"]; if (store->isValidPath(gitInfo.storePath)) { gitInfo.revCount = json["revCount"]; return gitInfo; } } catch (SysError & e) { if (e.errNo != ENOENT) throw; } // FIXME: should pipe this, or find some better way to extract a // revision. auto tar = runProgram("git", true, { "-C", cacheDir, "archive", gitInfo.rev }); Path tmpDir = createTempDir(); AutoDelete delTmpDir(tmpDir, true); runProgram("tar", true, { "x", "-C", tmpDir }, tar); gitInfo.storePath = store->addToStore(name, tmpDir); gitInfo.revCount = std::stoull(runProgram("git", true, { "-C", cacheDir, "rev-list", "--count", gitInfo.rev })); nlohmann::json json; json["storePath"] = gitInfo.storePath; json["uri"] = uri; json["name"] = name; json["rev"] = gitInfo.rev; json["revCount"] = gitInfo.revCount; writeFile(storeLink, json.dump()); return gitInfo; } static void prim_fetchGit(EvalState & state, const Pos & pos, Value * * args, Value & v) { std::string url; std::string ref = "master"; std::string rev; std::string name = "source"; state.forceValue(*args[0]); if (args[0]->type == tAttrs) { state.forceAttrs(*args[0], pos); for (auto & attr : *args[0]->attrs) { string n(attr.name); if (n == "url") { PathSet context; url = state.coerceToString(*attr.pos, *attr.value, context, false, false); if (hasPrefix(url, "/")) url = "file://" + url; } else if (n == "ref") ref = state.forceStringNoCtx(*attr.value, *attr.pos); else if (n == "rev") rev = state.forceStringNoCtx(*attr.value, *attr.pos); else if (n == "name") name = state.forceStringNoCtx(*attr.value, *attr.pos); else throw EvalError("unsupported argument '%s' to 'fetchGit', at %s", attr.name, *attr.pos); } if (url.empty()) throw EvalError(format("'url' argument required, at %1%") % pos); } else url = state.forceStringNoCtx(*args[0], pos); // FIXME: git externals probably can be used to bypass the URI // whitelist. Ah well. state.checkURI(url); auto gitInfo = exportGit(state.store, url, ref, rev, name); state.mkAttrs(v, 8); mkString(*state.allocAttr(v, state.sOutPath), gitInfo.storePath, PathSet({gitInfo.storePath})); mkString(*state.allocAttr(v, state.symbols.create("rev")), gitInfo.rev); mkString(*state.allocAttr(v, state.symbols.create("shortRev")), gitInfo.shortRev); mkInt(*state.allocAttr(v, state.symbols.create("revCount")), gitInfo.revCount); v.attrs->sort(); } static RegisterPrimOp r("fetchGit", 1, prim_fetchGit); } <|endoftext|>
<commit_before>#include <vector> #include <map> #include "HalfEdgeMesh2D.h" #include "Vertex.h" #include "Edge.h" #include "Face.h" #include <fstream> #include <string> using namespace cop4530; using namespace mwm; //std specialization namespace std { template <> class hash < Vertex* > { public: size_t operator()(const Vertex* val) const { return val->pos.a ^ val->pos.b; //return val->contactPoint.squareMag();//works } }; template <> class equal_to < Vertex* > { public: bool operator()(const Vertex* lhs, const Vertex* rhs) const { return (lhs->pos == rhs->pos); } }; } HalfEdgeMesh2D::HalfEdgeMesh2D() { vertexPool.CreatePoolParty(); edgePool.CreatePoolParty(); facePool.CreatePoolParty(); } HalfEdgeMesh2D::~HalfEdgeMesh2D() { } void HalfEdgeMesh2D::Construct(const char * path) { std::ifstream file1(path); std::string str; std::string map = ""; int width = 0; int height = 0; //loading the map into a single buffer while (std::getline(file1, str)) { map += str; height++; } width = str.length(); Vector<Face*> allFaces; allFaces.reserve(height*width); Face* emptyFace = new Face(); file1.close(); for (int y = 0; y < height; y++) { if (map[y*width] == '/' || map[y*width] == ';' || map[y*width] == '#') continue; /* ignore comment line */ for (int x = 0; x < width; x++) { int currentCell = y*width + x; if (map[currentCell] == 'X') { allFaces.push_back(emptyFace); } else { //connecting //let's get vertices we wanna work with Vertex* vertice1 = vertexPool.PoolPartyAlloc(); Vertex* vertice2 = vertexPool.PoolPartyAlloc(); Vertex* vertice3 = vertexPool.PoolPartyAlloc(); Vertex* vertice4 = vertexPool.PoolPartyAlloc(); vertice1->pos = Vector2((float)x, (float)(y + 1)); vertice2->pos = Vector2((float)x, (float)y); vertice3->pos = Vector2((float)(x + 1), (float)y); vertice4->pos = Vector2((float)(x + 1), (float)(y + 1)); //create new edges Edge* newEdge1 = edgePool.PoolPartyAlloc(); Edge* newEdge2 = edgePool.PoolPartyAlloc(); Edge* newEdge3 = edgePool.PoolPartyAlloc(); //connect vertices to edges newEdge1->vertex = vertice1; newEdge2->vertex = vertice2; newEdge3->vertex = vertice3; //connect edges with next newEdge1->next = newEdge2; newEdge2->next = newEdge3; newEdge3->next = newEdge1; //connect edges with previous newEdge1->prev = newEdge3; newEdge2->prev = newEdge1; newEdge3->prev = newEdge2; edges.push_back(newEdge1); edges.push_back(newEdge2); edges.push_back(newEdge3); Edge* newEdge4 = edgePool.PoolPartyAlloc(); Edge* newEdge5 = edgePool.PoolPartyAlloc(); Edge* newEdge6 = edgePool.PoolPartyAlloc(); //connect vertices to edges newEdge4->vertex = vertice3; newEdge5->vertex = vertice4; newEdge6->vertex = vertice1; //connect edges with next newEdge4->next = newEdge5; newEdge5->next = newEdge6; newEdge6->next = newEdge4; //connect edges with previous newEdge4->prev = newEdge6; newEdge5->prev = newEdge4; newEdge6->prev = newEdge5; newEdge6->pair = newEdge3; newEdge3->pair = newEdge6; //is not at x boundaries? if (x > 0) { //is cell to the right walkable? if (map[currentCell-1] != 'X') { //pair with the last added face (the one to the right) Edge* lastFaceEdge = faces.back()->edge; lastFaceEdge->pair = newEdge1; newEdge1->pair = lastFaceEdge; } } //is not at y boundaries? if (y > 0) { //is cell above walkable? int cellAbove = (y - 1)*width + x; if (map[cellAbove] != 'X') { //pair with the cell above Edge* aboveFaceEdge = allFaces[cellAbove]->edge->next; aboveFaceEdge->pair = newEdge2; newEdge2->pair = aboveFaceEdge; } } edges.push_back(newEdge4); edges.push_back(newEdge5); edges.push_back(newEdge6); vertices.push_back(vertice1); vertices.push_back(vertice2); vertices.push_back(vertice3); vertices.push_back(vertice4); Face* newFace = facePool.PoolPartyAlloc(); Face* newFace2 = facePool.PoolPartyAlloc(); newFace->edge = newEdge1; newFace2->edge = newEdge4; newEdge1->face = newFace; newEdge1->next->face = newFace; newEdge1->next->next->face = newFace; newEdge4->face = newFace2; newEdge4->next->face = newFace2; newEdge4->next->next->face = newFace2; faces.push_back(newFace); faces.push_back(newFace2); allFaces.push_back(newFace2); if (map[currentCell] == 'S') { startFace = newFace; //startFacePos = newFace->edge->vertex->pos; startFacePos = newFace->getMidPointAverage(); } if (map[currentCell] == 'G') { goals.push_back(newFace2); goalsPos.push_back(newFace2->getMidPointAverage()); endFace = newFace2; //endFacePos = newFace2->edge->vertex->pos; endFacePos = newFace2->getMidPointAverage(); } } } } for (int i = 0; i < allFaces.size(); i++) { if (allFaces[i]->edge == nullptr) { delete allFaces[i]; } } /* for (int i = 0; i < edges.size(); i++) //error check, if we connected the edge to itself as pair { if (edges.at(i)->next == edges.at(i)->pair) { printf("error %d \n", i); } } */ } Face* HalfEdgeMesh2D::findNode(Vector2 point) { for (int i = 0; i < faces.size(); i++) { if (this->isPointInNode(point, faces.at(i))) { return faces.at(i); } } return NULL; } bool HalfEdgeMesh2D::isPointInNode(Vector2 point, Face* node) { Edge* currentEdge = node->edge; //Looping through every edge in the current node do { Vector2 vectorOfEdge = (currentEdge->next->vertex->pos - currentEdge->vertex->pos).vectNormalize(); Vector2 vectorToPoint = point-currentEdge->vertex->pos; if (vectorToPoint.vect[0] != 0 && vectorToPoint.vect[1] != 0) { vectorToPoint = vectorToPoint.vectNormalize(); } //clockwise as halfedgemesh is clockwise Vector2 sideVectorToEdge = Vector2(vectorOfEdge.vect[1], -vectorOfEdge.vect[0]).vectNormalize(); if (sideVectorToEdge.dotAKAscalar(vectorToPoint) > 0) { return false; } currentEdge = currentEdge->next; } while (currentEdge != node->edge); return true; } void HalfEdgeMesh2D::quadrangulate() { std::list<Face*> toOptimize; Vector<Face*> optimized; for (int i = 0; i < faces.size(); i++) { toOptimize.push_back(faces.at(i)); } while (!toOptimize.empty()) { Face* face = toOptimize.front(); toOptimize.pop_front(); if (!face->joined) { if (tryToJoin(face)){ toOptimize.push_back(face); } else optimized.push_back(face); } } faces = optimized; } void HalfEdgeMesh2D::optimizeMesh() { std::list<Face*> toOptimize; Vector<Face*> optimized; for (int i = 0; i < faces.size(); i++) { toOptimize.push_back(faces.at(i)); } while (!toOptimize.empty()) { Face* face = toOptimize.front(); toOptimize.pop_front(); if (!face->joined) { if (tryToJoin2(face)){ toOptimize.push_back(face); } else optimized.push_back(face); } } faces = optimized; } bool HalfEdgeMesh2D::tryToJoin(Face* face) { Edge* currentEdge = face->edge; do { Edge* pair = currentEdge->pair; if (pair && turnsRight(currentEdge->prev, pair->next) && turnsRight(pair->prev, currentEdge->next)) { pair->face->joined = true; moveEdgesToFace(pair, face); currentEdge->prev->next = pair->next; pair->next->prev = currentEdge->prev; pair->prev->next = currentEdge->next; currentEdge->next->prev = pair->prev; if (currentEdge == face->edge) face->edge = currentEdge->prev; joinSharedEdges(face); return true; } currentEdge = currentEdge->next; } while (currentEdge != face->edge); return false; } bool HalfEdgeMesh2D::tryToJoin2(Face* face) { Edge* currentEdge = face->edge; do { Edge* pair = currentEdge->pair; if (pair && turnsRightOrParallel(currentEdge->prev, pair->next) && turnsRightOrParallel(pair->prev, currentEdge->next)) { pair->face->joined = true; moveEdgesToFace(pair, face); currentEdge->prev->next = pair->next; pair->next->prev = currentEdge->prev; pair->prev->next = currentEdge->next; currentEdge->next->prev = pair->prev; if (currentEdge == face->edge) face->edge = currentEdge->prev; joinSharedEdges(face); return true; } currentEdge = currentEdge->next; } while (currentEdge != face->edge); return false; } bool HalfEdgeMesh2D::turnsRight(Edge* e1, Edge* e2) { Vector2 vectorOfEdge1 = e1->next->vertex->pos - e1->vertex->pos; Vector2 vectorOfEdge2 = e2->next->vertex->pos - e2->vertex->pos; Vector2 sideVectorToEdge = Vector2(vectorOfEdge1.vect[1], -vectorOfEdge1.vect[0]); return sideVectorToEdge.dotAKAscalar(vectorOfEdge2) < 0; } bool HalfEdgeMesh2D::turnsRightOrParallel(Edge* e1, Edge* e2) { Vector2 vectorOfEdge1 = e1->next->vertex->pos - e1->vertex->pos; Vector2 vectorOfEdge2 = e2->next->vertex->pos - e2->vertex->pos; Vector2 sideVectorToEdge = Vector2(vectorOfEdge1.vect[1], -vectorOfEdge1.vect[0]); return sideVectorToEdge.dotAKAscalar(vectorOfEdge2) <= 0; } void HalfEdgeMesh2D::moveEdgesToFace(Edge* startEdge, Face* destFace) { Edge* currentEdge = startEdge; do { currentEdge->face = destFace; currentEdge = currentEdge->next; } while (currentEdge != startEdge); } void HalfEdgeMesh2D::joinSharedEdges(Face* testedFace) { Edge* currentEdge = testedFace->edge; do { Edge* pair = currentEdge->next->pair; if (pair && currentEdge->pair == pair->next) { if (currentEdge->next == testedFace->edge) testedFace->edge = currentEdge->next->next; if (pair->next == pair->face->edge) pair->face->edge = pair; currentEdge->next = currentEdge->next->next; currentEdge->next->prev = currentEdge; pair->next = pair->next->next; pair->next->prev = pair; currentEdge->pair = pair; pair->pair = currentEdge; } currentEdge = currentEdge->next; } while (currentEdge != testedFace->edge); }<commit_msg>just use the pool instead of new<commit_after>#include <vector> #include <map> #include "HalfEdgeMesh2D.h" #include "Vertex.h" #include "Edge.h" #include "Face.h" #include <fstream> #include <string> using namespace cop4530; using namespace mwm; //std specialization namespace std { template <> class hash < Vertex* > { public: size_t operator()(const Vertex* val) const { return val->pos.a ^ val->pos.b; //return val->contactPoint.squareMag();//works } }; template <> class equal_to < Vertex* > { public: bool operator()(const Vertex* lhs, const Vertex* rhs) const { return (lhs->pos == rhs->pos); } }; } HalfEdgeMesh2D::HalfEdgeMesh2D() { vertexPool.CreatePoolParty(); edgePool.CreatePoolParty(); facePool.CreatePoolParty(); } HalfEdgeMesh2D::~HalfEdgeMesh2D() { } void HalfEdgeMesh2D::Construct(const char * path) { std::ifstream file1(path); std::string str; std::string map = ""; int width = 0; int height = 0; //loading the map into a single buffer while (std::getline(file1, str)) { map += str; height++; } width = str.length(); Vector<Face*> allFaces; allFaces.reserve(height*width); Face* emptyFace = facePool.PoolPartyAlloc(); file1.close(); for (int y = 0; y < height; y++) { if (map[y*width] == '/' || map[y*width] == ';' || map[y*width] == '#') continue; /* ignore comment line */ for (int x = 0; x < width; x++) { int currentCell = y*width + x; if (map[currentCell] == 'X') { allFaces.push_back(emptyFace); } else { //connecting //let's get vertices we wanna work with Vertex* vertice1 = vertexPool.PoolPartyAlloc(); Vertex* vertice2 = vertexPool.PoolPartyAlloc(); Vertex* vertice3 = vertexPool.PoolPartyAlloc(); Vertex* vertice4 = vertexPool.PoolPartyAlloc(); vertice1->pos = Vector2((float)x, (float)(y + 1)); vertice2->pos = Vector2((float)x, (float)y); vertice3->pos = Vector2((float)(x + 1), (float)y); vertice4->pos = Vector2((float)(x + 1), (float)(y + 1)); //create new edges Edge* newEdge1 = edgePool.PoolPartyAlloc(); Edge* newEdge2 = edgePool.PoolPartyAlloc(); Edge* newEdge3 = edgePool.PoolPartyAlloc(); //connect vertices to edges newEdge1->vertex = vertice1; newEdge2->vertex = vertice2; newEdge3->vertex = vertice3; //connect edges with next newEdge1->next = newEdge2; newEdge2->next = newEdge3; newEdge3->next = newEdge1; //connect edges with previous newEdge1->prev = newEdge3; newEdge2->prev = newEdge1; newEdge3->prev = newEdge2; edges.push_back(newEdge1); edges.push_back(newEdge2); edges.push_back(newEdge3); Edge* newEdge4 = edgePool.PoolPartyAlloc(); Edge* newEdge5 = edgePool.PoolPartyAlloc(); Edge* newEdge6 = edgePool.PoolPartyAlloc(); //connect vertices to edges newEdge4->vertex = vertice3; newEdge5->vertex = vertice4; newEdge6->vertex = vertice1; //connect edges with next newEdge4->next = newEdge5; newEdge5->next = newEdge6; newEdge6->next = newEdge4; //connect edges with previous newEdge4->prev = newEdge6; newEdge5->prev = newEdge4; newEdge6->prev = newEdge5; newEdge6->pair = newEdge3; newEdge3->pair = newEdge6; //is not at x boundaries? if (x > 0) { //is cell to the right walkable? if (map[currentCell-1] != 'X') { //pair with the last added face (the one to the right) Edge* lastFaceEdge = faces.back()->edge; lastFaceEdge->pair = newEdge1; newEdge1->pair = lastFaceEdge; } } //is not at y boundaries? if (y > 0) { //is cell above walkable? int cellAbove = (y - 1)*width + x; if (map[cellAbove] != 'X') { //pair with the cell above Edge* aboveFaceEdge = allFaces[cellAbove]->edge->next; aboveFaceEdge->pair = newEdge2; newEdge2->pair = aboveFaceEdge; } } edges.push_back(newEdge4); edges.push_back(newEdge5); edges.push_back(newEdge6); vertices.push_back(vertice1); vertices.push_back(vertice2); vertices.push_back(vertice3); vertices.push_back(vertice4); Face* newFace = facePool.PoolPartyAlloc(); Face* newFace2 = facePool.PoolPartyAlloc(); newFace->edge = newEdge1; newFace2->edge = newEdge4; newEdge1->face = newFace; newEdge1->next->face = newFace; newEdge1->next->next->face = newFace; newEdge4->face = newFace2; newEdge4->next->face = newFace2; newEdge4->next->next->face = newFace2; faces.push_back(newFace); faces.push_back(newFace2); allFaces.push_back(newFace2); if (map[currentCell] == 'S') { startFace = newFace; //startFacePos = newFace->edge->vertex->pos; startFacePos = newFace->getMidPointAverage(); } if (map[currentCell] == 'G') { goals.push_back(newFace2); goalsPos.push_back(newFace2->getMidPointAverage()); endFace = newFace2; //endFacePos = newFace2->edge->vertex->pos; endFacePos = newFace2->getMidPointAverage(); } } } } /* for (int i = 0; i < edges.size(); i++) //error check, if we connected the edge to itself as pair { if (edges.at(i)->next == edges.at(i)->pair) { printf("error %d \n", i); } } */ } Face* HalfEdgeMesh2D::findNode(Vector2 point) { for (int i = 0; i < faces.size(); i++) { if (this->isPointInNode(point, faces.at(i))) { return faces.at(i); } } return NULL; } bool HalfEdgeMesh2D::isPointInNode(Vector2 point, Face* node) { Edge* currentEdge = node->edge; //Looping through every edge in the current node do { Vector2 vectorOfEdge = (currentEdge->next->vertex->pos - currentEdge->vertex->pos).vectNormalize(); Vector2 vectorToPoint = point-currentEdge->vertex->pos; if (vectorToPoint.vect[0] != 0 && vectorToPoint.vect[1] != 0) { vectorToPoint = vectorToPoint.vectNormalize(); } //clockwise as halfedgemesh is clockwise Vector2 sideVectorToEdge = Vector2(vectorOfEdge.vect[1], -vectorOfEdge.vect[0]).vectNormalize(); if (sideVectorToEdge.dotAKAscalar(vectorToPoint) > 0) { return false; } currentEdge = currentEdge->next; } while (currentEdge != node->edge); return true; } void HalfEdgeMesh2D::quadrangulate() { std::list<Face*> toOptimize; Vector<Face*> optimized; for (int i = 0; i < faces.size(); i++) { toOptimize.push_back(faces.at(i)); } while (!toOptimize.empty()) { Face* face = toOptimize.front(); toOptimize.pop_front(); if (!face->joined) { if (tryToJoin(face)){ toOptimize.push_back(face); } else optimized.push_back(face); } } faces = optimized; } void HalfEdgeMesh2D::optimizeMesh() { std::list<Face*> toOptimize; Vector<Face*> optimized; for (int i = 0; i < faces.size(); i++) { toOptimize.push_back(faces.at(i)); } while (!toOptimize.empty()) { Face* face = toOptimize.front(); toOptimize.pop_front(); if (!face->joined) { if (tryToJoin2(face)){ toOptimize.push_back(face); } else optimized.push_back(face); } } faces = optimized; } bool HalfEdgeMesh2D::tryToJoin(Face* face) { Edge* currentEdge = face->edge; do { Edge* pair = currentEdge->pair; if (pair && turnsRight(currentEdge->prev, pair->next) && turnsRight(pair->prev, currentEdge->next)) { pair->face->joined = true; moveEdgesToFace(pair, face); currentEdge->prev->next = pair->next; pair->next->prev = currentEdge->prev; pair->prev->next = currentEdge->next; currentEdge->next->prev = pair->prev; if (currentEdge == face->edge) face->edge = currentEdge->prev; joinSharedEdges(face); return true; } currentEdge = currentEdge->next; } while (currentEdge != face->edge); return false; } bool HalfEdgeMesh2D::tryToJoin2(Face* face) { Edge* currentEdge = face->edge; do { Edge* pair = currentEdge->pair; if (pair && turnsRightOrParallel(currentEdge->prev, pair->next) && turnsRightOrParallel(pair->prev, currentEdge->next)) { pair->face->joined = true; moveEdgesToFace(pair, face); currentEdge->prev->next = pair->next; pair->next->prev = currentEdge->prev; pair->prev->next = currentEdge->next; currentEdge->next->prev = pair->prev; if (currentEdge == face->edge) face->edge = currentEdge->prev; joinSharedEdges(face); return true; } currentEdge = currentEdge->next; } while (currentEdge != face->edge); return false; } bool HalfEdgeMesh2D::turnsRight(Edge* e1, Edge* e2) { Vector2 vectorOfEdge1 = e1->next->vertex->pos - e1->vertex->pos; Vector2 vectorOfEdge2 = e2->next->vertex->pos - e2->vertex->pos; Vector2 sideVectorToEdge = Vector2(vectorOfEdge1.vect[1], -vectorOfEdge1.vect[0]); return sideVectorToEdge.dotAKAscalar(vectorOfEdge2) < 0; } bool HalfEdgeMesh2D::turnsRightOrParallel(Edge* e1, Edge* e2) { Vector2 vectorOfEdge1 = e1->next->vertex->pos - e1->vertex->pos; Vector2 vectorOfEdge2 = e2->next->vertex->pos - e2->vertex->pos; Vector2 sideVectorToEdge = Vector2(vectorOfEdge1.vect[1], -vectorOfEdge1.vect[0]); return sideVectorToEdge.dotAKAscalar(vectorOfEdge2) <= 0; } void HalfEdgeMesh2D::moveEdgesToFace(Edge* startEdge, Face* destFace) { Edge* currentEdge = startEdge; do { currentEdge->face = destFace; currentEdge = currentEdge->next; } while (currentEdge != startEdge); } void HalfEdgeMesh2D::joinSharedEdges(Face* testedFace) { Edge* currentEdge = testedFace->edge; do { Edge* pair = currentEdge->next->pair; if (pair && currentEdge->pair == pair->next) { if (currentEdge->next == testedFace->edge) testedFace->edge = currentEdge->next->next; if (pair->next == pair->face->edge) pair->face->edge = pair; currentEdge->next = currentEdge->next->next; currentEdge->next->prev = currentEdge; pair->next = pair->next->next; pair->next->prev = pair; currentEdge->pair = pair; pair->pair = currentEdge; } currentEdge = currentEdge->next; } while (currentEdge != testedFace->edge); }<|endoftext|>
<commit_before>// Copyright (c) 2019 The Dash Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <llmq/quorums_chainlocks.h> #include <llmq/quorums_utils.h> #include <chain.h> #include <masternode/masternodesync.h> #include <net_processing.h> #include <spork.h> #include <txmempool.h> #include <validation.h> namespace llmq { static const std::string CLSIG_REQUESTID_PREFIX = "clsig"; CChainLocksHandler* chainLocksHandler; bool CChainLockSig::IsNull() const { return nHeight == -1 && blockHash == uint256(); } std::string CChainLockSig::ToString() const { return strprintf("CChainLockSig(nHeight=%d, blockHash=%s)", nHeight, blockHash.ToString()); } CChainLocksHandler::CChainLocksHandler(CConnman& _connman, PeerManager& _peerman): connman(_connman), peerman(_peerman) { } CChainLocksHandler::~CChainLocksHandler() { } void CChainLocksHandler::Start() { quorumSigningManager->RegisterRecoveredSigsListener(this); } void CChainLocksHandler::Stop() { quorumSigningManager->UnregisterRecoveredSigsListener(this); } bool CChainLocksHandler::AlreadyHave(const uint256& hash) { LOCK(cs); return seenChainLocks.count(hash) != 0; } bool CChainLocksHandler::GetChainLockByHash(const uint256& hash, llmq::CChainLockSig& ret) { LOCK(cs); if (hash != bestChainLockHash) { // we only propagate the best one and ditch all the old ones return false; } ret = bestChainLock; return true; } CChainLockSig CChainLocksHandler::GetBestChainLock() { LOCK(cs); return bestChainLock; } void CChainLocksHandler::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv) { if (!AreChainLocksEnabled()) { return; } if (strCommand == NetMsgType::CLSIG) { CChainLockSig clsig; vRecv >> clsig; auto hash = ::SerializeHash(clsig); ProcessNewChainLock(pfrom->GetId(), clsig, hash); } } void CChainLocksHandler::ProcessNewChainLock(NodeId from, const llmq::CChainLockSig& clsig, const uint256&hash ) { bool enforced; if (from != -1) { LOCK(cs_main); peerman.ReceivedResponse(from, hash); } bool bReturn = false; { LOCK(cs); enforced = isEnforced; if (!seenChainLocks.try_emplace(hash, GetTimeMillis()).second) { bReturn = true; } if (!bestChainLock.IsNull() && clsig.nHeight <= bestChainLock.nHeight) { // no need to process/relay older CLSIGs bReturn = true; } } if(bReturn) { LOCK(cs_main); peerman.ForgetTxHash(from, hash); return; } uint256 requestId = ::SerializeHash(std::make_pair(CLSIG_REQUESTID_PREFIX, clsig.nHeight)); uint256 msgHash = clsig.blockHash; if (!quorumSigningManager->VerifyRecoveredSig(Params().GetConsensus().llmqTypeChainLocks, clsig.nHeight, requestId, msgHash, clsig.sig)) { LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- invalid CLSIG (%s), peer=%d\n", __func__, clsig.ToString(), from); if (from != -1) { LOCK(cs_main); peerman.ForgetTxHash(from, hash); peerman.Misbehaving(from, 10, "invalid CLSIG"); } return; } bool clsSigInternalConflict = false; { LOCK(cs); if (InternalHasConflictingChainLock(clsig.nHeight, clsig.blockHash)) { // This should not happen. If it happens, it means that a malicious entity controls a large part of the MN // network. In this case, we don't allow him to reorg older chainlocks. LogPrintf("CChainLocksHandler::%s -- new CLSIG (%s) tries to reorg previous CLSIG (%s), peer=%d\n", __func__, clsig.ToString(), bestChainLock.ToString(), from); clsSigInternalConflict = true; } else { bestChainLockHash = hash; bestChainLock = clsig; } } if(clsSigInternalConflict) { LOCK(cs_main); peerman.ForgetTxHash(from, hash); return; } // don't hold lock while relaying which locks nodes/mempool CInv inv(MSG_CLSIG, hash); const CBlockIndex* pindex; connman.RelayOtherInv(inv); { LOCK(cs_main); pindex = g_chainman.m_blockman.LookupBlockIndex(clsig.blockHash); if (pindex == nullptr) { // we don't know the block/header for this CLSIG yet, so bail out for now // when the block or the header later comes in, we will enforce the correct chain return; } if (pindex->nHeight != clsig.nHeight) { // Should not happen, same as the conflict check from above. LogPrintf("CChainLocksHandler::%s -- height of CLSIG (%s) does not match the specified block's height (%d)\n", __func__, clsig.ToString(), pindex->nHeight); return; } peerman.ForgetTxHash(from, hash); } { LOCK(cs); bestChainLockBlockIndex = pindex; } CheckActiveState(); EnforceBestChainLock(bestChainLockBlockIndex, bestChainLock, enforced); LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- processed new CLSIG (%s), peer=%d\n", __func__, clsig.ToString(), from); } void CChainLocksHandler::UpdatedBlockTip(const CBlockIndex* pindexNew, bool fInitialDownload) { if(fInitialDownload) return; CheckActiveState(); TrySignChainTip(pindexNew); } void CChainLocksHandler::CheckActiveState() { bool sporkActive = AreChainLocksEnabled(); { LOCK(cs); bool oldIsEnforced = isEnforced; isEnabled = sporkActive; isEnforced = isEnabled; if (!oldIsEnforced && isEnforced) { // ChainLocks got activated just recently, but it's possible that it was already running before, leaving // us with some stale values which we should not try to enforce anymore (there probably was a good reason // to disable spork19) bestChainLockHash = uint256(); bestChainLock = CChainLockSig(); } } } void CChainLocksHandler::TrySignChainTip(const CBlockIndex* pindex) { Cleanup(); if (!fMasternodeMode) { return; } if (!masternodeSync.IsBlockchainSynced()) { return; } if (!pindex->pprev) { return; } const uint256 msgHash = pindex->GetBlockHash(); const int32_t nHeight = pindex->nHeight; // DIP8 defines a process called "Signing attempts" which should run before the CLSIG is finalized // To simplify the initial implementation, we skip this process and directly try to create a CLSIG // This will fail when multiple blocks compete, but we accept this for the initial implementation. // Later, we'll add the multiple attempts process. { LOCK(cs); if (!isEnabled) { return; } if (nHeight == lastSignedHeight) { // already signed this one return; } if (bestChainLock.nHeight >= nHeight) { // already got the same CLSIG or a better one return; } if (InternalHasConflictingChainLock(nHeight, msgHash)) { // don't sign if another conflicting CLSIG is already present. EnforceBestChainLock will later enforce // the correct chain. return; } } LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- trying to sign %s, height=%d\n", __func__, msgHash.ToString(), nHeight); uint256 requestId = ::SerializeHash(std::make_pair(CLSIG_REQUESTID_PREFIX, nHeight)); { LOCK(cs); if (bestChainLock.nHeight >= nHeight) { // might have happened while we didn't hold cs return; } lastSignedHeight = nHeight; lastSignedRequestId = requestId; lastSignedMsgHash = msgHash; } quorumSigningManager->AsyncSignIfMember(Params().GetConsensus().llmqTypeChainLocks, requestId, msgHash); } void CChainLocksHandler::HandleNewRecoveredSig(const llmq::CRecoveredSig& recoveredSig) { CChainLockSig clsig; { LOCK(cs); if (!isEnabled) { return; } if (recoveredSig.id != lastSignedRequestId || recoveredSig.msgHash != lastSignedMsgHash) { // this is not what we signed, so lets not create a CLSIG for it return; } if (bestChainLock.nHeight >= lastSignedHeight) { // already got the same or a better CLSIG through the CLSIG message return; } clsig.nHeight = lastSignedHeight; clsig.blockHash = lastSignedMsgHash; clsig.sig = recoveredSig.sig.Get(); } ProcessNewChainLock(-1, clsig, ::SerializeHash(clsig)); } bool CChainLocksHandler::HasChainLock(int nHeight, const uint256& blockHash) { LOCK(cs); return InternalHasChainLock(nHeight, blockHash); } bool CChainLocksHandler::InternalHasChainLock(int nHeight, const uint256& blockHash) { AssertLockHeld(cs); if (!isEnforced) { return false; } if (!bestChainLockBlockIndex) { return false; } if (nHeight > bestChainLockBlockIndex->nHeight) { return false; } if (nHeight == bestChainLockBlockIndex->nHeight) { return blockHash == bestChainLockBlockIndex->GetBlockHash(); } auto pAncestor = bestChainLockBlockIndex->GetAncestor(nHeight); return pAncestor && pAncestor->GetBlockHash() == blockHash; } bool CChainLocksHandler::HasConflictingChainLock(int nHeight, const uint256& blockHash) { LOCK(cs); return InternalHasConflictingChainLock(nHeight, blockHash); } bool CChainLocksHandler::InternalHasConflictingChainLock(int nHeight, const uint256& blockHash) { AssertLockHeld(cs); if (!isEnforced) { return false; } if (!bestChainLockBlockIndex) { return false; } if (nHeight > bestChainLockBlockIndex->nHeight) { return false; } if (nHeight == bestChainLockBlockIndex->nHeight) { return blockHash != bestChainLockBlockIndex->GetBlockHash(); } auto pAncestor = bestChainLockBlockIndex->GetAncestor(nHeight); assert(pAncestor); return pAncestor->GetBlockHash() != blockHash; } void CChainLocksHandler::Cleanup() { if (!masternodeSync.IsBlockchainSynced()) { return; } { LOCK(cs); if (GetTimeMillis() - lastCleanupTime < CLEANUP_INTERVAL) { return; } } LOCK(cs); for (auto it = seenChainLocks.begin(); it != seenChainLocks.end(); ) { if (GetTimeMillis() - it->second >= CLEANUP_SEEN_TIMEOUT) { it = seenChainLocks.erase(it); } else { ++it; } } lastCleanupTime = GetTimeMillis(); } bool AreChainLocksEnabled() { return sporkManager.IsSporkActive(SPORK_19_CHAINLOCKS_ENABLED); } } // namespace llmq <commit_msg>llmq: Some refactoring in CChainLocksHandler::ProcessNewChainLock<commit_after>// Copyright (c) 2019 The Dash Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <llmq/quorums_chainlocks.h> #include <llmq/quorums_utils.h> #include <chain.h> #include <masternode/masternodesync.h> #include <net_processing.h> #include <spork.h> #include <txmempool.h> #include <validation.h> namespace llmq { static const std::string CLSIG_REQUESTID_PREFIX = "clsig"; CChainLocksHandler* chainLocksHandler; bool CChainLockSig::IsNull() const { return nHeight == -1 && blockHash == uint256(); } std::string CChainLockSig::ToString() const { return strprintf("CChainLockSig(nHeight=%d, blockHash=%s)", nHeight, blockHash.ToString()); } CChainLocksHandler::CChainLocksHandler(CConnman& _connman, PeerManager& _peerman): connman(_connman), peerman(_peerman) { } CChainLocksHandler::~CChainLocksHandler() { } void CChainLocksHandler::Start() { quorumSigningManager->RegisterRecoveredSigsListener(this); } void CChainLocksHandler::Stop() { quorumSigningManager->UnregisterRecoveredSigsListener(this); } bool CChainLocksHandler::AlreadyHave(const uint256& hash) { LOCK(cs); return seenChainLocks.count(hash) != 0; } bool CChainLocksHandler::GetChainLockByHash(const uint256& hash, llmq::CChainLockSig& ret) { LOCK(cs); if (hash != bestChainLockHash) { // we only propagate the best one and ditch all the old ones return false; } ret = bestChainLock; return true; } CChainLockSig CChainLocksHandler::GetBestChainLock() { LOCK(cs); return bestChainLock; } void CChainLocksHandler::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv) { if (!AreChainLocksEnabled()) { return; } if (strCommand == NetMsgType::CLSIG) { CChainLockSig clsig; vRecv >> clsig; auto hash = ::SerializeHash(clsig); ProcessNewChainLock(pfrom->GetId(), clsig, hash); } } void CChainLocksHandler::ProcessNewChainLock(const NodeId from, const llmq::CChainLockSig& clsig, const uint256&hash ) { bool enforced; if (from != -1) { LOCK(cs_main); peerman.ReceivedResponse(from, hash); } bool bReturn = false; { LOCK(cs); enforced = isEnforced; if (!seenChainLocks.try_emplace(hash, GetTimeMillis()).second) { bReturn = true; } if (!bestChainLock.IsNull() && clsig.nHeight <= bestChainLock.nHeight) { // no need to process/relay older CLSIGs bReturn = true; } } if(bReturn) { LOCK(cs_main); peerman.ForgetTxHash(from, hash); return; } const uint256 requestId = ::SerializeHash(std::make_pair(CLSIG_REQUESTID_PREFIX, clsig.nHeight)); if (!quorumSigningManager->VerifyRecoveredSig(Params().GetConsensus().llmqTypeChainLocks, clsig.nHeight, requestId, clsig.blockHash, clsig.sig)) { LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- invalid CLSIG (%s), peer=%d\n", __func__, clsig.ToString(), from); if (from != -1) { LOCK(cs_main); peerman.ForgetTxHash(from, hash); peerman.Misbehaving(from, 10, "invalid CLSIG"); } return; } // don't hold lock while relaying which locks nodes/mempool const CBlockIndex* pindex; { LOCK(cs_main); pindex = g_chainman.m_blockman.LookupBlockIndex(clsig.blockHash); if (pindex == nullptr) { // we don't know the block/header for this CLSIG yet, so bail out for now // when the block or the header later comes in, we will enforce the correct chain return; } if (pindex->nHeight != clsig.nHeight) { // Should not happen, same as the conflict check from above. LogPrintf("CChainLocksHandler::%s -- height of CLSIG (%s) does not match the specified block's height (%d)\n", __func__, clsig.ToString(), pindex->nHeight); return; } peerman.ForgetTxHash(from, hash); } { LOCK(cs); bestChainLockBlockIndex = pindex; } connman.RelayOtherInv(CInv(MSG_CLSIG, hash)); CheckActiveState(); EnforceBestChainLock(bestChainLockBlockIndex, bestChainLock, enforced); LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- processed new CLSIG (%s), peer=%d\n", __func__, clsig.ToString(), from); } void CChainLocksHandler::UpdatedBlockTip(const CBlockIndex* pindexNew, bool fInitialDownload) { if(fInitialDownload) return; CheckActiveState(); TrySignChainTip(pindexNew); } void CChainLocksHandler::CheckActiveState() { bool sporkActive = AreChainLocksEnabled(); { LOCK(cs); bool oldIsEnforced = isEnforced; isEnabled = sporkActive; isEnforced = isEnabled; if (!oldIsEnforced && isEnforced) { // ChainLocks got activated just recently, but it's possible that it was already running before, leaving // us with some stale values which we should not try to enforce anymore (there probably was a good reason // to disable spork19) bestChainLockHash = uint256(); bestChainLock = CChainLockSig(); } } } void CChainLocksHandler::TrySignChainTip(const CBlockIndex* pindex) { Cleanup(); if (!fMasternodeMode) { return; } if (!masternodeSync.IsBlockchainSynced()) { return; } if (!pindex->pprev) { return; } const uint256 msgHash = pindex->GetBlockHash(); const int32_t nHeight = pindex->nHeight; // DIP8 defines a process called "Signing attempts" which should run before the CLSIG is finalized // To simplify the initial implementation, we skip this process and directly try to create a CLSIG // This will fail when multiple blocks compete, but we accept this for the initial implementation. // Later, we'll add the multiple attempts process. { LOCK(cs); if (!isEnabled) { return; } if (nHeight == lastSignedHeight) { // already signed this one return; } if (bestChainLock.nHeight >= nHeight) { // already got the same CLSIG or a better one return; } if (InternalHasConflictingChainLock(nHeight, msgHash)) { // don't sign if another conflicting CLSIG is already present. EnforceBestChainLock will later enforce // the correct chain. return; } } LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- trying to sign %s, height=%d\n", __func__, msgHash.ToString(), nHeight); uint256 requestId = ::SerializeHash(std::make_pair(CLSIG_REQUESTID_PREFIX, nHeight)); { LOCK(cs); if (bestChainLock.nHeight >= nHeight) { // might have happened while we didn't hold cs return; } lastSignedHeight = nHeight; lastSignedRequestId = requestId; lastSignedMsgHash = msgHash; } quorumSigningManager->AsyncSignIfMember(Params().GetConsensus().llmqTypeChainLocks, requestId, msgHash); } void CChainLocksHandler::HandleNewRecoveredSig(const llmq::CRecoveredSig& recoveredSig) { CChainLockSig clsig; { LOCK(cs); if (!isEnabled) { return; } if (recoveredSig.id != lastSignedRequestId || recoveredSig.msgHash != lastSignedMsgHash) { // this is not what we signed, so lets not create a CLSIG for it return; } if (bestChainLock.nHeight >= lastSignedHeight) { // already got the same or a better CLSIG through the CLSIG message return; } clsig.nHeight = lastSignedHeight; clsig.blockHash = lastSignedMsgHash; clsig.sig = recoveredSig.sig.Get(); } ProcessNewChainLock(-1, clsig, ::SerializeHash(clsig)); } bool CChainLocksHandler::HasChainLock(int nHeight, const uint256& blockHash) { LOCK(cs); return InternalHasChainLock(nHeight, blockHash); } bool CChainLocksHandler::InternalHasChainLock(int nHeight, const uint256& blockHash) { AssertLockHeld(cs); if (!isEnforced) { return false; } if (!bestChainLockBlockIndex) { return false; } if (nHeight > bestChainLockBlockIndex->nHeight) { return false; } if (nHeight == bestChainLockBlockIndex->nHeight) { return blockHash == bestChainLockBlockIndex->GetBlockHash(); } auto pAncestor = bestChainLockBlockIndex->GetAncestor(nHeight); return pAncestor && pAncestor->GetBlockHash() == blockHash; } bool CChainLocksHandler::HasConflictingChainLock(int nHeight, const uint256& blockHash) { LOCK(cs); return InternalHasConflictingChainLock(nHeight, blockHash); } bool CChainLocksHandler::InternalHasConflictingChainLock(int nHeight, const uint256& blockHash) { AssertLockHeld(cs); if (!isEnforced) { return false; } if (!bestChainLockBlockIndex) { return false; } if (nHeight > bestChainLockBlockIndex->nHeight) { return false; } if (nHeight == bestChainLockBlockIndex->nHeight) { return blockHash != bestChainLockBlockIndex->GetBlockHash(); } auto pAncestor = bestChainLockBlockIndex->GetAncestor(nHeight); assert(pAncestor); return pAncestor->GetBlockHash() != blockHash; } void CChainLocksHandler::Cleanup() { if (!masternodeSync.IsBlockchainSynced()) { return; } { LOCK(cs); if (GetTimeMillis() - lastCleanupTime < CLEANUP_INTERVAL) { return; } } LOCK(cs); for (auto it = seenChainLocks.begin(); it != seenChainLocks.end(); ) { if (GetTimeMillis() - it->second >= CLEANUP_SEEN_TIMEOUT) { it = seenChainLocks.erase(it); } else { ++it; } } lastCleanupTime = GetTimeMillis(); } bool AreChainLocksEnabled() { return sporkManager.IsSporkActive(SPORK_19_CHAINLOCKS_ENABLED); } } // namespace llmq <|endoftext|>
<commit_before>#include "readLoad.h" #include "ErrorWarning.h" int readLoad(istream& readInStream, Parameters* P, uint iMate, uint& Lread, uint& LreadOriginal, char* readName, char* Seq, char* SeqNum, char* Qual, char* QualNum, uint &clip3pNtotal, uint &clip5pNtotal, uint &clip3pAdapterN, uint &iReadAll, uint &readFilesIndex, char &readFilter, string &readNameExtra){ //load one read from a stream int readFileType=0; // readInStream.getline(readName,DEF_readNameLengthMax); //extract name if (readInStream.peek()!='@' && readInStream.peek()!='>') return -1; //end of the stream readName[0]=0;//clear char array readInStream >> readName; //TODO check that it does not overflow the array if (strlen(readName)>=DEF_readNameLengthMax-1) { ostringstream errOut; errOut << "EXITING because of FATAL ERROR in reads input: read name is too long:" << readInStream.gcount()<<"\n"; errOut << "Read Name="<<readName<<"\n"; errOut << "DEF_readNameLengthMax="<<DEF_readNameLengthMax<<"\n"; errOut << "SOLUTION: increase DEF_readNameLengthMax in IncludeDefine.h and re-compile STAR\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; readInStream >> iReadAll >> readFilter >> readFilesIndex; //extract read number getline(readInStream, readNameExtra); if (!readNameExtra.empty()) { size_t n1=readNameExtra.find_first_not_of(" \t"); if (n1!=std::string::npos) { readNameExtra=readNameExtra.substr(n1); } else { readNameExtra=""; }; }; // readInStream.ignore(DEF_readNameSeqLengthMax,'\n');//ignore the resit of the line - just in case readInStream.getline(Seq,DEF_readSeqLengthMax+1); //extract sequence Lread=(uint) readInStream.gcount(); if (Lread<=1) { ostringstream errOut; errOut << "EXITING because of FATAL ERROR in reads input: short read sequence line: " << Lread <<"\n"; errOut << "Read Name="<<readName<<"\n"; errOut << "Read Sequence="<<Seq<<"===\n"; errOut << "DEF_readNameLengthMax="<<DEF_readNameLengthMax<<"\n"; errOut << "DEF_readSeqLengthMax="<<DEF_readSeqLengthMax<<"\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; --Lread;//do not count /n in the read length LreadOriginal=Lread; if (Lread>DEF_readSeqLengthMax) { ostringstream errOut; errOut << "EXITING because of FATAL ERROR in reads input: Lread>=" << Lread << " while DEF_readSeqLengthMax=" << DEF_readSeqLengthMax <<"\n"; errOut << "Read Name="<<readName<<"\n"; errOut << "SOLUTION: increase DEF_readSeqLengthMax in IncludeDefine.h and re-compile STAR\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; // //was trying to read multi-line // char nextChar='A'; // Lread=0; // while (nextChar!='@' && nextChar!='>' && nextChar!='+' && nextChar!=' ' && nextChar!='\n' && !readInStream.eof()) {//read multi-line fasta // readInStream.getline(Seq+Lread,DEF_readSeqLengthMax+1); //extract sequence // Lread+=(uint) readInStream.gcount() - 1; //count chars in the sequence line, but do not read yet // nextChar=readInStream.peek(); // }; // if (Lread>DEF_readSeqLengthMax) { // ostringstream errOut; // errOut << "EXITING because of FATAL ERROR in reads input: Lread>=" << Lread << " while DEF_readSeqLengthMax=" << DEF_readSeqLengthMax <<"\n"; // errOut << "Read Name="<<readName<<"\n"; // errOut << "SOLUTION: increase DEF_readSeqLengthMax in IncludeDefine.h and re-compile STAR\n"; // exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); // }; // LreadOriginal=Lread; if ( Lread>(P->clip5pNbases[iMate]+P->clip3pNbases[iMate]) ) { Lread=Lread-(P->clip5pNbases[iMate]+P->clip3pNbases[iMate]); } else { Lread=0; }; convertNucleotidesToNumbers(Seq+P->clip5pNbases[iMate],SeqNum,Lread); //clip the adapter if (P->clip3pAdapterSeq.at(iMate).length()>0) { clip3pAdapterN = Lread-localSearch(SeqNum,Lread,P->clip3pAdapterSeqNum[iMate],P->clip3pAdapterSeq.at(iMate).length(),P->clip3pAdapterMMp[iMate]); Lread = Lread>clip3pAdapterN ? Lread-clip3pAdapterN : 0; } else { clip3pAdapterN = 0; }; //final read length, trim 3p after the adapter was clipped if (Lread>P->clip3pAfterAdapterNbases[iMate]) { Lread =Lread - P->clip3pAfterAdapterNbases[iMate]; } else { Lread=0; }; clip3pNtotal=P->clip3pNbases[iMate] + clip3pAdapterN + P->clip3pAfterAdapterNbases[iMate]; clip5pNtotal=P->clip5pNbases[iMate]; if (readName[0]=='@') {//fastq format, read qualities readFileType=2; readInStream.ignore(DEF_readNameLengthMax,'\n'); //extract header line readInStream.getline(Qual,DEF_readSeqLengthMax);//read qualities if ((uint) readInStream.gcount() != LreadOriginal+1) {//inconsistent read sequence and quality ostringstream errOut; errOut << "EXITING because of FATAL ERROR in reads input: quality string length is not equal to sequence length\n"; errOut << readName<<"\n"; errOut << Seq <<"\n"; errOut << Qual <<"\n"; errOut << "SOLUTION: fix your fastq file\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; if (P->outQSconversionAdd!=0) { for (uint ii=0;ii<LreadOriginal;ii++) { int qs=int(Qual[ii])+P->outQSconversionAdd; if (qs<33) { qs=33; } else if (qs>126) { qs=126; }; Qual[ii]=qs; }; }; } else if (readName[0]=='>') {//fasta format, assign Qtop to all qualities readFileType=1; for (uint ii=0;ii<LreadOriginal;ii++) Qual[ii]='A'; Qual[LreadOriginal]=0; } else {//header ostringstream errOut; errOut <<"Unknown reads file format: header line does not start with @ or > : "<< readName<<"\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; for (uint ii=0;ii<Lread;ii++) {//for now: qualities are all 1 if (SeqNum[ii]<4) { QualNum[ii]=1; } else { QualNum[ii]=0; }; }; // for (uint ii=0;ii<Lread;ii++) {//simply cut too high Qs // QualNum[ii]=(Qual[ii+P->clip5pNbases[iMate]] > P->QasciiSubtract) ? (Qual[ii+P->clip5pNbases[iMate]] - P->QasciiSubtract) : 0; //substract QasciiSubtract // QualNum[ii]=P->QSconv[(int) QualNum[ii]]; // QualNum[ii]=min(QualNum[ii], P->Qtop);//cut QSs at the Qtop // // if (QualNum[ii]==2) QualNum[ii]=P->Qtop; // if (SeqNum[ii]>3) QualNum[ii]=0; //QS=0 for Ns // Qual1[1][Lread-ii-1]=QualNum[ii]; //reverse // }; //trim read name for (uint ii=0; ii<P->readNameSeparatorChar.size(); ii++) { char* pSlash=strchr(readName,P->readNameSeparatorChar.at(ii)); //trim everything after ' ' if (pSlash!=NULL) *pSlash=0; }; return readFileType; }; <commit_msg>Don't exit when fastq contains a zero-length read<commit_after>#include "readLoad.h" #include "ErrorWarning.h" int readLoad(istream& readInStream, Parameters* P, uint iMate, uint& Lread, uint& LreadOriginal, char* readName, char* Seq, char* SeqNum, char* Qual, char* QualNum, uint &clip3pNtotal, uint &clip5pNtotal, uint &clip3pAdapterN, uint &iReadAll, uint &readFilesIndex, char &readFilter, string &readNameExtra){ //load one read from a stream int readFileType=0; // readInStream.getline(readName,DEF_readNameLengthMax); //extract name if (readInStream.peek()!='@' && readInStream.peek()!='>') return -1; //end of the stream readName[0]=0;//clear char array readInStream >> readName; //TODO check that it does not overflow the array if (strlen(readName)>=DEF_readNameLengthMax-1) { ostringstream errOut; errOut << "EXITING because of FATAL ERROR in reads input: read name is too long:" << readInStream.gcount()<<"\n"; errOut << "Read Name="<<readName<<"\n"; errOut << "DEF_readNameLengthMax="<<DEF_readNameLengthMax<<"\n"; errOut << "SOLUTION: increase DEF_readNameLengthMax in IncludeDefine.h and re-compile STAR\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; readInStream >> iReadAll >> readFilter >> readFilesIndex; //extract read number getline(readInStream, readNameExtra); if (!readNameExtra.empty()) { size_t n1=readNameExtra.find_first_not_of(" \t"); if (n1!=std::string::npos) { readNameExtra=readNameExtra.substr(n1); } else { readNameExtra=""; }; }; // readInStream.ignore(DEF_readNameSeqLengthMax,'\n');//ignore the resit of the line - just in case readInStream.getline(Seq,DEF_readSeqLengthMax+1); //extract sequence Lread=(uint) readInStream.gcount(); if (Lread<1) { ostringstream errOut; errOut << "EXITING because of FATAL ERROR in reads input: short read sequence line: " << Lread <<"\n"; errOut << "Read Name="<<readName<<"\n"; errOut << "Read Sequence="<<Seq<<"===\n"; errOut << "DEF_readNameLengthMax="<<DEF_readNameLengthMax<<"\n"; errOut << "DEF_readSeqLengthMax="<<DEF_readSeqLengthMax<<"\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; --Lread;//do not count /n in the read length LreadOriginal=Lread; if (Lread>DEF_readSeqLengthMax) { ostringstream errOut; errOut << "EXITING because of FATAL ERROR in reads input: Lread>=" << Lread << " while DEF_readSeqLengthMax=" << DEF_readSeqLengthMax <<"\n"; errOut << "Read Name="<<readName<<"\n"; errOut << "SOLUTION: increase DEF_readSeqLengthMax in IncludeDefine.h and re-compile STAR\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; // //was trying to read multi-line // char nextChar='A'; // Lread=0; // while (nextChar!='@' && nextChar!='>' && nextChar!='+' && nextChar!=' ' && nextChar!='\n' && !readInStream.eof()) {//read multi-line fasta // readInStream.getline(Seq+Lread,DEF_readSeqLengthMax+1); //extract sequence // Lread+=(uint) readInStream.gcount() - 1; //count chars in the sequence line, but do not read yet // nextChar=readInStream.peek(); // }; // if (Lread>DEF_readSeqLengthMax) { // ostringstream errOut; // errOut << "EXITING because of FATAL ERROR in reads input: Lread>=" << Lread << " while DEF_readSeqLengthMax=" << DEF_readSeqLengthMax <<"\n"; // errOut << "Read Name="<<readName<<"\n"; // errOut << "SOLUTION: increase DEF_readSeqLengthMax in IncludeDefine.h and re-compile STAR\n"; // exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); // }; // LreadOriginal=Lread; if ( Lread>(P->clip5pNbases[iMate]+P->clip3pNbases[iMate]) ) { Lread=Lread-(P->clip5pNbases[iMate]+P->clip3pNbases[iMate]); } else { Lread=0; }; convertNucleotidesToNumbers(Seq+P->clip5pNbases[iMate],SeqNum,Lread); //clip the adapter if (P->clip3pAdapterSeq.at(iMate).length()>0) { clip3pAdapterN = Lread-localSearch(SeqNum,Lread,P->clip3pAdapterSeqNum[iMate],P->clip3pAdapterSeq.at(iMate).length(),P->clip3pAdapterMMp[iMate]); Lread = Lread>clip3pAdapterN ? Lread-clip3pAdapterN : 0; } else { clip3pAdapterN = 0; }; //final read length, trim 3p after the adapter was clipped if (Lread>P->clip3pAfterAdapterNbases[iMate]) { Lread =Lread - P->clip3pAfterAdapterNbases[iMate]; } else { Lread=0; }; clip3pNtotal=P->clip3pNbases[iMate] + clip3pAdapterN + P->clip3pAfterAdapterNbases[iMate]; clip5pNtotal=P->clip5pNbases[iMate]; if (readName[0]=='@') {//fastq format, read qualities readFileType=2; readInStream.ignore(DEF_readNameLengthMax,'\n'); //extract header line readInStream.getline(Qual,DEF_readSeqLengthMax);//read qualities if ((uint) readInStream.gcount() != LreadOriginal+1) {//inconsistent read sequence and quality ostringstream errOut; errOut << "EXITING because of FATAL ERROR in reads input: quality string length is not equal to sequence length\n"; errOut << readName<<"\n"; errOut << Seq <<"\n"; errOut << Qual <<"\n"; errOut << "SOLUTION: fix your fastq file\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; if (P->outQSconversionAdd!=0) { for (uint ii=0;ii<LreadOriginal;ii++) { int qs=int(Qual[ii])+P->outQSconversionAdd; if (qs<33) { qs=33; } else if (qs>126) { qs=126; }; Qual[ii]=qs; }; }; } else if (readName[0]=='>') {//fasta format, assign Qtop to all qualities readFileType=1; for (uint ii=0;ii<LreadOriginal;ii++) Qual[ii]='A'; Qual[LreadOriginal]=0; } else {//header ostringstream errOut; errOut <<"Unknown reads file format: header line does not start with @ or > : "<< readName<<"\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; for (uint ii=0;ii<Lread;ii++) {//for now: qualities are all 1 if (SeqNum[ii]<4) { QualNum[ii]=1; } else { QualNum[ii]=0; }; }; // for (uint ii=0;ii<Lread;ii++) {//simply cut too high Qs // QualNum[ii]=(Qual[ii+P->clip5pNbases[iMate]] > P->QasciiSubtract) ? (Qual[ii+P->clip5pNbases[iMate]] - P->QasciiSubtract) : 0; //substract QasciiSubtract // QualNum[ii]=P->QSconv[(int) QualNum[ii]]; // QualNum[ii]=min(QualNum[ii], P->Qtop);//cut QSs at the Qtop // // if (QualNum[ii]==2) QualNum[ii]=P->Qtop; // if (SeqNum[ii]>3) QualNum[ii]=0; //QS=0 for Ns // Qual1[1][Lread-ii-1]=QualNum[ii]; //reverse // }; //trim read name for (uint ii=0; ii<P->readNameSeparatorChar.size(); ii++) { char* pSlash=strchr(readName,P->readNameSeparatorChar.at(ii)); //trim everything after ' ' if (pSlash!=NULL) *pSlash=0; }; return readFileType; }; <|endoftext|>
<commit_before><commit_msg>341 - Non-Stop Travel<commit_after><|endoftext|>
<commit_before>/*************************************************************************/ /* audio_stream_ogg_vorbis.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "audio_stream_ogg_vorbis.h" #include "core/os/file_access.h" void AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame *p_buffer, int p_frames) { ERR_FAIL_COND(!active); int todo = p_frames; int start_buffer = 0; while (todo && active) { float *buffer = (float *)p_buffer; if (start_buffer > 0) { buffer = (buffer + start_buffer * 2); } int mixed = stb_vorbis_get_samples_float_interleaved(ogg_stream, 2, buffer, todo * 2); if (vorbis_stream->channels == 1 && mixed > 0) { //mix mono to stereo for (int i = start_buffer; i < mixed; i++) { p_buffer[i].r = p_buffer[i].l; } } todo -= mixed; frames_mixed += mixed; if (todo) { //end of file! if (vorbis_stream->loop) { //loop seek(vorbis_stream->loop_offset); loops++; // we still have buffer to fill, start from this element in the next iteration. start_buffer = p_frames - todo; } else { for (int i = p_frames - todo; i < p_frames; i++) { p_buffer[i] = AudioFrame(0, 0); } active = false; todo = 0; } } } } float AudioStreamPlaybackOGGVorbis::get_stream_sampling_rate() { return vorbis_stream->sample_rate; } void AudioStreamPlaybackOGGVorbis::start(float p_from_pos) { active = true; seek(p_from_pos); loops = 0; _begin_resample(); } void AudioStreamPlaybackOGGVorbis::stop() { active = false; } bool AudioStreamPlaybackOGGVorbis::is_playing() const { return active; } int AudioStreamPlaybackOGGVorbis::get_loop_count() const { return loops; } float AudioStreamPlaybackOGGVorbis::get_playback_position() const { return float(frames_mixed) / vorbis_stream->sample_rate; } void AudioStreamPlaybackOGGVorbis::seek(float p_time) { if (!active) return; if (p_time >= vorbis_stream->get_length()) { p_time = 0; } frames_mixed = uint32_t(vorbis_stream->sample_rate * p_time); stb_vorbis_seek(ogg_stream, frames_mixed); } AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() { if (ogg_alloc.alloc_buffer) { stb_vorbis_close(ogg_stream); AudioServer::get_singleton()->audio_data_free(ogg_alloc.alloc_buffer); } } Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() { Ref<AudioStreamPlaybackOGGVorbis> ovs; ERR_FAIL_COND_V(data == NULL, ovs); ovs.instance(); ovs->vorbis_stream = Ref<AudioStreamOGGVorbis>(this); ovs->ogg_alloc.alloc_buffer = (char *)AudioServer::get_singleton()->audio_data_alloc(decode_mem_size); ovs->ogg_alloc.alloc_buffer_length_in_bytes = decode_mem_size; ovs->frames_mixed = 0; ovs->active = false; ovs->loops = 0; int error; ovs->ogg_stream = stb_vorbis_open_memory((const unsigned char *)data, data_len, &error, &ovs->ogg_alloc); if (!ovs->ogg_stream) { AudioServer::get_singleton()->audio_data_free(ovs->ogg_alloc.alloc_buffer); ovs->ogg_alloc.alloc_buffer = NULL; ERR_FAIL_COND_V(!ovs->ogg_stream, Ref<AudioStreamPlaybackOGGVorbis>()); } return ovs; } String AudioStreamOGGVorbis::get_stream_name() const { return ""; //return stream_name; } void AudioStreamOGGVorbis::clear_data() { if (data) { AudioServer::get_singleton()->audio_data_free(data); data = NULL; data_len = 0; } } void AudioStreamOGGVorbis::set_data(const PoolVector<uint8_t> &p_data) { int src_data_len = p_data.size(); #define MAX_TEST_MEM (1 << 20) uint32_t alloc_try = 1024; PoolVector<char> alloc_mem; PoolVector<char>::Write w; stb_vorbis *ogg_stream = NULL; stb_vorbis_alloc ogg_alloc; while (alloc_try < MAX_TEST_MEM) { alloc_mem.resize(alloc_try); w = alloc_mem.write(); ogg_alloc.alloc_buffer = w.ptr(); ogg_alloc.alloc_buffer_length_in_bytes = alloc_try; PoolVector<uint8_t>::Read src_datar = p_data.read(); int error; ogg_stream = stb_vorbis_open_memory((const unsigned char *)src_datar.ptr(), src_data_len, &error, &ogg_alloc); if (!ogg_stream && error == VORBIS_outofmem) { w.release(); alloc_try *= 2; } else { ERR_FAIL_COND(alloc_try == MAX_TEST_MEM); ERR_FAIL_COND(ogg_stream == NULL); stb_vorbis_info info = stb_vorbis_get_info(ogg_stream); channels = info.channels; sample_rate = info.sample_rate; decode_mem_size = alloc_try; //does this work? (it's less mem..) //decode_mem_size = ogg_alloc.alloc_buffer_length_in_bytes + info.setup_memory_required + info.temp_memory_required + info.max_frame_size; length = stb_vorbis_stream_length_in_seconds(ogg_stream); stb_vorbis_close(ogg_stream); // free any existing data clear_data(); data = AudioServer::get_singleton()->audio_data_alloc(src_data_len, src_datar.ptr()); data_len = src_data_len; break; } } } PoolVector<uint8_t> AudioStreamOGGVorbis::get_data() const { PoolVector<uint8_t> vdata; if (data_len && data) { vdata.resize(data_len); { PoolVector<uint8_t>::Write w = vdata.write(); copymem(w.ptr(), data, data_len); } } return vdata; } void AudioStreamOGGVorbis::set_loop(bool p_enable) { loop = p_enable; } bool AudioStreamOGGVorbis::has_loop() const { return loop; } void AudioStreamOGGVorbis::set_loop_offset(float p_seconds) { loop_offset = p_seconds; } float AudioStreamOGGVorbis::get_loop_offset() const { return loop_offset; } float AudioStreamOGGVorbis::get_length() const { return length; } void AudioStreamOGGVorbis::_bind_methods() { ClassDB::bind_method(D_METHOD("set_data", "data"), &AudioStreamOGGVorbis::set_data); ClassDB::bind_method(D_METHOD("get_data"), &AudioStreamOGGVorbis::get_data); ClassDB::bind_method(D_METHOD("set_loop", "enable"), &AudioStreamOGGVorbis::set_loop); ClassDB::bind_method(D_METHOD("has_loop"), &AudioStreamOGGVorbis::has_loop); ClassDB::bind_method(D_METHOD("set_loop_offset", "seconds"), &AudioStreamOGGVorbis::set_loop_offset); ClassDB::bind_method(D_METHOD("get_loop_offset"), &AudioStreamOGGVorbis::get_loop_offset); ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_data", "get_data"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_loop", "has_loop"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "loop_offset", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_loop_offset", "get_loop_offset"); } AudioStreamOGGVorbis::AudioStreamOGGVorbis() { data = NULL; data_len = 0; length = 0; sample_rate = 1; channels = 1; loop_offset = 0; decode_mem_size = 0; loop = false; } AudioStreamOGGVorbis::~AudioStreamOGGVorbis() { clear_data(); } <commit_msg>AudioStreamOGGVorbis: Expose loop and loop_offset as properties<commit_after>/*************************************************************************/ /* audio_stream_ogg_vorbis.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "audio_stream_ogg_vorbis.h" #include "core/os/file_access.h" void AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame *p_buffer, int p_frames) { ERR_FAIL_COND(!active); int todo = p_frames; int start_buffer = 0; while (todo && active) { float *buffer = (float *)p_buffer; if (start_buffer > 0) { buffer = (buffer + start_buffer * 2); } int mixed = stb_vorbis_get_samples_float_interleaved(ogg_stream, 2, buffer, todo * 2); if (vorbis_stream->channels == 1 && mixed > 0) { //mix mono to stereo for (int i = start_buffer; i < mixed; i++) { p_buffer[i].r = p_buffer[i].l; } } todo -= mixed; frames_mixed += mixed; if (todo) { //end of file! if (vorbis_stream->loop) { //loop seek(vorbis_stream->loop_offset); loops++; // we still have buffer to fill, start from this element in the next iteration. start_buffer = p_frames - todo; } else { for (int i = p_frames - todo; i < p_frames; i++) { p_buffer[i] = AudioFrame(0, 0); } active = false; todo = 0; } } } } float AudioStreamPlaybackOGGVorbis::get_stream_sampling_rate() { return vorbis_stream->sample_rate; } void AudioStreamPlaybackOGGVorbis::start(float p_from_pos) { active = true; seek(p_from_pos); loops = 0; _begin_resample(); } void AudioStreamPlaybackOGGVorbis::stop() { active = false; } bool AudioStreamPlaybackOGGVorbis::is_playing() const { return active; } int AudioStreamPlaybackOGGVorbis::get_loop_count() const { return loops; } float AudioStreamPlaybackOGGVorbis::get_playback_position() const { return float(frames_mixed) / vorbis_stream->sample_rate; } void AudioStreamPlaybackOGGVorbis::seek(float p_time) { if (!active) return; if (p_time >= vorbis_stream->get_length()) { p_time = 0; } frames_mixed = uint32_t(vorbis_stream->sample_rate * p_time); stb_vorbis_seek(ogg_stream, frames_mixed); } AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() { if (ogg_alloc.alloc_buffer) { stb_vorbis_close(ogg_stream); AudioServer::get_singleton()->audio_data_free(ogg_alloc.alloc_buffer); } } Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() { Ref<AudioStreamPlaybackOGGVorbis> ovs; ERR_FAIL_COND_V(data == NULL, ovs); ovs.instance(); ovs->vorbis_stream = Ref<AudioStreamOGGVorbis>(this); ovs->ogg_alloc.alloc_buffer = (char *)AudioServer::get_singleton()->audio_data_alloc(decode_mem_size); ovs->ogg_alloc.alloc_buffer_length_in_bytes = decode_mem_size; ovs->frames_mixed = 0; ovs->active = false; ovs->loops = 0; int error; ovs->ogg_stream = stb_vorbis_open_memory((const unsigned char *)data, data_len, &error, &ovs->ogg_alloc); if (!ovs->ogg_stream) { AudioServer::get_singleton()->audio_data_free(ovs->ogg_alloc.alloc_buffer); ovs->ogg_alloc.alloc_buffer = NULL; ERR_FAIL_COND_V(!ovs->ogg_stream, Ref<AudioStreamPlaybackOGGVorbis>()); } return ovs; } String AudioStreamOGGVorbis::get_stream_name() const { return ""; //return stream_name; } void AudioStreamOGGVorbis::clear_data() { if (data) { AudioServer::get_singleton()->audio_data_free(data); data = NULL; data_len = 0; } } void AudioStreamOGGVorbis::set_data(const PoolVector<uint8_t> &p_data) { int src_data_len = p_data.size(); #define MAX_TEST_MEM (1 << 20) uint32_t alloc_try = 1024; PoolVector<char> alloc_mem; PoolVector<char>::Write w; stb_vorbis *ogg_stream = NULL; stb_vorbis_alloc ogg_alloc; while (alloc_try < MAX_TEST_MEM) { alloc_mem.resize(alloc_try); w = alloc_mem.write(); ogg_alloc.alloc_buffer = w.ptr(); ogg_alloc.alloc_buffer_length_in_bytes = alloc_try; PoolVector<uint8_t>::Read src_datar = p_data.read(); int error; ogg_stream = stb_vorbis_open_memory((const unsigned char *)src_datar.ptr(), src_data_len, &error, &ogg_alloc); if (!ogg_stream && error == VORBIS_outofmem) { w.release(); alloc_try *= 2; } else { ERR_FAIL_COND(alloc_try == MAX_TEST_MEM); ERR_FAIL_COND(ogg_stream == NULL); stb_vorbis_info info = stb_vorbis_get_info(ogg_stream); channels = info.channels; sample_rate = info.sample_rate; decode_mem_size = alloc_try; //does this work? (it's less mem..) //decode_mem_size = ogg_alloc.alloc_buffer_length_in_bytes + info.setup_memory_required + info.temp_memory_required + info.max_frame_size; length = stb_vorbis_stream_length_in_seconds(ogg_stream); stb_vorbis_close(ogg_stream); // free any existing data clear_data(); data = AudioServer::get_singleton()->audio_data_alloc(src_data_len, src_datar.ptr()); data_len = src_data_len; break; } } } PoolVector<uint8_t> AudioStreamOGGVorbis::get_data() const { PoolVector<uint8_t> vdata; if (data_len && data) { vdata.resize(data_len); { PoolVector<uint8_t>::Write w = vdata.write(); copymem(w.ptr(), data, data_len); } } return vdata; } void AudioStreamOGGVorbis::set_loop(bool p_enable) { loop = p_enable; } bool AudioStreamOGGVorbis::has_loop() const { return loop; } void AudioStreamOGGVorbis::set_loop_offset(float p_seconds) { loop_offset = p_seconds; } float AudioStreamOGGVorbis::get_loop_offset() const { return loop_offset; } float AudioStreamOGGVorbis::get_length() const { return length; } void AudioStreamOGGVorbis::_bind_methods() { ClassDB::bind_method(D_METHOD("set_data", "data"), &AudioStreamOGGVorbis::set_data); ClassDB::bind_method(D_METHOD("get_data"), &AudioStreamOGGVorbis::get_data); ClassDB::bind_method(D_METHOD("set_loop", "enable"), &AudioStreamOGGVorbis::set_loop); ClassDB::bind_method(D_METHOD("has_loop"), &AudioStreamOGGVorbis::has_loop); ClassDB::bind_method(D_METHOD("set_loop_offset", "seconds"), &AudioStreamOGGVorbis::set_loop_offset); ClassDB::bind_method(D_METHOD("get_loop_offset"), &AudioStreamOGGVorbis::get_loop_offset); ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_data", "get_data"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop"), "set_loop", "has_loop"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "loop_offset"), "set_loop_offset", "get_loop_offset"); } AudioStreamOGGVorbis::AudioStreamOGGVorbis() { data = NULL; data_len = 0; length = 0; sample_rate = 1; channels = 1; loop_offset = 0; decode_mem_size = 0; loop = false; } AudioStreamOGGVorbis::~AudioStreamOGGVorbis() { clear_data(); } <|endoftext|>
<commit_before>#include "weapon_cooldown.h" #include "../SCBW/scbwdata.h" #include "../SCBW/enumerations.h" namespace hooks { /// Calculates the unit's weapon cooldown, factoring in upgrades and status effects. /// /// @return The modified cooldown value. u32 getModifiedWeaponCooldownHook(const CUnit* unit, u8 weaponId) { //Default StarCraft behavior u32 cooldown = Weapon::Cooldown[weaponId]; if (unit->acidSporeCount) { u32 increaseAmt = cooldown >> 3; if (increaseAmt < 3) increaseAmt = 3; cooldown += increaseAmt * unit->acidSporeCount; } int cooldownModifier = (unit->stimTimer ? 1 : 0) - (unit->ensnareTimer ? 1 : 0) + (unit->status & UnitStatus::CooldownUpgrade ? 1 : 0); if (cooldownModifier > 0) cooldown >>= 1; else if (cooldownModifier < 0) cooldown += cooldown >> 2; if (cooldown > 250) cooldown = 250; else if (cooldown < 5) cooldown = 5; return cooldown; } } //hooks <commit_msg>SCT: Added cooldown logic * Acid Spore: +12.5% cooldown, multiplicative * Ensnare: +25% cooldown AND nullifies Stim Packs / Adrenal Glands * Stim Packs / Adrenal Glands: -33.3% cooldown<commit_after>#include "weapon_cooldown.h" #include "../SCBW/scbwdata.h" #include "../SCBW/enumerations.h" #include <algorithm> namespace hooks { /// Calculates the unit's weapon cooldown, factoring in upgrades and status effects. /// /// @return The modified cooldown value. u32 getModifiedWeaponCooldownHook(const CUnit* unit, u8 weaponId) { u32 cooldown = Weapon::Cooldown[weaponId]; if (unit->acidSporeCount) { //Use proper rounding to better simulate the 12.5%-per-spore cooldown += (unit->acidSporeCount * cooldown + 4) / 8; } //Ensnare always overrides Stim Packs and Adrenal Glands if (unit->ensnareTimer) cooldown += (cooldown + 2) / 4; // +25%, rounded properly else if (unit->stimTimer != 0 || unit->status & UnitStatus::CooldownUpgrade) cooldown = (cooldown * 4 + 3) / 6; // -66.7%, rounded properly return CLAMP(cooldown, 5u, 250u); } } //hooks <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * HDF5ReaderP.cpp * * Created on: March 20, 2017 * Author: Junmin */ #include "HDF5ReaderP.h" #include "HDF5ReaderP.tcc" #include "adios2/ADIOSMPI.h" #include "adios2/helper/adiosFunctions.h" //CSVToVector namespace adios2 { HDF5ReaderP::HDF5ReaderP(IO &io, const std::string &name, const Mode openMode, MPI_Comm mpiComm) : Engine("HDF5Reader", io, name, openMode, mpiComm), m_H5File(io.m_DebugMode) { m_EndMessage = ", in call to IO HDF5Reader Open " + m_Name + "\n"; Init(); } HDF5ReaderP::~HDF5ReaderP() { DoClose(); } bool HDF5ReaderP::IsValid() { bool isValid = false; if (m_OpenMode != Mode::Read) { return isValid; } if (m_H5File.m_FileId >= 0) { isValid = true; } return isValid; } void HDF5ReaderP::Init() { if (m_OpenMode != Mode::Read) { throw std::invalid_argument( "ERROR: HDF5Reader only supports OpenMode::Read " ", in call to Open\n"); } m_H5File.Init(m_Name, m_MPIComm, false); /* int ts = m_H5File.GetNumAdiosSteps(); if (ts == 0) { throw std::runtime_error("This h5 file is NOT written by ADIOS2"); } */ if (!m_InStreamMode) { m_H5File.ReadAllVariables(m_IO); } else { m_H5File.ReadAllVariables(m_IO); } } template <class T> void HDF5ReaderP::UseHDFRead(Variable<T> &variable, T *data, hid_t h5Type) { T *values = data; if (!m_H5File.m_IsGeneratedByAdios) { // printf("Will read by Native reader ..%s\n", variable.m_Name.c_str()); hid_t dataSetId = H5Dopen(m_H5File.m_FileId, variable.m_Name.c_str(), H5P_DEFAULT); if (dataSetId < 0) { return; } hid_t fileSpace = H5Dget_space(dataSetId); if (fileSpace < 0) { return; } size_t slabsize = 1; int ndims = std::max(variable.m_Shape.size(), variable.m_Count.size()); if (0 == ndims) { // is scalar hid_t ret = H5Dread(dataSetId, h5Type, H5S_ALL, H5S_ALL, H5P_DEFAULT, values); } else { hsize_t start[ndims], count[ndims], stride[ndims]; bool isOrderC = IsRowMajor(m_IO.m_HostLanguage); for (int i = 0; i < ndims; i++) { if (isOrderC) { count[i] = variable.m_Count[i]; start[i] = variable.m_Start[i]; } else { count[i] = variable.m_Count[ndims - 1 - i]; start[i] = variable.m_Start[ndims - 1 - i]; } slabsize *= count[i]; stride[i] = 1; } hid_t ret = H5Sselect_hyperslab(fileSpace, H5S_SELECT_SET, start, stride, count, NULL); if (ret < 0) return; hid_t memDataSpace = H5Screate_simple(ndims, count, NULL); int elementsRead = 1; for (int i = 0; i < ndims; i++) { elementsRead *= count[i]; } ret = H5Dread(dataSetId, h5Type, memDataSpace, fileSpace, H5P_DEFAULT, values); H5Sclose(memDataSpace); } H5Sclose(fileSpace); H5Dclose(dataSetId); return; } int ts = 0; // T *values = data; size_t variableStart = variable.m_StepsStart; /* // looks like m_StepsStart is defaulted to be 0 now. if (!m_InStreamMode && (variableStart == 1)) { // variableBase::m_StepsStart min=1 variableStart = 0; } */ while (ts < variable.m_StepsCount) { if (m_H5File.m_IsGeneratedByAdios) { m_H5File.SetAdiosStep(variableStart + ts); } hid_t dataSetId = H5Dopen(m_H5File.m_GroupId, variable.m_Name.c_str(), H5P_DEFAULT); if (dataSetId < 0) { return; } hid_t fileSpace = H5Dget_space(dataSetId); if (fileSpace < 0) { return; } size_t slabsize = 1; int ndims = std::max(variable.m_Shape.size(), variable.m_Count.size()); if (0 == ndims) { // is scalar hid_t ret = H5Dread(dataSetId, h5Type, H5S_ALL, H5S_ALL, H5P_DEFAULT, values); } else { hsize_t start[ndims], count[ndims], stride[ndims]; bool isOrderC = IsRowMajor(m_IO.m_HostLanguage); for (int i = 0; i < ndims; i++) { if (isOrderC) { count[i] = variable.m_Count[i]; start[i] = variable.m_Start[i]; } else { count[i] = variable.m_Count[ndims - 1 - i]; start[i] = variable.m_Start[ndims - 1 - i]; } slabsize *= count[i]; stride[i] = 1; } hid_t ret = H5Sselect_hyperslab(fileSpace, H5S_SELECT_SET, start, stride, count, NULL); if (ret < 0) return; hid_t memDataSpace = H5Screate_simple(ndims, count, NULL); int elementsRead = 1; for (int i = 0; i < ndims; i++) { elementsRead *= count[i]; } ret = H5Dread(dataSetId, h5Type, memDataSpace, fileSpace, H5P_DEFAULT, values); H5Sclose(memDataSpace); } H5Sclose(fileSpace); H5Dclose(dataSetId); ts++; values += slabsize; } // while } /* template <class T> void HDF5ReaderP::UseHDFRead(const std::string &variableName, T *values, hid_t h5Type) { int rank, size; MPI_Comm_rank(m_MPIComm, &rank); MPI_Comm_size(m_MPIComm, &size); hid_t dataSetId = H5Dopen(m_H5File.m_GroupId, variableName.c_str(), H5P_DEFAULT); if (dataSetId < 0) { return; } hid_t fileSpace = H5Dget_space(dataSetId); if (fileSpace < 0) { return; } int ndims = H5Sget_simple_extent_ndims(fileSpace); if (ndims == 0) { // SCALAR hid_t ret = H5Dread(dataSetId, h5Type, H5S_ALL, H5S_ALL, H5P_DEFAULT, values); return; } hsize_t dims[ndims]; herr_t status_n = H5Sget_simple_extent_dims(fileSpace, dims, NULL); // hsize_t start[ndims] = {0}, count[ndims] = {0}, stride[ndims] = {1}; hsize_t start[ndims], count[ndims], stride[ndims]; int totalElements = 1; for (int i = 0; i < ndims; i++) { count[i] = dims[i]; totalElements *= dims[i]; start[i] = 0; //count[i] = 0; stride[i] = 1; } start[0] = rank * dims[0] / size; count[0] = dims[0] / size; if (rank == size - 1) { count[0] = dims[0] - count[0] * (size - 1); } hid_t ret = H5Sselect_hyperslab(fileSpace, H5S_SELECT_SET, start, stride, count, NULL); if (ret < 0) { return; } hid_t memDataSpace = H5Screate_simple(ndims, count, NULL); int elementsRead = 1; for (int i = 0; i < ndims; i++) { elementsRead *= count[i]; } #ifdef NEVER //T data_array[elementsRead]; std::vector<T> data_vector; data_vector.reserve(elementsRead); T* data_array = data_vector.data(); ret = H5Dread(dataSetId, h5Type, memDataSpace, fileSpace, H5P_DEFAULT, data_array); #else ret = H5Dread(dataSetId, h5Type, memDataSpace, fileSpace, H5P_DEFAULT, values); #endif H5Sclose(memDataSpace); H5Sclose(fileSpace); H5Dclose(dataSetId); } */ StepStatus HDF5ReaderP::BeginStep(StepMode mode, const float timeoutSeconds) { // printf(".... in begin step: \n"); m_InStreamMode = true; int ts = m_H5File.GetNumAdiosSteps(); if (m_StreamAt >= ts) { return StepStatus::EndOfStream; } return StepStatus::OK; } size_t HDF5ReaderP::CurrentStep() const { return m_StreamAt; } void HDF5ReaderP::EndStep() { if (m_DeferredStack.size() > 0) { PerformGets(); } m_StreamAt++; m_H5File.Advance(); } void HDF5ReaderP::PerformGets() { // looks this this is not enforced to be specific to stream mode!! if (!m_InStreamMode) { #define declare_type(T) \ for (std::string variableName : m_DeferredStack) \ { \ Variable<T> *var = m_IO.InquireVariable<T>(variableName); \ if (var != nullptr) \ { \ hid_t h5Type = m_H5File.GetHDF5Type<T>(); \ UseHDFRead(*var, var->GetData(), h5Type); \ break; \ } \ } ADIOS2_FOREACH_TYPE_1ARG(declare_type) #undef declare_type // throw std::runtime_error( // "PerformGets() needs to follow stream read sequeuences."); return; } #define declare_type(T) \ for (std::string variableName : m_DeferredStack) \ { \ Variable<T> *var = m_IO.InquireVariable<T>(variableName); \ if (var != nullptr) \ { \ var->m_StepsStart = m_StreamAt; \ var->m_StepsCount = 1; \ hid_t h5Type = m_H5File.GetHDF5Type<T>(); \ UseHDFRead(*var, var->GetData(), h5Type); \ break; \ } \ } ADIOS2_FOREACH_TYPE_1ARG(declare_type) #undef declare_type m_DeferredStack.clear(); } #define declare_type(T) \ void HDF5ReaderP::DoGetSync(Variable<T> &variable, T *data) \ { \ GetSyncCommon(variable, data); \ } \ void HDF5ReaderP::DoGetDeferred(Variable<T> &variable, T *data) \ { \ GetDeferredCommon(variable, data); \ } \ void HDF5ReaderP::DoGetDeferred(Variable<T> &variable, T &data) \ { \ GetDeferredCommon(variable, &data); \ } ADIOS2_FOREACH_TYPE_1ARG(declare_type) #undef declare_type void HDF5ReaderP::DoClose(const int transportIndex) { // printf("ReaderP::DoClose() %lu\n", m_DeferredStack.size()); if (m_DeferredStack.size() > 0) { if (m_InStreamMode) { PerformGets(); } else { #define declare_type(T) \ for (std::string variableName : m_DeferredStack) \ { \ Variable<T> *var = m_IO.InquireVariable<T>(variableName); \ if (var != nullptr) \ { \ hid_t h5Type = m_H5File.GetHDF5Type<T>(); \ UseHDFRead(*var, var->GetData(), h5Type); \ break; \ } \ } ADIOS2_FOREACH_TYPE_1ARG(declare_type) #undef declare_type m_DeferredStack.clear(); } } m_H5File.Close(); } } // end namespace adios2 <commit_msg>SetAdiosStep() run time error handled<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * HDF5ReaderP.cpp * * Created on: March 20, 2017 * Author: Junmin */ #include "HDF5ReaderP.h" #include "HDF5ReaderP.tcc" #include "adios2/ADIOSMPI.h" #include "adios2/helper/adiosFunctions.h" //CSVToVector namespace adios2 { HDF5ReaderP::HDF5ReaderP(IO &io, const std::string &name, const Mode openMode, MPI_Comm mpiComm) : Engine("HDF5Reader", io, name, openMode, mpiComm), m_H5File(io.m_DebugMode) { m_EndMessage = ", in call to IO HDF5Reader Open " + m_Name + "\n"; Init(); } HDF5ReaderP::~HDF5ReaderP() { DoClose(); } bool HDF5ReaderP::IsValid() { bool isValid = false; if (m_OpenMode != Mode::Read) { return isValid; } if (m_H5File.m_FileId >= 0) { isValid = true; } return isValid; } void HDF5ReaderP::Init() { if (m_OpenMode != Mode::Read) { throw std::invalid_argument( "ERROR: HDF5Reader only supports OpenMode::Read " ", in call to Open\n"); } m_H5File.Init(m_Name, m_MPIComm, false); /* int ts = m_H5File.GetNumAdiosSteps(); if (ts == 0) { throw std::runtime_error("This h5 file is NOT written by ADIOS2"); } */ if (!m_InStreamMode) { m_H5File.ReadAllVariables(m_IO); } else { m_H5File.ReadAllVariables(m_IO); } } template <class T> void HDF5ReaderP::UseHDFRead(Variable<T> &variable, T *data, hid_t h5Type) { T *values = data; if (!m_H5File.m_IsGeneratedByAdios) { // printf("Will read by Native reader ..%s\n", variable.m_Name.c_str()); hid_t dataSetId = H5Dopen(m_H5File.m_FileId, variable.m_Name.c_str(), H5P_DEFAULT); if (dataSetId < 0) { return; } hid_t fileSpace = H5Dget_space(dataSetId); if (fileSpace < 0) { return; } size_t slabsize = 1; int ndims = std::max(variable.m_Shape.size(), variable.m_Count.size()); if (0 == ndims) { // is scalar hid_t ret = H5Dread(dataSetId, h5Type, H5S_ALL, H5S_ALL, H5P_DEFAULT, values); } else { hsize_t start[ndims], count[ndims], stride[ndims]; bool isOrderC = IsRowMajor(m_IO.m_HostLanguage); for (int i = 0; i < ndims; i++) { if (isOrderC) { count[i] = variable.m_Count[i]; start[i] = variable.m_Start[i]; } else { count[i] = variable.m_Count[ndims - 1 - i]; start[i] = variable.m_Start[ndims - 1 - i]; } slabsize *= count[i]; stride[i] = 1; } hid_t ret = H5Sselect_hyperslab(fileSpace, H5S_SELECT_SET, start, stride, count, NULL); if (ret < 0) return; hid_t memDataSpace = H5Screate_simple(ndims, count, NULL); int elementsRead = 1; for (int i = 0; i < ndims; i++) { elementsRead *= count[i]; } ret = H5Dread(dataSetId, h5Type, memDataSpace, fileSpace, H5P_DEFAULT, values); H5Sclose(memDataSpace); } H5Sclose(fileSpace); H5Dclose(dataSetId); return; } int ts = 0; // T *values = data; size_t variableStart = variable.m_StepsStart; /* // looks like m_StepsStart is defaulted to be 0 now. if (!m_InStreamMode && (variableStart == 1)) { // variableBase::m_StepsStart min=1 variableStart = 0; } */ while (ts < variable.m_StepsCount) { if (m_H5File.m_IsGeneratedByAdios) { try { m_H5File.SetAdiosStep(variableStart + ts); } catch (std::exception &e) { printf("[Not fatal] %s\n", e.what()); break; } } hid_t dataSetId = H5Dopen(m_H5File.m_GroupId, variable.m_Name.c_str(), H5P_DEFAULT); if (dataSetId < 0) { return; } hid_t fileSpace = H5Dget_space(dataSetId); if (fileSpace < 0) { return; } size_t slabsize = 1; int ndims = std::max(variable.m_Shape.size(), variable.m_Count.size()); if (0 == ndims) { // is scalar hid_t ret = H5Dread(dataSetId, h5Type, H5S_ALL, H5S_ALL, H5P_DEFAULT, values); } else { hsize_t start[ndims], count[ndims], stride[ndims]; bool isOrderC = IsRowMajor(m_IO.m_HostLanguage); for (int i = 0; i < ndims; i++) { if (isOrderC) { count[i] = variable.m_Count[i]; start[i] = variable.m_Start[i]; } else { count[i] = variable.m_Count[ndims - 1 - i]; start[i] = variable.m_Start[ndims - 1 - i]; } slabsize *= count[i]; stride[i] = 1; } hid_t ret = H5Sselect_hyperslab(fileSpace, H5S_SELECT_SET, start, stride, count, NULL); if (ret < 0) return; hid_t memDataSpace = H5Screate_simple(ndims, count, NULL); int elementsRead = 1; for (int i = 0; i < ndims; i++) { elementsRead *= count[i]; } ret = H5Dread(dataSetId, h5Type, memDataSpace, fileSpace, H5P_DEFAULT, values); H5Sclose(memDataSpace); } H5Sclose(fileSpace); H5Dclose(dataSetId); ts++; values += slabsize; } // while } /* template <class T> void HDF5ReaderP::UseHDFRead(const std::string &variableName, T *values, hid_t h5Type) { int rank, size; MPI_Comm_rank(m_MPIComm, &rank); MPI_Comm_size(m_MPIComm, &size); hid_t dataSetId = H5Dopen(m_H5File.m_GroupId, variableName.c_str(), H5P_DEFAULT); if (dataSetId < 0) { return; } hid_t fileSpace = H5Dget_space(dataSetId); if (fileSpace < 0) { return; } int ndims = H5Sget_simple_extent_ndims(fileSpace); if (ndims == 0) { // SCALAR hid_t ret = H5Dread(dataSetId, h5Type, H5S_ALL, H5S_ALL, H5P_DEFAULT, values); return; } hsize_t dims[ndims]; herr_t status_n = H5Sget_simple_extent_dims(fileSpace, dims, NULL); // hsize_t start[ndims] = {0}, count[ndims] = {0}, stride[ndims] = {1}; hsize_t start[ndims], count[ndims], stride[ndims]; int totalElements = 1; for (int i = 0; i < ndims; i++) { count[i] = dims[i]; totalElements *= dims[i]; start[i] = 0; //count[i] = 0; stride[i] = 1; } start[0] = rank * dims[0] / size; count[0] = dims[0] / size; if (rank == size - 1) { count[0] = dims[0] - count[0] * (size - 1); } hid_t ret = H5Sselect_hyperslab(fileSpace, H5S_SELECT_SET, start, stride, count, NULL); if (ret < 0) { return; } hid_t memDataSpace = H5Screate_simple(ndims, count, NULL); int elementsRead = 1; for (int i = 0; i < ndims; i++) { elementsRead *= count[i]; } #ifdef NEVER //T data_array[elementsRead]; std::vector<T> data_vector; data_vector.reserve(elementsRead); T* data_array = data_vector.data(); ret = H5Dread(dataSetId, h5Type, memDataSpace, fileSpace, H5P_DEFAULT, data_array); #else ret = H5Dread(dataSetId, h5Type, memDataSpace, fileSpace, H5P_DEFAULT, values); #endif H5Sclose(memDataSpace); H5Sclose(fileSpace); H5Dclose(dataSetId); } */ StepStatus HDF5ReaderP::BeginStep(StepMode mode, const float timeoutSeconds) { // printf(".... in begin step: \n"); m_InStreamMode = true; int ts = m_H5File.GetNumAdiosSteps(); if (m_StreamAt >= ts) { return StepStatus::EndOfStream; } return StepStatus::OK; } size_t HDF5ReaderP::CurrentStep() const { return m_StreamAt; } void HDF5ReaderP::EndStep() { if (m_DeferredStack.size() > 0) { PerformGets(); } m_StreamAt++; m_H5File.Advance(); } void HDF5ReaderP::PerformGets() { // looks this this is not enforced to be specific to stream mode!! if (!m_InStreamMode) { #define declare_type(T) \ for (std::string variableName : m_DeferredStack) \ { \ Variable<T> *var = m_IO.InquireVariable<T>(variableName); \ if (var != nullptr) \ { \ hid_t h5Type = m_H5File.GetHDF5Type<T>(); \ UseHDFRead(*var, var->GetData(), h5Type); \ break; \ } \ } ADIOS2_FOREACH_TYPE_1ARG(declare_type) #undef declare_type // throw std::runtime_error( // "PerformGets() needs to follow stream read sequeuences."); return; } #define declare_type(T) \ for (std::string variableName : m_DeferredStack) \ { \ Variable<T> *var = m_IO.InquireVariable<T>(variableName); \ if (var != nullptr) \ { \ var->m_StepsStart = m_StreamAt; \ var->m_StepsCount = 1; \ hid_t h5Type = m_H5File.GetHDF5Type<T>(); \ UseHDFRead(*var, var->GetData(), h5Type); \ break; \ } \ } ADIOS2_FOREACH_TYPE_1ARG(declare_type) #undef declare_type m_DeferredStack.clear(); } #define declare_type(T) \ void HDF5ReaderP::DoGetSync(Variable<T> &variable, T *data) \ { \ GetSyncCommon(variable, data); \ } \ void HDF5ReaderP::DoGetDeferred(Variable<T> &variable, T *data) \ { \ GetDeferredCommon(variable, data); \ } \ void HDF5ReaderP::DoGetDeferred(Variable<T> &variable, T &data) \ { \ GetDeferredCommon(variable, &data); \ } ADIOS2_FOREACH_TYPE_1ARG(declare_type) #undef declare_type void HDF5ReaderP::DoClose(const int transportIndex) { // printf("ReaderP::DoClose() %lu\n", m_DeferredStack.size()); if (m_DeferredStack.size() > 0) { if (m_InStreamMode) { PerformGets(); } else { #define declare_type(T) \ for (std::string variableName : m_DeferredStack) \ { \ Variable<T> *var = m_IO.InquireVariable<T>(variableName); \ if (var != nullptr) \ { \ hid_t h5Type = m_H5File.GetHDF5Type<T>(); \ UseHDFRead(*var, var->GetData(), h5Type); \ break; \ } \ } ADIOS2_FOREACH_TYPE_1ARG(declare_type) #undef declare_type m_DeferredStack.clear(); } } m_H5File.Close(); } } // end namespace adios2 <|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: OOXMLStreamImpl.cxx,v $ * $Revision: 1.11 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "OOXMLStreamImpl.hxx" #include "OOXMLFastTokenHandler.hxx" #include <iostream> #ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALSTORAGEACCESS_HPP_ #include <com/sun/star/embed/XHierarchicalStorageAccess.hpp> #endif //#define DEBUG_STREAM namespace writerfilter { namespace ooxml { using namespace ::std; OOXMLStreamImpl::OOXMLStreamImpl (uno::Reference<uno::XComponentContext> xContext, uno::Reference<embed::XStorage> xStorage, StreamType_t nType) : mxContext(xContext), mxStorage(xStorage), mnStreamType(nType) { mxRelationshipAccess.set(mxStorage, uno::UNO_QUERY_THROW); init(); } OOXMLStreamImpl::OOXMLStreamImpl (OOXMLStreamImpl & rOOXMLStream, StreamType_t nStreamType) : mxContext(rOOXMLStream.mxContext), mxStorage(rOOXMLStream.mxStorage), mnStreamType(nStreamType), msPath(rOOXMLStream.msPath) { mxRelationshipAccess.set(rOOXMLStream.mxDocumentStream, uno::UNO_QUERY_THROW); init(); } OOXMLStreamImpl::OOXMLStreamImpl (uno::Reference<uno::XComponentContext> xContext, uno::Reference<embed::XStorage> xStorage, const rtl::OUString & rId) : mxContext(xContext), mxStorage(xStorage), mnStreamType(UNKNOWN), msId(rId) { mxRelationshipAccess.set(mxStorage, uno::UNO_QUERY_THROW); init(); } OOXMLStreamImpl::OOXMLStreamImpl (OOXMLStreamImpl & rOOXMLStream, const rtl::OUString & rId) : mxContext(rOOXMLStream.mxContext), mxStorage(rOOXMLStream.mxStorage), mnStreamType(UNKNOWN), msId(rId), msPath(rOOXMLStream.msPath) { mxRelationshipAccess.set(rOOXMLStream.mxDocumentStream, uno::UNO_QUERY_THROW); init(); } OOXMLStreamImpl::~OOXMLStreamImpl() { #ifdef DEBUG_STREAM logger("DEBUG", "</stream>"); #endif } bool OOXMLStreamImpl::getTarget(uno::Reference<embed::XRelationshipAccess> xRelationshipAccess, StreamType_t nStreamType, const ::rtl::OUString & rId, ::rtl::OUString & rDocumentTarget) { bool bFound = false; static rtl::OUString sType(RTL_CONSTASCII_USTRINGPARAM("Type")); static rtl::OUString sId(RTL_CONSTASCII_USTRINGPARAM("Id")); static rtl::OUString sDocumentType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument")); static rtl::OUString sStylesType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles")); static rtl::OUString sNumberingType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering")); static rtl::OUString sFonttableType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable")); static rtl::OUString sFootnotesType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes")); static rtl::OUString sEndnotesType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes")); static rtl::OUString sCommentsType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments")); static rtl::OUString sThemeType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme")); static rtl::OUString sTarget(RTL_CONSTASCII_USTRINGPARAM("Target")); static rtl::OUString sTargetMode(RTL_CONSTASCII_USTRINGPARAM("TargetMode")); static rtl::OUString sExternal(RTL_CONSTASCII_USTRINGPARAM("External")); rtl::OUString sStreamType; switch (nStreamType) { case DOCUMENT: sStreamType = sDocumentType; break; case STYLES: sStreamType = sStylesType; break; case NUMBERING: sStreamType = sNumberingType; break; case FONTTABLE: sStreamType = sFonttableType; break; case FOOTNOTES: sStreamType = sFootnotesType; break; case ENDNOTES: sStreamType = sEndnotesType; break; case COMMENTS: sStreamType = sCommentsType; break; case THEME: sStreamType = sThemeType; break; default: break; } if (xRelationshipAccess.is()) { uno::Sequence< uno::Sequence< beans::StringPair > >aSeqs = xRelationshipAccess->getAllRelationships(); for (sal_Int32 j = 0; j < aSeqs.getLength(); j++) { uno::Sequence< beans::StringPair > aSeq = aSeqs[j]; bool bExternalTarget = false; ::rtl::OUString sMyTarget; for (sal_Int32 i = 0; i < aSeq.getLength(); i++) { beans::StringPair aPair = aSeq[i]; if (aPair.First.compareTo(sType) == 0 && aPair.Second.compareTo(sStreamType) == 0) bFound = true; else if (aPair.First.compareTo(sId) == 0 && aPair.Second.compareTo(rId) == 0) bFound = true; else if (aPair.First.compareTo(sTarget) == 0) sMyTarget = aPair.Second; else if (aPair.First.compareTo(sTargetMode) == 0 && aPair.Second.compareTo(sExternal) == 0) bExternalTarget = true; } if (bFound) { if (bExternalTarget) rDocumentTarget = sMyTarget; else { rDocumentTarget = msPath; rDocumentTarget += sMyTarget; } break; } } } return bFound; } ::rtl::OUString OOXMLStreamImpl::getTargetForId(const ::rtl::OUString & rId) { ::rtl::OUString sTarget; uno::Reference<embed::XRelationshipAccess> xRelationshipAccess (mxDocumentStream, uno::UNO_QUERY_THROW); if (getTarget(xRelationshipAccess, UNKNOWN, rId, sTarget)) return sTarget; return ::rtl::OUString(); } void OOXMLStreamImpl::init() { ::rtl::OUString sDocumentTarget; bool bFound = getTarget(mxRelationshipAccess, mnStreamType, msId, sDocumentTarget); #ifdef DEBUG_STREAM logger("DEBUG", string("<stream>") + OUStringToOString(sDocumentTarget, RTL_TEXTENCODING_ASCII_US).getStr()); #endif if (bFound) { sal_Int32 nLastIndex = sDocumentTarget.lastIndexOf('/'); if (nLastIndex >= 0) msPath = sDocumentTarget.copy(0, nLastIndex + 1); uno::Reference<embed::XHierarchicalStorageAccess> xHierarchicalStorageAccess(mxStorage, uno::UNO_QUERY); if (xHierarchicalStorageAccess.is()) { uno::Any aAny(xHierarchicalStorageAccess-> openStreamElementByHierarchicalName (sDocumentTarget, embed::ElementModes::READ)); aAny >>= mxDocumentStream; } } } uno::Reference<io::XInputStream> OOXMLStreamImpl::getDocumentStream() { uno::Reference<io::XInputStream> xResult; if (mxDocumentStream.is()) xResult = mxDocumentStream->getInputStream(); return xResult; } uno::Reference<io::XInputStream> OOXMLStreamImpl::getInputStream() { return mxInputStream; } void OOXMLStreamImpl::setInputStream (uno::Reference<io::XInputStream> rxInputStream) { mxInputStream = rxInputStream; } uno::Reference<xml::sax::XParser> OOXMLStreamImpl::getParser() { uno::Reference<lang::XMultiComponentFactory> xFactory = uno::Reference<lang::XMultiComponentFactory> (mxContext->getServiceManager()); uno::Reference<xml::sax::XParser> xParser (xFactory->createInstanceWithContext ( rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Parser" ), mxContext ), uno::UNO_QUERY ); return xParser; } uno::Reference<uno::XComponentContext> OOXMLStreamImpl::getContext() { return mxContext; } uno::Reference <xml::sax::XFastTokenHandler> OOXMLStreamImpl::getFastTokenHandler (uno::Reference<uno::XComponentContext> xContext) { if (! mxFastTokenHandler.is()) mxFastTokenHandler.set(new OOXMLFastTokenHandler(xContext)); return mxFastTokenHandler; } OOXMLStream::Pointer_t OOXMLDocumentFactory::createStream (uno::Reference<uno::XComponentContext> xContext, uno::Reference<io::XInputStream> rStream, OOXMLStream::StreamType_t nStreamType) { uno::Reference<embed::XStorage> xStorage = comphelper::OStorageHelper::GetStorageOfFormatFromInputStream (OFOPXML_STORAGE_FORMAT_STRING, rStream); OOXMLStreamImpl * pStream = new OOXMLStreamImpl(xContext, xStorage, nStreamType); pStream->setInputStream(rStream); return OOXMLStream::Pointer_t(pStream); } OOXMLStream::Pointer_t OOXMLDocumentFactory::createStream (OOXMLStream::Pointer_t pStream, OOXMLStream::StreamType_t nStreamType) { return OOXMLStream::Pointer_t (new OOXMLStreamImpl(*dynamic_cast<OOXMLStreamImpl *>(pStream.get()), nStreamType)); } OOXMLStream::Pointer_t OOXMLDocumentFactory::createStream (OOXMLStream::Pointer_t pStream, const rtl::OUString & rId) { return OOXMLStream::Pointer_t (new OOXMLStreamImpl(*dynamic_cast<OOXMLStreamImpl *>(pStream.get()), rId)); } }} <commit_msg>INTEGRATION: CWS xmlfilter04 (1.9.14); FILE MERGED 2008/03/06 08:21:33 hbrinkm 1.9.14.2: removed getInputStream, new: getStorageStream, getTarget 2008/02/21 12:33:26 hbrinkm 1.9.14.1: joined changes from xmlfilter03<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: OOXMLStreamImpl.cxx,v $ * $Revision: 1.12 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "OOXMLStreamImpl.hxx" #include "OOXMLFastTokenHandler.hxx" #include <iostream> #ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALSTORAGEACCESS_HPP_ #include <com/sun/star/embed/XHierarchicalStorageAccess.hpp> #endif //#define DEBUG_STREAM namespace writerfilter { namespace ooxml { using namespace ::std; OOXMLStreamImpl::OOXMLStreamImpl (uno::Reference<uno::XComponentContext> xContext, uno::Reference<io::XInputStream> xStorageStream, StreamType_t nType) : mxContext(xContext), mxStorageStream(xStorageStream), mnStreamType(nType) { mxStorage.set (comphelper::OStorageHelper::GetStorageOfFormatFromInputStream (OFOPXML_STORAGE_FORMAT_STRING, mxStorageStream)); mxRelationshipAccess.set(mxStorage, uno::UNO_QUERY_THROW); init(); } OOXMLStreamImpl::OOXMLStreamImpl (OOXMLStreamImpl & rOOXMLStream, StreamType_t nStreamType) : mxContext(rOOXMLStream.mxContext), mxStorageStream(rOOXMLStream.mxStorageStream), mxStorage(rOOXMLStream.mxStorage), mnStreamType(nStreamType), msPath(rOOXMLStream.msPath) { mxRelationshipAccess.set(rOOXMLStream.mxDocumentStream, uno::UNO_QUERY_THROW); init(); } OOXMLStreamImpl::OOXMLStreamImpl (uno::Reference<uno::XComponentContext> xContext, uno::Reference<io::XInputStream> xStorageStream, const rtl::OUString & rId) : mxContext(xContext), mxStorageStream(xStorageStream), mnStreamType(UNKNOWN), msId(rId) { mxStorage.set (comphelper::OStorageHelper::GetStorageOfFormatFromInputStream (OFOPXML_STORAGE_FORMAT_STRING, mxStorageStream)); mxRelationshipAccess.set(mxStorage, uno::UNO_QUERY_THROW); init(); } OOXMLStreamImpl::OOXMLStreamImpl (OOXMLStreamImpl & rOOXMLStream, const rtl::OUString & rId) : mxContext(rOOXMLStream.mxContext), mxStorageStream(rOOXMLStream.mxStorageStream), mxStorage(rOOXMLStream.mxStorage), mnStreamType(UNKNOWN), msId(rId), msPath(rOOXMLStream.msPath) { mxRelationshipAccess.set(rOOXMLStream.mxDocumentStream, uno::UNO_QUERY_THROW); init(); } OOXMLStreamImpl::~OOXMLStreamImpl() { #ifdef DEBUG_STREAM logger("DEBUG", "</stream>"); #endif } const ::rtl::OUString & OOXMLStreamImpl::getTarget() const { return msTarget; } bool OOXMLStreamImpl::lcl_getTarget(uno::Reference<embed::XRelationshipAccess> xRelationshipAccess, StreamType_t nStreamType, const ::rtl::OUString & rId, ::rtl::OUString & rDocumentTarget) { bool bFound = false; static rtl::OUString sType(RTL_CONSTASCII_USTRINGPARAM("Type")); static rtl::OUString sId(RTL_CONSTASCII_USTRINGPARAM("Id")); static rtl::OUString sDocumentType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument")); static rtl::OUString sStylesType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles")); static rtl::OUString sNumberingType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering")); static rtl::OUString sFonttableType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable")); static rtl::OUString sFootnotesType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes")); static rtl::OUString sEndnotesType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes")); static rtl::OUString sCommentsType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments")); static rtl::OUString sThemeType(RTL_CONSTASCII_USTRINGPARAM("http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme")); static rtl::OUString sTarget(RTL_CONSTASCII_USTRINGPARAM("Target")); static rtl::OUString sTargetMode(RTL_CONSTASCII_USTRINGPARAM("TargetMode")); static rtl::OUString sExternal(RTL_CONSTASCII_USTRINGPARAM("External")); rtl::OUString sStreamType; switch (nStreamType) { case DOCUMENT: sStreamType = sDocumentType; break; case STYLES: sStreamType = sStylesType; break; case NUMBERING: sStreamType = sNumberingType; break; case FONTTABLE: sStreamType = sFonttableType; break; case FOOTNOTES: sStreamType = sFootnotesType; break; case ENDNOTES: sStreamType = sEndnotesType; break; case COMMENTS: sStreamType = sCommentsType; break; case THEME: sStreamType = sThemeType; break; default: break; } if (xRelationshipAccess.is()) { uno::Sequence< uno::Sequence< beans::StringPair > >aSeqs = xRelationshipAccess->getAllRelationships(); for (sal_Int32 j = 0; j < aSeqs.getLength(); j++) { uno::Sequence< beans::StringPair > aSeq = aSeqs[j]; bool bExternalTarget = false; ::rtl::OUString sMyTarget; for (sal_Int32 i = 0; i < aSeq.getLength(); i++) { beans::StringPair aPair = aSeq[i]; if (aPair.First.compareTo(sType) == 0 && aPair.Second.compareTo(sStreamType) == 0) bFound = true; else if (aPair.First.compareTo(sId) == 0 && aPair.Second.compareTo(rId) == 0) bFound = true; else if (aPair.First.compareTo(sTarget) == 0) sMyTarget = aPair.Second; else if (aPair.First.compareTo(sTargetMode) == 0 && aPair.Second.compareTo(sExternal) == 0) bExternalTarget = true; } if (bFound) { if (bExternalTarget) rDocumentTarget = sMyTarget; else { rDocumentTarget = msPath; rDocumentTarget += sMyTarget; } break; } } } return bFound; } ::rtl::OUString OOXMLStreamImpl::getTargetForId(const ::rtl::OUString & rId) { ::rtl::OUString sTarget; uno::Reference<embed::XRelationshipAccess> xRelationshipAccess (mxDocumentStream, uno::UNO_QUERY_THROW); if (lcl_getTarget(xRelationshipAccess, UNKNOWN, rId, sTarget)) return sTarget; return ::rtl::OUString(); } void OOXMLStreamImpl::init() { bool bFound = lcl_getTarget(mxRelationshipAccess, mnStreamType, msId, msTarget); #ifdef DEBUG_STREAM logger("DEBUG", string("<stream>") + OUStringToOString(msTarget, RTL_TEXTENCODING_ASCII_US).getStr()); #endif if (bFound) { sal_Int32 nLastIndex = msTarget.lastIndexOf('/'); if (nLastIndex >= 0) msPath = msTarget.copy(0, nLastIndex + 1); uno::Reference<embed::XHierarchicalStorageAccess> xHierarchicalStorageAccess(mxStorage, uno::UNO_QUERY); if (xHierarchicalStorageAccess.is()) { uno::Any aAny(xHierarchicalStorageAccess-> openStreamElementByHierarchicalName (msTarget, embed::ElementModes::SEEKABLEREAD)); aAny >>= mxDocumentStream; } } } uno::Reference<io::XInputStream> OOXMLStreamImpl::getDocumentStream() { uno::Reference<io::XInputStream> xResult; if (mxDocumentStream.is()) xResult = mxDocumentStream->getInputStream(); return xResult; } uno::Reference<io::XInputStream> OOXMLStreamImpl::getStorageStream() { return mxStorageStream; } uno::Reference<xml::sax::XParser> OOXMLStreamImpl::getParser() { uno::Reference<lang::XMultiComponentFactory> xFactory = uno::Reference<lang::XMultiComponentFactory> (mxContext->getServiceManager()); uno::Reference<xml::sax::XParser> xParser (xFactory->createInstanceWithContext ( rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Parser" ), mxContext ), uno::UNO_QUERY ); return xParser; } uno::Reference<uno::XComponentContext> OOXMLStreamImpl::getContext() { return mxContext; } uno::Reference <xml::sax::XFastTokenHandler> OOXMLStreamImpl::getFastTokenHandler (uno::Reference<uno::XComponentContext> xContext) { if (! mxFastTokenHandler.is()) mxFastTokenHandler.set(new OOXMLFastTokenHandler(xContext)); return mxFastTokenHandler; } OOXMLStream::Pointer_t OOXMLDocumentFactory::createStream (uno::Reference<uno::XComponentContext> xContext, uno::Reference<io::XInputStream> rStream, OOXMLStream::StreamType_t nStreamType) { OOXMLStreamImpl * pStream = new OOXMLStreamImpl(xContext, rStream, nStreamType); return OOXMLStream::Pointer_t(pStream); } OOXMLStream::Pointer_t OOXMLDocumentFactory::createStream (OOXMLStream::Pointer_t pStream, OOXMLStream::StreamType_t nStreamType) { return OOXMLStream::Pointer_t (new OOXMLStreamImpl(*dynamic_cast<OOXMLStreamImpl *>(pStream.get()), nStreamType)); } OOXMLStream::Pointer_t OOXMLDocumentFactory::createStream (OOXMLStream::Pointer_t pStream, const rtl::OUString & rId) { return OOXMLStream::Pointer_t (new OOXMLStreamImpl(*dynamic_cast<OOXMLStreamImpl *>(pStream.get()), rId)); } }} <|endoftext|>
<commit_before>// Read a file and parse each line according to the format file. // Output integer matrices with lookup maps in either ascii text // or matlab binary form. #include <stdlib.h> #include <stdio.h> #include <time.h> #include "utils.h" #include "gzstream.h" #define BUFSIZE 1048576 class stringIndexer { public: ivector count; unhash unh; strhash htab; int size; char * linebuf; stringIndexer() : htab(0), unh(0), count(0), size(0) { linebuf = new char[BUFSIZE]; }; stringIndexer(const stringIndexer & si); ~stringIndexer(); stringIndexer(char *); int writeMap(string fname, string suffix) { writeIntVec(count, fname + ".cnt.imat" + suffix, BUFSIZE); return writeSBVecs(unh, fname + ".sbmat" + suffix, BUFSIZE); } int checkword(char *str); }; int stringIndexer:: checkword(char * str) { int userno; char * newstr; if (htab.count(str)) { userno = htab[str]; count[userno-1]++; } else { try { newstr = new char[strlen(str)+1]; strcpy(newstr, str); userno = ++size; htab[newstr] = userno; count.push_back(1); unh.push_back(newstr); } catch (std::bad_alloc) { cerr << "stringIndexer:checkstr: allocation error" << endl; throw; } } return userno; } stringIndexer:: ~stringIndexer() { int i; for (i=0; i<unh.size(); i++) { if (unh[i]) { delete [] unh[i]; unh[i] = NULL; } } if (linebuf) { delete [] linebuf; linebuf = NULL; } } int parseLine(char * line, const char * delim1, const char * delim2, const char *delim3, const char * delim4, stringIndexer & si, fvector &labels, imatrix & imat, fvector & fvec) { char *here, *next, *fpos; int label, indx; float fval; ivector iv; here = line; next = strpbrk(here, delim1); // get the label(s) *(next++) = 0; sscanf(here, "%d", &label); here = next; labels.push_back(label); next = strpbrk(here, delim2); // get the tag *(next++) = 0; // Do nothing with the tag for now here = next; while (here != NULL) { next = strpbrk(here, delim3); // get a feature/value pair if (next) { *(next++) = 0; } // Actually parse in here fpos = strpbrk(here, delim4); // get a value, if there is one fval = 1.0; if (fpos) { sscanf(fpos+1, "%f", &fval); *fpos = 0; } indx = si.checkword(here); iv.push_back(indx); fvec.push_back(fval); here = next; } imat.push_back(iv); return 0; } void writefiles(string fname, imatrix &imat, fvector &fvec, fvector &labels, string suffix, int &ifile, int membuf) { char num[6]; sprintf(num, "%05d", ifile); writeIntVecs(imat, fname+"inds"+num+".imat"+suffix, membuf); writeFVec(fvec, fname+"vals"+num+".fmat"+suffix, membuf); writeFVec(labels, fname+"labels"+num+".fmat"+suffix, membuf); ifile++; imat.clear(); fvec.clear(); labels.clear(); } const char usage[] = "\nParser for generalized libsvm files. Arguments are\n" " -i <infile> input file[s] to read\n" " -o <outd> output files will be written to <outd><infile>.imat[.gz]\n" " -d <dictfile> dictionary will be written to <dictfile>.sbmat[.gz]\n" " and word counts will be written to <dictfile>.imat[.gz]\n" " -s N set buffer size to N.\n" " -n N split files at N lines.\n" " -c produce compressed (gzipped) output files.\n\n" ; int main(int argc, char ** argv) { int jmax, iarg=1, membuf=1048576, nsplit=100000, nfiles = 0; long long numlines; char *here, *linebuf, *readbuf; char *ifname = NULL; string odname="", dictname = "", suffix = ""; string delim1=" ", delim2="|", delim3=" ", delim4=":"; while (iarg < argc) { if (strncmp(argv[iarg], "-i", 2) == 0) { ifname = argv[++iarg]; } else if (strncmp(argv[iarg], "-o", 2) == 0) { odname = argv[++iarg]; } else if (strncmp(argv[iarg], "-d", 2) == 0) { dictname = argv[++iarg]; } else if (strncmp(argv[iarg], "-s", 2) == 0) { membuf = strtol(argv[++iarg],NULL,10); } else if (strncmp(argv[iarg], "-n", 2) == 0) { nsplit = strtol(argv[++iarg],NULL,10); } else if (strncmp(argv[iarg], "-c", 2) == 0) { suffix=".gz"; } else if (strncmp(argv[iarg], "-?", 2) == 0) { printf("%s", usage); return 1; } else if (strncmp(argv[iarg], "-h", 2) == 0) { printf("%s", usage); return 1; } else { cout << "Unknown option " << argv[iarg] << endl; exit(1); } iarg++; } imatrix imat; fvector fvec; fvector labels; istream * ifstr; stringIndexer si; linebuf = new char[membuf]; readbuf = new char[membuf]; if (dictname.size() == 0) dictname = odname+"dict"; here = strtok(ifname, " ,"); while (here != NULL) { ifstr = open_in_buf(ifname, readbuf, membuf); numlines = 0; while (!ifstr->bad() && !ifstr->eof()) { ifstr->getline(linebuf, membuf-1); linebuf[membuf-1] = 0; if (ifstr->fail()) { ifstr->clear(); ifstr->ignore(LONG_MAX,'\n'); } if (strlen(linebuf) > 0) { jmax++; numlines++; try { parseLine(linebuf, delim1.c_str(), delim2.c_str(), delim3.c_str(), delim4.c_str(), si, labels, imat, fvec); } catch (int e) { cerr << "Continuing" << endl; } } if ((numlines % 100000) == 0) { cout<<"\r"<<numlines<<" lines processed"; cout.flush(); } if ((numlines % nsplit) == 0) { writefiles(odname, imat, fvec, labels, suffix, nfiles, membuf); } } if ((numlines % nsplit) != 0) { writefiles(odname, imat, fvec, labels, suffix, nfiles, membuf); } if (ifstr) delete ifstr; cout<<"\r"<<numlines<<" lines processed"; cout.flush(); string rname = here; if (strstr(here, ".gz") - here == strlen(here) - 3) { rname = rname.substr(0, strlen(here) - 3); } here = strtok(NULL, " ,"); } fprintf(stderr, "\nWriting Dictionary\n"); si.writeMap(dictname, suffix); } <commit_msg>fix min long<commit_after>// Read a file and parse each line according to the format file. // Output integer matrices with lookup maps in either ascii text // or matlab binary form. #include <stdlib.h> #include <stdio.h> #include <time.h> #include "utils.h" #include "gzstream.h" #define BUFSIZE 1048576 class stringIndexer { public: ivector count; unhash unh; strhash htab; int size; char * linebuf; stringIndexer() : htab(0), unh(0), count(0), size(0) { linebuf = new char[BUFSIZE]; }; stringIndexer(const stringIndexer & si); ~stringIndexer(); stringIndexer(char *); int writeMap(string fname, string suffix) { writeIntVec(count, fname + ".cnt.imat" + suffix, BUFSIZE); return writeSBVecs(unh, fname + ".sbmat" + suffix, BUFSIZE); } int checkword(char *str); }; int stringIndexer:: checkword(char * str) { int userno; char * newstr; if (htab.count(str)) { userno = htab[str]; count[userno-1]++; } else { try { newstr = new char[strlen(str)+1]; strcpy(newstr, str); userno = ++size; htab[newstr] = userno; count.push_back(1); unh.push_back(newstr); } catch (std::bad_alloc) { cerr << "stringIndexer:checkstr: allocation error" << endl; throw; } } return userno; } stringIndexer:: ~stringIndexer() { int i; for (i=0; i<unh.size(); i++) { if (unh[i]) { delete [] unh[i]; unh[i] = NULL; } } if (linebuf) { delete [] linebuf; linebuf = NULL; } } int parseLine(char * line, const char * delim1, const char * delim2, const char *delim3, const char * delim4, stringIndexer & si, fvector &labels, imatrix & imat, fvector & fvec) { char *here, *next, *fpos; int label, indx; float fval; ivector iv; here = line; next = strpbrk(here, delim1); // get the label(s) *(next++) = 0; sscanf(here, "%d", &label); here = next; labels.push_back(label); next = strpbrk(here, delim2); // get the tag *(next++) = 0; // Do nothing with the tag for now here = next; while (here != NULL) { next = strpbrk(here, delim3); // get a feature/value pair if (next) { *(next++) = 0; } // Actually parse in here fpos = strpbrk(here, delim4); // get a value, if there is one fval = 1.0; if (fpos) { sscanf(fpos+1, "%f", &fval); *fpos = 0; } indx = si.checkword(here); iv.push_back(indx); fvec.push_back(fval); here = next; } imat.push_back(iv); return 0; } void writefiles(string fname, imatrix &imat, fvector &fvec, fvector &labels, string suffix, int &ifile, int membuf) { char num[6]; sprintf(num, "%05d", ifile); writeIntVecs(imat, fname+"inds"+num+".imat"+suffix, membuf); writeFVec(fvec, fname+"vals"+num+".fmat"+suffix, membuf); writeFVec(labels, fname+"labels"+num+".fmat"+suffix, membuf); ifile++; imat.clear(); fvec.clear(); labels.clear(); } const char usage[] = "\nParser for generalized libsvm files. Arguments are\n" " -i <infile> input file[s] to read\n" " -o <outd> output files will be written to <outd><infile>.imat[.gz]\n" " -d <dictfile> dictionary will be written to <dictfile>.sbmat[.gz]\n" " and word counts will be written to <dictfile>.imat[.gz]\n" " -s N set buffer size to N.\n" " -n N split files at N lines.\n" " -c produce compressed (gzipped) output files.\n\n" ; int main(int argc, char ** argv) { int jmax, iarg=1, membuf=1048576, nsplit=100000, nfiles = 0; long long numlines; char *here, *linebuf, *readbuf; char *ifname = NULL; string odname="", dictname = "", suffix = ""; string delim1=" ", delim2="|", delim3=" ", delim4=":"; while (iarg < argc) { if (strncmp(argv[iarg], "-i", 2) == 0) { ifname = argv[++iarg]; } else if (strncmp(argv[iarg], "-o", 2) == 0) { odname = argv[++iarg]; } else if (strncmp(argv[iarg], "-d", 2) == 0) { dictname = argv[++iarg]; } else if (strncmp(argv[iarg], "-s", 2) == 0) { membuf = strtol(argv[++iarg],NULL,10); } else if (strncmp(argv[iarg], "-n", 2) == 0) { nsplit = strtol(argv[++iarg],NULL,10); } else if (strncmp(argv[iarg], "-c", 2) == 0) { suffix=".gz"; } else if (strncmp(argv[iarg], "-?", 2) == 0) { printf("%s", usage); return 1; } else if (strncmp(argv[iarg], "-h", 2) == 0) { printf("%s", usage); return 1; } else { cout << "Unknown option " << argv[iarg] << endl; exit(1); } iarg++; } imatrix imat; fvector fvec; fvector labels; istream * ifstr; stringIndexer si; linebuf = new char[membuf]; readbuf = new char[membuf]; if (dictname.size() == 0) dictname = odname+"dict"; here = strtok(ifname, " ,"); while (here != NULL) { ifstr = open_in_buf(ifname, readbuf, membuf); numlines = 0; while (!ifstr->bad() && !ifstr->eof()) { ifstr->getline(linebuf, membuf-1); linebuf[membuf-1] = 0; if (ifstr->fail()) { ifstr->clear(); ifstr->ignore(std::numeric_limits<long>::max(),'\n'); } if (strlen(linebuf) > 0) { jmax++; numlines++; try { parseLine(linebuf, delim1.c_str(), delim2.c_str(), delim3.c_str(), delim4.c_str(), si, labels, imat, fvec); } catch (int e) { cerr << "Continuing" << endl; } } if ((numlines % 100000) == 0) { cout<<"\r"<<numlines<<" lines processed"; cout.flush(); } if ((numlines % nsplit) == 0) { writefiles(odname, imat, fvec, labels, suffix, nfiles, membuf); } } if ((numlines % nsplit) != 0) { writefiles(odname, imat, fvec, labels, suffix, nfiles, membuf); } if (ifstr) delete ifstr; cout<<"\r"<<numlines<<" lines processed"; cout.flush(); string rname = here; if (strstr(here, ".gz") - here == strlen(here) - 3) { rname = rname.substr(0, strlen(here) - 3); } here = strtok(NULL, " ,"); } fprintf(stderr, "\nWriting Dictionary\n"); si.writeMap(dictname, suffix); } <|endoftext|>
<commit_before><commit_msg>coverity#1130166 Unchecked return value<commit_after><|endoftext|>
<commit_before>#ifndef ARM_SERVICE_cpp #define ARM_SERVICE_cpp #include <Arm_service.h> #include <AutoPilot.h> extern uint8_t bit_autopilot_flags; //*************************************************** // This latch is what is called in the microcontroller's // main loop. Put any required processing here //*************************************************** void Arm_service::arm_service_latch() { // process any local LCD message packets process_local_TUN_packet(); // process any external LCD message packets process_external_TUN_packet(); } //*************************************************** //*************************************************** // This routine will query the XAPI to see // if there is a local message waiting for // the Land service. If so, we need to grab it and react. void Arm_service::process_external_TUN_packet() { // see if there is a packet waiting if(m_xapi.CONNECT_external_TUN_get_type() == TUN_TYPE_EXTERNAL_ARM) { // allocate the space uint8_t TUN_packet[MED_BUFF_SZ]; // extract the packet m_xapi.CONNECT_external_TUN_get_packet(TUN_packet, MED_BUFF_SZ); // do something //lcd prints are for debugging, should be removed //m_lcd.lcd_print("*********"); //m_lcd.lcd_print(0,0,"ltest1"); //m_lcd.lcd_print(0,0,"arm packet"); Serial.print("I should be armed AutoPilot: "); bit_autopilot_flags |= ARM_FLAG; // Turns bir on in flags Serial.println(bit_autopilot_flags); // Turns Turns off Arm --->> bit_autopilot_flags &= ~ARM_FLAG; //m_lcd.lcd_print(0,0,"ltest2"); } } //*************************************************** //*************************************************** // This routine will query the XAPI to see // if there is a local message waiting for // the Land service. If so, we need to grab it and do something. void Arm_service::process_local_TUN_packet() { // see if there is a packet waiting if(m_xapi.CONNECT_local_TUN_get_type() == TUN_TYPE_LOCAL_ARM) { // allocate the space uint8_t TUN_packet[MED_BUFF_SZ]; // extract the packet m_xapi.CONNECT_local_TUN_get_packet(TUN_packet, MED_BUFF_SZ); // do something } } //*************************************************** //*************************************************** // Resets the TUN packet storage void Arm_service::reset_TUN_storage() { // obsolete } //*************************************************** //*************************************************** Arm_service::Arm_service(Xapi& _xapi, LCD_service& _lcd): m_xapi(_xapi), m_lcd(_lcd) { reset_TUN_storage(); } #endif<commit_msg>Updated Arm Service<commit_after>#ifndef ARM_SERVICE_cpp #define ARM_SERVICE_cpp #include <Arm_service.h> //#include <AutoPilot.h> extern uint8_t bit_autopilot_flags; //*************************************************** // This latch is what is called in the microcontroller's // main loop. Put any required processing here //*************************************************** void Arm_service::arm_service_latch() { // process any local LCD message packets process_local_TUN_packet(); // process any external LCD message packets process_external_TUN_packet(); } //*************************************************** //*************************************************** // This routine will query the XAPI to see // if there is a local message waiting for // the Land service. If so, we need to grab it and react. void Arm_service::process_external_TUN_packet() { // see if there is a packet waiting if(m_xapi.CONNECT_external_TUN_get_type() == TUN_TYPE_EXTERNAL_ARM) { // allocate the space uint8_t TUN_packet[MED_BUFF_SZ]; uint8_t payload_buff[SMALL_BUFF_SZ]; uint8_t payload_buff_sz = 0; // extract the packet m_xapi.CONNECT_external_TUN_get_packet(TUN_packet, MED_BUFF_SZ); //extract payload payload_buff_sz = m_util.get_TUN_payload(TUN_packet, payload_buff, SMALL_BUFF_SZ); // do something //lcd prints are for debugging, should be removed //m_lcd.lcd_print("*********"); //m_lcd.lcd_print(0,0,"ltest1"); m_lcd.lcd_print(0,0,"arm packet"); if(m_util.hex_to_int(0, 1, 2, payload_buff) == 1){ //Serial.print("I should be armed AutoPilot: "); m_lcd.lcd_print(0,0,"armed!"); //bit_autopilot_flags |= ARM_FLAG; // Turns bir on in flags //Serial.println(bit_autopilot_flags); } else{ // Turns Turns off Arm --->> bit_autopilot_flags &= ~ARM_FLAG; m_lcd.lcd_print(0,0,"disarmed!"); //bit_autopilot_flags &= ~ARM_FLAG; } //m_lcd.lcd_print(0,0,"ltest2"); } } //*************************************************** //*************************************************** // This routine will query the XAPI to see // if there is a local message waiting for // the Land service. If so, we need to grab it and do something. void Arm_service::process_local_TUN_packet() { // see if there is a packet waiting if(m_xapi.CONNECT_local_TUN_get_type() == TUN_TYPE_LOCAL_ARM) { // allocate the space uint8_t TUN_packet[MED_BUFF_SZ]; // extract the packet m_xapi.CONNECT_local_TUN_get_packet(TUN_packet, MED_BUFF_SZ); // do something } } //*************************************************** //*************************************************** // Resets the TUN packet storage void Arm_service::reset_TUN_storage() { // obsolete } //*************************************************** //*************************************************** Arm_service::Arm_service(Xapi& _xapi, LCD_service& _lcd): m_xapi(_xapi), m_lcd(_lcd) { reset_TUN_storage(); } #endif<|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkTkAppInit.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /* * tkAppInit.c -- * * Provides a default version of the Tcl_AppInit procedure for * use in wish and similar Tk-based applications. * * Copyright (c) 1993 The Regents of the University of California. * Copyright (c) 1994 Sun Microsystems, Inc. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. */ #ifdef VTK_COMPILED_USING_MPI # include <mpi.h> # include "vtkMPIController.h" #endif // VTK_COMPILED_USING_MPI #include "vtkSystemIncludes.h" #include "vtkToolkits.h" #include "Wrapping/Tcl/vtkTkAppInitConfigure.h" #if defined(CMAKE_INTDIR) # define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD "/" CMAKE_INTDIR #else # define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD #endif #ifdef VTK_USE_RENDERING # include "tk.h" #else # include "tcl.h" #endif /* * Make sure all the kits register their classes with vtkInstantiator. */ #include "vtkCommonInstantiator.h" #include "vtkFilteringInstantiator.h" #include "vtkIOInstantiator.h" #include "vtkImagingInstantiator.h" #include "vtkGraphicsInstantiator.h" #ifdef VTK_USE_RENDERING #include "vtkRenderingInstantiator.h" #endif #ifdef VTK_USE_PATENTED #include "vtkPatentedInstantiator.h" #endif #ifdef VTK_USE_HYBRID #include "vtkHybridInstantiator.h" #endif #ifdef VTK_USE_PARALLEL #include "vtkParallelInstantiator.h" #endif static void vtkTkAppInitEnableMSVCDebugHook(); /* *---------------------------------------------------------------------- * * main -- * * This is the main program for the application. * * Results: * None: Tk_Main never returns here, so this procedure never * returns either. * * Side effects: * Whatever the application does. * *---------------------------------------------------------------------- */ #ifdef VTK_COMPILED_USING_MPI class vtkMPICleanup { public: vtkMPICleanup() { this->Controller = 0; } void Initialize(int *argc, char ***argv) { MPI_Init(argc, argv); this->Controller = vtkMPIController::New(); this->Controller->Initialize(argc, argv, 1); vtkMultiProcessController::SetGlobalController(this->Controller); } ~vtkMPICleanup() { if ( this->Controller ) { this->Controller->Finalize(); this->Controller->Delete(); } } private: vtkMPIController *Controller; }; static vtkMPICleanup VTKMPICleanup; #endif // VTK_COMPILED_USING_MPI int main(int argc, char **argv) { ios::sync_with_stdio(); vtkTkAppInitEnableMSVCDebugHook(); #ifdef VTK_COMPILED_USING_MPI VTKMPICleanup.Initialize(&argc, &argv); #endif // VTK_COMPILED_USING_MPI #ifdef VTK_USE_RENDERING Tk_Main(argc, argv, Tcl_AppInit); #else Tcl_Main(argc, argv, Tcl_AppInit); #endif return 0; /* Needed only to prevent compiler warning. */ } /* *---------------------------------------------------------------------- * * Tcl_AppInit -- * * This procedure performs application-specific initialization. * Most applications, especially those that incorporate additional * packages, will have their own version of this procedure. * * Results: * Returns a standard Tcl completion code, and leaves an error * message in interp->result if an error occurs. * * Side effects: * Depends on the startup script. * *---------------------------------------------------------------------- */ extern "C" int Vtkcommontcl_Init(Tcl_Interp *interp); extern "C" int Vtkfilteringtcl_Init(Tcl_Interp *interp); extern "C" int Vtkimagingtcl_Init(Tcl_Interp *interp); extern "C" int Vtkgraphicstcl_Init(Tcl_Interp *interp); extern "C" int Vtkiotcl_Init(Tcl_Interp *interp); #ifdef VTK_USE_RENDERING extern "C" int Vtkrenderingtcl_Init(Tcl_Interp *interp); #ifdef VTK_DISABLE_TK_INIT extern "C" int Vtktkrenderwidget_Init(Tcl_Interp *interp); extern "C" int Vtktkimageviewerwidget_Init(Tcl_Interp *interp); #endif #endif #ifdef VTK_USE_PATENTED extern "C" int Vtkpatentedtcl_Init(Tcl_Interp *interp); #endif #ifdef VTK_USE_HYBRID extern "C" int Vtkhybridtcl_Init(Tcl_Interp *interp); #endif #ifdef VTK_USE_PARALLEL extern "C" int Vtkparalleltcl_Init(Tcl_Interp *interp); #endif void help() { } int Tcl_AppInit(Tcl_Interp *interp) { if (Tcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #ifdef VTK_USE_RENDERING if (Tk_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif /* init the core vtk stuff */ if (Vtkcommontcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkfilteringtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkimagingtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkgraphicstcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkiotcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #ifdef VTK_USE_RENDERING if (Vtkrenderingtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #ifdef VTK_DISABLE_TK_INIT if (Vtktkrenderwidget_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtktkimageviewerwidget_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif #endif #ifdef VTK_USE_PATENTED if (Vtkpatentedtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif #ifdef VTK_USE_HYBRID if (Vtkhybridtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif #ifdef VTK_USE_PARALLEL if (Vtkparalleltcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif /* * Append path to VTK packages to auto_path */ static char script[] = "foreach dir [list {" VTK_TCL_PACKAGE_DIR "} {" VTK_TCL_INSTALL_DIR "}" " [file join [file dirname [file dirname [info nameofexecutable]]] Wrapping Tcl]" " [file join [file dirname [file dirname [info nameofexecutable]]] lib vtk tcl]" " ] {\n" " if {[file isdirectory $dir]} {\n" " lappend auto_path $dir\n" " }\n" "}\n" "rename package package.orig\n" "proc package {args} {\n" " if {[catch {set package_res [eval package.orig $args]} catch_res]} {\n" " global errorInfo env\n" " if {[lindex $args 0] == \"require\"} {\n" " set expecting {can\'t find package vtk}\n" " if {![string compare -length [string length $expecting] $catch_res $expecting]} {\n" " set msg {The Tcl interpreter was probably not able to find the" " VTK packages. Please check that your TCLLIBPATH environment variable" " includes the path to your VTK Tcl directory. You might find it under" " your VTK binary directory in Wrapping/Tcl, or under your" " site-specific {CMAKE_INSTALL_PREFIX}/lib/vtk/tcl directory.}\n" " if {[info exists env(TCLLIBPATH)]} {\n" " append msg \" The TCLLIBPATH current value is: $env(TCLLIBPATH).\"\n" " }\n" " set errorInfo \"$msg The TCLLIBPATH variable is a set of" " space separated paths (hence, path containing spaces should be" " surrounded by quotes first). Windows users should use forward" " (Unix-style) slashes \'/\' instead of the usual backward slashes. " " More informations can be found in the Wrapping/Tcl/README source" " file (also available online at" " http://www.vtk.org/cgi-bin/cvsweb.cgi/~checkout~/VTK/Wrapping/Tcl/README).\n" "$errorInfo\"\n" " }\n" " }\n" " error $catch_res $errorInfo\n" " }\n" " return $package_res\n" "}\n"; Tcl_Eval(interp, script); /* * Specify a user-specific startup file to invoke if the application * is run interactively. Typically the startup file is "~/.apprc" * where "app" is the name of the application. If this line is deleted * then no user-specific startup file will be run under any conditions. */ Tcl_SetVar(interp, (char *) "tcl_rcFileName", (char *) "~/.vtkrc", TCL_GLOBAL_ONLY); return TCL_OK; } // For a DEBUG build on MSVC, add a hook to prevent error dialogs when // being run from DART. #if defined(_MSC_VER) && defined(_DEBUG) # include <crtdbg.h> static int vtkTkAppInitDebugReport(int, char* message, int*) { fprintf(stderr, message); exit(1); return 0; } void vtkTkAppInitEnableMSVCDebugHook() { if(getenv("DART_TEST_FROM_DART")) { _CrtSetReportHook(vtkTkAppInitDebugReport); } } #else void vtkTkAppInitEnableMSVCDebugHook() { } #endif <commit_msg>better handling of cocoa and tk for MacOSX<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkTkAppInit.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /* * tkAppInit.c -- * * Provides a default version of the Tcl_AppInit procedure for * use in wish and similar Tk-based applications. * * Copyright (c) 1993 The Regents of the University of California. * Copyright (c) 1994 Sun Microsystems, Inc. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. */ #ifdef VTK_COMPILED_USING_MPI # include <mpi.h> # include "vtkMPIController.h" #endif // VTK_COMPILED_USING_MPI #include "vtkSystemIncludes.h" #include "vtkToolkits.h" #include "Wrapping/Tcl/vtkTkAppInitConfigure.h" #if defined(CMAKE_INTDIR) # define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD "/" CMAKE_INTDIR #else # define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD #endif #if defined(VTK_USE_RENDERING) && !defined(VTK_USE_COCOA) # include "tk.h" #else # include "tcl.h" #endif /* * Make sure all the kits register their classes with vtkInstantiator. */ #include "vtkCommonInstantiator.h" #include "vtkFilteringInstantiator.h" #include "vtkIOInstantiator.h" #include "vtkImagingInstantiator.h" #include "vtkGraphicsInstantiator.h" #ifdef VTK_USE_RENDERING #include "vtkRenderingInstantiator.h" #endif #ifdef VTK_USE_PATENTED #include "vtkPatentedInstantiator.h" #endif #ifdef VTK_USE_HYBRID #include "vtkHybridInstantiator.h" #endif #ifdef VTK_USE_PARALLEL #include "vtkParallelInstantiator.h" #endif static void vtkTkAppInitEnableMSVCDebugHook(); /* *---------------------------------------------------------------------- * * main -- * * This is the main program for the application. * * Results: * None: Tk_Main never returns here, so this procedure never * returns either. * * Side effects: * Whatever the application does. * *---------------------------------------------------------------------- */ #ifdef VTK_COMPILED_USING_MPI class vtkMPICleanup { public: vtkMPICleanup() { this->Controller = 0; } void Initialize(int *argc, char ***argv) { MPI_Init(argc, argv); this->Controller = vtkMPIController::New(); this->Controller->Initialize(argc, argv, 1); vtkMultiProcessController::SetGlobalController(this->Controller); } ~vtkMPICleanup() { if ( this->Controller ) { this->Controller->Finalize(); this->Controller->Delete(); } } private: vtkMPIController *Controller; }; static vtkMPICleanup VTKMPICleanup; #endif // VTK_COMPILED_USING_MPI int main(int argc, char **argv) { ios::sync_with_stdio(); vtkTkAppInitEnableMSVCDebugHook(); #ifdef VTK_COMPILED_USING_MPI VTKMPICleanup.Initialize(&argc, &argv); #endif // VTK_COMPILED_USING_MPI #if defined(VTK_USE_RENDERING) && !defined(VTK_USE_COCOA) Tk_Main(argc, argv, Tcl_AppInit); #else Tcl_Main(argc, argv, Tcl_AppInit); #endif return 0; /* Needed only to prevent compiler warning. */ } /* *---------------------------------------------------------------------- * * Tcl_AppInit -- * * This procedure performs application-specific initialization. * Most applications, especially those that incorporate additional * packages, will have their own version of this procedure. * * Results: * Returns a standard Tcl completion code, and leaves an error * message in interp->result if an error occurs. * * Side effects: * Depends on the startup script. * *---------------------------------------------------------------------- */ extern "C" int Vtkcommontcl_Init(Tcl_Interp *interp); extern "C" int Vtkfilteringtcl_Init(Tcl_Interp *interp); extern "C" int Vtkimagingtcl_Init(Tcl_Interp *interp); extern "C" int Vtkgraphicstcl_Init(Tcl_Interp *interp); extern "C" int Vtkiotcl_Init(Tcl_Interp *interp); #ifdef VTK_USE_RENDERING extern "C" int Vtkrenderingtcl_Init(Tcl_Interp *interp); #if defined(VTK_DISABLE_TK_INIT) && !defined(VTK_USE_COCOA) extern "C" int Vtktkrenderwidget_Init(Tcl_Interp *interp); extern "C" int Vtktkimageviewerwidget_Init(Tcl_Interp *interp); #endif #endif #ifdef VTK_USE_PATENTED extern "C" int Vtkpatentedtcl_Init(Tcl_Interp *interp); #endif #ifdef VTK_USE_HYBRID extern "C" int Vtkhybridtcl_Init(Tcl_Interp *interp); #endif #ifdef VTK_USE_PARALLEL extern "C" int Vtkparalleltcl_Init(Tcl_Interp *interp); #endif void help() { } int Tcl_AppInit(Tcl_Interp *interp) { if (Tcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #if defined(VTK_USE_RENDERING) && !defined(VTK_USE_COCOA) if (Tk_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif /* init the core vtk stuff */ if (Vtkcommontcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkfilteringtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkimagingtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkgraphicstcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkiotcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #ifdef VTK_USE_RENDERING if (Vtkrenderingtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #if defined(VTK_DISABLE_TK_INIT) && !defined(VTK_USE_COCOA) // Need to init here because rendering did not when this option is on if (Vtktkrenderwidget_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtktkimageviewerwidget_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif #endif #ifdef VTK_USE_PATENTED if (Vtkpatentedtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif #ifdef VTK_USE_HYBRID if (Vtkhybridtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif #ifdef VTK_USE_PARALLEL if (Vtkparalleltcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif /* * Append path to VTK packages to auto_path */ static char script[] = "foreach dir [list {" VTK_TCL_PACKAGE_DIR "} {" VTK_TCL_INSTALL_DIR "}" " [file join [file dirname [file dirname [info nameofexecutable]]] Wrapping Tcl]" " [file join [file dirname [file dirname [info nameofexecutable]]] lib vtk tcl]" " ] {\n" " if {[file isdirectory $dir]} {\n" " lappend auto_path $dir\n" " }\n" "}\n" "rename package package.orig\n" "proc package {args} {\n" " if {[catch {set package_res [eval package.orig $args]} catch_res]} {\n" " global errorInfo env\n" " if {[lindex $args 0] == \"require\"} {\n" " set expecting {can\'t find package vtk}\n" " if {![string compare -length [string length $expecting] $catch_res $expecting]} {\n" " set msg {The Tcl interpreter was probably not able to find the" " VTK packages. Please check that your TCLLIBPATH environment variable" " includes the path to your VTK Tcl directory. You might find it under" " your VTK binary directory in Wrapping/Tcl, or under your" " site-specific {CMAKE_INSTALL_PREFIX}/lib/vtk/tcl directory.}\n" " if {[info exists env(TCLLIBPATH)]} {\n" " append msg \" The TCLLIBPATH current value is: $env(TCLLIBPATH).\"\n" " }\n" " set errorInfo \"$msg The TCLLIBPATH variable is a set of" " space separated paths (hence, path containing spaces should be" " surrounded by quotes first). Windows users should use forward" " (Unix-style) slashes \'/\' instead of the usual backward slashes. " " More informations can be found in the Wrapping/Tcl/README source" " file (also available online at" " http://www.vtk.org/cgi-bin/cvsweb.cgi/~checkout~/VTK/Wrapping/Tcl/README).\n" "$errorInfo\"\n" " }\n" " }\n" " error $catch_res $errorInfo\n" " }\n" " return $package_res\n" "}\n"; Tcl_Eval(interp, script); /* * Specify a user-specific startup file to invoke if the application * is run interactively. Typically the startup file is "~/.apprc" * where "app" is the name of the application. If this line is deleted * then no user-specific startup file will be run under any conditions. */ Tcl_SetVar(interp, (char *) "tcl_rcFileName", (char *) "~/.vtkrc", TCL_GLOBAL_ONLY); return TCL_OK; } // For a DEBUG build on MSVC, add a hook to prevent error dialogs when // being run from DART. #if defined(_MSC_VER) && defined(_DEBUG) # include <crtdbg.h> static int vtkTkAppInitDebugReport(int, char* message, int*) { fprintf(stderr, message); exit(1); return 0; } void vtkTkAppInitEnableMSVCDebugHook() { if(getenv("DART_TEST_FROM_DART")) { _CrtSetReportHook(vtkTkAppInitDebugReport); } } #else void vtkTkAppInitEnableMSVCDebugHook() { } #endif <|endoftext|>
<commit_before>#ifndef SRC_NODES_BASE_NODE_HPP_ #define SRC_NODES_BASE_NODE_HPP_ #include <flexcore/extended/graph/graph.hpp> #include <flexcore/scheduler/parallelregion.hpp> #include <adobe/forest.hpp> #include <cassert> #include <string> #include <memory> #include <flexcore/ports.hpp> namespace fc { /** * \brief base class for nodes contained in forest * * Nodes are neither copy_constructyble nor copy_assignable. * * * \invariant region_ != null_ptr * \invariant self_ is always valid */ class tree_base_node { public: typedef adobe::forest<std::unique_ptr<tree_base_node>> forest_t; template<class data_t> using event_source = ::fc::event_source<data_t>; template<class data_t> using event_sink = ::fc::event_sink<data_t>; template<class data_t> using state_source = ::fc::state_source<data_t>; template<class data_t> using state_sink = ::fc::state_sink<data_t>; tree_base_node(forest_t* f, std::shared_ptr<parallel_region> r, std::string name); virtual ~tree_base_node() = default; const std::shared_ptr<parallel_region>& region() const { return region_; } std::string name() const; graph::graph_node_properties graph_info() const; graph::connection_graph& get_graph() const; protected: forest_t* forest_; private: /* Information about which region the node belongs to */ std::shared_ptr<parallel_region> region_; /* Information for abstract graph */ //stores the metainformation of the node used by the abstract graph graph::graph_node_properties graph_info_; }; /** * \brief base class for nodes which own other nodes, aka nested nodes. * * \invariant forest_ != nullptr * * Nodes of this type may have children nodes. * * Use make_child/make_child_named to create a node already inserted into * the ownership tree. * * Node creation examples: * \code{cpp} * owning_base_node root; * // simple creation * root.make_child<node>(); * root.make_child<node_tmpl<int>>(); * root.make_child_named<node_tmpl<int>>("name"); * \endcode */ class owning_base_node : public tree_base_node { public: owning_base_node(forest_t* f, std::shared_ptr<parallel_region> r, std::string name) : tree_base_node(f, r, name) { } tree_base_node* new_node(std::string name) { return add_child(std::make_unique<tree_base_node>(forest_, region(), name)); } tree_base_node* new_node(std::shared_ptr<parallel_region> r, std::string name) { return add_child(std::make_unique<tree_base_node>(forest_, r, name)); } /** * \brief creates child node of type node_t with constructor arguments args. * * Inserts new child into tree. * Child node is attached to region of parent node. * * \tparam node_t type of node to be created * \param args constructor arguments passed to node_t * \return pointer to child node * \post nr of children > 0 */ template<class node_t, class ... args_t> node_t* make_child(args_t&&... args) { return static_cast<node_t*>(add_child(std::make_unique<node_t>( std::forward<args_t>(args)..., forest_, region()))); } /** * \brief Overload of make_child with region. * * @param r Child is attached to this region * @param args onstructor arguments passed to node_t * @return pointer to child node */ template<class node_t, class ... args_t> node_t* make_child(std::shared_ptr<parallel_region> r, args_t&&... args) { return static_cast<node_t*>(add_child(std::make_unique<node_t>( std::forward<args_t>(args)..., forest_, r))); } /** * \brief Creates a new child node of type node_t from args * if node_t inherits from owning_base_node * * Sets name of child to n and inserts child into tree. * Sets forest of of child to forest of parent. * \return pointer to child node * \post nr of children > 0 */ template<class node_t, class ... args_t> node_t* make_child_named(std::string name, args_t&&... args) { return static_cast<node_t*>(add_child(std::make_unique<node_t>( std::forward<args_t>(args)..., forest_, region(), name))); } template<class node_t, class ... args_t> node_t* make_child_named(std::shared_ptr<parallel_region> r, std::string name, args_t&&... args) { return static_cast<node_t*>(add_child(std::make_unique<node_t>( std::forward<args_t>(args)..., forest_, std::move(r), std::move(name)))); } protected: forest_t::iterator self() const; // stores the access to the forest this node is contained in. private: /** * Takes ownership of child node and inserts into tree. * \return pointer to child node * \pre child != nullptr */ tree_base_node* add_child(std::unique_ptr<tree_base_node> child); }; class root_node : public owning_base_node { public: root_node(forest_t* f, std::shared_ptr<parallel_region> r, std::string n); graph::connection_graph& graph() { return graph_; } private: graph::connection_graph graph_; }; /** * \brief Root node for building node trees. * * Has ownership of the forest and thus serves * as the root node for all other nodes in the forest. */ class forest_owner { public: typedef adobe::forest<std::unique_ptr<tree_base_node>> forest_t; forest_owner(std::string n, std::shared_ptr<parallel_region> r); owning_base_node& nodes() { return *tree_root; } graph::connection_graph& get_graph() { return tree_root->graph(); } private: std::unique_ptr<forest_t> forest_; /// non_owning access to first node in tree, ownership is in forest. root_node* tree_root; }; /** * \brief Erases node and recursively erases all children. * * \param forest, forest to delete node from. * \position iterator of forest pointing to node. * \pre position must be in forest. * \returns todo * * invalidates iterators pointing to deleted node. */ inline tree_base_node::forest_t::iterator erase_with_subtree( tree_base_node::forest_t& forest, tree_base_node::forest_t::iterator position) { return forest.erase( adobe::child_begin(position).base(), adobe::child_end(position).base()); } /** * \brief Returns the full name of a node. * * The full name consists of the chained name of the nodes parent, grandparent etc. * and the name of the node itself. * The names are separated by a separation token. */ std::string full_name(tree_base_node::forest_t& forest, const tree_base_node* node); } // namespace fc #endif /* SRC_NODES_BASE_NODE_HPP_ */ <commit_msg>nodes: Add node interface<commit_after>#ifndef SRC_NODES_BASE_NODE_HPP_ #define SRC_NODES_BASE_NODE_HPP_ #include <flexcore/extended/graph/graph.hpp> #include <flexcore/scheduler/parallelregion.hpp> #include <adobe/forest.hpp> #include <cassert> #include <string> #include <memory> #include <flexcore/ports.hpp> namespace fc { /** * \brief Interface for all nodes (whether part of forest+graph or only graph) */ class node { public: virtual ~node() = default; virtual graph::graph_node_properties graph_info() const = 0; }; class graph_node : public node { public: graph_node(graph::connection_graph& graph, const std::string& name) : graph_node(graph, {}, name) { } graph_node(graph::connection_graph& graph, std::shared_ptr<parallel_region> r, const std::string& name) : region_(std::move(r)), props_(name), graph_(&graph) { assert(graph_); } graph::graph_node_properties graph_info() const { return props_; } private: std::shared_ptr<parallel_region> region_; graph::graph_node_properties props_; graph::connection_graph* graph_; }; /** * \brief base class for nodes contained in forest * * Nodes are neither copy_constructyble nor copy_assignable. * * * \invariant region_ != null_ptr */ class tree_base_node : public node { public: typedef adobe::forest<std::unique_ptr<tree_base_node>> forest_t; template<class data_t> using event_source = ::fc::event_source<data_t>; template<class data_t> using event_sink = ::fc::event_sink<data_t>; template<class data_t> using state_source = ::fc::state_source<data_t>; template<class data_t> using state_sink = ::fc::state_sink<data_t>; tree_base_node(forest_t* f, std::shared_ptr<parallel_region> r, std::string name); const std::shared_ptr<parallel_region>& region() const { return region_; } std::string name() const; graph::graph_node_properties graph_info() const override; graph::connection_graph& get_graph() const; protected: forest_t* forest_; private: /* Information about which region the node belongs to */ std::shared_ptr<parallel_region> region_; /* Information for abstract graph */ //stores the metainformation of the node used by the abstract graph graph::graph_node_properties graph_info_; }; /** * \brief base class for nodes which own other nodes, aka nested nodes. * * \invariant forest_ != nullptr * * Nodes of this type may have children nodes. * * Use make_child/make_child_named to create a node already inserted into * the ownership tree. * * Node creation examples: * \code{cpp} * owning_base_node root; * // simple creation * root.make_child<node>(); * root.make_child<node_tmpl<int>>(); * root.make_child_named<node_tmpl<int>>("name"); * \endcode */ class owning_base_node : public tree_base_node { public: owning_base_node(forest_t* f, std::shared_ptr<parallel_region> r, std::string name) : tree_base_node(f, r, name) { } tree_base_node* new_node(std::string name) { return add_child(std::make_unique<tree_base_node>(forest_, region(), name)); } tree_base_node* new_node(std::shared_ptr<parallel_region> r, std::string name) { return add_child(std::make_unique<tree_base_node>(forest_, r, name)); } /** * \brief creates child node of type node_t with constructor arguments args. * * Inserts new child into tree. * Child node is attached to region of parent node. * * \tparam node_t type of node to be created * \param args constructor arguments passed to node_t * \return pointer to child node * \post nr of children > 0 */ template<class node_t, class ... args_t> node_t* make_child(args_t&&... args) { return static_cast<node_t*>(add_child(std::make_unique<node_t>( std::forward<args_t>(args)..., forest_, region()))); } /** * \brief Overload of make_child with region. * * @param r Child is attached to this region * @param args onstructor arguments passed to node_t * @return pointer to child node */ template<class node_t, class ... args_t> node_t* make_child(std::shared_ptr<parallel_region> r, args_t&&... args) { return static_cast<node_t*>(add_child(std::make_unique<node_t>( std::forward<args_t>(args)..., forest_, r))); } /** * \brief Creates a new child node of type node_t from args * if node_t inherits from owning_base_node * * Sets name of child to n and inserts child into tree. * Sets forest of of child to forest of parent. * \return pointer to child node * \post nr of children > 0 */ template<class node_t, class ... args_t> node_t* make_child_named(std::string name, args_t&&... args) { return static_cast<node_t*>(add_child(std::make_unique<node_t>( std::forward<args_t>(args)..., forest_, region(), name))); } template<class node_t, class ... args_t> node_t* make_child_named(std::shared_ptr<parallel_region> r, std::string name, args_t&&... args) { return static_cast<node_t*>(add_child(std::make_unique<node_t>( std::forward<args_t>(args)..., forest_, std::move(r), std::move(name)))); } protected: forest_t::iterator self() const; // stores the access to the forest this node is contained in. private: /** * Takes ownership of child node and inserts into tree. * \return pointer to child node * \pre child != nullptr */ tree_base_node* add_child(std::unique_ptr<tree_base_node> child); }; class root_node : public owning_base_node { public: root_node(forest_t* f, std::shared_ptr<parallel_region> r, std::string n); graph::connection_graph& graph() { return graph_; } private: graph::connection_graph graph_; }; /** * \brief Root node for building node trees. * * Has ownership of the forest and thus serves * as the root node for all other nodes in the forest. */ class forest_owner { public: typedef adobe::forest<std::unique_ptr<tree_base_node>> forest_t; forest_owner(std::string n, std::shared_ptr<parallel_region> r); owning_base_node& nodes() { return *tree_root; } graph::connection_graph& get_graph() { return tree_root->graph(); } private: std::unique_ptr<forest_t> forest_; /// non_owning access to first node in tree, ownership is in forest. root_node* tree_root; }; /** * \brief Erases node and recursively erases all children. * * \param forest, forest to delete node from. * \position iterator of forest pointing to node. * \pre position must be in forest. * \returns todo * * invalidates iterators pointing to deleted node. */ inline tree_base_node::forest_t::iterator erase_with_subtree( tree_base_node::forest_t& forest, tree_base_node::forest_t::iterator position) { return forest.erase( adobe::child_begin(position).base(), adobe::child_end(position).base()); } /** * \brief Returns the full name of a node. * * The full name consists of the chained name of the nodes parent, grandparent etc. * and the name of the node itself. * The names are separated by a separation token. */ std::string full_name(tree_base_node::forest_t& forest, const tree_base_node* node); } // namespace fc #endif /* SRC_NODES_BASE_NODE_HPP_ */ <|endoftext|>
<commit_before><commit_msg>add more info to trace log<commit_after><|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_xmloff.hxx" #include "XMLEventImportHelper.hxx" #include <tools/debug.hxx> #include <xmloff/xmlimp.hxx> #include <xmloff/nmspmap.hxx> #include "xmlnmspe.hxx" #include "xmlerror.hxx" using ::rtl::OUString; using ::com::sun::star::xml::sax::XAttributeList; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; XMLEventImportHelper::XMLEventImportHelper() : aFactoryMap(), pEventNameMap(new NameMap()), aEventNameMapList() { } XMLEventImportHelper::~XMLEventImportHelper() { // delete factories FactoryMap::iterator aEnd = aFactoryMap.end(); for(FactoryMap::iterator aIter = aFactoryMap.begin(); aIter != aEnd; aIter++ ) { delete aIter->second; } aFactoryMap.clear(); // delete name map delete pEventNameMap; } void XMLEventImportHelper::RegisterFactory( const OUString& rLanguage, XMLEventContextFactory* pFactory ) { DBG_ASSERT(pFactory != NULL, "I need a factory."); if (NULL != pFactory) { aFactoryMap[rLanguage] = pFactory; } } void XMLEventImportHelper::AddTranslationTable( const XMLEventNameTranslation* pTransTable ) { if (NULL != pTransTable) { // put translation table into map for(const XMLEventNameTranslation* pTrans = pTransTable; pTrans->sAPIName != NULL; pTrans++) { XMLEventName aName( pTrans->nPrefix, pTrans->sXMLName ); // check for conflicting entries DBG_ASSERT(pEventNameMap->find(aName) == pEventNameMap->end(), "conflicting event translations"); // assign new translation (*pEventNameMap)[aName] = OUString::createFromAscii(pTrans->sAPIName); } } // else? ignore! } void XMLEventImportHelper::PushTranslationTable() { // save old map and install new one aEventNameMapList.push_back(pEventNameMap); pEventNameMap = new NameMap(); } void XMLEventImportHelper::PopTranslationTable() { DBG_ASSERT(aEventNameMapList.size() > 0, "no translation tables left to pop"); if ( !aEventNameMapList.empty() ) { // delete current and install old map delete pEventNameMap; pEventNameMap = aEventNameMapList.back(); aEventNameMapList.pop_back(); } } SvXMLImportContext* XMLEventImportHelper::CreateContext( SvXMLImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList, XMLEventsImportContext* rEvents, const OUString& rXmlEventName, const OUString& rLanguage) { SvXMLImportContext* pContext = NULL; // translate event name form xml to api OUString sMacroName; sal_uInt16 nMacroPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rXmlEventName, &sMacroName ); XMLEventName aEventName( nMacroPrefix, sMacroName ); NameMap::iterator aNameIter = pEventNameMap->find(aEventName); if (aNameIter != pEventNameMap->end()) { OUString aScriptLanguage; sal_uInt16 nScriptPrefix = rImport.GetNamespaceMap(). GetKeyByAttrName( rLanguage, &aScriptLanguage ); if( XML_NAMESPACE_OOO != nScriptPrefix ) aScriptLanguage = rLanguage ; // check for factory FactoryMap::iterator aFactoryIterator = aFactoryMap.find(aScriptLanguage); if (aFactoryIterator != aFactoryMap.end()) { // delegate to factory pContext = aFactoryIterator->second->CreateContext( rImport, nPrefix, rLocalName, xAttrList, rEvents, aNameIter->second, aScriptLanguage); } } // default context (if no context was created above) if( NULL == pContext ) { pContext = new SvXMLImportContext(rImport, nPrefix, rLocalName); Sequence<OUString> aMsgParams(2); aMsgParams[0] = rXmlEventName; aMsgParams[1] = rLanguage; rImport.SetError(XMLERROR_FLAG_ERROR | XMLERROR_ILLEGAL_EVENT, aMsgParams); } return pContext; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>cppcheck: prefer prefix variant<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_xmloff.hxx" #include "XMLEventImportHelper.hxx" #include <tools/debug.hxx> #include <xmloff/xmlimp.hxx> #include <xmloff/nmspmap.hxx> #include "xmlnmspe.hxx" #include "xmlerror.hxx" using ::rtl::OUString; using ::com::sun::star::xml::sax::XAttributeList; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; XMLEventImportHelper::XMLEventImportHelper() : aFactoryMap(), pEventNameMap(new NameMap()), aEventNameMapList() { } XMLEventImportHelper::~XMLEventImportHelper() { // delete factories FactoryMap::iterator aEnd = aFactoryMap.end(); for(FactoryMap::iterator aIter = aFactoryMap.begin(); aIter != aEnd; ++aIter) { delete aIter->second; } aFactoryMap.clear(); // delete name map delete pEventNameMap; } void XMLEventImportHelper::RegisterFactory( const OUString& rLanguage, XMLEventContextFactory* pFactory ) { DBG_ASSERT(pFactory != NULL, "I need a factory."); if (NULL != pFactory) { aFactoryMap[rLanguage] = pFactory; } } void XMLEventImportHelper::AddTranslationTable( const XMLEventNameTranslation* pTransTable ) { if (NULL != pTransTable) { // put translation table into map for(const XMLEventNameTranslation* pTrans = pTransTable; pTrans->sAPIName != NULL; pTrans++) { XMLEventName aName( pTrans->nPrefix, pTrans->sXMLName ); // check for conflicting entries DBG_ASSERT(pEventNameMap->find(aName) == pEventNameMap->end(), "conflicting event translations"); // assign new translation (*pEventNameMap)[aName] = OUString::createFromAscii(pTrans->sAPIName); } } // else? ignore! } void XMLEventImportHelper::PushTranslationTable() { // save old map and install new one aEventNameMapList.push_back(pEventNameMap); pEventNameMap = new NameMap(); } void XMLEventImportHelper::PopTranslationTable() { DBG_ASSERT(aEventNameMapList.size() > 0, "no translation tables left to pop"); if ( !aEventNameMapList.empty() ) { // delete current and install old map delete pEventNameMap; pEventNameMap = aEventNameMapList.back(); aEventNameMapList.pop_back(); } } SvXMLImportContext* XMLEventImportHelper::CreateContext( SvXMLImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList, XMLEventsImportContext* rEvents, const OUString& rXmlEventName, const OUString& rLanguage) { SvXMLImportContext* pContext = NULL; // translate event name form xml to api OUString sMacroName; sal_uInt16 nMacroPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rXmlEventName, &sMacroName ); XMLEventName aEventName( nMacroPrefix, sMacroName ); NameMap::iterator aNameIter = pEventNameMap->find(aEventName); if (aNameIter != pEventNameMap->end()) { OUString aScriptLanguage; sal_uInt16 nScriptPrefix = rImport.GetNamespaceMap(). GetKeyByAttrName( rLanguage, &aScriptLanguage ); if( XML_NAMESPACE_OOO != nScriptPrefix ) aScriptLanguage = rLanguage ; // check for factory FactoryMap::iterator aFactoryIterator = aFactoryMap.find(aScriptLanguage); if (aFactoryIterator != aFactoryMap.end()) { // delegate to factory pContext = aFactoryIterator->second->CreateContext( rImport, nPrefix, rLocalName, xAttrList, rEvents, aNameIter->second, aScriptLanguage); } } // default context (if no context was created above) if( NULL == pContext ) { pContext = new SvXMLImportContext(rImport, nPrefix, rLocalName); Sequence<OUString> aMsgParams(2); aMsgParams[0] = rXmlEventName; aMsgParams[1] = rLanguage; rImport.SetError(XMLERROR_FLAG_ERROR | XMLERROR_ILLEGAL_EVENT, aMsgParams); } return pContext; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLTextListItemContext.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:23:08 $ * * 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 _XMLTEXTLISTITEMCONTEXT_HXX #define _XMLTEXTLISTITEMCONTEXT_HXX #ifndef _XMLOFF_XMLICTXT_HXX #include "xmlictxt.hxx" #endif class XMLTextImportHelper; class XMLTextListItemContext : public SvXMLImportContext { XMLTextImportHelper& rTxtImport; sal_Int16 nStartValue; // SwXMLImport& GetSwImport() { return (SwXMLImport&)GetImport(); } public: TYPEINFO(); XMLTextListItemContext( SvXMLImport& rImport, XMLTextImportHelper& rTxtImp, sal_uInt16 nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList, sal_Bool bIsHeader = sal_False ); virtual ~XMLTextListItemContext(); virtual void EndElement(); SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); sal_Bool HasStartValue() const { return -1 != nStartValue; } sal_Int16 GetStartValue() const { return nStartValue; } }; #endif <commit_msg>INTEGRATION: CWS vgbugs07 (1.2.274); FILE MERGED 2007/06/04 13:23:39 vg 1.2.274.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLTextListItemContext.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2007-06-27 16:10:22 $ * * 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 _XMLTEXTLISTITEMCONTEXT_HXX #define _XMLTEXTLISTITEMCONTEXT_HXX #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif class XMLTextImportHelper; class XMLTextListItemContext : public SvXMLImportContext { XMLTextImportHelper& rTxtImport; sal_Int16 nStartValue; // SwXMLImport& GetSwImport() { return (SwXMLImport&)GetImport(); } public: TYPEINFO(); XMLTextListItemContext( SvXMLImport& rImport, XMLTextImportHelper& rTxtImp, sal_uInt16 nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList, sal_Bool bIsHeader = sal_False ); virtual ~XMLTextListItemContext(); virtual void EndElement(); SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); sal_Bool HasStartValue() const { return -1 != nStartValue; } sal_Int16 GetStartValue() const { return nStartValue; } }; #endif <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/futures/detail/Core.h> #include <folly/futures/Future.h> #include <folly/portability/GTest.h> using namespace folly; TEST(Core, size) { static constexpr size_t lambdaBufSize = 8 * sizeof(void*); struct Gold { typename std::aligned_storage<lambdaBufSize>::type lambdaBuf_; folly::Optional<Try<Unit>> result_; folly::Function<void(Try<Unit>&&)> callback_; std::atomic<futures::detail::State> state_; std::atomic<unsigned char> attached_; std::atomic<bool> interruptHandlerSet_; futures::detail::SpinLock interruptLock_; int8_t priority_; Executor* executor_; std::shared_ptr<RequestContext> context_; std::unique_ptr<exception_wrapper> interrupt_; std::function<void(exception_wrapper const&)> interruptHandler_; }; // If this number goes down, it's fine! // If it goes up, please seek professional advice ;-) EXPECT_GE(sizeof(Gold), sizeof(futures::detail::Core<Unit>)); } <commit_msg>update the Core fake layout for testing<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/futures/detail/Core.h> #include <folly/futures/Future.h> #include <folly/portability/GTest.h> using namespace folly; TEST(Core, size) { struct KeepAliveOrDeferredGold { enum class State {}; State state_; Executor* executor_; }; class CoreBaseGold { public: virtual ~CoreBaseGold() = 0; private: folly::Function<void(Try<Unit>&&)> callback_; std::atomic<futures::detail::State> state_; std::atomic<unsigned char> attached_; std::atomic<unsigned char> callbackReferences_; futures::detail::SpinLock interruptLock_; KeepAliveOrDeferredGold executor_; std::shared_ptr<RequestContext> context_; std::unique_ptr<exception_wrapper> interrupt_; std::atomic<futures::detail::InterruptHandler*> interruptHandler_{}; CoreBaseGold* proxy_; }; class CoreGold : Try<Unit>, public CoreBaseGold {}; // If this number goes down, it's fine! // If it goes up, please seek professional advice ;-) EXPECT_EQ(sizeof(CoreGold), sizeof(futures::detail::Core<Unit>)); EXPECT_EQ(alignof(CoreGold), alignof(futures::detail::Core<Unit>)); } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2019 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #define CAF_SUITE ipv4_endpoint #include "caf/ipv4_endpoint.hpp" #include "caf/test/unit_test.hpp" #include <vector> #include "caf/actor_system.hpp" #include "caf/actor_system_config.hpp" #include "caf/binary_deserializer.hpp" #include "caf/byte.hpp" #include "caf/ipv4_address.hpp" #include "caf/serializer_impl.hpp" #include "caf/span.hpp" using namespace caf; namespace { struct test_data { using endpoint = ipv4_endpoint; using comparison_testcase = std::pair<endpoint, endpoint>; using to_string_testcase = std::pair<endpoint, std::string>; test_data() { const auto addr = make_ipv4_address; // different ip but same port add({addr(127, 0, 0, 1), 8888}, {addr(127, 0, 0, 2), 8888}); add({addr(192, 168, 178, 1), 8888}, {addr(245, 114, 2, 89), 8888}); add({addr(188, 56, 23, 97), 1211}, {addr(189, 22, 36, 0), 1211}); add({addr(0, 0, 0, 0), 8888}, {addr(255, 255, 255, 1), 8888}); // same ip but different port add({addr(127, 0, 0, 1), 111}, {addr(127, 0, 0, 1), 8888}); add({addr(192, 168, 178, 1), 8888}, {addr(245, 114, 2, 89), 8888}); add({addr(127, 0, 0, 1), 111}, {addr(127, 0, 0, 1), 8888}); add({addr(123, 123, 123, 123), 8888}, {addr(123, 123, 123, 123), 8889}); add({addr(127, 0, 0, 1), 8888}, "127.0.0.1:8888"); add({addr(192, 168, 178, 1), 8888}, "192.168.178.1:8888"); add({addr(127, 0, 0, 1), 111}, "127.0.0.1:111"); add({addr(192, 168, 178, 1), 8888}, "192.168.178.1:8888"); add({addr(127, 0, 0, 1), 111}, "127.0.0.1:111"); add({addr(123, 123, 123, 123), 8888}, "123.123.123.123:8888"); } // First endpoint is always smaller than the second. std::vector<comparison_testcase> comparison_testdata; std::vector<to_string_testcase> to_string_testdata; private: void add(endpoint ep1, endpoint ep2) { comparison_testdata.emplace_back(comparison_testcase{ep1, ep2}); } void add(endpoint ep, const std::string& str) { to_string_testdata.emplace_back(to_string_testcase{ep, str}); } }; struct test_fixture : public test_data { actor_system_config cfg; actor_system sys{cfg}; }; } // namespace CAF_TEST(constructing assigning and hash_code) { const uint16_t port = 8888; auto addr = make_ipv4_address(127, 0, 0, 1); ipv4_endpoint ep1(addr, port); CAF_CHECK_EQUAL(ep1.address(), addr); CAF_CHECK_EQUAL(ep1.port(), port); ipv4_endpoint ep2; ep2.address(addr); ep2.port(port); CAF_CHECK_EQUAL(ep2.address(), addr); CAF_CHECK_EQUAL(ep2.port(), port); CAF_CHECK_EQUAL(ep1, ep2); CAF_CHECK_EQUAL(ep1.hash_code(), ep2.hash_code()); } CAF_TEST_FIXTURE_SCOPE(comparison_scope, test_fixture) CAF_TEST(to_string) { for (auto& testcase : to_string_testdata) CAF_CHECK_EQUAL(to_string(testcase.first), testcase.second); } CAF_TEST(comparison) { for (auto testcase : comparison_testdata) { // First member of this pair is always smaller than the second one. auto ep1 = testcase.first; auto ep2 = testcase.second; CAF_CHECK_GREATER(ep2, ep1); CAF_CHECK_GREATER_OR_EQUAL(ep2, ep1); CAF_CHECK_GREATER_OR_EQUAL(ep1, ep1); CAF_CHECK_GREATER_OR_EQUAL(ep2, ep2); CAF_CHECK_EQUAL(ep1, ep1); CAF_CHECK_EQUAL(ep2, ep2); CAF_CHECK_LESS_OR_EQUAL(ep1, ep2); CAF_CHECK_LESS_OR_EQUAL(ep1, ep1); CAF_CHECK_LESS_OR_EQUAL(ep2, ep2); CAF_CHECK_NOT_EQUAL(ep1, ep2); CAF_CHECK_NOT_EQUAL(ep2, ep1); } } CAF_TEST(serialization) { using container_type = std::vector<byte>; for (auto& testcase : comparison_testdata) { container_type buf; serializer_impl<container_type> sink(sys, buf); if (auto err = sink(testcase.first)) CAF_FAIL("serialization failed: " << sys.render(err)); binary_deserializer source(sys, make_span(buf)); ipv4_endpoint deserialized_data; if (auto err = source(deserialized_data)) CAF_FAIL("deserialization failed: " << sys.render(err)); CAF_CHECK_EQUAL(testcase.first, deserialized_data); } } CAF_TEST_FIXTURE_SCOPE_END()<commit_msg>Refactor ipv4_endpoint tests<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2019 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #define CAF_SUITE ipv4_endpoint #include "caf/ipv4_endpoint.hpp" #include "caf/test/dsl.hpp" #include "caf/test/unit_test.hpp" #include <cassert> #include <vector> #include "caf/actor_system.hpp" #include "caf/actor_system_config.hpp" #include "caf/binary_deserializer.hpp" #include "caf/byte.hpp" #include "caf/ipv4_address.hpp" #include "caf/serializer_impl.hpp" #include "caf/span.hpp" using namespace caf; namespace { ipv4_endpoint operator"" _ep(const char* str, size_t) { std::array<uint8_t, 4> bytes; char* next = nullptr; bytes[0] = static_cast<uint8_t>(strtol(str, &next, 10)); for (size_t n = 1; n < 4; ++n) { assert(*next == '.'); str = next + 1; bytes[n] = static_cast<uint8_t>(strtol(str, &next, 10)); } assert(*next == ':'); auto port = static_cast<uint16_t>(strtol(next + 1, nullptr, 10)); return ipv4_endpoint{ipv4_address{bytes}, port}; } struct fixture { actor_system_config cfg; actor_system sys{cfg}; template <class T> T roundtrip(T x) { using container_type = std::vector<byte>; container_type buf; serializer_impl<container_type> sink(sys, buf); if (auto err = sink(x)) CAF_FAIL("serialization failed: " << sys.render(err)); binary_deserializer source(sys, make_span(buf)); ipv4_endpoint y; if (auto err = source(y)) CAF_FAIL("deserialization failed: " << sys.render(err)); return y; } }; #define CHECK_TO_STRING(addr) CAF_CHECK_EQUAL(addr, to_string(addr##_ep)) #define CHECK_COMPARISON(addr1, addr2) \ CAF_CHECK_GREATER(addr2##_ep, addr1##_ep); \ CAF_CHECK_GREATER_OR_EQUAL(addr2##_ep, addr1##_ep); \ CAF_CHECK_GREATER_OR_EQUAL(addr1##_ep, addr1##_ep); \ CAF_CHECK_GREATER_OR_EQUAL(addr2##_ep, addr2##_ep); \ CAF_CHECK_EQUAL(addr1##_ep, addr1##_ep); \ CAF_CHECK_EQUAL(addr2##_ep, addr2##_ep); \ CAF_CHECK_LESS_OR_EQUAL(addr1##_ep, addr2##_ep); \ CAF_CHECK_LESS_OR_EQUAL(addr1##_ep, addr1##_ep); \ CAF_CHECK_LESS_OR_EQUAL(addr2##_ep, addr2##_ep); \ CAF_CHECK_NOT_EQUAL(addr1##_ep, addr2##_ep); \ CAF_CHECK_NOT_EQUAL(addr2##_ep, addr1##_ep); #define CHECK_SERIALIZATION(addr) \ CAF_CHECK_EQUAL(addr##_ep, roundtrip(addr##_ep)) } // namespace CAF_TEST_FIXTURE_SCOPE(ipv4_endpoint_tests, fixture) CAF_TEST(constructing assigning and hash_code) { const uint16_t port = 8888; auto addr = make_ipv4_address(127, 0, 0, 1); ipv4_endpoint ep1(addr, port); CAF_CHECK_EQUAL(ep1.address(), addr); CAF_CHECK_EQUAL(ep1.port(), port); ipv4_endpoint ep2; ep2.address(addr); ep2.port(port); CAF_CHECK_EQUAL(ep2.address(), addr); CAF_CHECK_EQUAL(ep2.port(), port); CAF_CHECK_EQUAL(ep1, ep2); CAF_CHECK_EQUAL(ep1.hash_code(), ep2.hash_code()); } CAF_TEST(to string) { CHECK_TO_STRING("127.0.0.1:8888"); CHECK_TO_STRING("192.168.178.1:8888"); CHECK_TO_STRING("255.255.255.1:17"); CHECK_TO_STRING("192.168.178.1:8888"); CHECK_TO_STRING("127.0.0.1:111"); CHECK_TO_STRING("123.123.123.123:8888"); CHECK_TO_STRING("127.0.0.1:8888"); } CAF_TEST(comparison) { CHECK_COMPARISON("127.0.0.1:8888", "127.0.0.2:8888"); CHECK_COMPARISON("192.168.178.1:8888", "245.114.2.89:8888"); CHECK_COMPARISON("188.56.23.97:1211", "189.22.36.0:1211"); CHECK_COMPARISON("0.0.0.0:8888", "255.255.255.1:8888"); CHECK_COMPARISON("127.0.0.1:111", "127.0.0.1:8888"); CHECK_COMPARISON("192.168.178.1:8888", "245.114.2.89:8888"); CHECK_COMPARISON("123.123.123.123:8888", "123.123.123.123:8889"); } CAF_TEST(serialization) { CHECK_SERIALIZATION("127.0.0.1:8888"); CHECK_SERIALIZATION("192.168.178.1:8888"); CHECK_SERIALIZATION("255.255.255.1:17"); CHECK_SERIALIZATION("192.168.178.1:8888"); CHECK_SERIALIZATION("127.0.0.1:111"); CHECK_SERIALIZATION("123.123.123.123:8888"); CHECK_SERIALIZATION("127.0.0.1:8888"); } CAF_TEST_FIXTURE_SCOPE_END() <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: Edit.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2004-04-02 10:51:20 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _FORMS_EDIT_HXX_ #define _FORMS_EDIT_HXX_ #ifndef _FORMS_EDITBASE_HXX_ #include "EditBase.hxx" #endif #ifndef _CPPUHELPER_IMPLBASE3_HXX_ #include <cppuhelper/implbase3.hxx> #endif //......................................................................... namespace frm { //================================================================== //= OEditModel //================================================================== class OEditModel :public OEditBaseModel ,public ::comphelper::OAggregationArrayUsageHelper< OEditModel > { ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter> m_xFormatter; ::rtl::OUString m_aSaveValue; sal_Int32 m_nFormatKey; ::com::sun::star::util::Date m_aNullDate; sal_Int32 m_nFieldType; sal_Int16 m_nKeyType; sal_Bool m_bMaxTextLenModified : 1; // set to <TRUE/> when we change the MaxTextLen of the aggregate sal_Bool m_bWritingFormattedFake : 1; // are we writing something which should be interpreted as formatted upon reading? sal_Bool m_bNumericField : 1; // are we bound to some kind of numeric field? protected: virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); DECLARE_DEFAULT_LEAF_XTOR( OEditModel ); void enableFormattedWriteFake() { m_bWritingFormattedFake = sal_True; } void disableFormattedWriteFake() { m_bWritingFormattedFake = sal_False; } sal_Bool lastReadWasFormattedFake() const { return (getLastReadVersion() & PF_FAKE_FORMATTED_FIELD) != 0; } friend InterfaceRef SAL_CALL OEditModel_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); friend class OFormattedFieldWrapper; friend class OFormattedModel; // temporary public: virtual void SAL_CALL disposing(); // XPropertySet virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const; // ::com::sun::star::io::XPersistObject virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException); // ::com::sun::star::beans::XPropertySet virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException); virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); // ::com::sun::star::lang::XServiceInfo IMPLEMENTATION_NAME(OEditModel); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // OAggregationArrayUsageHelper virtual void fillProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps, ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps ) const; IMPLEMENT_INFO_SERVICE() protected: // OBoundControlModel overridables virtual ::com::sun::star::uno::Any translateDbColumnToControlValue( ); virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset ); virtual ::com::sun::star::uno::Any getDefaultForReset() const; virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm ); virtual void onDisconnectedDbColumn(); virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding ); protected: virtual sal_Int16 getPersistenceFlags() const; DECLARE_XCLONEABLE(); }; //================================================================== //= OEditControl //================================================================== typedef ::cppu::ImplHelper3< ::com::sun::star::awt::XFocusListener, ::com::sun::star::awt::XKeyListener, ::com::sun::star::form::XChangeBroadcaster > OEditControl_BASE; class OEditControl : public OBoundControl ,public OEditControl_BASE { ::cppu::OInterfaceContainerHelper m_aChangeListeners; ::rtl::OUString m_aHtmlChangeValue; sal_uInt32 m_nKeyEvent; public: OEditControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); virtual ~OEditControl(); DECLARE_UNO3_AGG_DEFAULTS(OEditControl, OBoundControl); virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); // OComponentHelper virtual void SAL_CALL disposing(); // ::com::sun::star::lang::XEventListener virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException); // ::com::sun::star::lang::XServiceInfo IMPLEMENTATION_NAME(OEditControl); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // ::com::sun::star::form::XChangeBroadcaster virtual void SAL_CALL addChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException); // ::com::sun::star::awt::XFocusListener virtual void SAL_CALL focusGained( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL focusLost( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException); // ::com::sun::star::awt::XKeyListener virtual void SAL_CALL keyPressed(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL keyReleased(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException); private: DECL_LINK( OnKeyPressed, void* ); }; //......................................................................... } //......................................................................... #endif // _FORMS_EDIT_HXX_ <commit_msg>INTEGRATION: CWS frmcontrols03 (1.8.24); FILE MERGED 2004/04/28 12:05:30 fs 1.8.24.3: RESYNC: (1.8-1.9); FILE MERGED 2004/03/03 14:00:19 fs 1.8.24.2: #i24387# do not bind rich text controls 2004/03/02 15:01:40 fs 1.8.24.1: #i24387# care for compatibility when reading/writing binary format<commit_after>/************************************************************************* * * $RCSfile: Edit.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2004-05-07 16:06:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _FORMS_EDIT_HXX_ #define _FORMS_EDIT_HXX_ #ifndef _FORMS_EDITBASE_HXX_ #include "EditBase.hxx" #endif #ifndef _CPPUHELPER_IMPLBASE3_HXX_ #include <cppuhelper/implbase3.hxx> #endif //......................................................................... namespace frm { //================================================================== //= OEditModel //================================================================== class OEditModel :public OEditBaseModel ,public ::comphelper::OAggregationArrayUsageHelper< OEditModel > { ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter> m_xFormatter; ::rtl::OUString m_aSaveValue; sal_Int32 m_nFormatKey; ::com::sun::star::util::Date m_aNullDate; sal_Int32 m_nFieldType; sal_Int16 m_nKeyType; sal_Bool m_bMaxTextLenModified : 1; // set to <TRUE/> when we change the MaxTextLen of the aggregate sal_Bool m_bWritingFormattedFake : 1; // are we writing something which should be interpreted as formatted upon reading? sal_Bool m_bNumericField : 1; // are we bound to some kind of numeric field? protected: virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); DECLARE_DEFAULT_LEAF_XTOR( OEditModel ); void enableFormattedWriteFake() { m_bWritingFormattedFake = sal_True; } void disableFormattedWriteFake() { m_bWritingFormattedFake = sal_False; } sal_Bool lastReadWasFormattedFake() const { return (getLastReadVersion() & PF_FAKE_FORMATTED_FIELD) != 0; } friend InterfaceRef SAL_CALL OEditModel_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); friend class OFormattedFieldWrapper; friend class OFormattedModel; // temporary public: virtual void SAL_CALL disposing(); // XPropertySet virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const; // ::com::sun::star::io::XPersistObject virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException); // ::com::sun::star::beans::XPropertySet virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException); virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); // XReset virtual void SAL_CALL reset( ) throw(::com::sun::star::uno::RuntimeException); // ::com::sun::star::lang::XServiceInfo IMPLEMENTATION_NAME(OEditModel); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // OAggregationArrayUsageHelper virtual void fillProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps, ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps ) const; IMPLEMENT_INFO_SERVICE() protected: // OControlModel overridables virtual void writeAggregate( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream >& _rxOutStream ) const; virtual void readAggregate( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream >& _rxInStream ); // OBoundControlModel overridables virtual ::com::sun::star::uno::Any translateDbColumnToControlValue( ); virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset ); virtual ::com::sun::star::uno::Any getDefaultForReset() const; virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm ); virtual void onDisconnectedDbColumn(); virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding ); virtual sal_Bool approveDbColumnType( sal_Int32 _nColumnType ); protected: virtual sal_Int16 getPersistenceFlags() const; DECLARE_XCLONEABLE(); private: bool implActsAsRichText( ) const; }; //================================================================== //= OEditControl //================================================================== typedef ::cppu::ImplHelper3< ::com::sun::star::awt::XFocusListener, ::com::sun::star::awt::XKeyListener, ::com::sun::star::form::XChangeBroadcaster > OEditControl_BASE; class OEditControl : public OBoundControl ,public OEditControl_BASE { ::cppu::OInterfaceContainerHelper m_aChangeListeners; ::rtl::OUString m_aHtmlChangeValue; sal_uInt32 m_nKeyEvent; public: OEditControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); virtual ~OEditControl(); DECLARE_UNO3_AGG_DEFAULTS(OEditControl, OBoundControl); virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); // OComponentHelper virtual void SAL_CALL disposing(); // ::com::sun::star::lang::XEventListener virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException); // ::com::sun::star::lang::XServiceInfo IMPLEMENTATION_NAME(OEditControl); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // ::com::sun::star::form::XChangeBroadcaster virtual void SAL_CALL addChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException); // ::com::sun::star::awt::XFocusListener virtual void SAL_CALL focusGained( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL focusLost( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException); // ::com::sun::star::awt::XKeyListener virtual void SAL_CALL keyPressed(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL keyReleased(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException); private: DECL_LINK( OnKeyPressed, void* ); }; //......................................................................... } //......................................................................... #endif // _FORMS_EDIT_HXX_ <|endoftext|>
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2006 Artem Pavlenko * * Mapnik 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 any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id$ // stl #include <iostream> // qt #include <QtGui> #include <QSplitter> #include <QTreeView> #include <QListView> #include <QTabWidget> #include <QList> #include <QItemDelegate> #include <QSlider> // mapnik #include <mapnik/config_error.hpp> #include <mapnik/load_map.hpp> #include <mapnik/save_map.hpp> // qt #include "mainwindow.hpp" #include "layerlistmodel.hpp" #include "styles_model.hpp" #include "layerwidget.hpp" #include "layerdelegate.hpp" #include "about_dialog.hpp" MainWindow::MainWindow() : filename_(), default_extent_(-20037508.3428,-20037508.3428,20037508.3428,20037508.3428) { mapWidget_ = new MapWidget(this); QSplitter *splitter = new QSplitter(this); QTabWidget *tabWidget=new QTabWidget; layerTab_ = new LayerTab; layerTab_->setFocusPolicy(Qt::NoFocus); layerTab_->setIconSize(QSize(16,16)); //LayerDelegate *delegate = new LayerDelegate(this); //layerTab_->setItemDelegate(delegate); //layerTab_->setItemDelegate(new QItemDelegate(this)); //layerTab_->setViewMode(QListView::IconMode); layerTab_->setFlow(QListView::TopToBottom); tabWidget->addTab(layerTab_,tr("Layers")); // Styles tab styleTab_ = new StyleTab; tabWidget->addTab(styleTab_,tr("Styles")); splitter->addWidget(tabWidget); splitter->addWidget(mapWidget_); QList<int> list; list.push_back(200); list.push_back(600); splitter->setSizes(list); mapWidget_->setFocusPolicy(Qt::StrongFocus); mapWidget_->setFocus(); //setCentralWidget(mapWidget_); setCentralWidget(splitter); createActions(); createMenus(); createToolBars(); createContextMenu(); setWindowTitle(tr("Mapnik Viewer")); status=new QStatusBar(this); status->showMessage(tr("")); setStatusBar(status); resize(800,600); //connect mapview to layerlist connect(mapWidget_, SIGNAL(mapViewChanged()),layerTab_, SLOT(update())); // slider connect(slider_,SIGNAL(valueChanged(int)),mapWidget_,SLOT(zoomToLevel(int))); // connect(layerTab_,SIGNAL(update_mapwidget()),mapWidget_,SLOT(updateMap())); connect(layerTab_,SIGNAL(layerSelected(int)), mapWidget_,SLOT(layerSelected(int))); } MainWindow::~MainWindow() { delete mapWidget_; } void MainWindow::closeEvent(QCloseEvent* event) { event->accept(); } void MainWindow::createContextMenu() { layerTab_->setContextMenuPolicy(Qt::ActionsContextMenu); layerTab_->addAction(openAct); layerTab_->addAction(layerInfo); } void MainWindow::open(QString const& path) { if (path.isNull()) { filename_ = QFileDialog::getOpenFileName(this,tr("Open Mapnik file"), currentPath,"*.xml"); } else { filename_ = path; } if (!filename_.isEmpty()) { load_map_file(filename_); //zoom_all(); setWindowTitle(tr("%1 - Mapnik Viewer").arg(filename_)); } } void MainWindow::reload() { if (!filename_.isEmpty()) { mapnik::box2d<double> bbox = mapWidget_->getMap()->getCurrentExtent(); load_map_file(filename_); mapWidget_->zoomToBox(bbox); setWindowTitle(tr("%1 - *Reloaded*").arg(filename_)); } } void MainWindow::save() { QString initialPath = QDir::currentPath() + "/untitled.xml"; QString filename = QFileDialog::getSaveFileName(this, tr("Save"), initialPath, tr("%1 Files (*.xml)") .arg(QString("Mapnik definition"))); if (!filename.isEmpty()) { std::cout<<"saving "<< filename.toStdString() << std::endl; mapnik::save_map(*mapWidget_->getMap(),filename.toStdString()); } } void MainWindow::load_map_file(QString const& filename) { std::cout<<"loading "<< filename.toStdString() << std::endl; unsigned width = mapWidget_->width(); unsigned height = mapWidget_->height(); boost::shared_ptr<mapnik::Map> map(new mapnik::Map(width,height)); mapWidget_->setMap(map); try { mapnik::load_map(*map,filename.toStdString()); } catch (mapnik::config_error & ex) { std::cout << ex.what() << "\n"; } map->zoom_all(); mapnik::box2d<double> const& ext = map->getCurrentExtent(); mapWidget_->zoomToBox(ext); layerTab_->setModel(new LayerListModel(map,this)); styleTab_->setModel(new StyleModel(map,this)); } void MainWindow::zoom_all() { mapWidget_->defaultView(); } void MainWindow::zoom_to_box() { mapWidget_->setTool(MapWidget::ZoomToBox); } void MainWindow::pan() { mapWidget_->setTool(MapWidget::Pan); } void MainWindow::info() { mapWidget_->setTool(MapWidget::Info); } void MainWindow::pan_left() { mapWidget_->panLeft(); } void MainWindow::pan_right() { mapWidget_->panRight(); } void MainWindow::pan_up() { mapWidget_->panUp(); } void MainWindow::pan_down() { mapWidget_->panDown(); } void MainWindow::about() { about_dialog dlg; dlg.exec(); } void MainWindow::export_as() { QAction *action = qobject_cast<QAction *>(sender()); QByteArray fileFormat = action->data().toByteArray(); QString initialPath = QDir::currentPath() + "/map." + fileFormat; QString fileName = QFileDialog::getSaveFileName(this, tr("Export As"), initialPath, tr("%1 Files (*.%2);;All Files (*)") .arg(QString(fileFormat.toUpper())) .arg(QString(fileFormat))); if (!fileName.isEmpty()) { QPixmap const& pix = mapWidget_->pixmap(); pix.save(fileName); } } void MainWindow::print() { //Q_ASSERT(mapWidget_->pixmap()); //QPrintDialog dialog(&printer, this); //if (dialog.exec()) { // QPainter painter(&printer); // QRect rect = painter.viewport(); // QSize size = mapWidget_->pixmap()->size(); // size.scale(rect.size(), Qt::KeepAspectRatio); // painter.setViewport(rect.x(), rect.y(), size.width(), size.height()); // painter.setWindow(mapWidget_->pixmap()->rect()); // painter.drawPixmap(0, 0, *mapWidget_->pixmap()); //} } void MainWindow::createActions() { //exportAct = new QAction(tr("&Export as ..."),this); //exportAct->setShortcut(tr("Ctrl+E")); //connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as())); zoomAllAct = new QAction(QIcon(":/images/home.png"),tr("Zoom All"),this); connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all())); zoomBoxAct = new QAction(QIcon(":/images/zoombox.png"),tr("Zoom To Box"),this); zoomBoxAct->setCheckable(true); connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box())); panAct = new QAction(QIcon(":/images/pan.png"),tr("Pan"),this); panAct->setCheckable(true); connect(panAct, SIGNAL(triggered()), this, SLOT(pan())); infoAct = new QAction(QIcon(":/images/info.png"),tr("Info"),this); infoAct->setCheckable(true); connect(infoAct, SIGNAL(triggered()), this, SLOT(info())); toolsGroup=new QActionGroup(this); toolsGroup->addAction(zoomBoxAct); toolsGroup->addAction(panAct); toolsGroup->addAction(infoAct); zoomBoxAct->setChecked(true); openAct=new QAction(tr("Open Map definition"),this); connect(openAct,SIGNAL(triggered()),this,SLOT(open())); saveAct=new QAction(tr("Save Map definition"),this); connect(saveAct,SIGNAL(triggered()),this,SLOT(save())); panLeftAct = new QAction(QIcon(":/images/left.png"),tr("&Pan Left"),this); connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left())); panRightAct = new QAction(QIcon(":/images/right.png"),tr("&Pan Right"),this); connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right())); panUpAct = new QAction(QIcon(":/images/up.png"),tr("&Pan Up"),this); connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up())); panDownAct = new QAction(QIcon(":/images/down.png"),tr("&Pan Down"),this); connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down())); reloadAct = new QAction(QIcon(":/images/reload.png"),tr("Reload"),this); connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload())); layerInfo = new QAction(QIcon(":/images/info.png"),tr("&Layer info"),layerTab_); connect(layerInfo, SIGNAL(triggered()), layerTab_,SLOT(layerInfo())); connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_,SLOT(layerInfo2(QModelIndex const&))); foreach (QByteArray format, QImageWriter::supportedImageFormats()) { QString text = tr("%1...").arg(QString(format).toUpper()); QAction *action = new QAction(text, this); action->setData(format); connect(action, SIGNAL(triggered()), this, SLOT(export_as())); exportAsActs.append(action); } printAct = new QAction(QIcon(":/images/print.png"),tr("&Print ..."),this); printAct->setShortcut(tr("Ctrl+E")); connect(printAct, SIGNAL(triggered()), this, SLOT(print())); exitAct = new QAction(tr("E&xit"), this); exitAct->setShortcut(tr("Ctrl+Q")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); aboutAct = new QAction(QIcon(":/images/about.png"),tr("&About"), this); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); } void MainWindow::createMenus() { exportMenu = new QMenu(tr("&Export As"), this); foreach (QAction *action, exportAsActs) exportMenu->addAction(action); fileMenu = new QMenu(tr("&File"),this); fileMenu->addAction(openAct); fileMenu->addAction(saveAct); fileMenu->addMenu(exportMenu); fileMenu->addAction(printAct); fileMenu->addSeparator(); fileMenu->addAction(exitAct); menuBar()->addMenu(fileMenu); helpMenu = new QMenu(tr("&Help"), this); helpMenu->addAction(aboutAct); menuBar()->addMenu(helpMenu); } void MainWindow::createToolBars() { fileToolBar = addToolBar(tr("Actions")); fileToolBar->addAction(zoomAllAct); fileToolBar->addAction(zoomBoxAct); fileToolBar->addAction(panAct); fileToolBar->addAction(panLeftAct); fileToolBar->addAction(panRightAct); fileToolBar->addAction(panUpAct); fileToolBar->addAction(panDownAct); fileToolBar->addAction(infoAct); fileToolBar->addAction(reloadAct); fileToolBar->addAction(printAct); slider_ = new QSlider(Qt::Horizontal,fileToolBar); slider_->setRange(1,18); slider_->setTickPosition(QSlider::TicksBelow); slider_->setTickInterval(1); slider_->setTracking(false); fileToolBar->addWidget(slider_); fileToolBar->addAction(aboutAct); } void MainWindow::set_default_extent(double x0,double y0, double x1, double y1) { try { boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap(); if (map_ptr) { mapnik::projection prj(map_ptr->srs()); prj.forward(x0,y0); prj.forward(x1,y1); default_extent_=mapnik::box2d<double>(x0,y0,x1,y1); mapWidget_->zoomToBox(default_extent_); std::cout << "SET DEFAULT EXT\n"; } } catch (...) {} } <commit_msg>+ don't call zoom_all if bounding box is supplied<commit_after>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2006 Artem Pavlenko * * Mapnik 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 any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id$ // stl #include <iostream> // qt #include <QtGui> #include <QSplitter> #include <QTreeView> #include <QListView> #include <QTabWidget> #include <QList> #include <QItemDelegate> #include <QSlider> // mapnik #include <mapnik/config_error.hpp> #include <mapnik/load_map.hpp> #include <mapnik/save_map.hpp> // qt #include "mainwindow.hpp" #include "layerlistmodel.hpp" #include "styles_model.hpp" #include "layerwidget.hpp" #include "layerdelegate.hpp" #include "about_dialog.hpp" MainWindow::MainWindow() : filename_(), default_extent_(-20037508.3428,-20037508.3428,20037508.3428,20037508.3428) { mapWidget_ = new MapWidget(this); QSplitter *splitter = new QSplitter(this); QTabWidget *tabWidget=new QTabWidget; layerTab_ = new LayerTab; layerTab_->setFocusPolicy(Qt::NoFocus); layerTab_->setIconSize(QSize(16,16)); //LayerDelegate *delegate = new LayerDelegate(this); //layerTab_->setItemDelegate(delegate); //layerTab_->setItemDelegate(new QItemDelegate(this)); //layerTab_->setViewMode(QListView::IconMode); layerTab_->setFlow(QListView::TopToBottom); tabWidget->addTab(layerTab_,tr("Layers")); // Styles tab styleTab_ = new StyleTab; tabWidget->addTab(styleTab_,tr("Styles")); splitter->addWidget(tabWidget); splitter->addWidget(mapWidget_); QList<int> list; list.push_back(200); list.push_back(600); splitter->setSizes(list); mapWidget_->setFocusPolicy(Qt::StrongFocus); mapWidget_->setFocus(); //setCentralWidget(mapWidget_); setCentralWidget(splitter); createActions(); createMenus(); createToolBars(); createContextMenu(); setWindowTitle(tr("Mapnik Viewer")); status=new QStatusBar(this); status->showMessage(tr("")); setStatusBar(status); resize(800,600); //connect mapview to layerlist connect(mapWidget_, SIGNAL(mapViewChanged()),layerTab_, SLOT(update())); // slider connect(slider_,SIGNAL(valueChanged(int)),mapWidget_,SLOT(zoomToLevel(int))); // connect(layerTab_,SIGNAL(update_mapwidget()),mapWidget_,SLOT(updateMap())); connect(layerTab_,SIGNAL(layerSelected(int)), mapWidget_,SLOT(layerSelected(int))); } MainWindow::~MainWindow() { delete mapWidget_; } void MainWindow::closeEvent(QCloseEvent* event) { event->accept(); } void MainWindow::createContextMenu() { layerTab_->setContextMenuPolicy(Qt::ActionsContextMenu); layerTab_->addAction(openAct); layerTab_->addAction(layerInfo); } void MainWindow::open(QString const& path) { if (path.isNull()) { filename_ = QFileDialog::getOpenFileName(this,tr("Open Mapnik file"), currentPath,"*.xml"); } else { filename_ = path; } if (!filename_.isEmpty()) { load_map_file(filename_); //zoom_all(); setWindowTitle(tr("%1 - Mapnik Viewer").arg(filename_)); } } void MainWindow::reload() { if (!filename_.isEmpty()) { mapnik::box2d<double> bbox = mapWidget_->getMap()->getCurrentExtent(); load_map_file(filename_); mapWidget_->zoomToBox(bbox); setWindowTitle(tr("%1 - *Reloaded*").arg(filename_)); } } void MainWindow::save() { QString initialPath = QDir::currentPath() + "/untitled.xml"; QString filename = QFileDialog::getSaveFileName(this, tr("Save"), initialPath, tr("%1 Files (*.xml)") .arg(QString("Mapnik definition"))); if (!filename.isEmpty()) { std::cout<<"saving "<< filename.toStdString() << std::endl; mapnik::save_map(*mapWidget_->getMap(),filename.toStdString()); } } void MainWindow::load_map_file(QString const& filename) { std::cout<<"loading "<< filename.toStdString() << std::endl; unsigned width = mapWidget_->width(); unsigned height = mapWidget_->height(); boost::shared_ptr<mapnik::Map> map(new mapnik::Map(width,height)); mapWidget_->setMap(map); try { mapnik::load_map(*map,filename.toStdString()); } catch (mapnik::config_error & ex) { std::cout << ex.what() << "\n"; } //map->zoom_all(); //mapnik::box2d<double> const& ext = map->getCurrentExtent(); //mapWidget_->zoomToBox(ext); layerTab_->setModel(new LayerListModel(map,this)); styleTab_->setModel(new StyleModel(map,this)); } void MainWindow::zoom_all() { mapWidget_->defaultView(); } void MainWindow::zoom_to_box() { mapWidget_->setTool(MapWidget::ZoomToBox); } void MainWindow::pan() { mapWidget_->setTool(MapWidget::Pan); } void MainWindow::info() { mapWidget_->setTool(MapWidget::Info); } void MainWindow::pan_left() { mapWidget_->panLeft(); } void MainWindow::pan_right() { mapWidget_->panRight(); } void MainWindow::pan_up() { mapWidget_->panUp(); } void MainWindow::pan_down() { mapWidget_->panDown(); } void MainWindow::about() { about_dialog dlg; dlg.exec(); } void MainWindow::export_as() { QAction *action = qobject_cast<QAction *>(sender()); QByteArray fileFormat = action->data().toByteArray(); QString initialPath = QDir::currentPath() + "/map." + fileFormat; QString fileName = QFileDialog::getSaveFileName(this, tr("Export As"), initialPath, tr("%1 Files (*.%2);;All Files (*)") .arg(QString(fileFormat.toUpper())) .arg(QString(fileFormat))); if (!fileName.isEmpty()) { QPixmap const& pix = mapWidget_->pixmap(); pix.save(fileName); } } void MainWindow::print() { //Q_ASSERT(mapWidget_->pixmap()); //QPrintDialog dialog(&printer, this); //if (dialog.exec()) { // QPainter painter(&printer); // QRect rect = painter.viewport(); // QSize size = mapWidget_->pixmap()->size(); // size.scale(rect.size(), Qt::KeepAspectRatio); // painter.setViewport(rect.x(), rect.y(), size.width(), size.height()); // painter.setWindow(mapWidget_->pixmap()->rect()); // painter.drawPixmap(0, 0, *mapWidget_->pixmap()); //} } void MainWindow::createActions() { //exportAct = new QAction(tr("&Export as ..."),this); //exportAct->setShortcut(tr("Ctrl+E")); //connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as())); zoomAllAct = new QAction(QIcon(":/images/home.png"),tr("Zoom All"),this); connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all())); zoomBoxAct = new QAction(QIcon(":/images/zoombox.png"),tr("Zoom To Box"),this); zoomBoxAct->setCheckable(true); connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box())); panAct = new QAction(QIcon(":/images/pan.png"),tr("Pan"),this); panAct->setCheckable(true); connect(panAct, SIGNAL(triggered()), this, SLOT(pan())); infoAct = new QAction(QIcon(":/images/info.png"),tr("Info"),this); infoAct->setCheckable(true); connect(infoAct, SIGNAL(triggered()), this, SLOT(info())); toolsGroup=new QActionGroup(this); toolsGroup->addAction(zoomBoxAct); toolsGroup->addAction(panAct); toolsGroup->addAction(infoAct); zoomBoxAct->setChecked(true); openAct=new QAction(tr("Open Map definition"),this); connect(openAct,SIGNAL(triggered()),this,SLOT(open())); saveAct=new QAction(tr("Save Map definition"),this); connect(saveAct,SIGNAL(triggered()),this,SLOT(save())); panLeftAct = new QAction(QIcon(":/images/left.png"),tr("&Pan Left"),this); connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left())); panRightAct = new QAction(QIcon(":/images/right.png"),tr("&Pan Right"),this); connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right())); panUpAct = new QAction(QIcon(":/images/up.png"),tr("&Pan Up"),this); connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up())); panDownAct = new QAction(QIcon(":/images/down.png"),tr("&Pan Down"),this); connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down())); reloadAct = new QAction(QIcon(":/images/reload.png"),tr("Reload"),this); connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload())); layerInfo = new QAction(QIcon(":/images/info.png"),tr("&Layer info"),layerTab_); connect(layerInfo, SIGNAL(triggered()), layerTab_,SLOT(layerInfo())); connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_,SLOT(layerInfo2(QModelIndex const&))); foreach (QByteArray format, QImageWriter::supportedImageFormats()) { QString text = tr("%1...").arg(QString(format).toUpper()); QAction *action = new QAction(text, this); action->setData(format); connect(action, SIGNAL(triggered()), this, SLOT(export_as())); exportAsActs.append(action); } printAct = new QAction(QIcon(":/images/print.png"),tr("&Print ..."),this); printAct->setShortcut(tr("Ctrl+E")); connect(printAct, SIGNAL(triggered()), this, SLOT(print())); exitAct = new QAction(tr("E&xit"), this); exitAct->setShortcut(tr("Ctrl+Q")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); aboutAct = new QAction(QIcon(":/images/about.png"),tr("&About"), this); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); } void MainWindow::createMenus() { exportMenu = new QMenu(tr("&Export As"), this); foreach (QAction *action, exportAsActs) exportMenu->addAction(action); fileMenu = new QMenu(tr("&File"),this); fileMenu->addAction(openAct); fileMenu->addAction(saveAct); fileMenu->addMenu(exportMenu); fileMenu->addAction(printAct); fileMenu->addSeparator(); fileMenu->addAction(exitAct); menuBar()->addMenu(fileMenu); helpMenu = new QMenu(tr("&Help"), this); helpMenu->addAction(aboutAct); menuBar()->addMenu(helpMenu); } void MainWindow::createToolBars() { fileToolBar = addToolBar(tr("Actions")); fileToolBar->addAction(zoomAllAct); fileToolBar->addAction(zoomBoxAct); fileToolBar->addAction(panAct); fileToolBar->addAction(panLeftAct); fileToolBar->addAction(panRightAct); fileToolBar->addAction(panUpAct); fileToolBar->addAction(panDownAct); fileToolBar->addAction(infoAct); fileToolBar->addAction(reloadAct); fileToolBar->addAction(printAct); slider_ = new QSlider(Qt::Horizontal,fileToolBar); slider_->setRange(1,18); slider_->setTickPosition(QSlider::TicksBelow); slider_->setTickInterval(1); slider_->setTracking(false); fileToolBar->addWidget(slider_); fileToolBar->addAction(aboutAct); } void MainWindow::set_default_extent(double x0,double y0, double x1, double y1) { try { boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap(); if (map_ptr) { mapnik::projection prj(map_ptr->srs()); prj.forward(x0,y0); prj.forward(x1,y1); default_extent_=mapnik::box2d<double>(x0,y0,x1,y1); mapWidget_->zoomToBox(default_extent_); std::cout << "SET DEFAULT EXT\n"; } } catch (...) {} } <|endoftext|>
<commit_before><commit_msg>[SofaKernel] ObjectFactory: the last added component will overload previously defined components in the factory. A component can then be redefined in a plugin.<commit_after><|endoftext|>
<commit_before>/* * Author: Jeff Thompson * * BSD license, See the LICENSE file for more information. */ #ifndef BINARYXMLSTRUCTUREDECODER_HPP #define BINARYXMLSTRUCTUREDECODER_HPP #include <stdexcept> #include "../c/encoding/BinaryXMLStructureDecoder.h" namespace ndn { /** * A BinaryXMLStructureDecoder wraps a C struct ndn_BinaryXMLStructureDecoder and * related functions. */ class BinaryXMLStructureDecoder { public: BinaryXMLStructureDecoder() { ndn_BinaryXMLStructureDecoder_init(&base_); } /** * Continue scanning input starting from getOffset() to find the element end. * If the end of the element which started at offset 0 is found, then return true and getOffset() is the length of * the element. Otherwise return false, which means you should read more into input and call again. * @param input the input buffer. You have to pass in input each time because the buffer could be reallocated. * @param inputLength the number of bytes in input. * @return true if found the element end, false if need to read more. (This is the same as returning gotElementEnd().) */ bool findElementEnd(unsigned char *input, unsigned int inputLength) { char *error; if (error = ndn_BinaryXMLStructureDecoder_findElementEnd(&base_, input, inputLength)) throw std::runtime_error(error); return gotElementEnd(); } unsigned int getOffset() { return base_. offset; } bool gotElementEnd() { return base_.gotElementEnd != 0; } private: struct ndn_BinaryXMLStructureDecoder base_; }; } #endif /* BINARYXMLSTRUCTUREDECODER_HPP */ <commit_msg>Fix comment.<commit_after>/* * Author: Jeff Thompson * * BSD license, See the LICENSE file for more information. */ #ifndef BINARYXMLSTRUCTUREDECODER_HPP #define BINARYXMLSTRUCTUREDECODER_HPP #include <stdexcept> #include "../c/encoding/BinaryXMLStructureDecoder.h" namespace ndn { /** * A BinaryXMLStructureDecoder wraps a C ndn_BinaryXMLStructureDecoder struct and related functions. */ class BinaryXMLStructureDecoder { public: BinaryXMLStructureDecoder() { ndn_BinaryXMLStructureDecoder_init(&base_); } /** * Continue scanning input starting from getOffset() to find the element end. * If the end of the element which started at offset 0 is found, then return true and getOffset() is the length of * the element. Otherwise return false, which means you should read more into input and call again. * @param input the input buffer. You have to pass in input each time because the buffer could be reallocated. * @param inputLength the number of bytes in input. * @return true if found the element end, false if need to read more. (This is the same as returning gotElementEnd().) */ bool findElementEnd(unsigned char *input, unsigned int inputLength) { char *error; if (error = ndn_BinaryXMLStructureDecoder_findElementEnd(&base_, input, inputLength)) throw std::runtime_error(error); return gotElementEnd(); } unsigned int getOffset() { return base_._offset; } bool gotElementEnd() { return base_.gotElementEnd != 0; } private: struct ndn_BinaryXMLStructureDecoder base_; }; } #endif /* BINARYXMLSTRUCTUREDECODER_HPP */ <|endoftext|>
<commit_before>/* WPN-XM Server Control Panel WPN-XM SCP is a tool to manage Nginx, PHP and MariaDb daemons under windows. It's a fork of Easy WEMP originally written by Yann Le Moigne and (c) 2010. WPN-XM SCP is written by Jens-Andre Koch and (c) 2011 - onwards. This file is part of WPN-XM Serverpack for Windows. WPN-XM SCP 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. WPN-XM SCP 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 WPN-XM SCP. If not, see <http://www.gnu.org/licenses/>. */ // QT includes #include <QApplication> #include <QObject> #include <QSystemTrayIcon> #include <QMessageBox> #include <QSharedMemory> #include <QtGui> // WPN-XM SCP includes #include "main.h" #include "mainwindow.h" // main method int main(int argc, char * argv[]) { // Single Instance Check exitIfAlreadyRunning(); Q_INIT_RESOURCE(Resources); QApplication application(argc, argv); // Application Meta Data application.setApplicationName(APP_NAME); application.setApplicationVersion(APP_VERSION); application.setOrganizationName("Jens-Andr Koch"); application.setOrganizationDomain("http://wpn-xm.org/"); application.setWindowIcon(QIcon(":/wpnxm")); // if setStyle() is not used, the submenus are not displayed properly. bug? //application.setStyle("windowsxp"); // do not leave until Quit is clicked in the tray menu application.setQuitOnLastWindowClosed(false); MainWindow mainWindow; mainWindow.show(); qDebug() << APP_NAME; qDebug() << APP_VERSION; // enter the Qt Event loop here return application.exec(); } /* * Single Instance Check * Although some people tend to solve this problem by using QtSingleApplication, * this approach uses a GUID stored into shared memory. */ void exitIfAlreadyRunning() { // Set GUID for WPN-XM Server Control Panel to memory QSharedMemory shared("004d54f6-7d00-4478-b612-f242f081b023"); // already running if( !shared.create( 512, QSharedMemory::ReadWrite) ) { QMessageBox msgBox; msgBox.setWindowTitle(APP_NAME); msgBox.setText( QObject::tr("WPN-XM is already running.") ); msgBox.setIcon( QMessageBox::Critical ); msgBox.exec(); exit(0); } else { qDebug() << "Application started and not already running."; } } <commit_msg>fixed exitIfAlreadyRunning() method<commit_after>/* WPN-XM Server Control Panel WPN-XM SCP is a tool to manage Nginx, PHP and MariaDb daemons under windows. It's a fork of Easy WEMP originally written by Yann Le Moigne and (c) 2010. WPN-XM SCP is written by Jens-Andre Koch and (c) 2011 - onwards. This file is part of WPN-XM Serverpack for Windows. WPN-XM SCP 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. WPN-XM SCP 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 WPN-XM SCP. If not, see <http://www.gnu.org/licenses/>. */ // QT includes #include <QApplication> #include <QObject> #include <QSystemTrayIcon> #include <QMessageBox> #include <QSharedMemory> #include <QtGui> // WPN-XM SCP includes #include "main.h" #include "mainwindow.h" // main method int main(int argc, char * argv[]) { Q_INIT_RESOURCE(Resources); QApplication application(argc, argv); // Single Instance Check exitIfAlreadyRunning(); // Application Meta Data application.setApplicationName(APP_NAME); application.setApplicationVersion(APP_VERSION); application.setOrganizationName("Jens-Andr Koch"); application.setOrganizationDomain("http://wpn-xm.org/"); application.setWindowIcon(QIcon(":/wpnxm")); // if setStyle() is not used, the submenus are not displayed properly. bug? //application.setStyle("windowsxp"); // do not leave until Quit is clicked in the tray menu application.setQuitOnLastWindowClosed(false); MainWindow mainWindow; mainWindow.show(); qDebug() << APP_NAME; qDebug() << APP_VERSION; // enter the Qt Event loop here return application.exec(); } /* * Single Instance Check * Although some people tend to solve this problem by using QtSingleApplication, * this approach uses a GUID stored into shared memory. */ void exitIfAlreadyRunning() { // Set GUID for WPN-XM Server Control Panel to memory // It needs to be "static", because the QSharedMemory instance gets destroyed // at the end of the function and so does the shared memory segment. static QSharedMemory shared("004d54f6-7d00-4478-b612-f242f081b023"); // already running if( !shared.create( 512, QSharedMemory::ReadWrite) ) { QMessageBox msgBox; msgBox.setWindowTitle(APP_NAME); msgBox.setText( QObject::tr("WPN-XM is already running.") ); msgBox.setIcon( QMessageBox::Critical ); msgBox.exec(); exit(0); } else { qDebug() << "Application started and not already running."; } } <|endoftext|>
<commit_before>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */ /** * Copyright (C) 2013 Regents of the University of California. * @author: Yingdi Yu <yingdi@cs.ucla.edu> * @author: Jeff Thompson <jefft0@remap.ucla.edu> * See COPYING for copyright and distribution information. */ #if 1 // TODO: Remove this when we don't throw "not implemented". #include <stdexcept> #endif #include <ndn-cpp/ndn-cpp-config.h> #if NDN_CPP_HAVE_TIME_H #include <time.h> #endif #if NDN_CPP_HAVE_SYS_TIME_H #include <sys/time.h> #endif #include <ctime> #include <fstream> #include <math.h> #include <ndn-cpp/key.hpp> #include <ndn-cpp/sha256-with-rsa-signature.hpp> #include <ndn-cpp/security/security-exception.hpp> #include "../../util/logging.hpp" #include "../../c/util/time.h" #include <ndn-cpp/security/identity/identity-manager.hpp> INIT_LOGGER("ndn.security.IdentityManager") using namespace std; using namespace ndn::ptr_lib; namespace ndn { Name IdentityManager::createIdentity(const Name& identityName) { if (!identityStorage_->doesIdentityExist(identityName)) { _LOG_DEBUG("Create Identity"); identityStorage_->addIdentity(identityName); _LOG_DEBUG("Create Default RSA key pair"); Name keyName = generateRSAKeyPairAsDefault(identityName, true); _LOG_DEBUG("Create self-signed certificate"); shared_ptr<IdentityCertificate> selfCert = selfSign(keyName); _LOG_DEBUG("Add self-signed certificate as default"); addCertificateAsDefault(*selfCert); return keyName; } else throw SecurityException("Identity has already been created!"); } Name IdentityManager::generateKeyPair(const Name& identityName, bool isKsk, KeyType keyType, int keySize) { _LOG_DEBUG("Get new key ID"); Name keyName = identityStorage_->getNewKeyName(identityName, isKsk); _LOG_DEBUG("Generate key pair in private storage"); privateKeyStorage_->generateKeyPair(keyName.toUri(), keyType, keySize); _LOG_DEBUG("Create a key record in public storage"); shared_ptr<PublicKey> pubKey = privateKeyStorage_->getPublicKey(keyName.toUri()); identityStorage_->addKey(keyName, keyType, pubKey->getKeyDer()); _LOG_DEBUG("OK"); return keyName; } Name IdentityManager::generateRSAKeyPair(const Name& identityName, bool isKsk, int keySize) { Name keyName = generateKeyPair(identityName, isKsk, KEY_TYPE_RSA, keySize); _LOG_DEBUG("OK2"); return keyName; } Name IdentityManager::generateRSAKeyPairAsDefault(const Name& identityName, bool isKsk, int keySize) { Name keyName = generateKeyPair(identityName, isKsk, KEY_TYPE_RSA, keySize); identityStorage_->setDefaultKeyNameForIdentity(keyName, identityName); return keyName; } Name IdentityManager::createIdentityCertificate(const Name& keyName, const Name& signerCertificateName, const MillisecondsSince1970& notBefore, const MillisecondsSince1970& notAfter) { Blob keyBlob = identityStorage_->getKey(keyName); shared_ptr<PublicKey> publicKey = PublicKey::fromDer(keyBlob); shared_ptr<IdentityCertificate> certificate = createIdentityCertificate (keyName, *publicKey, signerCertificateName, notBefore, notAfter); identityStorage_->addCertificate(*certificate); return certificate->getName(); } ptr_lib::shared_ptr<IdentityCertificate> IdentityManager::createIdentityCertificate (const Name& keyName, const PublicKey& publicKey, const Name& signerCertificateName, const MillisecondsSince1970& notBefore, const MillisecondsSince1970& notAfter) { shared_ptr<IdentityCertificate> certificate(new IdentityCertificate()); Name certificateName; MillisecondsSince1970 ti = ::ndn_getNowMilliseconds(); // Get the number of seconds. ostringstream oss; oss << floor(ti / 1000.0); certificateName.append(keyName).append("ID-CERT").append(oss.str()); certificate->setName(certificateName); certificate->setNotBefore(notBefore); certificate->setNotAfter(notAfter); certificate->setPublicKeyInfo(publicKey); certificate->addSubjectDescription(CertificateSubjectDescription("2.5.4.41", keyName.toUri())); certificate->encode(); shared_ptr<Sha256WithRsaSignature> sha256Sig(new Sha256WithRsaSignature()); KeyLocator keyLocator; keyLocator.setType(ndn_KeyLocatorType_KEYNAME); keyLocator.setKeyName(signerCertificateName); sha256Sig->setKeyLocator(keyLocator); sha256Sig->getPublisherPublicKeyDigest().setPublisherPublicKeyDigest(publicKey.getDigest()); certificate->setSignature(*sha256Sig); SignedBlob unsignedData = certificate->wireEncode(); Blob sigBits = privateKeyStorage_->sign(unsignedData, keyName); sha256Sig->setSignature(sigBits); return certificate; } void IdentityManager::addCertificateAsDefault(const IdentityCertificate& certificate) { identityStorage_->addCertificate(certificate); Name keyName = identityStorage_->getKeyNameForCertificate(certificate.getName()); setDefaultKeyForIdentity(keyName); setDefaultCertificateForKey(certificate.getName()); } void IdentityManager::setDefaultCertificateForKey(const Name& certificateName) { Name keyName = identityStorage_->getKeyNameForCertificate(certificateName); if(!identityStorage_->doesKeyExist(keyName)) throw SecurityException("No corresponding Key record for certificaite!"); identityStorage_->setDefaultCertificateNameForKey(keyName, certificateName); } ptr_lib::shared_ptr<Signature> IdentityManager::signByCertificate(const uint8_t* data, size_t dataLength, const Name& certificateName) { Name keyName = identityStorage_->getKeyNameForCertificate(certificateName); shared_ptr<PublicKey> publicKey = privateKeyStorage_->getPublicKey(keyName.toUri()); Blob sigBits = privateKeyStorage_->sign(data, dataLength, keyName.toUri()); //For temporary usage, we support RSA + SHA256 only, but will support more. shared_ptr<Sha256WithRsaSignature> sha256Sig(new Sha256WithRsaSignature()); KeyLocator keyLocator; keyLocator.setType(ndn_KeyLocatorType_KEYNAME); keyLocator.setKeyName(certificateName); sha256Sig->setKeyLocator(keyLocator); sha256Sig->getPublisherPublicKeyDigest().setPublisherPublicKeyDigest(publicKey->getDigest()); sha256Sig->setSignature(sigBits); return sha256Sig; } void IdentityManager::signByCertificate(Data &data, const Name &certificateName, WireFormat& wireFormat) { Name keyName = identityStorage_->getKeyNameForCertificate(certificateName); shared_ptr<PublicKey> publicKey = privateKeyStorage_->getPublicKey(keyName); // For temporary usage, we support RSA + SHA256 only, but will support more. data.setSignature(Sha256WithRsaSignature()); // Get a pointer to the clone which Data made. Sha256WithRsaSignature *signature = dynamic_cast<Sha256WithRsaSignature*>(data.getSignature()); DigestAlgorithm digestAlgorithm = DIGEST_ALGORITHM_SHA256; signature->getKeyLocator().setType(ndn_KeyLocatorType_KEYNAME); signature->getKeyLocator().setKeyName(certificateName); // Omit the certificate digest. signature->getKeyLocator().setKeyNameType((ndn_KeyNameType)-1); // Ignore witness and leave the digestAlgorithm as the default. signature->getPublisherPublicKeyDigest().setPublisherPublicKeyDigest(publicKey->getDigest()); // Encode once to get the signed portion. SignedBlob encoding = data.wireEncode(wireFormat); signature->setSignature (privateKeyStorage_->sign(encoding.signedBuf(), encoding.signedSize(), keyName, digestAlgorithm)); // Encode again to include the signature. data.wireEncode(wireFormat); } shared_ptr<IdentityCertificate> IdentityManager::selfSign(const Name& keyName) { shared_ptr<IdentityCertificate> certificate(new IdentityCertificate()); Name certificateName; certificateName.append(keyName).append("ID-CERT").append("0"); certificate->setName(certificateName); Blob keyBlob = identityStorage_->getKey(keyName); shared_ptr<PublicKey> publicKey = PublicKey::fromDer(keyBlob); #if NDN_CPP_HAVE_GMTIME_SUPPORT time_t nowSeconds = time(NULL); struct tm current = *gmtime(&nowSeconds); current.tm_hour = 0; current.tm_min = 0; current.tm_sec = 0; MillisecondsSince1970 notBefore = timegm(&current) * 1000.0; current.tm_year = current.tm_year + 20; MillisecondsSince1970 notAfter = timegm(&current) * 1000.0; certificate->setNotBefore(notBefore); certificate->setNotAfter(notAfter); #else // Don't really expect this to happen. throw SecurityException("selfSign: Can't set certificate validity because time functions are not supported by the standard library."); #endif certificate->setPublicKeyInfo(*publicKey); certificate->addSubjectDescription(CertificateSubjectDescription("2.5.4.41", keyName.toUri())); certificate->encode(); shared_ptr<Sha256WithRsaSignature> sha256Sig(new Sha256WithRsaSignature()); KeyLocator keyLocator; keyLocator.setType(ndn_KeyLocatorType_KEYNAME); keyLocator.setKeyName(certificateName); sha256Sig->setKeyLocator(keyLocator); sha256Sig->getPublisherPublicKeyDigest().setPublisherPublicKeyDigest(publicKey->getDigest()); certificate->setSignature(*sha256Sig); Blob unsignedData = certificate->wireEncode(); Blob sigBits = privateKeyStorage_->sign(unsignedData, keyName.toUri()); sha256Sig->setSignature(sigBits); return certificate; } } <commit_msg>security: Clean up IdentityManager: remove unused #include <stdexcept>.<commit_after>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */ /** * Copyright (C) 2013 Regents of the University of California. * @author: Yingdi Yu <yingdi@cs.ucla.edu> * @author: Jeff Thompson <jefft0@remap.ucla.edu> * See COPYING for copyright and distribution information. */ #include <ndn-cpp/ndn-cpp-config.h> #if NDN_CPP_HAVE_TIME_H #include <time.h> #endif #if NDN_CPP_HAVE_SYS_TIME_H #include <sys/time.h> #endif #include <ctime> #include <fstream> #include <math.h> #include <ndn-cpp/key.hpp> #include <ndn-cpp/sha256-with-rsa-signature.hpp> #include <ndn-cpp/security/security-exception.hpp> #include "../../util/logging.hpp" #include "../../c/util/time.h" #include <ndn-cpp/security/identity/identity-manager.hpp> INIT_LOGGER("ndn.security.IdentityManager") using namespace std; using namespace ndn::ptr_lib; namespace ndn { Name IdentityManager::createIdentity(const Name& identityName) { if (!identityStorage_->doesIdentityExist(identityName)) { _LOG_DEBUG("Create Identity"); identityStorage_->addIdentity(identityName); _LOG_DEBUG("Create Default RSA key pair"); Name keyName = generateRSAKeyPairAsDefault(identityName, true); _LOG_DEBUG("Create self-signed certificate"); shared_ptr<IdentityCertificate> selfCert = selfSign(keyName); _LOG_DEBUG("Add self-signed certificate as default"); addCertificateAsDefault(*selfCert); return keyName; } else throw SecurityException("Identity has already been created!"); } Name IdentityManager::generateKeyPair(const Name& identityName, bool isKsk, KeyType keyType, int keySize) { _LOG_DEBUG("Get new key ID"); Name keyName = identityStorage_->getNewKeyName(identityName, isKsk); _LOG_DEBUG("Generate key pair in private storage"); privateKeyStorage_->generateKeyPair(keyName.toUri(), keyType, keySize); _LOG_DEBUG("Create a key record in public storage"); shared_ptr<PublicKey> pubKey = privateKeyStorage_->getPublicKey(keyName.toUri()); identityStorage_->addKey(keyName, keyType, pubKey->getKeyDer()); _LOG_DEBUG("OK"); return keyName; } Name IdentityManager::generateRSAKeyPair(const Name& identityName, bool isKsk, int keySize) { Name keyName = generateKeyPair(identityName, isKsk, KEY_TYPE_RSA, keySize); _LOG_DEBUG("OK2"); return keyName; } Name IdentityManager::generateRSAKeyPairAsDefault(const Name& identityName, bool isKsk, int keySize) { Name keyName = generateKeyPair(identityName, isKsk, KEY_TYPE_RSA, keySize); identityStorage_->setDefaultKeyNameForIdentity(keyName, identityName); return keyName; } Name IdentityManager::createIdentityCertificate(const Name& keyName, const Name& signerCertificateName, const MillisecondsSince1970& notBefore, const MillisecondsSince1970& notAfter) { Blob keyBlob = identityStorage_->getKey(keyName); shared_ptr<PublicKey> publicKey = PublicKey::fromDer(keyBlob); shared_ptr<IdentityCertificate> certificate = createIdentityCertificate (keyName, *publicKey, signerCertificateName, notBefore, notAfter); identityStorage_->addCertificate(*certificate); return certificate->getName(); } ptr_lib::shared_ptr<IdentityCertificate> IdentityManager::createIdentityCertificate (const Name& keyName, const PublicKey& publicKey, const Name& signerCertificateName, const MillisecondsSince1970& notBefore, const MillisecondsSince1970& notAfter) { shared_ptr<IdentityCertificate> certificate(new IdentityCertificate()); Name certificateName; MillisecondsSince1970 ti = ::ndn_getNowMilliseconds(); // Get the number of seconds. ostringstream oss; oss << floor(ti / 1000.0); certificateName.append(keyName).append("ID-CERT").append(oss.str()); certificate->setName(certificateName); certificate->setNotBefore(notBefore); certificate->setNotAfter(notAfter); certificate->setPublicKeyInfo(publicKey); certificate->addSubjectDescription(CertificateSubjectDescription("2.5.4.41", keyName.toUri())); certificate->encode(); shared_ptr<Sha256WithRsaSignature> sha256Sig(new Sha256WithRsaSignature()); KeyLocator keyLocator; keyLocator.setType(ndn_KeyLocatorType_KEYNAME); keyLocator.setKeyName(signerCertificateName); sha256Sig->setKeyLocator(keyLocator); sha256Sig->getPublisherPublicKeyDigest().setPublisherPublicKeyDigest(publicKey.getDigest()); certificate->setSignature(*sha256Sig); SignedBlob unsignedData = certificate->wireEncode(); Blob sigBits = privateKeyStorage_->sign(unsignedData, keyName); sha256Sig->setSignature(sigBits); return certificate; } void IdentityManager::addCertificateAsDefault(const IdentityCertificate& certificate) { identityStorage_->addCertificate(certificate); Name keyName = identityStorage_->getKeyNameForCertificate(certificate.getName()); setDefaultKeyForIdentity(keyName); setDefaultCertificateForKey(certificate.getName()); } void IdentityManager::setDefaultCertificateForKey(const Name& certificateName) { Name keyName = identityStorage_->getKeyNameForCertificate(certificateName); if(!identityStorage_->doesKeyExist(keyName)) throw SecurityException("No corresponding Key record for certificaite!"); identityStorage_->setDefaultCertificateNameForKey(keyName, certificateName); } ptr_lib::shared_ptr<Signature> IdentityManager::signByCertificate(const uint8_t* data, size_t dataLength, const Name& certificateName) { Name keyName = identityStorage_->getKeyNameForCertificate(certificateName); shared_ptr<PublicKey> publicKey = privateKeyStorage_->getPublicKey(keyName.toUri()); Blob sigBits = privateKeyStorage_->sign(data, dataLength, keyName.toUri()); //For temporary usage, we support RSA + SHA256 only, but will support more. shared_ptr<Sha256WithRsaSignature> sha256Sig(new Sha256WithRsaSignature()); KeyLocator keyLocator; keyLocator.setType(ndn_KeyLocatorType_KEYNAME); keyLocator.setKeyName(certificateName); sha256Sig->setKeyLocator(keyLocator); sha256Sig->getPublisherPublicKeyDigest().setPublisherPublicKeyDigest(publicKey->getDigest()); sha256Sig->setSignature(sigBits); return sha256Sig; } void IdentityManager::signByCertificate(Data &data, const Name &certificateName, WireFormat& wireFormat) { Name keyName = identityStorage_->getKeyNameForCertificate(certificateName); shared_ptr<PublicKey> publicKey = privateKeyStorage_->getPublicKey(keyName); // For temporary usage, we support RSA + SHA256 only, but will support more. data.setSignature(Sha256WithRsaSignature()); // Get a pointer to the clone which Data made. Sha256WithRsaSignature *signature = dynamic_cast<Sha256WithRsaSignature*>(data.getSignature()); DigestAlgorithm digestAlgorithm = DIGEST_ALGORITHM_SHA256; signature->getKeyLocator().setType(ndn_KeyLocatorType_KEYNAME); signature->getKeyLocator().setKeyName(certificateName); // Omit the certificate digest. signature->getKeyLocator().setKeyNameType((ndn_KeyNameType)-1); // Ignore witness and leave the digestAlgorithm as the default. signature->getPublisherPublicKeyDigest().setPublisherPublicKeyDigest(publicKey->getDigest()); // Encode once to get the signed portion. SignedBlob encoding = data.wireEncode(wireFormat); signature->setSignature (privateKeyStorage_->sign(encoding.signedBuf(), encoding.signedSize(), keyName, digestAlgorithm)); // Encode again to include the signature. data.wireEncode(wireFormat); } shared_ptr<IdentityCertificate> IdentityManager::selfSign(const Name& keyName) { shared_ptr<IdentityCertificate> certificate(new IdentityCertificate()); Name certificateName; certificateName.append(keyName).append("ID-CERT").append("0"); certificate->setName(certificateName); Blob keyBlob = identityStorage_->getKey(keyName); shared_ptr<PublicKey> publicKey = PublicKey::fromDer(keyBlob); #if NDN_CPP_HAVE_GMTIME_SUPPORT time_t nowSeconds = time(NULL); struct tm current = *gmtime(&nowSeconds); current.tm_hour = 0; current.tm_min = 0; current.tm_sec = 0; MillisecondsSince1970 notBefore = timegm(&current) * 1000.0; current.tm_year = current.tm_year + 20; MillisecondsSince1970 notAfter = timegm(&current) * 1000.0; certificate->setNotBefore(notBefore); certificate->setNotAfter(notAfter); #else // Don't really expect this to happen. throw SecurityException("selfSign: Can't set certificate validity because time functions are not supported by the standard library."); #endif certificate->setPublicKeyInfo(*publicKey); certificate->addSubjectDescription(CertificateSubjectDescription("2.5.4.41", keyName.toUri())); certificate->encode(); shared_ptr<Sha256WithRsaSignature> sha256Sig(new Sha256WithRsaSignature()); KeyLocator keyLocator; keyLocator.setType(ndn_KeyLocatorType_KEYNAME); keyLocator.setKeyName(certificateName); sha256Sig->setKeyLocator(keyLocator); sha256Sig->getPublisherPublicKeyDigest().setPublisherPublicKeyDigest(publicKey->getDigest()); certificate->setSignature(*sha256Sig); Blob unsignedData = certificate->wireEncode(); Blob sigBits = privateKeyStorage_->sign(unsignedData, keyName.toUri()); sha256Sig->setSignature(sigBits); return certificate; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2010 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "User.h" #include "znc.h" class CFOModule : public CModule { public: MODCONSTRUCTOR(CFOModule) {} virtual ~CFOModule() {} bool IsOnlineModNick(const CString& sNick) { const CString& sPrefix = m_pUser->GetStatusPrefix(); if (!sNick.Equals(sPrefix, false, sPrefix.length())) return false; CString sModNick = sNick.substr(sPrefix.length()); if (!sModNick.Equals("status") && !m_pUser->GetModules().FindModule(sModNick) && !CZNC::Get().GetModules().FindModule(sModNick)) return false; return true; } virtual EModRet OnUserRaw(CString& sLine) { //Handle ISON if (sLine.Token(0).Equals("ison")) { VCString vsNicks; VCString::const_iterator it; // Get the list of nicks which are being asked for sLine.Token(1, true).TrimLeft_n(":").Split(" ", vsNicks, false); CString sBNCNicks = ""; for (it = vsNicks.begin(); it != vsNicks.end(); ++it) { if (IsOnlineModNick(*it)) { sBNCNicks += " " + *it; } } // Remove the leading space sBNCNicks.LeftChomp(); // We let the server handle this request and then act on // the 303 response. m_ISONRequests.push_back(sBNCNicks); } //Handle WHOIS if (sLine.Token(0).Equals("whois")) { CString sNick = sLine.Token(1); if (IsOnlineModNick(sNick)) { PutUser(":znc.in 311 " + m_pUser->GetCurNick() + " " + sNick + " " + sNick + " znc.in * :" + sNick); PutUser(":znc.in 312 " + m_pUser->GetCurNick() + " " + sNick + " *.znc.in :Bouncer"); PutUser(":znc.in 318 " + m_pUser->GetCurNick() + " " + sNick + " :End of /WHOIS list."); return HALT; } } return CONTINUE; } virtual EModRet OnRaw(CString& sLine) { //Handle 303 reply if m_Requests is not empty if (sLine.Token(1) == "303" && !m_ISONRequests.empty()) { VCString::iterator it = m_ISONRequests.begin(); sLine.Trim(); // Only append a space if this isn't an empty reply if (sLine.Right(1) != ":") { sLine += " "; } //add BNC nicks to the reply sLine += *it; m_ISONRequests.erase(it); } return CONTINUE; } private: VCString m_ISONRequests; }; MODULEDEFS(CFOModule, "Fakes online status of ZNC *-users.") <commit_msg>Made fakeonline behave properly when ZNC is not connected to any IRC server. Reported by devilspgd's imaginary girl friend. Patch by MEEEEE!!<commit_after>/* * Copyright (C) 2008-2010 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "User.h" #include "znc.h" class CFOModule : public CModule { public: MODCONSTRUCTOR(CFOModule) {} virtual ~CFOModule() {} bool IsOnlineModNick(const CString& sNick) { const CString& sPrefix = m_pUser->GetStatusPrefix(); if (!sNick.Equals(sPrefix, false, sPrefix.length())) return false; CString sModNick = sNick.substr(sPrefix.length()); if (!sModNick.Equals("status") && !m_pUser->GetModules().FindModule(sModNick) && !CZNC::Get().GetModules().FindModule(sModNick)) return false; return true; } virtual EModRet OnUserRaw(CString& sLine) { //Handle ISON if (sLine.Token(0).Equals("ison")) { VCString vsNicks; VCString::const_iterator it; // Get the list of nicks which are being asked for sLine.Token(1, true).TrimLeft_n(":").Split(" ", vsNicks, false); CString sBNCNicks; for (it = vsNicks.begin(); it != vsNicks.end(); ++it) { if (IsOnlineModNick(*it)) { sBNCNicks += " " + *it; } } // Remove the leading space sBNCNicks.LeftChomp(); if (!m_pUser->GetIRCSock()) { // if we are not connected to any IRC server, send // an empty or module-nick filled response. PutUser(":irc.znc.in 303 " + m_pUser->GetNick() + " :" + sBNCNicks); } else { // We let the server handle this request and then act on // the 303 response from the IRC server. m_ISONRequests.push_back(sBNCNicks); } } //Handle WHOIS if (sLine.Token(0).Equals("whois")) { CString sNick = sLine.Token(1); if (IsOnlineModNick(sNick)) { PutUser(":znc.in 311 " + m_pUser->GetCurNick() + " " + sNick + " " + sNick + " znc.in * :" + sNick); PutUser(":znc.in 312 " + m_pUser->GetCurNick() + " " + sNick + " *.znc.in :Bouncer"); PutUser(":znc.in 318 " + m_pUser->GetCurNick() + " " + sNick + " :End of /WHOIS list."); return HALT; } } return CONTINUE; } virtual EModRet OnRaw(CString& sLine) { //Handle 303 reply if m_Requests is not empty if (sLine.Token(1) == "303" && !m_ISONRequests.empty()) { VCString::iterator it = m_ISONRequests.begin(); sLine.Trim(); // Only append a space if this isn't an empty reply if (sLine.Right(1) != ":") { sLine += " "; } //add BNC nicks to the reply sLine += *it; m_ISONRequests.erase(it); } return CONTINUE; } private: VCString m_ISONRequests; }; MODULEDEFS(CFOModule, "Fakes online status of ZNC *-users.") <|endoftext|>
<commit_before>/* * BayesianClassifier.cpp * * Created on: Mar 20, 2009 * Author: Simon Lavigne-Giroux */ #include "BayesianClassifier.h" #include <fstream> #define WRITE_PROGRESS 1 #if WRITE_PROGRESS #include <iostream> #endif // The threshold to get to select whether an output is valid #define outputProbabilityTreshold 0.003f // There is a minimum denominator value to remove the possibility of INF and NaN #define minimumDenominatorValue 0.0000000001 /** * BayesianClassifier constructor. It constructs the classifier with raw training data from the file * and uses domains to generate discrete values (TrainingData). * * Beware : The file must not have an empty line at the end. */ BayesianClassifier::BayesianClassifier(std::string filename, std::vector<Domain> const &_domains) : max_number_of_domain_values(0) { domains = _domains; numberOfColumns = _domains.size(); constructClassifier(filename); } /** * BayesianClassifier constructor. It constructs a classifier with the specified domain. * Raw training data are not given, it is possible to add data after the construction. */ BayesianClassifier::BayesianClassifier(std::vector<Domain> const &_domains) : max_number_of_domain_values(0) { domains = _domains; numberOfColumns = _domains.size(); calculateProbabilitiesOfInputs(); calculateProbabilitiesOfOutputs(); numberOfTrainingData = data.size(); data.clear(); } /** * Construct the classifier from the RawTrainingData in the file. * * Beware : The file must not have an empty line at the end. */ void BayesianClassifier::constructClassifier(std::string const &filename) { std::ifstream inputFile(filename.c_str()); while (!inputFile.eof()) { TrainingData trainingData; float value; for (int i = 0; i < numberOfColumns; ++i) { inputFile >> value; trainingData.push_back(domains[i].calculateDiscreteValue(value)); } data.push_back(trainingData); } inputFile.close(); calculateProbabilitiesOfInputs(); calculateProbabilitiesOfOutputs(); numberOfTrainingData = data.size(); data.clear(); } /** * Calculate the probabilities for each possibility of inputs. */ void BayesianClassifier::calculateProbabilitiesOfInputs() { // pre-allocate the vector for the input probabilities size_t count = 0; for (int i = 0; i < numberOfColumns - 1; ++i) { max_number_of_domain_values = std::max(max_number_of_domain_values, domains[i].getNumberOfValues()); for (int j = 0; j < domains[i].getNumberOfValues(); ++j) ++count; } #if WRITE_PROGRESS std::cout.imbue(std::locale("")); std::cout << "\nInput probability array is " << (count * getOutputDomain().getNumberOfValues() * sizeof(std::pair<unsigned long const, float>))/1024 << " Kb" << std::flush; #endif probabilitiesOfInputs.reserve(count * getOutputDomain().getNumberOfValues()); // if we don't have any initialization data, then there is // no calculation of the initial probabilities, and we can // populate the vector much more quickly if (data.size() == 0) calculateProbabilitiesOfInputsWithoutData(); else { for (int k = 0; k < getOutputDomain().getNumberOfValues(); ++k) for (int i = 0; i < numberOfColumns - 1; ++i) for (int j = 0; j < domains[i].getNumberOfValues(); ++j) calculateProbability(i, j, k); } #if USE_VECTOR_MAP assert(probabilitiesOfInputs.is_sorted()); assert(probabilitiesOfInputs.size() == probabilitiesOfInputs.capacity()); #endif } void BayesianClassifier::calculateProbabilitiesOfInputsWithoutData() { for (int k = 0; k < getOutputDomain().getNumberOfValues(); ++k) { for (int i = 0; i < numberOfColumns - 1; ++i) { for (int j = 0; j < domains[i].getNumberOfValues(); ++j) { unsigned long key = calculateMapKey(i, j, k); #if USE_VECTOR_MAP probabilitiesOfInputs.emplace_back(key, 0.0f); #else probabilitiesOfInputs[key] = 0.0f; #endif } } } } /** * Calculate the probability of P(effectColum:effectValue | lastColumn:causeValue) * It saves data into the variable probabilitiesOfInputs. */ void BayesianClassifier::calculateProbability(int effectColumn, int effectValue, int causeValue) { // The numerator is the number of TrainingData with this effectValue given this causeValue float numerator = 0.0; // The denominator is the number of TrainingData with this causeValue float denominator = 0.0; //Calculate the numerator and denominator by scanning the TrainingData for (unsigned int i = 0; i < data.size(); ++i) { TrainingData const &trainingData = data[i]; if (trainingData[numberOfColumns - 1] == causeValue) { denominator++; if (trainingData[effectColumn] == effectValue) { numerator++; } } } float probability = 0.0; if (denominator != 0) { probability = numerator / denominator; } unsigned long key = calculateMapKey(effectColumn, effectValue, causeValue); #if USE_VECTOR_MAP probabilitiesOfInputs.emplace_back(key, probability); #else probabilitiesOfInputs[key] = probability; #endif } /** * Calculate P(Output) of each output. * It saves data into the variable probabilitiesOfOuputs. */ void BayesianClassifier::calculateProbabilitiesOfOutputs() { probabilitiesOfOutputs.resize(getOutputDomain().getNumberOfValues()); if (data.size() == 0) return; for (int i = 0; i < getOutputDomain().getNumberOfValues(); ++i) { float count = 0.0; for (unsigned int j = 0; j < data.size(); ++j) { if (data[j][numberOfColumns - 1] == i) { count++; } } probabilitiesOfOutputs[i] = count / (float) data.size(); } } /** * Calculate the map key for each value in the variable probabilitiesOfInputs */ unsigned long BayesianClassifier::calculateMapKey(int effectColumn, int effectValue, int causeValue) const { if (max_number_of_domain_values == 0) throw std::logic_error("BayesianClassifier::calculateMapKey called before initialisation of max_number_of_domain_values"); size_t effect_column = effectColumn; effect_column *= max_number_of_domain_values; size_t cause_value = causeValue; cause_value *= (numberOfColumns - 1) * max_number_of_domain_values; // assert our cast is valid if (causeValue * 100000UL + effectColumn * 100 + effectValue > (size_t)std::numeric_limits<unsigned long>::max()) throw overflow_exception(); return (unsigned long)(effect_column + effectValue + cause_value); } /** * Calculate the most probable output given this input with this formula : * P(Output | Input) = 1/Z * P(Output) * P(InputValue1 | Ouput) * P(InputValue2 | Ouput) * ... * The output with the highest probability is returned. */ int BayesianClassifier::calculateOutput(std::vector<float> const &input) { float highestProbability = outputProbabilityTreshold; int highestOutput = rand() % getOutputDomain().getNumberOfValues(); unsigned long key = 0; for (int i = 0; i < getOutputDomain().getNumberOfValues(); ++i) { float probability = probabilitiesOfOutputs[i]; for (unsigned int j = 0; j < input.size(); ++j) { key = calculateMapKey(j, domains[j].calculateDiscreteValue(input[j]), i); probability *= probabilitiesOfInputs[key]; } if (probability > highestProbability) { highestProbability = probability; highestOutput = i; } } return highestOutput; } /** * calculate all possible outputs */ std::vector<std::pair<int, float>> BayesianClassifier::calculatePossibleOutputs(std::vector<float> const &input) const { std::vector<std::pair<int, float>> outputs; size_t key_offset = 0; for(int i = 0; i < numberOfColumns - 1; ++i) { for(int j = 0; j < domains[i].getNumberOfValues(); ++j) ++key_offset; } float const threshold = outputProbabilityTreshold; for (int i = 0; i < getOutputDomain().getNumberOfValues(); ++i) { float probability = probabilitiesOfOutputs[i]; auto key_it = probabilitiesOfInputs.cbegin() + i * key_offset; for (unsigned int j = 0; j < input.size() && probability > threshold; j++, key_it += domains[i].getNumberOfValues()) { // if this assert fails, then the key_it is not finding the correct key, ie the // same key as would be returned by calling // probabilitiesOfInputs.find(calculateMapKey(j, domains[j].calculateDiscreteValue(input[j]), i)); assert((key_it + domains[j].calculateDiscreteValue(input[j]))->first == calculateMapKey(j, domains[j].calculateDiscreteValue(input[j]), i)); probability *= (key_it + domains[j].calculateDiscreteValue(input[j]))->second; } if (probability > threshold) outputs.emplace_back(i, probability); } return outputs; } /** * Calculate the probability of this output given this input. * P(Output | Input) = 1/Z * P(Output) * P(InputValue1 | Ouput) * P(InputValue2 | Ouput) * ... */ float BayesianClassifier::calculateProbabilityOfOutput(std::vector<float> const &input, float output) { unsigned long key = 0; std::vector<float> probabilities; for(int i = 0; i < getOutputDomain().getNumberOfValues(); ++i) { float probability = probabilitiesOfOutputs[i]; for (unsigned int j = 0; j < input.size(); ++j) { key = calculateMapKey(j, domains[j].calculateDiscreteValue(input[j]), i); probability *= probabilitiesOfInputs[key]; } probabilities.push_back(probability); } float sumOfProbabilities = 0.0; for(unsigned int i = 0; i < probabilities.size(); ++i) { sumOfProbabilities += probabilities[i]; } float alpha = 0.0; if(sumOfProbabilities > minimumDenominatorValue) { alpha = 1.0f / sumOfProbabilities; } float probability = probabilities[getOutputDomain().calculateDiscreteValue(output)]*alpha; if(probability > 1.0f) { return 1.0f; } else { return probability; } } /** * Add raw training data from a file to adapt the classifier. * It updates the variables containing the probabilities. * * Beware : The file must not have an empty line at the end. */ void BayesianClassifier::addRawTrainingData(std::string const &filename) { std::ifstream inputFile(filename.c_str()); while (!inputFile.eof()) { RawTrainingData rawTrainingData; float value; for (int i = 0; i < numberOfColumns; ++i) { inputFile >> value; rawTrainingData.push_back(value); } addRawTrainingData(rawTrainingData); } inputFile.close(); } /** * Add one set of raw training data to adapt the classifier * It updates the variables containing the probabilities. */ void BayesianClassifier::addRawTrainingData(RawTrainingData const &rawTrainingData){ std::vector<int> trainingData = convertRawTrainingData(rawTrainingData); updateProbabilities(trainingData); updateOutputProbabilities(domains[numberOfColumns-1].calculateDiscreteValue(rawTrainingData[numberOfColumns - 1])); numberOfTrainingData++; } /** * Convert a vector<float> into a vector<int> by discretizing the values * using the domain for each column. */ TrainingData BayesianClassifier::convertRawTrainingData(RawTrainingData const &floatVector) { TrainingData trainingData; trainingData.reserve(floatVector.size()); for(unsigned int i = 0; i < floatVector.size(); ++i) { trainingData.push_back(domains[i].calculateDiscreteValue(floatVector[i])); } return trainingData; } /** * Update the output probabilities from a new set of raw training data. */ void BayesianClassifier::updateOutputProbabilities(int output){ float denominator = float(numberOfTrainingData); for (unsigned int i = 0; i < probabilitiesOfOutputs.size(); ++i) { float numberOfOutput = probabilitiesOfOutputs[i] * denominator; if(i == (unsigned int)output) { numberOfOutput++; } probabilitiesOfOutputs[i] = float(numberOfOutput / (denominator + 1.0)); } } /** * Update the probabilities after adding one set of training data. */ void BayesianClassifier::updateProbabilities(TrainingData const &trainingData){ float denominator = probabilitiesOfOutputs[trainingData[numberOfColumns - 1]]*numberOfTrainingData; #if USE_VECTOR_MAP auto key = calculateMapKey(0, 0, trainingData[numberOfColumns - 1]); auto it = probabilitiesOfInputs.find(key); #endif for(int i = 0; i < numberOfColumns - 1; ++i) { for(int j = 0; j < domains[i].getNumberOfValues(); ++j) { #if !USE_VECTOR_MAP auto key = calculateMapKey(i, j, trainingData[numberOfColumns - 1]); auto it = probabilitiesOfInputs.find(key); if (it == probabilitiesOfInputs.end()) it = probabilitiesOfInputs.insert(std::make_pair(key, 0.0f)).first; #endif assert(it != probabilitiesOfInputs.end()); float numerator = it->second * denominator; if (j == trainingData[i]) numerator++; if (numerator > 0) it->second = numerator / (denominator + 1.0f); #if USE_VECTOR_MAP ++it; #endif } } } /** * Returns the domain of the output column. */ Domain const &BayesianClassifier::getOutputDomain() const { return domains[numberOfColumns - 1]; } <commit_msg>fixed bug in key iteration. conditional compilation to verify key iteration<commit_after>/* * BayesianClassifier.cpp * * Created on: Mar 20, 2009 * Author: Simon Lavigne-Giroux */ #include "BayesianClassifier.h" #include <fstream> #define WRITE_PROGRESS 1 #ifndef VERIFY_MAP_KEY_ITERATOR # ifdef NDEBUG # define VERIFY_MAP_KEY_ITERATOR 0 # else # define VERIFY_MAP_KEY_ITERATOR 1 # endif #endif #if WRITE_PROGRESS #include <iostream> #endif // The threshold to get to select whether an output is valid #define outputProbabilityTreshold 0.003f // There is a minimum denominator value to remove the possibility of INF and NaN #define minimumDenominatorValue 0.0000000001 /** * BayesianClassifier constructor. It constructs the classifier with raw training data from the file * and uses domains to generate discrete values (TrainingData). * * Beware : The file must not have an empty line at the end. */ BayesianClassifier::BayesianClassifier(std::string filename, std::vector<Domain> const &_domains) : max_number_of_domain_values(0) { domains = _domains; numberOfColumns = _domains.size(); constructClassifier(filename); } /** * BayesianClassifier constructor. It constructs a classifier with the specified domain. * Raw training data are not given, it is possible to add data after the construction. */ BayesianClassifier::BayesianClassifier(std::vector<Domain> const &_domains) : max_number_of_domain_values(0) { domains = _domains; numberOfColumns = _domains.size(); calculateProbabilitiesOfInputs(); calculateProbabilitiesOfOutputs(); numberOfTrainingData = data.size(); data.clear(); } /** * Construct the classifier from the RawTrainingData in the file. * * Beware : The file must not have an empty line at the end. */ void BayesianClassifier::constructClassifier(std::string const &filename) { std::ifstream inputFile(filename.c_str()); while (!inputFile.eof()) { TrainingData trainingData; float value; for (int i = 0; i < numberOfColumns; ++i) { inputFile >> value; trainingData.push_back(domains[i].calculateDiscreteValue(value)); } data.push_back(trainingData); } inputFile.close(); calculateProbabilitiesOfInputs(); calculateProbabilitiesOfOutputs(); numberOfTrainingData = data.size(); data.clear(); } /** * Calculate the probabilities for each possibility of inputs. */ void BayesianClassifier::calculateProbabilitiesOfInputs() { // pre-allocate the vector for the input probabilities size_t count = 0; for (int i = 0; i < numberOfColumns - 1; ++i) { max_number_of_domain_values = std::max(max_number_of_domain_values, domains[i].getNumberOfValues()); for (int j = 0; j < domains[i].getNumberOfValues(); ++j) ++count; } #if WRITE_PROGRESS std::cout.imbue(std::locale("")); std::cout << "\nInput probability array is " << (count * getOutputDomain().getNumberOfValues() * sizeof(std::pair<unsigned long const, float>))/1024 << " Kb" << std::flush; #endif probabilitiesOfInputs.reserve(count * getOutputDomain().getNumberOfValues()); // if we don't have any initialization data, then there is // no calculation of the initial probabilities, and we can // populate the vector much more quickly if (data.size() == 0) calculateProbabilitiesOfInputsWithoutData(); else { for (int k = 0; k < getOutputDomain().getNumberOfValues(); ++k) for (int i = 0; i < numberOfColumns - 1; ++i) for (int j = 0; j < domains[i].getNumberOfValues(); ++j) calculateProbability(i, j, k); } #if USE_VECTOR_MAP assert(probabilitiesOfInputs.is_sorted()); assert(probabilitiesOfInputs.size() == probabilitiesOfInputs.capacity()); #endif } void BayesianClassifier::calculateProbabilitiesOfInputsWithoutData() { for (int k = 0; k < getOutputDomain().getNumberOfValues(); ++k) { for (int i = 0; i < numberOfColumns - 1; ++i) { for (int j = 0; j < domains[i].getNumberOfValues(); ++j) { unsigned long key = calculateMapKey(i, j, k); #if USE_VECTOR_MAP probabilitiesOfInputs.emplace_back(key, 0.0f); #else probabilitiesOfInputs[key] = 0.0f; #endif } } } } /** * Calculate the probability of P(effectColum:effectValue | lastColumn:causeValue) * It saves data into the variable probabilitiesOfInputs. */ void BayesianClassifier::calculateProbability(int effectColumn, int effectValue, int causeValue) { // The numerator is the number of TrainingData with this effectValue given this causeValue float numerator = 0.0; // The denominator is the number of TrainingData with this causeValue float denominator = 0.0; //Calculate the numerator and denominator by scanning the TrainingData for (unsigned int i = 0; i < data.size(); ++i) { TrainingData const &trainingData = data[i]; if (trainingData[numberOfColumns - 1] == causeValue) { denominator++; if (trainingData[effectColumn] == effectValue) { numerator++; } } } float probability = 0.0; if (denominator != 0) { probability = numerator / denominator; } unsigned long key = calculateMapKey(effectColumn, effectValue, causeValue); #if USE_VECTOR_MAP probabilitiesOfInputs.emplace_back(key, probability); #else probabilitiesOfInputs[key] = probability; #endif } /** * Calculate P(Output) of each output. * It saves data into the variable probabilitiesOfOuputs. */ void BayesianClassifier::calculateProbabilitiesOfOutputs() { probabilitiesOfOutputs.resize(getOutputDomain().getNumberOfValues()); if (data.size() == 0) return; for (int i = 0; i < getOutputDomain().getNumberOfValues(); ++i) { float count = 0.0; for (unsigned int j = 0; j < data.size(); ++j) { if (data[j][numberOfColumns - 1] == i) { count++; } } probabilitiesOfOutputs[i] = count / (float) data.size(); } } /** * Calculate the map key for each value in the variable probabilitiesOfInputs */ unsigned long const BayesianClassifier::calculateMapKey(int effectColumn, int effectValue, int causeValue) const { if (max_number_of_domain_values == 0) throw std::logic_error("BayesianClassifier::calculateMapKey called before initialisation of max_number_of_domain_values"); size_t effect_column = effectColumn; effect_column *= max_number_of_domain_values; size_t cause_value = causeValue; cause_value *= (numberOfColumns - 1) * max_number_of_domain_values; // assert our cast is valid if (causeValue * 100000UL + effectColumn * 100 + effectValue > (size_t)std::numeric_limits<unsigned long>::max()) throw overflow_exception(); return (unsigned long)(effect_column + effectValue + cause_value); } /** * Calculate the most probable output given this input with this formula : * P(Output | Input) = 1/Z * P(Output) * P(InputValue1 | Ouput) * P(InputValue2 | Ouput) * ... * The output with the highest probability is returned. */ int const BayesianClassifier::calculateOutput(std::vector<float> const &input) { float highestProbability = outputProbabilityTreshold; int highestOutput = rand() % getOutputDomain().getNumberOfValues(); unsigned long key = 0; for (int i = 0; i < getOutputDomain().getNumberOfValues(); ++i) { float probability = probabilitiesOfOutputs[i]; for (unsigned int j = 0; j < input.size(); ++j) { key = calculateMapKey(j, domains[j].calculateDiscreteValue(input[j]), i); probability *= probabilitiesOfInputs[key]; } if (probability > highestProbability) { highestProbability = probability; highestOutput = i; } } return highestOutput; } /** * calculate all possible outputs */ std::vector<std::pair<int, float>> BayesianClassifier::calculatePossibleOutputs(std::vector<float> const &input) const { std::vector<std::pair<int, float>> outputs; size_t key_offset = 0; for(int i = 0; i < numberOfColumns - 1; ++i) { for(int j = 0; j < domains[i].getNumberOfValues(); ++j) ++key_offset; } float const threshold = outputProbabilityTreshold; for (int i = 0; i < getOutputDomain().getNumberOfValues(); ++i) { float probability = probabilitiesOfOutputs[i]; auto key_it = probabilitiesOfInputs.cbegin() + i * key_offset; for (unsigned int j = 0; j < input.size() && probability > threshold; ++j) { #if VERIFY_MAP_KEY_ITERATOR { // if this assert fails, then the key_it is not finding the correct key, ie the // same key as would be returned by calling // probabilitiesOfInputs.find(calculateMapKey(j, domains[j].calculateDiscreteValue(input[j]), i)); auto const mapkey = calculateMapKey(j, domains[j].calculateDiscreteValue(input[j]), i); assert((key_it + domains[j].calculateDiscreteValue(input[j]))->first == mapkey); if ((key_it + domains[j].calculateDiscreteValue(input[j]))->first != mapkey) throw std::runtime_error("key_it is not finding the correct key, i.e. it doesn't match calculateMapKey()"); } #endif probability *= (key_it + domains[j].calculateDiscreteValue(input[j]))->second; key_it += domains[j].getNumberOfValues(); } if (probability > threshold) outputs.emplace_back(i, probability); } return outputs; } /** * Calculate the probability of this output given this input. * P(Output | Input) = 1/Z * P(Output) * P(InputValue1 | Ouput) * P(InputValue2 | Ouput) * ... */ float const BayesianClassifier::calculateProbabilityOfOutput(std::vector<float> const &input, float output) { unsigned long key = 0; std::vector<float> probabilities; for(int i = 0; i < getOutputDomain().getNumberOfValues(); ++i) { float probability = probabilitiesOfOutputs[i]; for (unsigned int j = 0; j < input.size(); ++j) { key = calculateMapKey(j, domains[j].calculateDiscreteValue(input[j]), i); probability *= probabilitiesOfInputs[key]; } probabilities.push_back(probability); } float sumOfProbabilities = 0.0; for(unsigned int i = 0; i < probabilities.size(); ++i) { sumOfProbabilities += probabilities[i]; } float alpha = 0.0; if(sumOfProbabilities > minimumDenominatorValue) { alpha = 1.0f / sumOfProbabilities; } float probability = probabilities[getOutputDomain().calculateDiscreteValue(output)]*alpha; if(probability > 1.0f) { return 1.0f; } else { return probability; } } /** * Add raw training data from a file to adapt the classifier. * It updates the variables containing the probabilities. * * Beware : The file must not have an empty line at the end. */ void BayesianClassifier::addRawTrainingData(std::string const &filename) { std::ifstream inputFile(filename.c_str()); while (!inputFile.eof()) { RawTrainingData rawTrainingData; float value; for (int i = 0; i < numberOfColumns; ++i) { inputFile >> value; rawTrainingData.push_back(value); } addRawTrainingData(rawTrainingData); } inputFile.close(); } /** * Add one set of raw training data to adapt the classifier * It updates the variables containing the probabilities. */ void BayesianClassifier::addRawTrainingData(RawTrainingData const &rawTrainingData){ std::vector<int> trainingData = convertRawTrainingData(rawTrainingData); updateProbabilities(trainingData); updateOutputProbabilities(domains[numberOfColumns-1].calculateDiscreteValue(rawTrainingData[numberOfColumns - 1])); numberOfTrainingData++; } /** * Convert a vector<float> into a vector<int> by discretizing the values * using the domain for each column. */ TrainingData BayesianClassifier::convertRawTrainingData(RawTrainingData const &floatVector) { TrainingData trainingData; trainingData.reserve(floatVector.size()); for(unsigned int i = 0; i < floatVector.size(); ++i) { trainingData.push_back(domains[i].calculateDiscreteValue(floatVector[i])); } return trainingData; } /** * Update the output probabilities from a new set of raw training data. */ void BayesianClassifier::updateOutputProbabilities(int output){ float denominator = float(numberOfTrainingData); for (unsigned int i = 0; i < probabilitiesOfOutputs.size(); ++i) { float numberOfOutput = probabilitiesOfOutputs[i] * denominator; if(i == (unsigned int)output) { numberOfOutput++; } probabilitiesOfOutputs[i] = float(numberOfOutput / (denominator + 1.0)); } } /** * Update the probabilities after adding one set of training data. */ void BayesianClassifier::updateProbabilities(TrainingData const &trainingData){ float denominator = probabilitiesOfOutputs[trainingData[numberOfColumns - 1]]*numberOfTrainingData; #if USE_VECTOR_MAP auto key = calculateMapKey(0, 0, trainingData[numberOfColumns - 1]); auto it = probabilitiesOfInputs.find(key); #endif for(int i = 0; i < numberOfColumns - 1; ++i) { for(int j = 0; j < domains[i].getNumberOfValues(); ++j) { #if !USE_VECTOR_MAP auto key = calculateMapKey(i, j, trainingData[numberOfColumns - 1]); auto it = probabilitiesOfInputs.find(key); if (it == probabilitiesOfInputs.end()) it = probabilitiesOfInputs.insert(std::make_pair(key, 0.0f)).first; #endif assert(it != probabilitiesOfInputs.end()); float numerator = it->second * denominator; if (j == trainingData[i]) numerator++; if (numerator > 0) it->second = numerator / (denominator + 1.0f); #if USE_VECTOR_MAP ++it; #endif } } } /** * Returns the domain of the output column. */ Domain const &BayesianClassifier::getOutputDomain() const { return domains[numberOfColumns - 1]; } <|endoftext|>
<commit_before>//===--- ASTConsumers.cpp - ASTConsumer implementations -------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // AST Consumer Implementations. // //===----------------------------------------------------------------------===// #include "ASTConsumers.h" #include "clang/AST/AST.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/CFG.h" #include "clang/Analysis/LiveVariables.h" #include "clang/Analysis/LocalCheckers.h" using namespace clang; static void PrintFunctionDeclStart(FunctionDecl *FD) { bool HasBody = FD->getBody(); fprintf(stderr, "\n"); switch (FD->getStorageClass()) { default: assert(0 && "Unknown storage class"); case FunctionDecl::None: break; case FunctionDecl::Extern: fprintf(stderr, "extern "); break; case FunctionDecl::Static: fprintf(stderr, "static "); break; } if (FD->isInline()) fprintf(stderr, "inline "); std::string Proto = FD->getName(); FunctionType *AFT = cast<FunctionType>(FD->getType()); if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(AFT)) { Proto += "("; for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { if (i) Proto += ", "; std::string ParamStr; if (HasBody) ParamStr = FD->getParamDecl(i)->getName(); FT->getArgType(i).getAsStringInternal(ParamStr); Proto += ParamStr; } if (FT->isVariadic()) { if (FD->getNumParams()) Proto += ", "; Proto += "..."; } Proto += ")"; } else { assert(isa<FunctionTypeNoProto>(AFT)); Proto += "()"; } AFT->getResultType().getAsStringInternal(Proto); fprintf(stderr, "%s", Proto.c_str()); if (!FD->getBody()) fprintf(stderr, ";\n"); // Doesn't print the body. } static void PrintTypeDefDecl(TypedefDecl *TD) { std::string S = TD->getName(); TD->getUnderlyingType().getAsStringInternal(S); fprintf(stderr, "typedef %s;\n", S.c_str()); } static void PrintObjcInterfaceDecl(ObjcInterfaceDecl *OID) { std::string I = OID->getName(); ObjcInterfaceDecl *SID = OID->getSuperClass(); if (SID) { std::string S = SID->getName(); fprintf(stderr, "@interface %s : %s", I.c_str(), S.c_str()); } else fprintf(stderr, "@interface %s", I.c_str()); // Protocols? int count = OID->getNumIntfRefProtocols(); if (count > 0) { ObjcProtocolDecl **refProtocols = OID->getReferencedProtocols(); for (int i = 0; i < count; i++) fprintf(stderr, "%c%s", (i == 0 ? '<' : ','), refProtocols[i]->getName()); } if (count > 0) fprintf(stderr, ">;\n"); else fprintf(stderr, ";\n"); // FIXME: implement the rest... } static void PrintObjcProtocolDecl(ObjcProtocolDecl *PID) { std::string S = PID->getName(); fprintf(stderr, "@protocol %s;\n", S.c_str()); // FIXME: implement the rest... } static void PrintObjcCategoryImplDecl(ObjcCategoryImplDecl *PID) { std::string S = PID->getName(); std::string I = PID->getClassInterface()->getName(); fprintf(stderr, "@implementation %s(%s);\n", I.c_str(), S.c_str()); // FIXME: implement the rest... } static void PrintObjcCategoryDecl(ObjcCategoryDecl *PID) { std::string S = PID->getName(); std::string I = PID->getClassInterface()->getName(); fprintf(stderr, "@interface %s(%s);\n", I.c_str(), S.c_str()); // FIXME: implement the rest... } static void PrintObjcCompatibleAliasDecl(ObjcCompatibleAliasDecl *AID) { std::string A = AID->getName(); std::string I = AID->getClassInterface()->getName(); fprintf(stderr, "@compatibility_alias %s %s;\n", A.c_str(), I.c_str()); } namespace { class ASTPrinter : public ASTConsumer { virtual void HandleTopLevelDecl(Decl *D) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { PrintFunctionDeclStart(FD); if (FD->getBody()) { fprintf(stderr, " "); FD->getBody()->dumpPretty(); fprintf(stderr, "\n"); } } else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) { PrintTypeDefDecl(TD); } else if (ObjcInterfaceDecl *OID = dyn_cast<ObjcInterfaceDecl>(D)) { PrintObjcInterfaceDecl(OID); } else if (ObjcProtocolDecl *PID = dyn_cast<ObjcProtocolDecl>(D)) { PrintObjcProtocolDecl(PID); } else if (ObjcForwardProtocolDecl *OFPD = dyn_cast<ObjcForwardProtocolDecl>(D)) { fprintf(stderr, "@protocol "); for (unsigned i = 0, e = OFPD->getNumForwardDecls(); i != e; ++i) { const ObjcProtocolDecl *D = OFPD->getForwardProtocolDecl(i); if (i) fprintf(stderr, ", "); fprintf(stderr, "%s", D->getName()); } fprintf(stderr, ";\n"); } else if (ObjcImplementationDecl *OID = dyn_cast<ObjcImplementationDecl>(D)) { fprintf(stderr, "@implementation %s [printing todo]\n", OID->getName()); } else if (ObjcCategoryImplDecl *OID = dyn_cast<ObjcCategoryImplDecl>(D)) { PrintObjcCategoryImplDecl(OID); } else if (ObjcCategoryDecl *OID = dyn_cast<ObjcCategoryDecl>(D)) { PrintObjcCategoryDecl(OID); } else if (ObjcCompatibleAliasDecl *OID = dyn_cast<ObjcCompatibleAliasDecl>(D)) { PrintObjcCompatibleAliasDecl(OID); } else if (isa<ObjcClassDecl>(D)) { fprintf(stderr, "@class [printing todo]\n"); } else if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D)) { fprintf(stderr, "Read top-level variable decl: '%s'\n", SD->getName()); } else { assert(0 && "Unknown decl type!"); } } }; } ASTConsumer *clang::CreateASTPrinter() { return new ASTPrinter(); } namespace { class ASTDumper : public ASTConsumer { SourceManager *SM; public: void Initialize(ASTContext &Context, unsigned MainFileID) { SM = &Context.SourceMgr; } virtual void HandleTopLevelDecl(Decl *D) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { PrintFunctionDeclStart(FD); if (FD->getBody()) { fprintf(stderr, "\n"); FD->getBody()->dumpAll(*SM); fprintf(stderr, "\n"); } } else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) { PrintTypeDefDecl(TD); } else if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D)) { fprintf(stderr, "Read top-level variable decl: '%s'\n", SD->getName()); } else if (ObjcInterfaceDecl *OID = dyn_cast<ObjcInterfaceDecl>(D)) { fprintf(stderr, "Read objc interface '%s'\n", OID->getName()); } else if (isa<ObjcForwardProtocolDecl>(D)) { fprintf(stderr, "Read objc fwd protocol decl\n"); } else { assert(0 && "Unknown decl type!"); } } }; } ASTConsumer *clang::CreateASTDumper() { return new ASTDumper(); } namespace { class ASTViewer : public ASTConsumer { SourceManager *SM; public: void Initialize(ASTContext &Context, unsigned MainFileID) { SM = &Context.SourceMgr; } virtual void HandleTopLevelDecl(Decl *D) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { PrintFunctionDeclStart(FD); if (FD->getBody()) { fprintf(stderr, "\n"); FD->getBody()->viewAST(); fprintf(stderr, "\n"); } } } }; } ASTConsumer *clang::CreateASTViewer() { return new ASTViewer(); } //===----------------------------------------------------------------------===// // CFGVisitor & VisitCFGs - Boilerplate interface and logic to visit // the CFGs for all function definitions. namespace { class CFGVisitor : public ASTConsumer { public: // CFG Visitor interface to be implemented by subclass. virtual void VisitCFG(CFG& C) = 0; virtual bool printFuncDeclStart() { return true; } virtual void HandleTopLevelDecl(Decl *D); }; } // end anonymous namespace void CFGVisitor::HandleTopLevelDecl(Decl *D) { FunctionDecl *FD = dyn_cast<FunctionDecl>(D); if (!FD || !FD->getBody()) return; if (printFuncDeclStart()) { PrintFunctionDeclStart(FD); fprintf(stderr,"\n"); } CFG *C = CFG::buildCFG(FD->getBody()); VisitCFG(*C); delete C; } //===----------------------------------------------------------------------===// // DumpCFGs - Dump CFGs to stderr or visualize with Graphviz namespace { class CFGDumper : public CFGVisitor { const bool UseGraphviz; public: CFGDumper(bool use_graphviz) : UseGraphviz(use_graphviz) {} virtual void VisitCFG(CFG &C) { if (UseGraphviz) C.viewCFG(); else C.dump(); } }; } // end anonymous namespace ASTConsumer *clang::CreateCFGDumper(bool ViewGraphs) { return new CFGDumper(ViewGraphs); } //===----------------------------------------------------------------------===// // AnalyzeLiveVariables - perform live variable analysis and dump results namespace { class LivenessVisitor : public CFGVisitor { SourceManager *SM; public: virtual void Initialize(ASTContext &Context, unsigned MainFileID) { SM = &Context.SourceMgr; } virtual void VisitCFG(CFG& C) { LiveVariables L(C); L.runOnCFG(C); L.dumpBlockLiveness(*SM); } }; } // end anonymous namespace ASTConsumer *clang::CreateLiveVarAnalyzer() { return new LivenessVisitor(); } //===----------------------------------------------------------------------===// // DeadStores - run checker to locate dead stores in a function namespace { class DeadStoreVisitor : public CFGVisitor { Diagnostic &Diags; ASTContext *Ctx; public: DeadStoreVisitor(Diagnostic &diags) : Diags(diags) {} virtual void Initialize(ASTContext &Context, unsigned MainFileID) { Ctx = &Context; } virtual void VisitCFG(CFG& C) { CheckDeadStores(C, *Ctx, Diags); } virtual bool printFuncDeclStart() { return false; } }; } // end anonymous namespace ASTConsumer *clang::CreateDeadStoreChecker(Diagnostic &Diags) { return new DeadStoreVisitor(Diags); } //===----------------------------------------------------------------------===// // Unitialized Values - run checker to flag potential uses of uninitalized // variables. namespace { class UninitValsVisitor : public CFGVisitor { Diagnostic &Diags; ASTContext *Ctx; public: UninitValsVisitor(Diagnostic &diags) : Diags(diags) {} virtual void Initialize(ASTContext &Context, unsigned MainFileID) { Ctx = &Context; } virtual void VisitCFG(CFG& C) { CheckUninitializedValues(C, *Ctx, Diags); } virtual bool printFuncDeclStart() { return false; } }; } // end anonymous namespace ASTConsumer *clang::CreateUnitValsChecker(Diagnostic &Diags) { return new UninitValsVisitor(Diags); } //===----------------------------------------------------------------------===// // LLVM Emitter #include "clang/Basic/Diagnostic.h" #include "clang/CodeGen/ModuleBuilder.h" #include "llvm/Module.h" #include <iostream> namespace { class LLVMEmitter : public ASTConsumer { Diagnostic &Diags; llvm::Module *M; ASTContext *Ctx; CodeGen::BuilderTy *Builder; public: LLVMEmitter(Diagnostic &diags) : Diags(diags) {} virtual void Initialize(ASTContext &Context, unsigned MainFileID) { Ctx = &Context; M = new llvm::Module("foo"); Builder = CodeGen::Init(Context, *M); } virtual void HandleTopLevelDecl(Decl *D) { // If an error occurred, stop code generation, but continue parsing and // semantic analysis (to ensure all warnings and errors are emitted). if (Diags.hasErrorOccurred()) return; if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { CodeGen::CodeGenFunction(Builder, FD); } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) { CodeGen::CodeGenGlobalVar(Builder, FVD); } else { assert(isa<TypedefDecl>(D) && "Only expected typedefs here"); // don't codegen for now, eventually pass down for debug info. //std::cerr << "Read top-level typedef decl: '" << D->getName() << "'\n"; } } ~LLVMEmitter() { CodeGen::Terminate(Builder); // Print the generated code. M->print(std::cout); delete M; } }; } // end anonymous namespace ASTConsumer *clang::CreateLLVMEmitter(Diagnostic &Diags) { return new LLVMEmitter(Diags); } <commit_msg><commit_after>//===--- ASTConsumers.cpp - ASTConsumer implementations -------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // AST Consumer Implementations. // //===----------------------------------------------------------------------===// #include "ASTConsumers.h" #include "clang/AST/AST.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/CFG.h" #include "clang/Analysis/LiveVariables.h" #include "clang/Analysis/LocalCheckers.h" using namespace clang; static void PrintFunctionDeclStart(FunctionDecl *FD) { bool HasBody = FD->getBody(); fprintf(stderr, "\n"); switch (FD->getStorageClass()) { default: assert(0 && "Unknown storage class"); case FunctionDecl::None: break; case FunctionDecl::Extern: fprintf(stderr, "extern "); break; case FunctionDecl::Static: fprintf(stderr, "static "); break; } if (FD->isInline()) fprintf(stderr, "inline "); std::string Proto = FD->getName(); FunctionType *AFT = cast<FunctionType>(FD->getType()); if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(AFT)) { Proto += "("; for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { if (i) Proto += ", "; std::string ParamStr; if (HasBody) ParamStr = FD->getParamDecl(i)->getName(); FT->getArgType(i).getAsStringInternal(ParamStr); Proto += ParamStr; } if (FT->isVariadic()) { if (FD->getNumParams()) Proto += ", "; Proto += "..."; } Proto += ")"; } else { assert(isa<FunctionTypeNoProto>(AFT)); Proto += "()"; } AFT->getResultType().getAsStringInternal(Proto); fprintf(stderr, "%s", Proto.c_str()); if (!FD->getBody()) fprintf(stderr, ";\n"); // Doesn't print the body. } static void PrintTypeDefDecl(TypedefDecl *TD) { std::string S = TD->getName(); TD->getUnderlyingType().getAsStringInternal(S); fprintf(stderr, "typedef %s;\n", S.c_str()); } static void PrintObjcInterfaceDecl(ObjcInterfaceDecl *OID) { std::string I = OID->getName(); ObjcInterfaceDecl *SID = OID->getSuperClass(); if (SID) { std::string S = SID->getName(); fprintf(stderr, "@interface %s : %s", I.c_str(), S.c_str()); } else fprintf(stderr, "@interface %s", I.c_str()); // Protocols? int count = OID->getNumIntfRefProtocols(); if (count > 0) { ObjcProtocolDecl **refProtocols = OID->getReferencedProtocols(); for (int i = 0; i < count; i++) fprintf(stderr, "%c%s", (i == 0 ? '<' : ','), refProtocols[i]->getName()); } if (count > 0) fprintf(stderr, ">;\n"); else fprintf(stderr, ";\n"); // FIXME: implement the rest... } static void PrintObjcProtocolDecl(ObjcProtocolDecl *PID) { std::string S = PID->getName(); fprintf(stderr, "@protocol %s;\n", S.c_str()); // FIXME: implement the rest... } static void PrintObjcCategoryImplDecl(ObjcCategoryImplDecl *PID) { std::string S = PID->getName(); std::string I = PID->getClassInterface()->getName(); fprintf(stderr, "@implementation %s(%s);\n", I.c_str(), S.c_str()); // FIXME: implement the rest... } static void PrintObjcCategoryDecl(ObjcCategoryDecl *PID) { std::string S = PID->getName(); std::string I = PID->getClassInterface()->getName(); fprintf(stderr, "@interface %s(%s);\n", I.c_str(), S.c_str()); // FIXME: implement the rest... } static void PrintObjcCompatibleAliasDecl(ObjcCompatibleAliasDecl *AID) { std::string A = AID->getName(); std::string I = AID->getClassInterface()->getName(); fprintf(stderr, "@compatibility_alias %s %s;\n", A.c_str(), I.c_str()); } namespace { class ASTPrinter : public ASTConsumer { virtual void HandleTopLevelDecl(Decl *D) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { PrintFunctionDeclStart(FD); if (FD->getBody()) { fprintf(stderr, " "); FD->getBody()->dumpPretty(); fprintf(stderr, "\n"); } } else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) { PrintTypeDefDecl(TD); } else if (ObjcInterfaceDecl *OID = dyn_cast<ObjcInterfaceDecl>(D)) { PrintObjcInterfaceDecl(OID); } else if (ObjcProtocolDecl *PID = dyn_cast<ObjcProtocolDecl>(D)) { PrintObjcProtocolDecl(PID); } else if (ObjcForwardProtocolDecl *OFPD = dyn_cast<ObjcForwardProtocolDecl>(D)) { fprintf(stderr, "@protocol "); for (unsigned i = 0, e = OFPD->getNumForwardDecls(); i != e; ++i) { const ObjcProtocolDecl *D = OFPD->getForwardProtocolDecl(i); if (i) fprintf(stderr, ", "); fprintf(stderr, "%s", D->getName()); } fprintf(stderr, ";\n"); } else if (ObjcImplementationDecl *OID = dyn_cast<ObjcImplementationDecl>(D)) { fprintf(stderr, "@implementation %s [printing todo]\n", OID->getName()); } else if (ObjcCategoryImplDecl *OID = dyn_cast<ObjcCategoryImplDecl>(D)) { PrintObjcCategoryImplDecl(OID); } else if (ObjcCategoryDecl *OID = dyn_cast<ObjcCategoryDecl>(D)) { PrintObjcCategoryDecl(OID); } else if (ObjcCompatibleAliasDecl *OID = dyn_cast<ObjcCompatibleAliasDecl>(D)) { PrintObjcCompatibleAliasDecl(OID); } else if (isa<ObjcClassDecl>(D)) { fprintf(stderr, "@class [printing todo]\n"); } else if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D)) { fprintf(stderr, "Read top-level variable decl: '%s'\n", SD->getName()); } else { assert(0 && "Unknown decl type!"); } } }; } ASTConsumer *clang::CreateASTPrinter() { return new ASTPrinter(); } namespace { class ASTDumper : public ASTConsumer { SourceManager *SM; public: void Initialize(ASTContext &Context, unsigned MainFileID) { SM = &Context.SourceMgr; } virtual void HandleTopLevelDecl(Decl *D) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { PrintFunctionDeclStart(FD); if (FD->getBody()) { fprintf(stderr, "\n"); FD->getBody()->dumpAll(*SM); fprintf(stderr, "\n"); } } else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) { PrintTypeDefDecl(TD); } else if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D)) { fprintf(stderr, "Read top-level variable decl: '%s'\n", SD->getName()); } else if (ObjcInterfaceDecl *OID = dyn_cast<ObjcInterfaceDecl>(D)) { fprintf(stderr, "Read objc interface '%s'\n", OID->getName()); } else if (ObjcProtocolDecl *OPD = dyn_cast<ObjcProtocolDecl>(D)) { fprintf(stderr, "Read objc protocol '%s'\n", OPD->getName()); } else if (ObjcCategoryDecl *OCD = dyn_cast<ObjcCategoryDecl>(D)) { fprintf(stderr, "Read objc category '%s'\n", OCD->getName()); } else if (isa<ObjcForwardProtocolDecl>(D)) { fprintf(stderr, "Read objc fwd protocol decl\n"); } else if (isa<ObjcClassDecl>(D)) { fprintf(stderr, "Read objc fwd class decl\n"); } else { assert(0 && "Unknown decl type!"); } } }; } ASTConsumer *clang::CreateASTDumper() { return new ASTDumper(); } namespace { class ASTViewer : public ASTConsumer { SourceManager *SM; public: void Initialize(ASTContext &Context, unsigned MainFileID) { SM = &Context.SourceMgr; } virtual void HandleTopLevelDecl(Decl *D) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { PrintFunctionDeclStart(FD); if (FD->getBody()) { fprintf(stderr, "\n"); FD->getBody()->viewAST(); fprintf(stderr, "\n"); } } } }; } ASTConsumer *clang::CreateASTViewer() { return new ASTViewer(); } //===----------------------------------------------------------------------===// // CFGVisitor & VisitCFGs - Boilerplate interface and logic to visit // the CFGs for all function definitions. namespace { class CFGVisitor : public ASTConsumer { public: // CFG Visitor interface to be implemented by subclass. virtual void VisitCFG(CFG& C) = 0; virtual bool printFuncDeclStart() { return true; } virtual void HandleTopLevelDecl(Decl *D); }; } // end anonymous namespace void CFGVisitor::HandleTopLevelDecl(Decl *D) { FunctionDecl *FD = dyn_cast<FunctionDecl>(D); if (!FD || !FD->getBody()) return; if (printFuncDeclStart()) { PrintFunctionDeclStart(FD); fprintf(stderr,"\n"); } CFG *C = CFG::buildCFG(FD->getBody()); VisitCFG(*C); delete C; } //===----------------------------------------------------------------------===// // DumpCFGs - Dump CFGs to stderr or visualize with Graphviz namespace { class CFGDumper : public CFGVisitor { const bool UseGraphviz; public: CFGDumper(bool use_graphviz) : UseGraphviz(use_graphviz) {} virtual void VisitCFG(CFG &C) { if (UseGraphviz) C.viewCFG(); else C.dump(); } }; } // end anonymous namespace ASTConsumer *clang::CreateCFGDumper(bool ViewGraphs) { return new CFGDumper(ViewGraphs); } //===----------------------------------------------------------------------===// // AnalyzeLiveVariables - perform live variable analysis and dump results namespace { class LivenessVisitor : public CFGVisitor { SourceManager *SM; public: virtual void Initialize(ASTContext &Context, unsigned MainFileID) { SM = &Context.SourceMgr; } virtual void VisitCFG(CFG& C) { LiveVariables L(C); L.runOnCFG(C); L.dumpBlockLiveness(*SM); } }; } // end anonymous namespace ASTConsumer *clang::CreateLiveVarAnalyzer() { return new LivenessVisitor(); } //===----------------------------------------------------------------------===// // DeadStores - run checker to locate dead stores in a function namespace { class DeadStoreVisitor : public CFGVisitor { Diagnostic &Diags; ASTContext *Ctx; public: DeadStoreVisitor(Diagnostic &diags) : Diags(diags) {} virtual void Initialize(ASTContext &Context, unsigned MainFileID) { Ctx = &Context; } virtual void VisitCFG(CFG& C) { CheckDeadStores(C, *Ctx, Diags); } virtual bool printFuncDeclStart() { return false; } }; } // end anonymous namespace ASTConsumer *clang::CreateDeadStoreChecker(Diagnostic &Diags) { return new DeadStoreVisitor(Diags); } //===----------------------------------------------------------------------===// // Unitialized Values - run checker to flag potential uses of uninitalized // variables. namespace { class UninitValsVisitor : public CFGVisitor { Diagnostic &Diags; ASTContext *Ctx; public: UninitValsVisitor(Diagnostic &diags) : Diags(diags) {} virtual void Initialize(ASTContext &Context, unsigned MainFileID) { Ctx = &Context; } virtual void VisitCFG(CFG& C) { CheckUninitializedValues(C, *Ctx, Diags); } virtual bool printFuncDeclStart() { return false; } }; } // end anonymous namespace ASTConsumer *clang::CreateUnitValsChecker(Diagnostic &Diags) { return new UninitValsVisitor(Diags); } //===----------------------------------------------------------------------===// // LLVM Emitter #include "clang/Basic/Diagnostic.h" #include "clang/CodeGen/ModuleBuilder.h" #include "llvm/Module.h" #include <iostream> namespace { class LLVMEmitter : public ASTConsumer { Diagnostic &Diags; llvm::Module *M; ASTContext *Ctx; CodeGen::BuilderTy *Builder; public: LLVMEmitter(Diagnostic &diags) : Diags(diags) {} virtual void Initialize(ASTContext &Context, unsigned MainFileID) { Ctx = &Context; M = new llvm::Module("foo"); Builder = CodeGen::Init(Context, *M); } virtual void HandleTopLevelDecl(Decl *D) { // If an error occurred, stop code generation, but continue parsing and // semantic analysis (to ensure all warnings and errors are emitted). if (Diags.hasErrorOccurred()) return; if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { CodeGen::CodeGenFunction(Builder, FD); } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) { CodeGen::CodeGenGlobalVar(Builder, FVD); } else { assert(isa<TypedefDecl>(D) && "Only expected typedefs here"); // don't codegen for now, eventually pass down for debug info. //std::cerr << "Read top-level typedef decl: '" << D->getName() << "'\n"; } } ~LLVMEmitter() { CodeGen::Terminate(Builder); // Print the generated code. M->print(std::cout); delete M; } }; } // end anonymous namespace ASTConsumer *clang::CreateLLVMEmitter(Diagnostic &Diags) { return new LLVMEmitter(Diags); } <|endoftext|>
<commit_before>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <fstream> #include <string> #include <vector> #include <exception> // StdAir #include <stdair/STDAIR_Types.hpp> #include <stdair/bom/OutboundPathTypes.hpp> #include <stdair/bom/BookingRequestStruct.hpp> #include <stdair/bom/TravelSolutionStruct.hpp> #include <stdair/service/Logger.hpp> // Distribution #include <simcrs/SIMCRS_Service.hpp> // TRADEMGEN #include <trademgen/TRADEMGEN_Service.hpp> // Airsched #include <airsched/AIRSCHED_Service.hpp> // Dsim #include <dsim/DSIM_Types.hpp> #include <dsim/command/Simulator.hpp> namespace DSIM { // //////////////////////////////////////////////////////////////////// void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service) { try { // DEBUG STDAIR_LOG_DEBUG ("The simulation is starting"); // Generate a booking request. stdair::BookingRequestStruct lBookingRequest = ioTRADEMGEN_Service.generateBookingRequest (); // Play booking request playBookingRequest (ioSIMCRS_Service, lBookingRequest); // DEBUG STDAIR_LOG_DEBUG ("The simulation has ended"); } catch (const std::exception& lStdError) { STDAIR_LOG_ERROR ("Error: " << lStdError.what()); throw SimulationException(); } } // //////////////////////////////////////////////////////////////////// void Simulator:: playBookingRequest (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, const stdair::BookingRequestStruct& iBookingRequest) { // Retrieve a list of travel solutions corresponding the given // booking request. stdair::TravelSolutionList_T lTravelSolutionList = ioSIMCRS_Service.getTravelSolutions (iBookingRequest); // Hardcode a travel solution choice. if (lTravelSolutionList.empty() == false) { // DEBUG STDAIR_LOG_DEBUG ("A travel solution is chosen."); stdair::TravelSolutionStruct lChosenTravelSolution = lTravelSolutionList.at(0); // Get the number of seats in the request. const stdair::NbOfSeats_T& lNbOfSeats = iBookingRequest.getPartySize(); // Make a sale. ioSIMCRS_Service.sell (lChosenTravelSolution, lNbOfSeats); } else { // DEBUG STDAIR_LOG_DEBUG ("No travel solution is chosen."); } } } <commit_msg>[dev] Added the request generation code into the simulator.<commit_after>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <fstream> #include <string> #include <vector> #include <exception> // StdAir #include <stdair/STDAIR_Types.hpp> #include <stdair/basic/DemandCharacteristics.hpp> #include <stdair/basic/DemandDistribution.hpp> #include <stdair/basic/CategoricalAttribute.hpp> #include <stdair/basic/ContinuousAttribute.hpp> #include <stdair/bom/EventStruct.hpp> #include <stdair/bom/EventQueue.hpp> #include <stdair/bom/OutboundPathTypes.hpp> #include <stdair/bom/BookingRequestStruct.hpp> #include <stdair/bom/TravelSolutionStruct.hpp> #include <stdair/service/Logger.hpp> // Distribution #include <simcrs/SIMCRS_Service.hpp> // TRADEMGEN #include <trademgen/TRADEMGEN_Service.hpp> // Airsched #include <airsched/AIRSCHED_Service.hpp> // Dsim #include <dsim/DSIM_Types.hpp> #include <dsim/command/Simulator.hpp> namespace DSIM { // //////////////////////////////////////////////////////////////////// void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service) { try { // DEBUG STDAIR_LOG_DEBUG ("The simulation is starting"); // Hardcoded section for demand generation. // Demand characteristics stdair::DemandCharacteristics demandCharacteristics1; stdair::DemandCharacteristics demandCharacteristics2; // Demand distribution stdair::DemandDistribution demandDistribution1; stdair::DemandDistribution demandDistribution2; // distribution of number of requests demandDistribution1.setMeanNumberOfRequests (10.0); demandDistribution1.setStandardDeviationNumberOfRequests (2.0); demandDistribution2.setMeanNumberOfRequests (12.0); demandDistribution2.setStandardDeviationNumberOfRequests (1.0); // origin demandCharacteristics1.setOrigin ("LHR"); demandCharacteristics2.setOrigin ("LHR"); // destination demandCharacteristics1.setDestination ("JFK"); demandCharacteristics2.setDestination ("JFK"); // preferred departure date demandCharacteristics1.setPreferredDepartureDate (boost::gregorian::date (2010,1,17)); demandCharacteristics2.setPreferredDepartureDate (boost::gregorian::date (2010,1,18)); // Passenger type demandCharacteristics1.setPaxType ("L"); demandCharacteristics2.setPaxType ("B"); // arrival pattern std::multimap<stdair::FloatDuration_T, stdair::Probability_T> arrivalPatternCumulativeDistribution1; arrivalPatternCumulativeDistribution1. insert ( std::pair<stdair::FloatDuration_T, stdair::Probability_T> (-365.0, 0) ); arrivalPatternCumulativeDistribution1. insert ( std::pair<stdair::FloatDuration_T, stdair::Probability_T> (-67.0, 0.2) ); arrivalPatternCumulativeDistribution1. insert ( std::pair<stdair::FloatDuration_T, stdair::Probability_T> (-17.0, 0.5) ); arrivalPatternCumulativeDistribution1. insert ( std::pair<stdair::FloatDuration_T, stdair::Probability_T> (0.0, 1.0) ); std::multimap<stdair::FloatDuration_T, stdair::Probability_T> arrivalPatternCumulativeDistribution2; arrivalPatternCumulativeDistribution2. insert ( std::pair<stdair::FloatDuration_T, stdair::Probability_T> (-365.0, 0) ); arrivalPatternCumulativeDistribution2. insert ( std::pair<stdair::FloatDuration_T, stdair::Probability_T> (-300.0, 0.5) ); arrivalPatternCumulativeDistribution2. insert ( std::pair<stdair::FloatDuration_T, stdair::Probability_T> (-200.0, 0.9) ); arrivalPatternCumulativeDistribution2. insert ( std::pair<stdair::FloatDuration_T, stdair::Probability_T> (0.0, 1.0) ); // When creating the ContinuousAttribute object, the mapping is // inverted, i.e., the inverse cumulative distribution can be // derived from the cumulative distribution const stdair::ContinuousAttribute<stdair::FloatDuration_T> arrivalPattern1 (arrivalPatternCumulativeDistribution1); demandCharacteristics1.setArrivalPattern (arrivalPattern1); const stdair::ContinuousAttribute<stdair::FloatDuration_T> arrivalPattern2 (arrivalPatternCumulativeDistribution2); demandCharacteristics2.setArrivalPattern (arrivalPattern2); // Display STDAIR_LOG_DEBUG ("Demand 1: " << demandCharacteristics1.display() << demandDistribution1.display() << std::endl << std::endl); STDAIR_LOG_DEBUG ("Demand 2: " << demandCharacteristics2.display() << demandDistribution2.display() << std::endl << std::endl); // Seeds stdair::RandomSeed_T seed = 2; // Key stdair::DemandStreamKey_T key1 = 1; stdair::DemandStreamKey_T key2 = 2; // Initialize the demand stream ioTRADEMGEN_Service.addDemandStream (key1, demandCharacteristics1, demandDistribution1, seed, seed, seed); ioTRADEMGEN_Service.addDemandStream (key2, demandCharacteristics2, demandDistribution2, seed, seed, seed); // Get the total number of requests to be generated stdair::Count_T totalNumberOfRequestsToBeGenerated1 = ioTRADEMGEN_Service.getTotalNumberOfRequestsToBeGenerated (key1); stdair::Count_T totalNumberOfRequestsToBeGenerated2 = ioTRADEMGEN_Service.getTotalNumberOfRequestsToBeGenerated (key2); STDAIR_LOG_DEBUG ("Number of requests to be generated (demand 1): " << totalNumberOfRequestsToBeGenerated1 << std::endl); STDAIR_LOG_DEBUG ("Number of requests to be generated (demand 2): " << totalNumberOfRequestsToBeGenerated2 << std::endl); // ///////////////////////////////////////////////////// // Event queue stdair::EventQueue lEventQueue = stdair::EventQueue (); // Initialize by adding one request of each type const bool stillHavingRequestsToBeGenerated1 = ioTRADEMGEN_Service.stillHavingRequestsToBeGenerated (key1); if (stillHavingRequestsToBeGenerated1) { stdair::BookingRequestPtr_T lRequest1 = ioTRADEMGEN_Service.generateNextRequest (key1); assert (lRequest1 != NULL); stdair::DateTime_T lRequestDateTime = lRequest1->getRequestDateTime (); stdair::EventStruct lEventStruct ("Request", lRequestDateTime, key1, lRequest1); lEventQueue.addEvent (lEventStruct); } const bool stillHavingRequestsToBeGenerated2 = ioTRADEMGEN_Service.stillHavingRequestsToBeGenerated (key2); if (stillHavingRequestsToBeGenerated2) { stdair::BookingRequestPtr_T lRequest2 = ioTRADEMGEN_Service.generateNextRequest (key2); assert (lRequest2 != NULL); stdair::DateTime_T lRequestDateTime = lRequest2->getRequestDateTime (); stdair::EventStruct lEventStruct("Request", lRequestDateTime, key2, lRequest2); lEventQueue.addEvent (lEventStruct); } // Pop requests, get type, and generate next request of same type int i = 0; while (lEventQueue.isQueueDone() == false && i < 20) { // DEBUG STDAIR_LOG_DEBUG ("Before popping (" << i << ")" ); STDAIR_LOG_DEBUG ("Queue size: " << lEventQueue.getQueueSize () ); STDAIR_LOG_DEBUG ("Is queue done? " << lEventQueue.isQueueDone () ); stdair::EventStruct& lEventStruct = lEventQueue.popEvent (); // DEBUG STDAIR_LOG_DEBUG ("After popping" ); STDAIR_LOG_DEBUG ("Queue size: " << lEventQueue.getQueueSize ()); STDAIR_LOG_DEBUG ("Is queue done? " << lEventQueue.isQueueDone ()); STDAIR_LOG_DEBUG ("Popped request " << i ); const stdair::BookingRequestStruct& lPoppedRequest = lEventStruct.getBookingRequest (); // DEBUG STDAIR_LOG_DEBUG (lPoppedRequest.describe()); // Play booking request playBookingRequest (ioSIMCRS_Service, lPoppedRequest); // Retrieve the corresponding demand stream const stdair::DemandStreamKey_T& lDemandStreamKey = lEventStruct.getDemandStreamKey (); // generate next request bool stillHavingRequestsToBeGenerated = ioTRADEMGEN_Service.stillHavingRequestsToBeGenerated(lDemandStreamKey); STDAIR_LOG_DEBUG ("stillHavingRequestsToBeGenerated: " << stillHavingRequestsToBeGenerated ); if (stillHavingRequestsToBeGenerated) { stdair::BookingRequestPtr_T lNextRequest = ioTRADEMGEN_Service.generateNextRequest (lDemandStreamKey); assert (lNextRequest != NULL); // DEBUG STDAIR_LOG_DEBUG ("Added request: " << lNextRequest->describe()); stdair::DateTime_T lNextRequestDateTime = lNextRequest->getRequestDateTime (); stdair::EventStruct lNextEventStruct ("Request", lNextRequestDateTime, lDemandStreamKey, lNextRequest); lEventQueue.eraseLastUsedEvent (); lEventQueue.addEvent (lNextEventStruct); // DEBUG STDAIR_LOG_DEBUG ("After adding"); STDAIR_LOG_DEBUG ("Queue size: " << lEventQueue.getQueueSize ()); STDAIR_LOG_DEBUG ("Is queue done? " << lEventQueue.isQueueDone ()); } // DEBUG STDAIR_LOG_DEBUG (std::endl); // Iterate ++i; } // Play booking request //playBookingRequest (ioSIMCRS_Service, lBookingRequest); // DEBUG STDAIR_LOG_DEBUG ("The simulation has ended"); } catch (const std::exception& lStdError) { STDAIR_LOG_ERROR ("Error: " << lStdError.what()); throw SimulationException(); } } // //////////////////////////////////////////////////////////////////// void Simulator:: playBookingRequest (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, const stdair::BookingRequestStruct& iBookingRequest) { // Retrieve a list of travel solutions corresponding the given // booking request. stdair::TravelSolutionList_T lTravelSolutionList = ioSIMCRS_Service.getTravelSolutions (iBookingRequest); // Hardcode a travel solution choice. if (lTravelSolutionList.empty() == false) { // DEBUG STDAIR_LOG_DEBUG ("A travel solution is chosen."); stdair::TravelSolutionStruct lChosenTravelSolution = lTravelSolutionList.at(0); // Get the number of seats in the request. const stdair::NbOfSeats_T& lNbOfSeats = iBookingRequest.getPartySize(); // Make a sale. ioSIMCRS_Service.sell (lChosenTravelSolution, lNbOfSeats); } else { // DEBUG STDAIR_LOG_DEBUG ("No travel solution is chosen."); } } } <|endoftext|>
<commit_before><commit_msg>WaE: -Werror=missing-field-initializers<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <graphene/chain/protocol/asset.hpp> #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> namespace graphene { namespace chain { typedef boost::multiprecision::uint128_t uint128_t; typedef boost::multiprecision::int128_t int128_t; bool operator == ( const price& a, const price& b ) { if( std::tie( a.base.asset_id, a.quote.asset_id ) != std::tie( b.base.asset_id, b.quote.asset_id ) ) return false; const auto amult = uint128_t( b.quote.amount.value ) * a.base.amount.value; const auto bmult = uint128_t( a.quote.amount.value ) * b.base.amount.value; return amult == bmult; } bool operator < ( const price& a, const price& b ) { if( a.base.asset_id < b.base.asset_id ) return true; if( a.base.asset_id > b.base.asset_id ) return false; if( a.quote.asset_id < b.quote.asset_id ) return true; if( a.quote.asset_id > b.quote.asset_id ) return false; const auto amult = uint128_t( b.quote.amount.value ) * a.base.amount.value; const auto bmult = uint128_t( a.quote.amount.value ) * b.base.amount.value; return amult < bmult; } asset operator * ( const asset& a, const price& b ) { if( a.asset_id == b.base.asset_id ) { FC_ASSERT( b.base.amount.value > 0 ); uint128_t result = (uint128_t(a.amount.value) * b.quote.amount.value)/b.base.amount.value; FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY ); return asset( result.convert_to<int64_t>(), b.quote.asset_id ); } else if( a.asset_id == b.quote.asset_id ) { FC_ASSERT( b.quote.amount.value > 0 ); uint128_t result = (uint128_t(a.amount.value) * b.base.amount.value)/b.quote.amount.value; FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY ); return asset( result.convert_to<int64_t>(), b.base.asset_id ); } FC_THROW_EXCEPTION( fc::assert_exception, "invalid asset * price", ("asset",a)("price",b) ); } asset asset::multiply_and_round_up( const price& b )const { const asset& a = *this; if( a.asset_id == b.base.asset_id ) { FC_ASSERT( b.base.amount.value > 0 ); uint128_t result = (uint128_t(a.amount.value) * b.quote.amount.value + b.base.amount.value - 1)/b.base.amount.value; FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY ); return asset( result.convert_to<int64_t>(), b.quote.asset_id ); } else if( a.asset_id == b.quote.asset_id ) { FC_ASSERT( b.quote.amount.value > 0 ); uint128_t result = (uint128_t(a.amount.value) * b.base.amount.value + b.quote.amount.value - 1)/b.quote.amount.value; FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY ); return asset( result.convert_to<int64_t>(), b.base.asset_id ); } FC_THROW_EXCEPTION( fc::assert_exception, "invalid asset::multiply_and_round_up(price)", ("asset",a)("price",b) ); } price operator / ( const asset& base, const asset& quote ) { try { FC_ASSERT( base.asset_id != quote.asset_id ); return price{base,quote}; } FC_CAPTURE_AND_RETHROW( (base)(quote) ) } price price::max( asset_id_type base, asset_id_type quote ) { return asset( share_type(GRAPHENE_MAX_SHARE_SUPPLY), base ) / asset( share_type(1), quote); } price price::min( asset_id_type base, asset_id_type quote ) { return asset( 1, base ) / asset( GRAPHENE_MAX_SHARE_SUPPLY, quote); } price operator * ( const price& p, const ratio_type& r ) { try { p.validate(); FC_ASSERT( r.numerator() > 0 && r.denominator() > 0 ); if( r.numerator() == r.denominator() ) return p; boost::rational<int128_t> p128( p.base.amount.value, p.quote.amount.value ); boost::rational<int128_t> r128( r.numerator(), r.denominator() ); auto cp = p128 * r128; auto ocp = cp; bool shrinked = false; static const int128_t max( GRAPHENE_MAX_SHARE_SUPPLY ); while( cp.numerator() > max || cp.denominator() > max ) { if( cp.numerator() == 1 ) { cp = boost::rational<int128_t>( 1, max ); break; } else if( cp.denominator() == 1 ) { cp = boost::rational<int128_t>( max, 1 ); break; } else { cp = boost::rational<int128_t>( cp.numerator() >> 1, cp.denominator() >> 1 ); shrinked = true; } } if( shrinked ) // maybe not accurate enough due to rounding, do additional checks here { int128_t num = ocp.numerator(); int128_t den = ocp.denominator(); if( num > den ) { num /= den; if( num > max ) num = max; den = 1; } else { den /= num; if( den > max ) den = max; num = 1; } boost::rational<int128_t> ncp( num, den ); if( num == max || den == max ) // it's on the edge, we know it's accurate enough cp = ncp; else { // from the accurate ocp, now we have ncp and cp. use the one which is closer to ocp. // TODO improve performance auto diff1 = abs( ncp - ocp ); auto diff2 = abs( cp - ocp ); if( diff1 < diff2 ) cp = ncp; } } price np = asset( cp.numerator().convert_to<int64_t>(), p.base.asset_id ) / asset( cp.denominator().convert_to<int64_t>(), p.quote.asset_id ); if( ( r.numerator() > r.denominator() && np < p ) || ( r.numerator() < r.denominator() && np > p ) ) // even with an accurate result, if p is out of valid range, return it np = p; np.validate(); return np; } FC_CAPTURE_AND_RETHROW( (p)(r.numerator())(r.denominator()) ) } price operator / ( const price& p, const ratio_type& r ) { try { return p * ratio_type( r.denominator(), r.numerator() ); } FC_CAPTURE_AND_RETHROW( (p)(r.numerator())(r.denominator()) ) } /** * The black swan price is defined as debt/collateral, we want to perform a margin call * before debt == collateral. Given a debt/collateral ratio of 1 USD / CORE and * a maintenance collateral requirement of 2x we can define the call price to be * 2 USD / CORE. * * This method divides the collateral by the maintenance collateral ratio to derive * a call price for the given black swan ratio. * * There exists some cases where the debt and collateral values are so small that * dividing by the collateral ratio will result in a 0 price or really poor * rounding errors. No matter what the collateral part of the price ratio can * never go to 0 and the debt can never go more than GRAPHENE_MAX_SHARE_SUPPLY * * CR * DEBT/COLLAT or DEBT/(COLLAT/CR) */ price price::call_price( const asset& debt, const asset& collateral, uint16_t collateral_ratio) { try { // TODO replace the calculation with new operator*() and/or operator/(), could be a hardfork change due to edge cases //wdump((debt)(collateral)(collateral_ratio)); boost::rational<int128_t> swan(debt.amount.value,collateral.amount.value); boost::rational<int128_t> ratio( collateral_ratio, GRAPHENE_COLLATERAL_RATIO_DENOM ); auto cp = swan * ratio; while( cp.numerator() > GRAPHENE_MAX_SHARE_SUPPLY || cp.denominator() > GRAPHENE_MAX_SHARE_SUPPLY ) cp = boost::rational<int128_t>( (cp.numerator() >> 1)+1, (cp.denominator() >> 1)+1 ); return ~(asset( cp.numerator().convert_to<int64_t>(), debt.asset_id ) / asset( cp.denominator().convert_to<int64_t>(), collateral.asset_id )); } FC_CAPTURE_AND_RETHROW( (debt)(collateral)(collateral_ratio) ) } bool price::is_null() const { // Effectively same as "return *this == price();" but perhaps faster return ( base.asset_id == asset_id_type() && quote.asset_id == asset_id_type() ); } void price::validate() const { try { FC_ASSERT( base.amount > share_type(0) ); FC_ASSERT( quote.amount > share_type(0) ); FC_ASSERT( base.asset_id != quote.asset_id ); } FC_CAPTURE_AND_RETHROW( (base)(quote) ) } void price_feed::validate() const { try { if( !settlement_price.is_null() ) settlement_price.validate(); FC_ASSERT( maximum_short_squeeze_ratio >= GRAPHENE_MIN_COLLATERAL_RATIO ); FC_ASSERT( maximum_short_squeeze_ratio <= GRAPHENE_MAX_COLLATERAL_RATIO ); FC_ASSERT( maintenance_collateral_ratio >= GRAPHENE_MIN_COLLATERAL_RATIO ); FC_ASSERT( maintenance_collateral_ratio <= GRAPHENE_MAX_COLLATERAL_RATIO ); max_short_squeeze_price(); // make sure that it doesn't overflow //FC_ASSERT( maintenance_collateral_ratio >= maximum_short_squeeze_ratio ); } FC_CAPTURE_AND_RETHROW( (*this) ) } bool price_feed::is_for( asset_id_type asset_id ) const { try { if( !settlement_price.is_null() ) return (settlement_price.base.asset_id == asset_id); if( !core_exchange_rate.is_null() ) return (core_exchange_rate.base.asset_id == asset_id); // (null, null) is valid for any feed return true; } FC_CAPTURE_AND_RETHROW( (*this) ) } price price_feed::max_short_squeeze_price()const { // TODO replace the calculation with new operator*() and/or operator/(), could be a hardfork change due to edge cases boost::rational<int128_t> sp( settlement_price.base.amount.value, settlement_price.quote.amount.value ); //debt.amount.value,collateral.amount.value); boost::rational<int128_t> ratio( GRAPHENE_COLLATERAL_RATIO_DENOM, maximum_short_squeeze_ratio ); auto cp = sp * ratio; while( cp.numerator() > GRAPHENE_MAX_SHARE_SUPPLY || cp.denominator() > GRAPHENE_MAX_SHARE_SUPPLY ) cp = boost::rational<int128_t>( (cp.numerator() >> 1)+(cp.numerator()&1), (cp.denominator() >> 1)+(cp.denominator()&1) ); return (asset( cp.numerator().convert_to<int64_t>(), settlement_price.base.asset_id ) / asset( cp.denominator().convert_to<int64_t>(), settlement_price.quote.asset_id )); } // compile-time table of powers of 10 using template metaprogramming template< int N > struct p10 { static const int64_t v = 10 * p10<N-1>::v; }; template<> struct p10<0> { static const int64_t v = 1; }; const int64_t scaled_precision_lut[19] = { p10< 0 >::v, p10< 1 >::v, p10< 2 >::v, p10< 3 >::v, p10< 4 >::v, p10< 5 >::v, p10< 6 >::v, p10< 7 >::v, p10< 8 >::v, p10< 9 >::v, p10< 10 >::v, p10< 11 >::v, p10< 12 >::v, p10< 13 >::v, p10< 14 >::v, p10< 15 >::v, p10< 16 >::v, p10< 17 >::v, p10< 18 >::v }; } } // graphene::chain <commit_msg>Improved performance for price * ratio<commit_after>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <graphene/chain/protocol/asset.hpp> #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> namespace graphene { namespace chain { typedef boost::multiprecision::uint128_t uint128_t; typedef boost::multiprecision::int128_t int128_t; bool operator == ( const price& a, const price& b ) { if( std::tie( a.base.asset_id, a.quote.asset_id ) != std::tie( b.base.asset_id, b.quote.asset_id ) ) return false; const auto amult = uint128_t( b.quote.amount.value ) * a.base.amount.value; const auto bmult = uint128_t( a.quote.amount.value ) * b.base.amount.value; return amult == bmult; } bool operator < ( const price& a, const price& b ) { if( a.base.asset_id < b.base.asset_id ) return true; if( a.base.asset_id > b.base.asset_id ) return false; if( a.quote.asset_id < b.quote.asset_id ) return true; if( a.quote.asset_id > b.quote.asset_id ) return false; const auto amult = uint128_t( b.quote.amount.value ) * a.base.amount.value; const auto bmult = uint128_t( a.quote.amount.value ) * b.base.amount.value; return amult < bmult; } asset operator * ( const asset& a, const price& b ) { if( a.asset_id == b.base.asset_id ) { FC_ASSERT( b.base.amount.value > 0 ); uint128_t result = (uint128_t(a.amount.value) * b.quote.amount.value)/b.base.amount.value; FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY ); return asset( result.convert_to<int64_t>(), b.quote.asset_id ); } else if( a.asset_id == b.quote.asset_id ) { FC_ASSERT( b.quote.amount.value > 0 ); uint128_t result = (uint128_t(a.amount.value) * b.base.amount.value)/b.quote.amount.value; FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY ); return asset( result.convert_to<int64_t>(), b.base.asset_id ); } FC_THROW_EXCEPTION( fc::assert_exception, "invalid asset * price", ("asset",a)("price",b) ); } asset asset::multiply_and_round_up( const price& b )const { const asset& a = *this; if( a.asset_id == b.base.asset_id ) { FC_ASSERT( b.base.amount.value > 0 ); uint128_t result = (uint128_t(a.amount.value) * b.quote.amount.value + b.base.amount.value - 1)/b.base.amount.value; FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY ); return asset( result.convert_to<int64_t>(), b.quote.asset_id ); } else if( a.asset_id == b.quote.asset_id ) { FC_ASSERT( b.quote.amount.value > 0 ); uint128_t result = (uint128_t(a.amount.value) * b.base.amount.value + b.quote.amount.value - 1)/b.quote.amount.value; FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY ); return asset( result.convert_to<int64_t>(), b.base.asset_id ); } FC_THROW_EXCEPTION( fc::assert_exception, "invalid asset::multiply_and_round_up(price)", ("asset",a)("price",b) ); } price operator / ( const asset& base, const asset& quote ) { try { FC_ASSERT( base.asset_id != quote.asset_id ); return price{base,quote}; } FC_CAPTURE_AND_RETHROW( (base)(quote) ) } price price::max( asset_id_type base, asset_id_type quote ) { return asset( share_type(GRAPHENE_MAX_SHARE_SUPPLY), base ) / asset( share_type(1), quote); } price price::min( asset_id_type base, asset_id_type quote ) { return asset( 1, base ) / asset( GRAPHENE_MAX_SHARE_SUPPLY, quote); } price operator * ( const price& p, const ratio_type& r ) { try { p.validate(); FC_ASSERT( r.numerator() > 0 && r.denominator() > 0 ); if( r.numerator() == r.denominator() ) return p; boost::rational<int128_t> p128( p.base.amount.value, p.quote.amount.value ); boost::rational<int128_t> r128( r.numerator(), r.denominator() ); auto cp = p128 * r128; auto ocp = cp; bool shrinked = false; bool using_max = false; static const int128_t max( GRAPHENE_MAX_SHARE_SUPPLY ); while( cp.numerator() > max || cp.denominator() > max ) { if( cp.numerator() == 1 ) { cp = boost::rational<int128_t>( 1, max ); using_max = true; break; } else if( cp.denominator() == 1 ) { cp = boost::rational<int128_t>( max, 1 ); using_max = true; break; } else { cp = boost::rational<int128_t>( cp.numerator() >> 1, cp.denominator() >> 1 ); shrinked = true; } } if( shrinked ) // maybe not accurate enough due to rounding, do additional checks here { int128_t num = ocp.numerator(); int128_t den = ocp.denominator(); if( num > den ) { num /= den; if( num > max ) num = max; den = 1; } else { den /= num; if( den > max ) den = max; num = 1; } boost::rational<int128_t> ncp( num, den ); if( num == max || den == max ) // it's on the edge, we know it's accurate enough cp = ncp; else { // from the accurate ocp, now we have ncp and cp. use the one which is closer to ocp. // TODO improve performance auto diff1 = abs( ncp - ocp ); auto diff2 = abs( cp - ocp ); if( diff1 < diff2 ) cp = ncp; } } price np = asset( cp.numerator().convert_to<int64_t>(), p.base.asset_id ) / asset( cp.denominator().convert_to<int64_t>(), p.quote.asset_id ); if( shrinked || using_max ) { if( ( r.numerator() > r.denominator() && np < p ) || ( r.numerator() < r.denominator() && np > p ) ) // even with an accurate result, if p is out of valid range, return it np = p; } np.validate(); return np; } FC_CAPTURE_AND_RETHROW( (p)(r.numerator())(r.denominator()) ) } price operator / ( const price& p, const ratio_type& r ) { try { return p * ratio_type( r.denominator(), r.numerator() ); } FC_CAPTURE_AND_RETHROW( (p)(r.numerator())(r.denominator()) ) } /** * The black swan price is defined as debt/collateral, we want to perform a margin call * before debt == collateral. Given a debt/collateral ratio of 1 USD / CORE and * a maintenance collateral requirement of 2x we can define the call price to be * 2 USD / CORE. * * This method divides the collateral by the maintenance collateral ratio to derive * a call price for the given black swan ratio. * * There exists some cases where the debt and collateral values are so small that * dividing by the collateral ratio will result in a 0 price or really poor * rounding errors. No matter what the collateral part of the price ratio can * never go to 0 and the debt can never go more than GRAPHENE_MAX_SHARE_SUPPLY * * CR * DEBT/COLLAT or DEBT/(COLLAT/CR) */ price price::call_price( const asset& debt, const asset& collateral, uint16_t collateral_ratio) { try { // TODO replace the calculation with new operator*() and/or operator/(), could be a hardfork change due to edge cases //wdump((debt)(collateral)(collateral_ratio)); boost::rational<int128_t> swan(debt.amount.value,collateral.amount.value); boost::rational<int128_t> ratio( collateral_ratio, GRAPHENE_COLLATERAL_RATIO_DENOM ); auto cp = swan * ratio; while( cp.numerator() > GRAPHENE_MAX_SHARE_SUPPLY || cp.denominator() > GRAPHENE_MAX_SHARE_SUPPLY ) cp = boost::rational<int128_t>( (cp.numerator() >> 1)+1, (cp.denominator() >> 1)+1 ); return ~(asset( cp.numerator().convert_to<int64_t>(), debt.asset_id ) / asset( cp.denominator().convert_to<int64_t>(), collateral.asset_id )); } FC_CAPTURE_AND_RETHROW( (debt)(collateral)(collateral_ratio) ) } bool price::is_null() const { // Effectively same as "return *this == price();" but perhaps faster return ( base.asset_id == asset_id_type() && quote.asset_id == asset_id_type() ); } void price::validate() const { try { FC_ASSERT( base.amount > share_type(0) ); FC_ASSERT( quote.amount > share_type(0) ); FC_ASSERT( base.asset_id != quote.asset_id ); } FC_CAPTURE_AND_RETHROW( (base)(quote) ) } void price_feed::validate() const { try { if( !settlement_price.is_null() ) settlement_price.validate(); FC_ASSERT( maximum_short_squeeze_ratio >= GRAPHENE_MIN_COLLATERAL_RATIO ); FC_ASSERT( maximum_short_squeeze_ratio <= GRAPHENE_MAX_COLLATERAL_RATIO ); FC_ASSERT( maintenance_collateral_ratio >= GRAPHENE_MIN_COLLATERAL_RATIO ); FC_ASSERT( maintenance_collateral_ratio <= GRAPHENE_MAX_COLLATERAL_RATIO ); max_short_squeeze_price(); // make sure that it doesn't overflow //FC_ASSERT( maintenance_collateral_ratio >= maximum_short_squeeze_ratio ); } FC_CAPTURE_AND_RETHROW( (*this) ) } bool price_feed::is_for( asset_id_type asset_id ) const { try { if( !settlement_price.is_null() ) return (settlement_price.base.asset_id == asset_id); if( !core_exchange_rate.is_null() ) return (core_exchange_rate.base.asset_id == asset_id); // (null, null) is valid for any feed return true; } FC_CAPTURE_AND_RETHROW( (*this) ) } price price_feed::max_short_squeeze_price()const { // TODO replace the calculation with new operator*() and/or operator/(), could be a hardfork change due to edge cases boost::rational<int128_t> sp( settlement_price.base.amount.value, settlement_price.quote.amount.value ); //debt.amount.value,collateral.amount.value); boost::rational<int128_t> ratio( GRAPHENE_COLLATERAL_RATIO_DENOM, maximum_short_squeeze_ratio ); auto cp = sp * ratio; while( cp.numerator() > GRAPHENE_MAX_SHARE_SUPPLY || cp.denominator() > GRAPHENE_MAX_SHARE_SUPPLY ) cp = boost::rational<int128_t>( (cp.numerator() >> 1)+(cp.numerator()&1), (cp.denominator() >> 1)+(cp.denominator()&1) ); return (asset( cp.numerator().convert_to<int64_t>(), settlement_price.base.asset_id ) / asset( cp.denominator().convert_to<int64_t>(), settlement_price.quote.asset_id )); } // compile-time table of powers of 10 using template metaprogramming template< int N > struct p10 { static const int64_t v = 10 * p10<N-1>::v; }; template<> struct p10<0> { static const int64_t v = 1; }; const int64_t scaled_precision_lut[19] = { p10< 0 >::v, p10< 1 >::v, p10< 2 >::v, p10< 3 >::v, p10< 4 >::v, p10< 5 >::v, p10< 6 >::v, p10< 7 >::v, p10< 8 >::v, p10< 9 >::v, p10< 10 >::v, p10< 11 >::v, p10< 12 >::v, p10< 13 >::v, p10< 14 >::v, p10< 15 >::v, p10< 16 >::v, p10< 17 >::v, p10< 18 >::v }; } } // graphene::chain <|endoftext|>
<commit_before>#include "kkrworkboard.h" #include <QPainter> // dimensions static const int MARGIN = 10; static const int FRAME_THICK = 5; static const int BORDER_THICK = 1; static const int CELL_WIDTH = 36; static const int CLUE_WIDTH = CELL_WIDTH/2 - 4; // font face static const char FONT_ANS[] = "consolas"; static const char FONT_CLUE[] = "consolas"; KkrBoardView::KkrBoardView(KkrBoardManager *pBoardData, QWidget *parent) : QWidget(parent) , m_fontAns(FONT_ANS) , m_fontClue(FONT_CLUE) , m_pBoardData(pBoardData) { m_fontAns.setPixelSize(CELL_WIDTH); m_fontClue.setPixelSize(CLUE_WIDTH); setMinimumHeight(300); setMinimumWidth(400); connect(pBoardData, &KkrBoardManager::sigReset, this, &KkrBoardView::slReset); } QRect KkrBoardView::getCellRect(int col, int row) const { const int x = MARGIN + FRAME_THICK + col * (CELL_WIDTH + BORDER_THICK); const int y = MARGIN + FRAME_THICK + row * (CELL_WIDTH + BORDER_THICK); return QRect(x, y, CELL_WIDTH, CELL_WIDTH); } QRect KkrBoardView::getClueRectRight(const QRect &cellRect) const { const QPoint topRight{cellRect.topRight()}; const int x = topRight.x() - CLUE_WIDTH - 1; const int y = topRight.y() + 2; return QRect(x, y, CLUE_WIDTH, CLUE_WIDTH); } QRect KkrBoardView::getClueRectDown(const QRect &cellRect) const { const QPoint bottomLeft{cellRect.bottomLeft()}; const int x = bottomLeft.x() + 2; const int y = bottomLeft.y() - CLUE_WIDTH - 1; return QRect(x, y, CLUE_WIDTH, CLUE_WIDTH); } void KkrBoardView::drawCell(QPainter &p, int col, int row) const { static const char * digits[] = { " ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45" }; const QRect cellRect{getCellRect(col, row)}; switch(m_pBoardData->getCellType(col, row)) { case CellType::CellAnswer: { if(m_curCol == col && m_curRow == row) { QBrush brCyan(Qt::cyan); p.fillRect(cellRect, brCyan); } const int ans = m_pBoardData->getAnswer(col, row); if(ans != EMPTY_ANSWER) { p.setFont(m_fontAns); p.drawText(cellRect, Qt::AlignCenter | Qt::AlignHCenter, digits[ans]); } } break; case CellType::CellClue: { QBrush brFG{ m_curCol==col && m_curRow==row ? Qt::cyan : Qt::black }; p.setBrush(brFG); std::array<QPoint, 3> points; // upper right triangle points[0] = cellRect.topLeft(); points[0] += QPoint(2,1); points[1] = cellRect.topRight(); points[1] += QPoint(-1,1); points[2] = cellRect.bottomRight(); points[2] += QPoint(-1,-2); p.drawPolygon(points.data(), static_cast<int>(points.size())); // bottom left triangle points[0] = cellRect.topLeft(); points[0] += QPoint(1,2); points[1] = cellRect.bottomLeft(); points[1] += QPoint(1,-1); points[2] = cellRect.bottomRight(); points[2] += QPoint(-2,-1); p.drawPolygon(points.data(), static_cast<int>(points.size())); QBrush brWhite(Qt::white); if(m_pBoardData->getClueRight(col, row) != CLOSED_CLUE) { const QRect clueRect{getClueRectRight(cellRect)}; p.fillRect(clueRect, brWhite); p.setFont(m_fontClue); p.drawText(clueRect, Qt::AlignCenter | Qt::AlignHCenter, digits[m_pBoardData->getClueRight(col, row)]); } if(m_pBoardData->getClueDown(col, row) != CLOSED_CLUE) { const QRect clueRect{getClueRectDown(cellRect)}; p.fillRect(clueRect, brWhite); p.setFont(m_fontClue); p.drawText(clueRect, Qt::AlignCenter | Qt::AlignHCenter, digits[m_pBoardData->getClueDown(col, row)]); } } break; default: Q_ASSERT(false); } } void KkrBoardView::paintEvent(QPaintEvent * /*e*/) { QPainter p{this}; const auto C = m_pBoardData->getNumCols(); if(C < 3) return; // frame p.fillRect(MARGIN, MARGIN, m_frame_width, FRAME_THICK, Qt::SolidPattern); p.fillRect(MARGIN, MARGIN+m_frame_height-FRAME_THICK, m_frame_width, FRAME_THICK, Qt::SolidPattern); p.fillRect(MARGIN, MARGIN, FRAME_THICK, m_frame_height, Qt::SolidPattern); p.fillRect(MARGIN+m_frame_width-FRAME_THICK, MARGIN, FRAME_THICK, m_frame_height, Qt::SolidPattern); // cell borders const int TL = MARGIN + FRAME_THICK; for(int yi = 1; yi < m_pBoardData->getNumRows(); ++yi) { const int y = TL - BORDER_THICK + yi * (BORDER_THICK+CELL_WIDTH); p.fillRect(TL, y, m_inner_width, BORDER_THICK, Qt::SolidPattern); } for(int xi = 1; xi < m_pBoardData->getNumCols(); ++xi) { const int x = TL - BORDER_THICK + xi * (BORDER_THICK+CELL_WIDTH); p.fillRect(x, TL, BORDER_THICK, m_inner_height, Qt::SolidPattern); } for(int c = 0; c < m_pBoardData->getNumCols(); ++c) { for(int r = 0; r < m_pBoardData->getNumRows(); ++r) { drawCell(p, c, r); } } } /* * slots */ void KkrBoardView::slReset() { // sizes m_inner_width = (CELL_WIDTH + BORDER_THICK) * m_pBoardData->getNumCols() - BORDER_THICK; m_inner_height = (CELL_WIDTH + BORDER_THICK) * m_pBoardData->getNumRows() - BORDER_THICK; m_frame_width = 2*FRAME_THICK + m_inner_width; m_frame_height = 2*FRAME_THICK + m_inner_height; m_board_width = 2*MARGIN + m_frame_width; m_board_height = 2*MARGIN + m_frame_height; // initial cursor position m_curCol = m_curRow = 0; m_curDown = true; setFixedSize(m_board_width, m_board_height); update(); } <commit_msg>Now includes <array> to complie on Windows<commit_after>#include "kkrworkboard.h" #include <QPainter> #include <array> // dimensions static const int MARGIN = 10; static const int FRAME_THICK = 5; static const int BORDER_THICK = 1; static const int CELL_WIDTH = 36; static const int CLUE_WIDTH = CELL_WIDTH/2 - 4; // font face static const char FONT_ANS[] = "consolas"; static const char FONT_CLUE[] = "consolas"; KkrBoardView::KkrBoardView(KkrBoardManager *pBoardData, QWidget *parent) : QWidget(parent) , m_fontAns(FONT_ANS) , m_fontClue(FONT_CLUE) , m_pBoardData(pBoardData) { m_fontAns.setPixelSize(CELL_WIDTH); m_fontClue.setPixelSize(CLUE_WIDTH); setMinimumHeight(300); setMinimumWidth(400); connect(pBoardData, &KkrBoardManager::sigReset, this, &KkrBoardView::slReset); } QRect KkrBoardView::getCellRect(int col, int row) const { const int x = MARGIN + FRAME_THICK + col * (CELL_WIDTH + BORDER_THICK); const int y = MARGIN + FRAME_THICK + row * (CELL_WIDTH + BORDER_THICK); return QRect(x, y, CELL_WIDTH, CELL_WIDTH); } QRect KkrBoardView::getClueRectRight(const QRect &cellRect) const { const QPoint topRight{cellRect.topRight()}; const int x = topRight.x() - CLUE_WIDTH - 1; const int y = topRight.y() + 2; return QRect(x, y, CLUE_WIDTH, CLUE_WIDTH); } QRect KkrBoardView::getClueRectDown(const QRect &cellRect) const { const QPoint bottomLeft{cellRect.bottomLeft()}; const int x = bottomLeft.x() + 2; const int y = bottomLeft.y() - CLUE_WIDTH - 1; return QRect(x, y, CLUE_WIDTH, CLUE_WIDTH); } void KkrBoardView::drawCell(QPainter &p, int col, int row) const { static const char * digits[] = { " ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45" }; const QRect cellRect{getCellRect(col, row)}; switch(m_pBoardData->getCellType(col, row)) { case CellType::CellAnswer: { if(m_curCol == col && m_curRow == row) { QBrush brCyan(Qt::cyan); p.fillRect(cellRect, brCyan); } const int ans = m_pBoardData->getAnswer(col, row); if(ans != EMPTY_ANSWER) { p.setFont(m_fontAns); p.drawText(cellRect, Qt::AlignCenter | Qt::AlignHCenter, digits[ans]); } } break; case CellType::CellClue: { QBrush brFG{ m_curCol==col && m_curRow==row ? Qt::cyan : Qt::black }; p.setBrush(brFG); std::array<QPoint, 3> points; // upper right triangle points[0] = cellRect.topLeft(); points[0] += QPoint(2,1); points[1] = cellRect.topRight(); points[1] += QPoint(-1,1); points[2] = cellRect.bottomRight(); points[2] += QPoint(-1,-2); p.drawPolygon(points.data(), static_cast<int>(points.size())); // bottom left triangle points[0] = cellRect.topLeft(); points[0] += QPoint(1,2); points[1] = cellRect.bottomLeft(); points[1] += QPoint(1,-1); points[2] = cellRect.bottomRight(); points[2] += QPoint(-2,-1); p.drawPolygon(points.data(), static_cast<int>(points.size())); QBrush brWhite(Qt::white); if(m_pBoardData->getClueRight(col, row) != CLOSED_CLUE) { const QRect clueRect{getClueRectRight(cellRect)}; p.fillRect(clueRect, brWhite); p.setFont(m_fontClue); p.drawText(clueRect, Qt::AlignCenter | Qt::AlignHCenter, digits[m_pBoardData->getClueRight(col, row)]); } if(m_pBoardData->getClueDown(col, row) != CLOSED_CLUE) { const QRect clueRect{getClueRectDown(cellRect)}; p.fillRect(clueRect, brWhite); p.setFont(m_fontClue); p.drawText(clueRect, Qt::AlignCenter | Qt::AlignHCenter, digits[m_pBoardData->getClueDown(col, row)]); } } break; default: Q_ASSERT(false); } } void KkrBoardView::paintEvent(QPaintEvent * /*e*/) { QPainter p{this}; const auto C = m_pBoardData->getNumCols(); if(C < 3) return; // frame p.fillRect(MARGIN, MARGIN, m_frame_width, FRAME_THICK, Qt::SolidPattern); p.fillRect(MARGIN, MARGIN+m_frame_height-FRAME_THICK, m_frame_width, FRAME_THICK, Qt::SolidPattern); p.fillRect(MARGIN, MARGIN, FRAME_THICK, m_frame_height, Qt::SolidPattern); p.fillRect(MARGIN+m_frame_width-FRAME_THICK, MARGIN, FRAME_THICK, m_frame_height, Qt::SolidPattern); // cell borders const int TL = MARGIN + FRAME_THICK; for(int yi = 1; yi < m_pBoardData->getNumRows(); ++yi) { const int y = TL - BORDER_THICK + yi * (BORDER_THICK+CELL_WIDTH); p.fillRect(TL, y, m_inner_width, BORDER_THICK, Qt::SolidPattern); } for(int xi = 1; xi < m_pBoardData->getNumCols(); ++xi) { const int x = TL - BORDER_THICK + xi * (BORDER_THICK+CELL_WIDTH); p.fillRect(x, TL, BORDER_THICK, m_inner_height, Qt::SolidPattern); } for(int c = 0; c < m_pBoardData->getNumCols(); ++c) { for(int r = 0; r < m_pBoardData->getNumRows(); ++r) { drawCell(p, c, r); } } } /* * slots */ void KkrBoardView::slReset() { // sizes m_inner_width = (CELL_WIDTH + BORDER_THICK) * m_pBoardData->getNumCols() - BORDER_THICK; m_inner_height = (CELL_WIDTH + BORDER_THICK) * m_pBoardData->getNumRows() - BORDER_THICK; m_frame_width = 2*FRAME_THICK + m_inner_width; m_frame_height = 2*FRAME_THICK + m_inner_height; m_board_width = 2*MARGIN + m_frame_width; m_board_height = 2*MARGIN + m_frame_height; // initial cursor position m_curCol = m_curRow = 0; m_curDown = true; setFixedSize(m_board_width, m_board_height); update(); } <|endoftext|>
<commit_before>#pragma once #include "CompMaterial.h" #include "Color.h" #include "GAmeObject.h" #include "parson.h" #include "Application.h" #include "ModuleFS.h" #include "ImportMaterial.h" #include "ResourceMaterial.h" #include "Scene.h" CompMaterial::CompMaterial(Comp_Type t, GameObject* parent): Component(t, parent) { uid = App->random->Int(); color = White; nameComponent = "Material"; } CompMaterial::CompMaterial(const CompMaterial& copy, GameObject* parent) : Component(Comp_Type::C_CAMERA, parent) { uid = App->random->Int(); color = copy.color; resourceMaterial = copy.resourceMaterial; if (resourceMaterial != nullptr) { resourceMaterial->NumGameObjectsUseMe++; } nameComponent = "Material"; } CompMaterial::~CompMaterial() { if (resourceMaterial != nullptr) { if (resourceMaterial->NumGameObjectsUseMe > 0) { resourceMaterial->NumGameObjectsUseMe--; } } resourceMaterial = nullptr; } void CompMaterial::preUpdate(float dt) { // Before delete Resource Set this pointer to nullptr if (resourceMaterial != nullptr) { if (resourceMaterial->GetState() == Resource::State::WANTDELETE) { resourceMaterial = nullptr; } if (resourceMaterial->GetState() == Resource::State::REIMPORTED) { uuidResourceReimported = resourceMaterial->GetUUID(); resourceMaterial = nullptr; } } else { if (uuidResourceReimported != 0) { resourceMaterial = (ResourceMaterial*)App->resource_manager->GetResource(uuidResourceReimported); resourceMaterial->NumGameObjectsUseMe++; // Check if loaded! if (resourceMaterial->IsLoadedToMemory() == Resource::State::UNLOADED) { App->importer->iMaterial->LoadResource(std::to_string(resourceMaterial->GetUUID()).c_str(), resourceMaterial); } uuidResourceReimported = 0; } } } void CompMaterial::SetColor(float r, float g, float b, float a) { color.r = r; color.g = g; color.b = b; color.a = a; } Color CompMaterial::GetColor() const { return color; } //void CompMaterial::SetTexture(std::vector<Texture> textures) //{ // texture = textures; //} // //void CompMaterial::AddTexture(const Texture tex) //{ // texture.push_back(tex); //} uint CompMaterial::GetTextureID() { //if(texture.size() > 0) // return texture[0].id; if (resourceMaterial != nullptr) { return resourceMaterial->GetTextureID(); } return 0; } void CompMaterial::SetUUIDMesh(uint uuid) { uuid_material = uuid; } void CompMaterial::ShowOptions() { //ImGui::MenuItem("CREATE", NULL, false, false); if (ImGui::MenuItem("Reset")) { // Not implmented yet. } ImGui::Separator(); if (ImGui::MenuItem("Move to Front", NULL, false, false)) { // Not implmented yet. } if (ImGui::MenuItem("Move to Back", NULL, false, false)) { // Not implmented yet. } if (ImGui::MenuItem("Remove Component")) { toDelete = true; } if (ImGui::MenuItem("Move Up", NULL, false, false)) { // Not implmented yet. } if (ImGui::MenuItem("Move Down", NULL, false, false)) { // Not implmented yet. } if (ImGui::MenuItem("Copy Component")) { // Component* Copy = this; } if (ImGui::MenuItem("Paste Component", NULL, false, false)) { //parent->AddComponent(App->scene->copyComponent->GetType()) // Create contructor Component Copy or add funtion to add info } } void CompMaterial::ShowInspectorInfo() { // Reset Values Button ------------------------------------------- ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(3, 0)); ImGui::SameLine(ImGui::GetWindowWidth() - 26); if (ImGui::ImageButton((ImTextureID*)App->scene->icon_options_transform, ImVec2(13, 13), ImVec2(-1, 1), ImVec2(0, 0))) { ImGui::OpenPopup("OptionsMaterial"); } // Button Options -------------------------------------- ImGui::PushStyleColor(ImGuiCol_PopupBg, ImVec4(0.2f, 0.2f, 0.2f, 1.00f)); if (ImGui::BeginPopup("OptionsMaterial")) { ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10, 2)); if (ImGui::Button("Reset Material")) { if (resourceMaterial != nullptr) { if (resourceMaterial->NumGameObjectsUseMe > 0) { resourceMaterial->NumGameObjectsUseMe--; } } resourceMaterial = nullptr; ImGui::CloseCurrentPopup(); } ImGui::Separator(); if (ImGui::Button("Select Material...")) { selectMaterial = true; ImGui::CloseCurrentPopup(); } ImGui::PopStyleVar(); ImGui::EndPopup(); } ImGui::PopStyleColor(); ImGui::PopStyleVar(); ImGui::ColorEdit3("", (float*)&color); if (resourceMaterial != nullptr) { ImGui::Text("Name:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.25f, 1.00f, 0.00f, 1.00f), "%s", resourceMaterial->name); //ImGui::Checkbox("Render", &render); } if(resourceMaterial == nullptr || selectMaterial) { if (resourceMaterial == nullptr) { if (ImGui::Button("Select Material...")) { selectMaterial = true; } } if (selectMaterial) { ResourceMaterial* temp = (ResourceMaterial*)App->resource_manager->ShowResources(selectMaterial, Resource::Type::MATERIAL); if (temp != nullptr) { if (resourceMaterial != nullptr) { if (resourceMaterial->NumGameObjectsUseMe > 0) { resourceMaterial->NumGameObjectsUseMe--; } } resourceMaterial = temp; resourceMaterial->NumGameObjectsUseMe++; if (resourceMaterial->IsLoadedToMemory() == Resource::State::UNLOADED) { App->importer->iMaterial->LoadResource(std::to_string(resourceMaterial->GetUUID()).c_str(), resourceMaterial); } Enable(); } } } ImGui::TreePop(); } void CompMaterial::Save(JSON_Object* object, std::string name, bool saveScene, uint& countResources) const { json_object_dotset_number_with_std(object, name + "Type", C_MATERIAL); float4 tempColor = { color.r, color.g, color.b, color.a }; App->fs->json_array_dotset_float4(object, name + "Color", tempColor); json_object_dotset_number_with_std(object, name + "UUID", uid); if (resourceMaterial != nullptr) { //if (saveScene == false) // At the moment we only save info of the Resoruce Mesh //{ // // Save Info of Resource in Prefab (next we use this info for Reimport this prefab) // std::string temp = std::to_string(countResources++); // json_object_dotset_number_with_std(object, "Info.Resources.Resource " + temp + ".UUID Resource", resourceMaterial->GetUUID()); // json_object_dotset_string_with_std(object, "Info.Resources.Resource " + temp + ".name", resourceMaterial->name); //} json_object_dotset_number_with_std(object, name + "Resource Material UUID", resourceMaterial->GetUUID()); } else { json_object_dotset_number_with_std(object, name + "Resource Material UUID", 0); } } void CompMaterial::Load(const JSON_Object* object, std::string name) { float4 tempColor = App->fs->json_array_dotget_float4_string(object, name + "Color"); color.Set(tempColor.x, tempColor.y, tempColor.z, tempColor.w); uid = json_object_dotget_number_with_std(object, name + "UUID"); uint resourceID = json_object_dotget_number_with_std(object, name + "Resource Material UUID"); if (resourceID > 0) { resourceMaterial = (ResourceMaterial*)App->resource_manager->GetResource(resourceID); if (resourceMaterial != nullptr) { resourceMaterial->NumGameObjectsUseMe++; // LOAD MATERIAL if (resourceMaterial->IsLoadedToMemory() == Resource::State::UNLOADED) { App->importer->iMaterial->LoadResource(std::to_string(resourceMaterial->GetUUID()).c_str(), resourceMaterial); } } } Enable(); } <commit_msg>Added texture image to inspector<commit_after>#pragma once #include "CompMaterial.h" #include "Color.h" #include "GAmeObject.h" #include "parson.h" #include "Application.h" #include "ModuleFS.h" #include "ImportMaterial.h" #include "ResourceMaterial.h" #include "Scene.h" CompMaterial::CompMaterial(Comp_Type t, GameObject* parent): Component(t, parent) { uid = App->random->Int(); color = White; nameComponent = "Material"; } CompMaterial::CompMaterial(const CompMaterial& copy, GameObject* parent) : Component(Comp_Type::C_CAMERA, parent) { uid = App->random->Int(); color = copy.color; resourceMaterial = copy.resourceMaterial; if (resourceMaterial != nullptr) { resourceMaterial->NumGameObjectsUseMe++; } nameComponent = "Material"; } CompMaterial::~CompMaterial() { if (resourceMaterial != nullptr) { if (resourceMaterial->NumGameObjectsUseMe > 0) { resourceMaterial->NumGameObjectsUseMe--; } } resourceMaterial = nullptr; } void CompMaterial::preUpdate(float dt) { // Before delete Resource Set this pointer to nullptr if (resourceMaterial != nullptr) { if (resourceMaterial->GetState() == Resource::State::WANTDELETE) { resourceMaterial = nullptr; } if (resourceMaterial->GetState() == Resource::State::REIMPORTED) { uuidResourceReimported = resourceMaterial->GetUUID(); resourceMaterial = nullptr; } } else { if (uuidResourceReimported != 0) { resourceMaterial = (ResourceMaterial*)App->resource_manager->GetResource(uuidResourceReimported); resourceMaterial->NumGameObjectsUseMe++; // Check if loaded! if (resourceMaterial->IsLoadedToMemory() == Resource::State::UNLOADED) { App->importer->iMaterial->LoadResource(std::to_string(resourceMaterial->GetUUID()).c_str(), resourceMaterial); } uuidResourceReimported = 0; } } } void CompMaterial::SetColor(float r, float g, float b, float a) { color.r = r; color.g = g; color.b = b; color.a = a; } Color CompMaterial::GetColor() const { return color; } //void CompMaterial::SetTexture(std::vector<Texture> textures) //{ // texture = textures; //} // //void CompMaterial::AddTexture(const Texture tex) //{ // texture.push_back(tex); //} uint CompMaterial::GetTextureID() { //if(texture.size() > 0) // return texture[0].id; if (resourceMaterial != nullptr) { return resourceMaterial->GetTextureID(); } return 0; } void CompMaterial::SetUUIDMesh(uint uuid) { uuid_material = uuid; } void CompMaterial::ShowOptions() { //ImGui::MenuItem("CREATE", NULL, false, false); if (ImGui::MenuItem("Reset")) { // Not implmented yet. } ImGui::Separator(); if (ImGui::MenuItem("Move to Front", NULL, false, false)) { // Not implmented yet. } if (ImGui::MenuItem("Move to Back", NULL, false, false)) { // Not implmented yet. } if (ImGui::MenuItem("Remove Component")) { toDelete = true; } if (ImGui::MenuItem("Move Up", NULL, false, false)) { // Not implmented yet. } if (ImGui::MenuItem("Move Down", NULL, false, false)) { // Not implmented yet. } if (ImGui::MenuItem("Copy Component")) { // Component* Copy = this; } if (ImGui::MenuItem("Paste Component", NULL, false, false)) { //parent->AddComponent(App->scene->copyComponent->GetType()) // Create contructor Component Copy or add funtion to add info } } void CompMaterial::ShowInspectorInfo() { // Reset Values Button ------------------------------------------- ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(3, 0)); ImGui::SameLine(ImGui::GetWindowWidth() - 26); if (ImGui::ImageButton((ImTextureID*)App->scene->icon_options_transform, ImVec2(13, 13), ImVec2(-1, 1), ImVec2(0, 0))) { ImGui::OpenPopup("OptionsMaterial"); } // Button Options -------------------------------------- ImGui::PushStyleColor(ImGuiCol_PopupBg, ImVec4(0.2f, 0.2f, 0.2f, 1.00f)); if (ImGui::BeginPopup("OptionsMaterial")) { ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10, 2)); if (ImGui::Button("Reset Material")) { if (resourceMaterial != nullptr) { if (resourceMaterial->NumGameObjectsUseMe > 0) { resourceMaterial->NumGameObjectsUseMe--; } } resourceMaterial = nullptr; ImGui::CloseCurrentPopup(); } ImGui::Separator(); if (ImGui::Button("Select Material...")) { selectMaterial = true; ImGui::CloseCurrentPopup(); } ImGui::PopStyleVar(); ImGui::EndPopup(); } ImGui::PopStyleColor(); ImGui::PopStyleVar(); ImGui::ColorEdit3("", (float*)&color); if (resourceMaterial != nullptr) { ImGui::Text("Name:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.25f, 1.00f, 0.00f, 1.00f), "%s", resourceMaterial->name); ImGui::Image((ImTextureID*)resourceMaterial->GetTextureID(), ImVec2(170, 170), ImVec2(-1, 1), ImVec2(0, 0)); //ImGui::Checkbox("Render", &render); } if(resourceMaterial == nullptr || selectMaterial) { if (resourceMaterial == nullptr) { if (ImGui::Button("Select Material...")) { selectMaterial = true; } } if (selectMaterial) { ResourceMaterial* temp = (ResourceMaterial*)App->resource_manager->ShowResources(selectMaterial, Resource::Type::MATERIAL); if (temp != nullptr) { if (resourceMaterial != nullptr) { if (resourceMaterial->NumGameObjectsUseMe > 0) { resourceMaterial->NumGameObjectsUseMe--; } } resourceMaterial = temp; resourceMaterial->NumGameObjectsUseMe++; if (resourceMaterial->IsLoadedToMemory() == Resource::State::UNLOADED) { App->importer->iMaterial->LoadResource(std::to_string(resourceMaterial->GetUUID()).c_str(), resourceMaterial); } Enable(); } } } ImGui::TreePop(); } void CompMaterial::Save(JSON_Object* object, std::string name, bool saveScene, uint& countResources) const { json_object_dotset_number_with_std(object, name + "Type", C_MATERIAL); float4 tempColor = { color.r, color.g, color.b, color.a }; App->fs->json_array_dotset_float4(object, name + "Color", tempColor); json_object_dotset_number_with_std(object, name + "UUID", uid); if (resourceMaterial != nullptr) { //if (saveScene == false) // At the moment we only save info of the Resoruce Mesh //{ // // Save Info of Resource in Prefab (next we use this info for Reimport this prefab) // std::string temp = std::to_string(countResources++); // json_object_dotset_number_with_std(object, "Info.Resources.Resource " + temp + ".UUID Resource", resourceMaterial->GetUUID()); // json_object_dotset_string_with_std(object, "Info.Resources.Resource " + temp + ".name", resourceMaterial->name); //} json_object_dotset_number_with_std(object, name + "Resource Material UUID", resourceMaterial->GetUUID()); } else { json_object_dotset_number_with_std(object, name + "Resource Material UUID", 0); } } void CompMaterial::Load(const JSON_Object* object, std::string name) { float4 tempColor = App->fs->json_array_dotget_float4_string(object, name + "Color"); color.Set(tempColor.x, tempColor.y, tempColor.z, tempColor.w); uid = json_object_dotget_number_with_std(object, name + "UUID"); uint resourceID = json_object_dotget_number_with_std(object, name + "Resource Material UUID"); if (resourceID > 0) { resourceMaterial = (ResourceMaterial*)App->resource_manager->GetResource(resourceID); if (resourceMaterial != nullptr) { resourceMaterial->NumGameObjectsUseMe++; // LOAD MATERIAL if (resourceMaterial->IsLoadedToMemory() == Resource::State::UNLOADED) { App->importer->iMaterial->LoadResource(std::to_string(resourceMaterial->GetUUID()).c_str(), resourceMaterial); } } } Enable(); } <|endoftext|>
<commit_before>/* Copyright (c) 2019-2021, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * * 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 "platform.h" #include <algorithm> #include <ctime> #include <mutex> #include <vector> #include <spdlog/async_logger.h> #include <spdlog/details/thread_pool.h> #include <spdlog/sinks/basic_file_sink.h> #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/spdlog.h> #include "common/logging.h" #include "force_close/force_close.h" #include "platform/filesystem.h" #include "platform/parsers/CLI11.h" #include "platform/plugins/plugin.h" namespace vkb { const uint32_t Platform::MIN_WINDOW_WIDTH = 420; const uint32_t Platform::MIN_WINDOW_HEIGHT = 320; std::vector<std::string> Platform::arguments = {}; std::string Platform::external_storage_directory = ""; std::string Platform::temp_directory = ""; ExitCode Platform::initialize(const std::vector<Plugin *> &plugins = {}) { auto sinks = get_platform_sinks(); auto logger = std::make_shared<spdlog::logger>("logger", sinks.begin(), sinks.end()); #ifdef VKB_DEBUG logger->set_level(spdlog::level::debug); #else logger->set_level(spdlog::level::info); #endif logger->set_pattern(LOGGER_FORMAT); spdlog::set_default_logger(logger); LOGI("Logger initialized"); parser = std::make_unique<CLI11CommandParser>("vulkan_samples", "\n\tVulkan Samples\n\n\t\tA collection of samples to demonstrate the Vulkan best practice.\n", arguments); // Process command line arguments if (!parser->parse(associate_plugins(plugins))) { return ExitCode::Help; } // Subscribe plugins to requested hooks and store activated plugins for (auto *plugin : plugins) { if (plugin->activate_plugin(this, *parser.get())) { auto &plugin_hooks = plugin->get_hooks(); for (auto hook : plugin_hooks) { auto it = hooks.find(hook); if (it == hooks.end()) { auto r = hooks.emplace(hook, std::vector<Plugin *>{}); if (r.second) { it = r.first; } } it->second.emplace_back(plugin); } active_plugins.emplace_back(plugin); } } // Platform has been closed by a plugins initialization phase if (close_requested) { return ExitCode::Close; } create_window(window_properties); if (!window) { LOGE("Window creation failed!"); return ExitCode::FatalError; } return ExitCode::Success; } ExitCode Platform::main_loop() { if (!app_requested()) { LOGI("An app was not requested, can not continue"); return ExitCode::Close; } while (!window->should_close() && !close_requested) { try { // Load the requested app if (app_requested()) { if (!start_app()) { LOGE("Failed to load requested application"); return ExitCode::FatalError; } // Compensate for load times of the app by rendering the first frame pre-emptively timer.tick<Timer::Seconds>(); active_app->update(0.01667f); } update(); window->process_events(); } catch (std::exception e) { LOGE("Error Message: {}", e.what()); LOGE("Failed when running application {}", active_app->get_name()); on_app_error(active_app->get_name()); if (app_requested()) { LOGI("Attempting to load next application"); } else { return ExitCode::FatalError; } } } return ExitCode::Success; } void Platform::update() { auto delta_time = static_cast<float>(timer.tick<Timer::Seconds>()); if (focused) { on_update(delta_time); if (fixed_simulation_fps) { delta_time = simulation_frame_time; } active_app->update(delta_time); } } std::unique_ptr<RenderContext> Platform::create_render_context(Device &device, VkSurfaceKHR surface, const std::vector<VkSurfaceFormatKHR> &surface_format_priority) const { assert(!surface_format_priority.empty() && "Surface format priority list must contain atleast one preffered surface format"); auto extent = window->get_extent(); auto context = std::make_unique<RenderContext>(device, surface, extent.width, extent.height); context->set_surface_format_priority(surface_format_priority); context->request_image_format(surface_format_priority[0].format); context->set_present_mode_priority({ VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, }); switch (window_properties.vsync) { case Window::Vsync::ON: context->request_present_mode(VK_PRESENT_MODE_FIFO_KHR); break; case Window::Vsync::OFF: default: context->request_present_mode(VK_PRESENT_MODE_MAILBOX_KHR); break; } return std::move(context); } void Platform::terminate(ExitCode code) { if (code == ExitCode::Help) { auto help = parser->help(); for (auto &line : help) { LOGI(line); } } if (active_app) { std::string id = active_app->get_name(); on_app_close(id); active_app->finish(); } active_app.reset(); window.reset(); spdlog::drop_all(); on_platform_close(); // Halt on all unsuccessful exit codes unless ForceClose is in use if (code != ExitCode::Success && !using_plugin<::plugins::ForceClose>()) { #ifndef ANDROID std::cout << "Press any key to continue"; std::cin.get(); #endif } } void Platform::close() { if (window) { window->close(); } // Fallback incase a window is not yet in use close_requested = true; } void Platform::force_simulation_fps(float fps) { fixed_simulation_fps = true; simulation_frame_time = 1 / fps; } void Platform::disable_input_processing() { process_input_events = false; } void Platform::set_focus(bool focused) { focused = focused; } void Platform::set_window_properties(const Window::OptionalProperties &properties) { window_properties.title = properties.title.has_value() ? properties.title.value() : window_properties.title; window_properties.mode = properties.mode.has_value() ? properties.mode.value() : window_properties.mode; window_properties.resizable = properties.resizable.has_value() ? properties.resizable.value() : window_properties.resizable; window_properties.vsync = properties.vsync.has_value() ? properties.vsync.value() : window_properties.vsync; window_properties.extent.width = properties.extent.width.has_value() ? properties.extent.width.value() : window_properties.extent.width; window_properties.extent.height = properties.extent.height.has_value() ? properties.extent.height.value() : window_properties.extent.height; } const std::string &Platform::get_external_storage_directory() { return external_storage_directory; } const std::string &Platform::get_temp_directory() { return temp_directory; } Application &Platform::get_app() { assert(active_app && "Application is not valid"); return *active_app; } Application &Platform::get_app() const { assert(active_app && "Application is not valid"); return *active_app; } Window &Platform::get_window() const { return *window; } std::vector<std::string> &Platform::get_arguments() { return Platform::arguments; } void Platform::set_arguments(const std::vector<std::string> &args) { arguments = args; } void Platform::set_external_storage_directory(const std::string &dir) { external_storage_directory = dir; } void Platform::set_temp_directory(const std::string &dir) { temp_directory = dir; } std::vector<spdlog::sink_ptr> Platform::get_platform_sinks() { std::vector<spdlog::sink_ptr> sinks; sinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>()); return sinks; } bool Platform::app_requested() { return requested_app != nullptr; } void Platform::request_application(const apps::AppInfo *app) { requested_app = app; } bool Platform::start_app() { auto *requested_app_info = requested_app; // Reset early incase error in preperation stage requested_app = nullptr; if (active_app) { auto execution_time = timer.stop(); LOGI("Closing App (Runtime: {:.1f})", execution_time); auto app_id = active_app->get_name(); active_app->finish(); } active_app = requested_app_info->create(); active_app->set_name(requested_app_info->id); if (!active_app) { LOGE("Failed to create a valid vulkan app."); return false; } if (!active_app->prepare(*this)) { LOGE("Failed to prepare vulkan app."); return false; } on_app_start(requested_app_info->id); return true; } void Platform::input_event(const InputEvent &input_event) { if (process_input_events && active_app) { active_app->input_event(input_event); } if (input_event.get_source() == EventSource::Keyboard) { const auto &key_event = static_cast<const KeyInputEvent &>(input_event); if (key_event.get_code() == KeyCode::Back || key_event.get_code() == KeyCode::Escape) { close(); } } } void Platform::resize(uint32_t width, uint32_t height) { auto extent = Window::Extent{std::max<uint32_t>(width, MIN_WINDOW_WIDTH), std::max<uint32_t>(height, MIN_WINDOW_HEIGHT)}; if (window) { auto actual_extent = window->resize(extent); if (active_app) { active_app->resize(actual_extent.width, actual_extent.height); } } } #define HOOK(enum, func) \ static auto res = hooks.find(enum); \ if (res != hooks.end()) \ { \ for (auto plugin : res->second) \ { \ plugin->func; \ } \ } void Platform::on_post_draw(RenderContext &context) { HOOK(Hook::PostDraw, on_post_draw(context)); } void Platform::on_app_error(const std::string &app_id) { HOOK(Hook::OnAppError, on_app_error(app_id)); } void Platform::on_update(float delta_time) { HOOK(Hook::OnUpdate, on_update(delta_time)); } void Platform::on_app_start(const std::string &app_id) { HOOK(Hook::OnAppStart, on_app_start(app_id)); } void Platform::on_app_close(const std::string &app_id) { HOOK(Hook::OnAppClose, on_app_close(app_id)); } void Platform::on_platform_close() { HOOK(Hook::OnPlatformClose, on_platform_close()); } #undef HOOK } // namespace vkb <commit_msg>allow for exceptions to throw more relevant errors (#344)<commit_after>/* Copyright (c) 2019-2021, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * * 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 "platform.h" #include <algorithm> #include <ctime> #include <mutex> #include <vector> #include <spdlog/async_logger.h> #include <spdlog/details/thread_pool.h> #include <spdlog/sinks/basic_file_sink.h> #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/spdlog.h> #include "common/logging.h" #include "force_close/force_close.h" #include "platform/filesystem.h" #include "platform/parsers/CLI11.h" #include "platform/plugins/plugin.h" namespace vkb { const uint32_t Platform::MIN_WINDOW_WIDTH = 420; const uint32_t Platform::MIN_WINDOW_HEIGHT = 320; std::vector<std::string> Platform::arguments = {}; std::string Platform::external_storage_directory = ""; std::string Platform::temp_directory = ""; ExitCode Platform::initialize(const std::vector<Plugin *> &plugins = {}) { auto sinks = get_platform_sinks(); auto logger = std::make_shared<spdlog::logger>("logger", sinks.begin(), sinks.end()); #ifdef VKB_DEBUG logger->set_level(spdlog::level::debug); #else logger->set_level(spdlog::level::info); #endif logger->set_pattern(LOGGER_FORMAT); spdlog::set_default_logger(logger); LOGI("Logger initialized"); parser = std::make_unique<CLI11CommandParser>("vulkan_samples", "\n\tVulkan Samples\n\n\t\tA collection of samples to demonstrate the Vulkan best practice.\n", arguments); // Process command line arguments if (!parser->parse(associate_plugins(plugins))) { return ExitCode::Help; } // Subscribe plugins to requested hooks and store activated plugins for (auto *plugin : plugins) { if (plugin->activate_plugin(this, *parser.get())) { auto &plugin_hooks = plugin->get_hooks(); for (auto hook : plugin_hooks) { auto it = hooks.find(hook); if (it == hooks.end()) { auto r = hooks.emplace(hook, std::vector<Plugin *>{}); if (r.second) { it = r.first; } } it->second.emplace_back(plugin); } active_plugins.emplace_back(plugin); } } // Platform has been closed by a plugins initialization phase if (close_requested) { return ExitCode::Close; } create_window(window_properties); if (!window) { LOGE("Window creation failed!"); return ExitCode::FatalError; } return ExitCode::Success; } ExitCode Platform::main_loop() { if (!app_requested()) { LOGI("An app was not requested, can not continue"); return ExitCode::Close; } while (!window->should_close() && !close_requested) { try { // Load the requested app if (app_requested()) { if (!start_app()) { LOGE("Failed to load requested application"); return ExitCode::FatalError; } // Compensate for load times of the app by rendering the first frame pre-emptively timer.tick<Timer::Seconds>(); active_app->update(0.01667f); } update(); window->process_events(); } catch (std::exception &e) { LOGE("Error Message: {}", e.what()); LOGE("Failed when running application {}", active_app->get_name()); on_app_error(active_app->get_name()); if (app_requested()) { LOGI("Attempting to load next application"); } else { return ExitCode::FatalError; } } } return ExitCode::Success; } void Platform::update() { auto delta_time = static_cast<float>(timer.tick<Timer::Seconds>()); if (focused) { on_update(delta_time); if (fixed_simulation_fps) { delta_time = simulation_frame_time; } active_app->update(delta_time); } } std::unique_ptr<RenderContext> Platform::create_render_context(Device &device, VkSurfaceKHR surface, const std::vector<VkSurfaceFormatKHR> &surface_format_priority) const { assert(!surface_format_priority.empty() && "Surface format priority list must contain atleast one preffered surface format"); auto extent = window->get_extent(); auto context = std::make_unique<RenderContext>(device, surface, extent.width, extent.height); context->set_surface_format_priority(surface_format_priority); context->request_image_format(surface_format_priority[0].format); context->set_present_mode_priority({ VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, }); switch (window_properties.vsync) { case Window::Vsync::ON: context->request_present_mode(VK_PRESENT_MODE_FIFO_KHR); break; case Window::Vsync::OFF: default: context->request_present_mode(VK_PRESENT_MODE_MAILBOX_KHR); break; } return std::move(context); } void Platform::terminate(ExitCode code) { if (code == ExitCode::Help) { auto help = parser->help(); for (auto &line : help) { LOGI(line); } } if (active_app) { std::string id = active_app->get_name(); on_app_close(id); active_app->finish(); } active_app.reset(); window.reset(); spdlog::drop_all(); on_platform_close(); // Halt on all unsuccessful exit codes unless ForceClose is in use if (code != ExitCode::Success && !using_plugin<::plugins::ForceClose>()) { #ifndef ANDROID std::cout << "Press any key to continue"; std::cin.get(); #endif } } void Platform::close() { if (window) { window->close(); } // Fallback incase a window is not yet in use close_requested = true; } void Platform::force_simulation_fps(float fps) { fixed_simulation_fps = true; simulation_frame_time = 1 / fps; } void Platform::disable_input_processing() { process_input_events = false; } void Platform::set_focus(bool focused) { focused = focused; } void Platform::set_window_properties(const Window::OptionalProperties &properties) { window_properties.title = properties.title.has_value() ? properties.title.value() : window_properties.title; window_properties.mode = properties.mode.has_value() ? properties.mode.value() : window_properties.mode; window_properties.resizable = properties.resizable.has_value() ? properties.resizable.value() : window_properties.resizable; window_properties.vsync = properties.vsync.has_value() ? properties.vsync.value() : window_properties.vsync; window_properties.extent.width = properties.extent.width.has_value() ? properties.extent.width.value() : window_properties.extent.width; window_properties.extent.height = properties.extent.height.has_value() ? properties.extent.height.value() : window_properties.extent.height; } const std::string &Platform::get_external_storage_directory() { return external_storage_directory; } const std::string &Platform::get_temp_directory() { return temp_directory; } Application &Platform::get_app() { assert(active_app && "Application is not valid"); return *active_app; } Application &Platform::get_app() const { assert(active_app && "Application is not valid"); return *active_app; } Window &Platform::get_window() const { return *window; } std::vector<std::string> &Platform::get_arguments() { return Platform::arguments; } void Platform::set_arguments(const std::vector<std::string> &args) { arguments = args; } void Platform::set_external_storage_directory(const std::string &dir) { external_storage_directory = dir; } void Platform::set_temp_directory(const std::string &dir) { temp_directory = dir; } std::vector<spdlog::sink_ptr> Platform::get_platform_sinks() { std::vector<spdlog::sink_ptr> sinks; sinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>()); return sinks; } bool Platform::app_requested() { return requested_app != nullptr; } void Platform::request_application(const apps::AppInfo *app) { requested_app = app; } bool Platform::start_app() { auto *requested_app_info = requested_app; // Reset early incase error in preperation stage requested_app = nullptr; if (active_app) { auto execution_time = timer.stop(); LOGI("Closing App (Runtime: {:.1f})", execution_time); auto app_id = active_app->get_name(); active_app->finish(); } active_app = requested_app_info->create(); active_app->set_name(requested_app_info->id); if (!active_app) { LOGE("Failed to create a valid vulkan app."); return false; } if (!active_app->prepare(*this)) { LOGE("Failed to prepare vulkan app."); return false; } on_app_start(requested_app_info->id); return true; } void Platform::input_event(const InputEvent &input_event) { if (process_input_events && active_app) { active_app->input_event(input_event); } if (input_event.get_source() == EventSource::Keyboard) { const auto &key_event = static_cast<const KeyInputEvent &>(input_event); if (key_event.get_code() == KeyCode::Back || key_event.get_code() == KeyCode::Escape) { close(); } } } void Platform::resize(uint32_t width, uint32_t height) { auto extent = Window::Extent{std::max<uint32_t>(width, MIN_WINDOW_WIDTH), std::max<uint32_t>(height, MIN_WINDOW_HEIGHT)}; if (window) { auto actual_extent = window->resize(extent); if (active_app) { active_app->resize(actual_extent.width, actual_extent.height); } } } #define HOOK(enum, func) \ static auto res = hooks.find(enum); \ if (res != hooks.end()) \ { \ for (auto plugin : res->second) \ { \ plugin->func; \ } \ } void Platform::on_post_draw(RenderContext &context) { HOOK(Hook::PostDraw, on_post_draw(context)); } void Platform::on_app_error(const std::string &app_id) { HOOK(Hook::OnAppError, on_app_error(app_id)); } void Platform::on_update(float delta_time) { HOOK(Hook::OnUpdate, on_update(delta_time)); } void Platform::on_app_start(const std::string &app_id) { HOOK(Hook::OnAppStart, on_app_start(app_id)); } void Platform::on_app_close(const std::string &app_id) { HOOK(Hook::OnAppClose, on_app_close(app_id)); } void Platform::on_platform_close() { HOOK(Hook::OnPlatformClose, on_platform_close()); } #undef HOOK } // namespace vkb <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "ADFParser.h" ADFParser::ADFParser() : FunctionParserAD(), _epsilon(1e-12) {} ADFParser::ADFParser(const ADFParser & cpy) : FunctionParserAD(cpy), _epsilon(1e-12) {} bool ADFParser::JITCompile() { #if LIBMESH_HAVE_FPARSER_JIT auto result = JITCompileHelper("ADReal", ADFPARSER_INCLUDES, "#include \"ADReal.h\"\n"); if (!result) #endif mooseError("ADFParser::JITCompile() failed. Evaluation not possible."); return true; } ADReal ADFParser::Eval(const ADReal * vars) { mooseAssert(compiledFunction, "ADFParser objects must be JIT compiled before evaluation!"); ADReal ret; (*reinterpret_cast<CompiledFunctionPtr<ADReal>>(compiledFunction))(&ret, vars, pImmed, _epsilon); return ret; } <commit_msg>Add compile error message (#15480)<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "ADFParser.h" ADFParser::ADFParser() : FunctionParserAD(), _epsilon(1e-12) {} ADFParser::ADFParser(const ADFParser & cpy) : FunctionParserAD(cpy), _epsilon(1e-12) {} #ifndef ADFPARSER_INCLUDES #error ... \ The ADFPARSER_INCLUDES macro is not defined. A possible reason is that you \ are compiling MOOSE from a custom application. Please check your application \ Makefile and make sure that you are appending options to ADDITIONAL_CPPFLAGS \ using the += operator, rather than overwriting the variable with the := operator. #endif bool ADFParser::JITCompile() { #if LIBMESH_HAVE_FPARSER_JIT auto result = JITCompileHelper("ADReal", ADFPARSER_INCLUDES, "#include \"ADReal.h\"\n"); if (!result) #endif mooseError("ADFParser::JITCompile() failed. Evaluation not possible."); return true; } ADReal ADFParser::Eval(const ADReal * vars) { mooseAssert(compiledFunction, "ADFParser objects must be JIT compiled before evaluation!"); ADReal ret; (*reinterpret_cast<CompiledFunctionPtr<ADReal>>(compiledFunction))(&ret, vars, pImmed, _epsilon); return ret; } <|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 "base/command_line.h" #include "base/utf_string_conversions.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "content/shell/shell.h" #include "content/test/content_browser_test.h" #include "content/test/content_browser_test_utils.h" #include "net/test/test_server.h" #if defined(OS_WIN) #include "base/win/windows_version.h" #endif namespace content { class WebrtcBrowserTest: public ContentBrowserTest { public: WebrtcBrowserTest() {} virtual ~WebrtcBrowserTest() {} virtual void SetUp() OVERRIDE { // We need fake devices in this test since we want to run on naked VMs. We // assume this switch is set by default in content_browsertests. ASSERT_TRUE(CommandLine::ForCurrentProcess()->HasSwitch( switches::kUseFakeDeviceForMediaStream)); ASSERT_TRUE(test_server()->Start()); ContentBrowserTest::SetUp(); } protected: bool ExecuteJavascript(const std::string& javascript) { return ExecuteScript(shell()->web_contents(), javascript); } void ExpectTitle(const std::string& expected_title) const { string16 expected_title16(ASCIIToUTF16(expected_title)); TitleWatcher title_watcher(shell()->web_contents(), expected_title16); EXPECT_EQ(expected_title16, title_watcher.WaitAndGetTitle()); } }; // These tests will all make a getUserMedia call with different constraints and // see that the success callback is called. If the error callback is called or // none of the callbacks are called the tests will simply time out and fail. IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetVideoStreamAndStop) { GURL url(test_server()->GetURL("files/media/getusermedia_and_stop.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("getUserMedia({video: true});")); ExpectTitle("OK"); } IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetAudioAndVideoStreamAndStop) { GURL url(test_server()->GetURL("files/media/getusermedia_and_stop.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("getUserMedia({video: true, audio: true});")); ExpectTitle("OK"); } // These tests will make a complete PeerConnection-based call and verify that // video is playing for the call. IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupVideoCall) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("call({video: true});")); ExpectTitle("OK"); } IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupAudioAndVideoCall) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("call({video: true, audio: true});")); ExpectTitle("OK"); } IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, MANUAL_CanSetupCallAndSendDtmf) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); EXPECT_TRUE( ExecuteJavascript("callAndSendDtmf('123,abc');")); } IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanMakeEmptyCallThenAddStreamsAndRenegotiate) { #if defined(OS_WIN) // This test is flaky on Win XP. if (base::win::GetVersion() <= base::win::VERSION_XP) return; #endif GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); const char* kJavascript = "makeEmptyCallThenAddOneStreamAndRenegotiate(" "{video: true, audio: true});"; EXPECT_TRUE(ExecuteJavascript(kJavascript)); ExpectTitle("OK"); } // This test will make a complete PeerConnection-based call but remove the // MSID and bundle attribute from the initial offer to verify that // video is playing for the call even if the initiating client don't support // MSID. http://tools.ietf.org/html/draft-alvestrand-rtcweb-msid-02 IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupAudioAndVideoCallWithoutMsidAndBundle) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("callWithoutMsidAndBundle();")); ExpectTitle("OK"); } // This test will make a PeerConnection-based call and test an unreliable text // dataChannel. IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataOnly) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("callWithDataOnly();")); ExpectTitle("OK"); } // This test will make a PeerConnection-based call and test an unreliable text // dataChannel and audio and video tracks. IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataAndMedia) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("callWithDataAndMedia();")); ExpectTitle("OK"); } // This test will make a PeerConnection-based call and test an unreliable text // dataChannel and later add an audio and video track. // Flaky. http://crbug.com/175683 IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, DISABLED_CallWithDataAndLaterAddMedia) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("callWithDataAndLaterAddMedia();")); ExpectTitle("OK"); } } // namespace content <commit_msg>Disabling WebrtcBrowserTest.CanMakeEmptyCallThenAddStreamsAndRenegotiate on all platforms.<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 "base/command_line.h" #include "base/utf_string_conversions.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "content/shell/shell.h" #include "content/test/content_browser_test.h" #include "content/test/content_browser_test_utils.h" #include "net/test/test_server.h" #if defined(OS_WIN) #include "base/win/windows_version.h" #endif namespace content { class WebrtcBrowserTest: public ContentBrowserTest { public: WebrtcBrowserTest() {} virtual ~WebrtcBrowserTest() {} virtual void SetUp() OVERRIDE { // We need fake devices in this test since we want to run on naked VMs. We // assume this switch is set by default in content_browsertests. ASSERT_TRUE(CommandLine::ForCurrentProcess()->HasSwitch( switches::kUseFakeDeviceForMediaStream)); ASSERT_TRUE(test_server()->Start()); ContentBrowserTest::SetUp(); } protected: bool ExecuteJavascript(const std::string& javascript) { return ExecuteScript(shell()->web_contents(), javascript); } void ExpectTitle(const std::string& expected_title) const { string16 expected_title16(ASCIIToUTF16(expected_title)); TitleWatcher title_watcher(shell()->web_contents(), expected_title16); EXPECT_EQ(expected_title16, title_watcher.WaitAndGetTitle()); } }; // These tests will all make a getUserMedia call with different constraints and // see that the success callback is called. If the error callback is called or // none of the callbacks are called the tests will simply time out and fail. IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetVideoStreamAndStop) { GURL url(test_server()->GetURL("files/media/getusermedia_and_stop.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("getUserMedia({video: true});")); ExpectTitle("OK"); } IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetAudioAndVideoStreamAndStop) { GURL url(test_server()->GetURL("files/media/getusermedia_and_stop.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("getUserMedia({video: true, audio: true});")); ExpectTitle("OK"); } // These tests will make a complete PeerConnection-based call and verify that // video is playing for the call. IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupVideoCall) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("call({video: true});")); ExpectTitle("OK"); } IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupAudioAndVideoCall) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("call({video: true, audio: true});")); ExpectTitle("OK"); } IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, MANUAL_CanSetupCallAndSendDtmf) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); EXPECT_TRUE( ExecuteJavascript("callAndSendDtmf('123,abc');")); } // This test is flaky on Win XP, Win7 and Linux Precise. Disabling on all just // in case. IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, DISABLED_CanMakeEmptyCallThenAddStreamsAndRenegotiate) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); const char* kJavascript = "makeEmptyCallThenAddOneStreamAndRenegotiate(" "{video: true, audio: true});"; EXPECT_TRUE(ExecuteJavascript(kJavascript)); ExpectTitle("OK"); } // This test will make a complete PeerConnection-based call but remove the // MSID and bundle attribute from the initial offer to verify that // video is playing for the call even if the initiating client don't support // MSID. http://tools.ietf.org/html/draft-alvestrand-rtcweb-msid-02 IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupAudioAndVideoCallWithoutMsidAndBundle) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("callWithoutMsidAndBundle();")); ExpectTitle("OK"); } // This test will make a PeerConnection-based call and test an unreliable text // dataChannel. IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataOnly) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("callWithDataOnly();")); ExpectTitle("OK"); } // This test will make a PeerConnection-based call and test an unreliable text // dataChannel and audio and video tracks. IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataAndMedia) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("callWithDataAndMedia();")); ExpectTitle("OK"); } // This test will make a PeerConnection-based call and test an unreliable text // dataChannel and later add an audio and video track. // Flaky. http://crbug.com/175683 IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, DISABLED_CallWithDataAndLaterAddMedia) { GURL url(test_server()->GetURL("files/media/peerconnection-call.html")); NavigateToURL(shell(), url); EXPECT_TRUE(ExecuteJavascript("callWithDataAndLaterAddMedia();")); ExpectTitle("OK"); } } // namespace content <|endoftext|>
<commit_before>/* * Copyright 2011, 2012 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CounterImp.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { namespace { struct AdditiveGlyph { int weight; char16_t* glyph; }; // 1 4999 AdditiveGlyph upperRoman[] = { 1000, u"M", 900, u"CM", 500, u"D", 400, u"CD", 100, u"C", 90, u"XC", 50, u"L", 40, u"XL", 10, u"X", 9, u"IX", 5, u"V", 4, u"IV", 1, u"I", 0, 0 }; // 1 4999 AdditiveGlyph lowerRoman[] = { 1000, u"m", 900, u"cm", 500, u"d", 400, u"cd", 100, u"c", 90, u"xc", 50, u"l", 40, u"xl", 10, u"x", 9, u"ix", 5, u"v", 4, u"iv", 1, u"i", 0, 0 }; std::u16string convertToRoman(int n, AdditiveGlyph* glyphList) { if (n < 0 || 5000 <= n) return toString(n); std::u16string value; for (AdditiveGlyph* i = glyphList; i->glyph; ++i) { int t = n / i->weight; if (0 < t) { n -= t * i->weight; while (0 < t--) value += i->glyph; } } return value; } std::u16string emit(int i, unsigned type) { std::u16string value; switch (type) { case CSSListStyleTypeValueImp::None: break; case CSSListStyleTypeValueImp::Disc: value = u"\u2022"; // • break; case CSSListStyleTypeValueImp::Circle: value = u"\u25E6"; // ◦ break; case CSSListStyleTypeValueImp::Square: // Use u25A0 instead of u25FE for the IPA font for now value = u"\u25A0"; // ◾ "\u25FE" break; case CSSListStyleTypeValueImp::Decimal: value = toString(i); break; case CSSListStyleTypeValueImp::DecimalLeadingZero: value = toString(i < 0 ? -i : i); if (-9 <= i && i <= 9) value = u"0" + value; if (i < 0) value = u"-" + value; break; case CSSListStyleTypeValueImp::LowerAlpha: case CSSListStyleTypeValueImp::LowerLatin: value = std::u16string(1, u'a' + static_cast<unsigned>(i) % 26 - 1); break; case CSSListStyleTypeValueImp::UpperAlpha: case CSSListStyleTypeValueImp::UpperLatin: value = std::u16string(1, u'A' + static_cast<unsigned>(i) % 26 - 1); break; case CSSListStyleTypeValueImp::LowerGreek: // This style is only defined because CSS2.1 has it. // It doesn't appear to actually be used in Greek texts. value = std::u16string(1, u"αβγδεζηθικλμνξοπρστυφχψω"[static_cast<unsigned>(i - 1) % 24]); break; case CSSListStyleTypeValueImp::LowerRoman: value = convertToRoman(i, lowerRoman); break; case CSSListStyleTypeValueImp::UpperRoman: value = convertToRoman(i, upperRoman); break; case CSSListStyleTypeValueImp::Armenian: case CSSListStyleTypeValueImp::Georgian: default: value = toString(i); break; } return value; } } void CounterImp::nest(int number) { counters.push_back(number); } void CounterImp::reset(int number) { if (counters.empty()) nest(number); else counters.back() = number; } void CounterImp::increment(int number) { if (counters.empty()) nest(0); counters.back() += number; } bool CounterImp::restore() { counters.pop_back(); return counters.empty(); } std::u16string CounterImp::eval(unsigned type, CSSAutoNumberingValueImp::CounterContext* context) { this->separator = u""; this->listStyle.setValue(type); if (counters.empty()) { nest(0); context->addCounter(this); } return emit(counters.back(), type); } std::u16string CounterImp::eval(const std::u16string& separator, unsigned type, CSSAutoNumberingValueImp::CounterContext* context) { this->separator = separator; this->listStyle.setValue(type); if (counters.empty()) { nest(0); context->addCounter(this); } std::u16string value; for (auto i = counters.begin(); i != counters.end(); ++i) { if (i != counters.begin()) value += separator; value += emit(*i, type); } return value; } std::u16string CounterImp::getIdentifier() { return identifier; } std::u16string CounterImp::getListStyle() { return listStyle.getCssText(); } std::u16string CounterImp::getSeparator() { return separator; } } } } } <commit_msg>(CounterImp) : Support 'armenian' and 'georgian'; cf. content-counter-009 and content-counter-010.<commit_after>/* * Copyright 2011, 2012 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CounterImp.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { namespace { struct AdditiveGlyph { int weight; char16_t* glyph; }; // 1 4999 AdditiveGlyph upperRoman[] = { 1000, u"M", 900, u"CM", 500, u"D", 400, u"CD", 100, u"C", 90, u"XC", 50, u"L", 40, u"XL", 10, u"X", 9, u"IX", 5, u"V", 4, u"IV", 1, u"I", 0, 0 }; // 1 4999 AdditiveGlyph lowerRoman[] = { 1000, u"m", 900, u"cm", 500, u"d", 400, u"cd", 100, u"c", 90, u"xc", 50, u"l", 40, u"xl", 10, u"x", 9, u"ix", 5, u"v", 4, u"iv", 1, u"i", 0, 0 }; // 1 9999 AdditiveGlyph armenian[] = { 9000, u"\u0554", 8000, u"\u0553", 7000, u"\u0552", 6000, u"\u0551", 5000, u"\u0550", 4000, u"\u054F", 3000, u"\u054E", 2000, u"\u054D", 1000, u"\u054C", 900, u"\u054B", 800, u"\u054A", 700, u"\u0549", 600, u"\u0548", 500, u"\u0547", 400, u"\u0546", 300, u"\u0545", 200, u"\u0544", 100, u"\u0543", 90, u"\u0542", 80, u"\u0541", 70, u"\u0540", 60, u"\u053F", 50, u"\u053E", 40, u"\u053D", 30, u"\u053C", 20, u"\u053B", 10, u"\u053A", 9, u"\u0539", 8, u"\u0538", 7, u"\u0537", 6, u"\u0536", 5, u"\u0535", 4, u"\u0534", 3, u"\u0533", 2, u"\u0532", 1, u"\u0531" }; // 1 19999 AdditiveGlyph georgian[] = { 10000, u"\u10F5", 9000, u"\u10F0", 8000, u"\u10EF", 7000, u"\u10F4", 6000, u"\u10EE", 5000, u"\u10ED", 4000, u"\u10EC", 3000, u"\u10EB", 2000, u"\u10EA", 1000, u"\u10E9", 900, u"\u10E8", 800, u"\u10E7", 700, u"\u10E6", 600, u"\u10E5", 500, u"\u10E4", 400, u"\u10F3", 300, u"\u10E2", 200, u"\u10E1", 100, u"\u10E0", 90, u"\u10DF", 80, u"\u10DE", 70, u"\u10DD", 60, u"\u10F2", 50, u"\u10DC", 40, u"\u10DB", 30, u"\u10DA", 20, u"\u10D9", 10, u"\u10D8", 9, u"\u10D7", 8, u"\u10F1", 7, u"\u10D6", 6, u"\u10D5", 5, u"\u10D4", 4, u"\u10D3", 3, u"\u10D2", 2, u"\u10D1", 1, u"\u10D0" }; std::u16string convertToRoman(int n, AdditiveGlyph* glyphList, int min = 1, int max = 4999) { if (n < min || max < n) return toString(n); std::u16string value; for (AdditiveGlyph* i = glyphList; i->glyph; ++i) { int t = n / i->weight; if (0 < t) { n -= t * i->weight; while (0 < t--) value += i->glyph; } } return value; } std::u16string emit(int i, unsigned type) { std::u16string value; switch (type) { case CSSListStyleTypeValueImp::None: break; case CSSListStyleTypeValueImp::Disc: value = u"\u2022"; // • break; case CSSListStyleTypeValueImp::Circle: value = u"\u25E6"; // ◦ break; case CSSListStyleTypeValueImp::Square: // Use u25A0 instead of u25FE for the IPA font for now value = u"\u25A0"; // ◾ "\u25FE" break; case CSSListStyleTypeValueImp::Decimal: value = toString(i); break; case CSSListStyleTypeValueImp::DecimalLeadingZero: value = toString(i < 0 ? -i : i); if (-9 <= i && i <= 9) value = u"0" + value; if (i < 0) value = u"-" + value; break; case CSSListStyleTypeValueImp::LowerAlpha: case CSSListStyleTypeValueImp::LowerLatin: value = std::u16string(1, u'a' + static_cast<unsigned>(i) % 26 - 1); break; case CSSListStyleTypeValueImp::UpperAlpha: case CSSListStyleTypeValueImp::UpperLatin: value = std::u16string(1, u'A' + static_cast<unsigned>(i) % 26 - 1); break; case CSSListStyleTypeValueImp::LowerGreek: // This style is only defined because CSS2.1 has it. // It doesn't appear to actually be used in Greek texts. value = std::u16string(1, u"αβγδεζηθικλμνξοπρστυφχψω"[static_cast<unsigned>(i - 1) % 24]); break; case CSSListStyleTypeValueImp::LowerRoman: value = convertToRoman(i, lowerRoman); break; case CSSListStyleTypeValueImp::UpperRoman: value = convertToRoman(i, upperRoman); break; case CSSListStyleTypeValueImp::Armenian: value = convertToRoman(i, armenian, 1, 9999); break; case CSSListStyleTypeValueImp::Georgian: value = convertToRoman(i, georgian, 1, 19999); break; default: value = toString(i); break; } return value; } } void CounterImp::nest(int number) { counters.push_back(number); } void CounterImp::reset(int number) { if (counters.empty()) nest(number); else counters.back() = number; } void CounterImp::increment(int number) { if (counters.empty()) nest(0); counters.back() += number; } bool CounterImp::restore() { counters.pop_back(); return counters.empty(); } std::u16string CounterImp::eval(unsigned type, CSSAutoNumberingValueImp::CounterContext* context) { this->separator = u""; this->listStyle.setValue(type); if (counters.empty()) { nest(0); context->addCounter(this); } return emit(counters.back(), type); } std::u16string CounterImp::eval(const std::u16string& separator, unsigned type, CSSAutoNumberingValueImp::CounterContext* context) { this->separator = separator; this->listStyle.setValue(type); if (counters.empty()) { nest(0); context->addCounter(this); } std::u16string value; for (auto i = counters.begin(); i != counters.end(); ++i) { if (i != counters.begin()) value += separator; value += emit(*i, type); } return value; } std::u16string CounterImp::getIdentifier() { return identifier; } std::u16string CounterImp::getListStyle() { return listStyle.getCssText(); } std::u16string CounterImp::getSeparator() { return separator; } } } } } <|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/test/accessibility_test_utils_win.h" #include <oleacc.h> #include <map> #include <string> #include "base/memory/singleton.h" #include "base/string_util.h" #include "third_party/iaccessible2/ia2_api_all.h" namespace { class AccessibilityRoleStateMap { public: static AccessibilityRoleStateMap* GetInstance(); std::map<int32, string16> ia_role_string_map; std::map<int32, string16> ia2_role_string_map; std::map<int32, string16> ia_state_string_map; std::map<int32, string16> ia2_state_string_map; private: AccessibilityRoleStateMap(); virtual ~AccessibilityRoleStateMap() {} friend struct DefaultSingletonTraits<AccessibilityRoleStateMap>; DISALLOW_COPY_AND_ASSIGN(AccessibilityRoleStateMap); }; // static AccessibilityRoleStateMap* AccessibilityRoleStateMap::GetInstance() { return Singleton<AccessibilityRoleStateMap, LeakySingletonTraits<AccessibilityRoleStateMap> >::get(); } AccessibilityRoleStateMap::AccessibilityRoleStateMap() { // Convenience macros for generating readable strings. #define IA_ROLE_MAP(x) ia_role_string_map[x] = L#x; \ ia2_role_string_map[x] = L#x; #define IA2_ROLE_MAP(x) ia2_role_string_map[x] = L#x; #define IA_STATE_MAP(x) ia_state_string_map[STATE_SYSTEM_##x] = L#x; #define IA2_STATE_MAP(x) ia2_state_string_map[x] = L#x; // MSAA / IAccessible roles. Each one of these is also a valid // IAccessible2 role, the IA_ROLE_MAP macro adds it to both. IA_ROLE_MAP(ROLE_SYSTEM_ALERT) IA_ROLE_MAP(ROLE_SYSTEM_ANIMATION) IA_ROLE_MAP(ROLE_SYSTEM_APPLICATION) IA_ROLE_MAP(ROLE_SYSTEM_BORDER) IA_ROLE_MAP(ROLE_SYSTEM_BUTTONDROPDOWN) IA_ROLE_MAP(ROLE_SYSTEM_BUTTONDROPDOWNGRID) IA_ROLE_MAP(ROLE_SYSTEM_BUTTONMENU) IA_ROLE_MAP(ROLE_SYSTEM_CARET) IA_ROLE_MAP(ROLE_SYSTEM_CELL) IA_ROLE_MAP(ROLE_SYSTEM_CHARACTER) IA_ROLE_MAP(ROLE_SYSTEM_CHART) IA_ROLE_MAP(ROLE_SYSTEM_CHECKBUTTON) IA_ROLE_MAP(ROLE_SYSTEM_CLIENT) IA_ROLE_MAP(ROLE_SYSTEM_CLOCK) IA_ROLE_MAP(ROLE_SYSTEM_COLUMN) IA_ROLE_MAP(ROLE_SYSTEM_COLUMNHEADER) IA_ROLE_MAP(ROLE_SYSTEM_COMBOBOX) IA_ROLE_MAP(ROLE_SYSTEM_CURSOR) IA_ROLE_MAP(ROLE_SYSTEM_DIAGRAM) IA_ROLE_MAP(ROLE_SYSTEM_DIAL) IA_ROLE_MAP(ROLE_SYSTEM_DIALOG) IA_ROLE_MAP(ROLE_SYSTEM_DOCUMENT) IA_ROLE_MAP(ROLE_SYSTEM_DROPLIST) IA_ROLE_MAP(ROLE_SYSTEM_EQUATION) IA_ROLE_MAP(ROLE_SYSTEM_GRAPHIC) IA_ROLE_MAP(ROLE_SYSTEM_GRIP) IA_ROLE_MAP(ROLE_SYSTEM_GROUPING) IA_ROLE_MAP(ROLE_SYSTEM_HELPBALLOON) IA_ROLE_MAP(ROLE_SYSTEM_HOTKEYFIELD) IA_ROLE_MAP(ROLE_SYSTEM_INDICATOR) IA_ROLE_MAP(ROLE_SYSTEM_IPADDRESS) IA_ROLE_MAP(ROLE_SYSTEM_LINK) IA_ROLE_MAP(ROLE_SYSTEM_LIST) IA_ROLE_MAP(ROLE_SYSTEM_LISTITEM) IA_ROLE_MAP(ROLE_SYSTEM_MENUBAR) IA_ROLE_MAP(ROLE_SYSTEM_MENUITEM) IA_ROLE_MAP(ROLE_SYSTEM_MENUPOPUP) IA_ROLE_MAP(ROLE_SYSTEM_OUTLINE) IA_ROLE_MAP(ROLE_SYSTEM_OUTLINEBUTTON) IA_ROLE_MAP(ROLE_SYSTEM_OUTLINEITEM) IA_ROLE_MAP(ROLE_SYSTEM_PAGETAB) IA_ROLE_MAP(ROLE_SYSTEM_PAGETABLIST) IA_ROLE_MAP(ROLE_SYSTEM_PANE) IA_ROLE_MAP(ROLE_SYSTEM_PROGRESSBAR) IA_ROLE_MAP(ROLE_SYSTEM_PROPERTYPAGE) IA_ROLE_MAP(ROLE_SYSTEM_PUSHBUTTON) IA_ROLE_MAP(ROLE_SYSTEM_RADIOBUTTON) IA_ROLE_MAP(ROLE_SYSTEM_ROW) IA_ROLE_MAP(ROLE_SYSTEM_ROWHEADER) IA_ROLE_MAP(ROLE_SYSTEM_SCROLLBAR) IA_ROLE_MAP(ROLE_SYSTEM_SEPARATOR) IA_ROLE_MAP(ROLE_SYSTEM_SLIDER) IA_ROLE_MAP(ROLE_SYSTEM_SOUND) IA_ROLE_MAP(ROLE_SYSTEM_SPINBUTTON) IA_ROLE_MAP(ROLE_SYSTEM_SPLITBUTTON) IA_ROLE_MAP(ROLE_SYSTEM_STATICTEXT) IA_ROLE_MAP(ROLE_SYSTEM_STATUSBAR) IA_ROLE_MAP(ROLE_SYSTEM_TABLE) IA_ROLE_MAP(ROLE_SYSTEM_TEXT) IA_ROLE_MAP(ROLE_SYSTEM_TITLEBAR) IA_ROLE_MAP(ROLE_SYSTEM_TOOLBAR) IA_ROLE_MAP(ROLE_SYSTEM_TOOLTIP) IA_ROLE_MAP(ROLE_SYSTEM_WHITESPACE) IA_ROLE_MAP(ROLE_SYSTEM_WINDOW) // IAccessible2 roles. IA2_ROLE_MAP(IA2_ROLE_CANVAS) IA2_ROLE_MAP(IA2_ROLE_CAPTION) IA2_ROLE_MAP(IA2_ROLE_CHECK_MENU_ITEM) IA2_ROLE_MAP(IA2_ROLE_COLOR_CHOOSER) IA2_ROLE_MAP(IA2_ROLE_DATE_EDITOR) IA2_ROLE_MAP(IA2_ROLE_DESKTOP_ICON) IA2_ROLE_MAP(IA2_ROLE_DESKTOP_PANE) IA2_ROLE_MAP(IA2_ROLE_DIRECTORY_PANE) IA2_ROLE_MAP(IA2_ROLE_EDITBAR) IA2_ROLE_MAP(IA2_ROLE_EMBEDDED_OBJECT) IA2_ROLE_MAP(IA2_ROLE_ENDNOTE) IA2_ROLE_MAP(IA2_ROLE_FILE_CHOOSER) IA2_ROLE_MAP(IA2_ROLE_FONT_CHOOSER) IA2_ROLE_MAP(IA2_ROLE_FOOTER) IA2_ROLE_MAP(IA2_ROLE_FOOTNOTE) IA2_ROLE_MAP(IA2_ROLE_FORM) IA2_ROLE_MAP(IA2_ROLE_FRAME) IA2_ROLE_MAP(IA2_ROLE_GLASS_PANE) IA2_ROLE_MAP(IA2_ROLE_HEADER) IA2_ROLE_MAP(IA2_ROLE_HEADING) IA2_ROLE_MAP(IA2_ROLE_ICON) IA2_ROLE_MAP(IA2_ROLE_IMAGE_MAP) IA2_ROLE_MAP(IA2_ROLE_INPUT_METHOD_WINDOW) IA2_ROLE_MAP(IA2_ROLE_INTERNAL_FRAME) IA2_ROLE_MAP(IA2_ROLE_LABEL) IA2_ROLE_MAP(IA2_ROLE_LAYERED_PANE) IA2_ROLE_MAP(IA2_ROLE_NOTE) IA2_ROLE_MAP(IA2_ROLE_OPTION_PANE) IA2_ROLE_MAP(IA2_ROLE_PAGE) IA2_ROLE_MAP(IA2_ROLE_PARAGRAPH) IA2_ROLE_MAP(IA2_ROLE_RADIO_MENU_ITEM) IA2_ROLE_MAP(IA2_ROLE_REDUNDANT_OBJECT) IA2_ROLE_MAP(IA2_ROLE_ROOT_PANE) IA2_ROLE_MAP(IA2_ROLE_RULER) IA2_ROLE_MAP(IA2_ROLE_SCROLL_PANE) IA2_ROLE_MAP(IA2_ROLE_SECTION) IA2_ROLE_MAP(IA2_ROLE_SHAPE) IA2_ROLE_MAP(IA2_ROLE_SPLIT_PANE) IA2_ROLE_MAP(IA2_ROLE_TEAR_OFF_MENU) IA2_ROLE_MAP(IA2_ROLE_TERMINAL) IA2_ROLE_MAP(IA2_ROLE_TEXT_FRAME) IA2_ROLE_MAP(IA2_ROLE_TOGGLE_BUTTON) IA2_ROLE_MAP(IA2_ROLE_UNKNOWN) IA2_ROLE_MAP(IA2_ROLE_VIEW_PORT) // MSAA / IAccessible states. Unlike roles, these are not also IA2 states. IA_STATE_MAP(ALERT_HIGH) IA_STATE_MAP(ALERT_LOW) IA_STATE_MAP(ALERT_MEDIUM) IA_STATE_MAP(ANIMATED) IA_STATE_MAP(BUSY) IA_STATE_MAP(CHECKED) IA_STATE_MAP(COLLAPSED) IA_STATE_MAP(DEFAULT) IA_STATE_MAP(EXPANDED) IA_STATE_MAP(EXTSELECTABLE) IA_STATE_MAP(FLOATING) IA_STATE_MAP(FOCUSABLE) IA_STATE_MAP(FOCUSED) IA_STATE_MAP(HASPOPUP) IA_STATE_MAP(HOTTRACKED) IA_STATE_MAP(INVISIBLE) IA_STATE_MAP(LINKED) IA_STATE_MAP(MARQUEED) IA_STATE_MAP(MIXED) IA_STATE_MAP(MOVEABLE) IA_STATE_MAP(MULTISELECTABLE) IA_STATE_MAP(PRESSED) IA_STATE_MAP(PROTECTED) IA_STATE_MAP(READONLY) IA_STATE_MAP(SELECTABLE) IA_STATE_MAP(SELECTED) IA_STATE_MAP(SELFVOICING) IA_STATE_MAP(SIZEABLE) IA_STATE_MAP(TRAVERSED) IA_STATE_MAP(UNAVAILABLE) // Untested states include those that would be repeated on nearly every node, // or would vary based on window size. // IA_STATE_MAP(OFFSCREEN) // Untested. // IAccessible2 states. IA2_STATE_MAP(IA2_STATE_ACTIVE) IA2_STATE_MAP(IA2_STATE_ARMED) IA2_STATE_MAP(IA2_STATE_DEFUNCT) IA2_STATE_MAP(IA2_STATE_EDITABLE) IA2_STATE_MAP(IA2_STATE_ICONIFIED) IA2_STATE_MAP(IA2_STATE_INVALID_ENTRY) IA2_STATE_MAP(IA2_STATE_MANAGES_DESCENDANTS) IA2_STATE_MAP(IA2_STATE_MODAL) IA2_STATE_MAP(IA2_STATE_MULTI_LINE) IA2_STATE_MAP(IA2_STATE_REQUIRED) IA2_STATE_MAP(IA2_STATE_SELECTABLE_TEXT) IA2_STATE_MAP(IA2_STATE_SINGLE_LINE) IA2_STATE_MAP(IA2_STATE_STALE) IA2_STATE_MAP(IA2_STATE_SUPPORTS_AUTOCOMPLETION) IA2_STATE_MAP(IA2_STATE_TRANSIENT) // Untested states include those that would be repeated on nearly every node, // or would vary based on window size. // IA2_STATE_MAP(IA2_STATE_HORIZONTAL) // Untested. // IA2_STATE_MAP(IA2_STATE_OPAQUE) // Untested. // IA2_STATE_MAP(IA2_STATE_VERTICAL) // Untested. } } // namespace. string16 IAccessibleRoleToString(int32 ia_role) { return AccessibilityRoleStateMap::GetInstance()->ia_role_string_map[ia_role]; } string16 IAccessible2RoleToString(int32 ia_role) { return AccessibilityRoleStateMap::GetInstance()->ia2_role_string_map[ia_role]; } string16 IAccessibleStateToString(int32 ia_state) { string16 state_str; const std::map<int32, string16>& state_string_map = AccessibilityRoleStateMap::GetInstance()->ia_state_string_map; std::map<int32, string16>::const_iterator it; for (it = state_string_map.begin(); it != state_string_map.end(); ++it) { if (it->first & ia_state) { if (!state_str.empty()) state_str += L","; state_str += it->second; } } return state_str; } string16 IAccessible2StateToString(int32 ia2_state) { string16 state_str; const std::map<int32, string16>& state_string_map = AccessibilityRoleStateMap::GetInstance()->ia2_state_string_map; std::map<int32, string16>::const_iterator it; for (it = state_string_map.begin(); it != state_string_map.end(); ++it) { if (it->first & ia2_state) { if (!state_str.empty()) state_str += L","; state_str += it->second; } } return state_str; } <commit_msg>add missing file from previous checkin<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/public/test/accessibility_test_utils_win.h" #include <oleacc.h> #include <map> #include <string> #include "base/memory/singleton.h" #include "base/string_util.h" #include "third_party/iaccessible2/ia2_api_all.h" namespace { class AccessibilityRoleStateMap { public: static AccessibilityRoleStateMap* GetInstance(); std::map<int32, string16> ia_role_string_map; std::map<int32, string16> ia2_role_string_map; std::map<int32, string16> ia_state_string_map; std::map<int32, string16> ia2_state_string_map; private: AccessibilityRoleStateMap(); virtual ~AccessibilityRoleStateMap() {} friend struct DefaultSingletonTraits<AccessibilityRoleStateMap>; DISALLOW_COPY_AND_ASSIGN(AccessibilityRoleStateMap); }; // static AccessibilityRoleStateMap* AccessibilityRoleStateMap::GetInstance() { return Singleton<AccessibilityRoleStateMap, LeakySingletonTraits<AccessibilityRoleStateMap> >::get(); } AccessibilityRoleStateMap::AccessibilityRoleStateMap() { // Convenience macros for generating readable strings. #define IA_ROLE_MAP(x) ia_role_string_map[x] = L#x; \ ia2_role_string_map[x] = L#x; #define IA2_ROLE_MAP(x) ia2_role_string_map[x] = L#x; #define IA_STATE_MAP(x) ia_state_string_map[STATE_SYSTEM_##x] = L#x; #define IA2_STATE_MAP(x) ia2_state_string_map[x] = L#x; // MSAA / IAccessible roles. Each one of these is also a valid // IAccessible2 role, the IA_ROLE_MAP macro adds it to both. IA_ROLE_MAP(ROLE_SYSTEM_ALERT) IA_ROLE_MAP(ROLE_SYSTEM_ANIMATION) IA_ROLE_MAP(ROLE_SYSTEM_APPLICATION) IA_ROLE_MAP(ROLE_SYSTEM_BORDER) IA_ROLE_MAP(ROLE_SYSTEM_BUTTONDROPDOWN) IA_ROLE_MAP(ROLE_SYSTEM_BUTTONDROPDOWNGRID) IA_ROLE_MAP(ROLE_SYSTEM_BUTTONMENU) IA_ROLE_MAP(ROLE_SYSTEM_CARET) IA_ROLE_MAP(ROLE_SYSTEM_CELL) IA_ROLE_MAP(ROLE_SYSTEM_CHARACTER) IA_ROLE_MAP(ROLE_SYSTEM_CHART) IA_ROLE_MAP(ROLE_SYSTEM_CHECKBUTTON) IA_ROLE_MAP(ROLE_SYSTEM_CLIENT) IA_ROLE_MAP(ROLE_SYSTEM_CLOCK) IA_ROLE_MAP(ROLE_SYSTEM_COLUMN) IA_ROLE_MAP(ROLE_SYSTEM_COLUMNHEADER) IA_ROLE_MAP(ROLE_SYSTEM_COMBOBOX) IA_ROLE_MAP(ROLE_SYSTEM_CURSOR) IA_ROLE_MAP(ROLE_SYSTEM_DIAGRAM) IA_ROLE_MAP(ROLE_SYSTEM_DIAL) IA_ROLE_MAP(ROLE_SYSTEM_DIALOG) IA_ROLE_MAP(ROLE_SYSTEM_DOCUMENT) IA_ROLE_MAP(ROLE_SYSTEM_DROPLIST) IA_ROLE_MAP(ROLE_SYSTEM_EQUATION) IA_ROLE_MAP(ROLE_SYSTEM_GRAPHIC) IA_ROLE_MAP(ROLE_SYSTEM_GRIP) IA_ROLE_MAP(ROLE_SYSTEM_GROUPING) IA_ROLE_MAP(ROLE_SYSTEM_HELPBALLOON) IA_ROLE_MAP(ROLE_SYSTEM_HOTKEYFIELD) IA_ROLE_MAP(ROLE_SYSTEM_INDICATOR) IA_ROLE_MAP(ROLE_SYSTEM_IPADDRESS) IA_ROLE_MAP(ROLE_SYSTEM_LINK) IA_ROLE_MAP(ROLE_SYSTEM_LIST) IA_ROLE_MAP(ROLE_SYSTEM_LISTITEM) IA_ROLE_MAP(ROLE_SYSTEM_MENUBAR) IA_ROLE_MAP(ROLE_SYSTEM_MENUITEM) IA_ROLE_MAP(ROLE_SYSTEM_MENUPOPUP) IA_ROLE_MAP(ROLE_SYSTEM_OUTLINE) IA_ROLE_MAP(ROLE_SYSTEM_OUTLINEBUTTON) IA_ROLE_MAP(ROLE_SYSTEM_OUTLINEITEM) IA_ROLE_MAP(ROLE_SYSTEM_PAGETAB) IA_ROLE_MAP(ROLE_SYSTEM_PAGETABLIST) IA_ROLE_MAP(ROLE_SYSTEM_PANE) IA_ROLE_MAP(ROLE_SYSTEM_PROGRESSBAR) IA_ROLE_MAP(ROLE_SYSTEM_PROPERTYPAGE) IA_ROLE_MAP(ROLE_SYSTEM_PUSHBUTTON) IA_ROLE_MAP(ROLE_SYSTEM_RADIOBUTTON) IA_ROLE_MAP(ROLE_SYSTEM_ROW) IA_ROLE_MAP(ROLE_SYSTEM_ROWHEADER) IA_ROLE_MAP(ROLE_SYSTEM_SCROLLBAR) IA_ROLE_MAP(ROLE_SYSTEM_SEPARATOR) IA_ROLE_MAP(ROLE_SYSTEM_SLIDER) IA_ROLE_MAP(ROLE_SYSTEM_SOUND) IA_ROLE_MAP(ROLE_SYSTEM_SPINBUTTON) IA_ROLE_MAP(ROLE_SYSTEM_SPLITBUTTON) IA_ROLE_MAP(ROLE_SYSTEM_STATICTEXT) IA_ROLE_MAP(ROLE_SYSTEM_STATUSBAR) IA_ROLE_MAP(ROLE_SYSTEM_TABLE) IA_ROLE_MAP(ROLE_SYSTEM_TEXT) IA_ROLE_MAP(ROLE_SYSTEM_TITLEBAR) IA_ROLE_MAP(ROLE_SYSTEM_TOOLBAR) IA_ROLE_MAP(ROLE_SYSTEM_TOOLTIP) IA_ROLE_MAP(ROLE_SYSTEM_WHITESPACE) IA_ROLE_MAP(ROLE_SYSTEM_WINDOW) // IAccessible2 roles. IA2_ROLE_MAP(IA2_ROLE_CANVAS) IA2_ROLE_MAP(IA2_ROLE_CAPTION) IA2_ROLE_MAP(IA2_ROLE_CHECK_MENU_ITEM) IA2_ROLE_MAP(IA2_ROLE_COLOR_CHOOSER) IA2_ROLE_MAP(IA2_ROLE_DATE_EDITOR) IA2_ROLE_MAP(IA2_ROLE_DESKTOP_ICON) IA2_ROLE_MAP(IA2_ROLE_DESKTOP_PANE) IA2_ROLE_MAP(IA2_ROLE_DIRECTORY_PANE) IA2_ROLE_MAP(IA2_ROLE_EDITBAR) IA2_ROLE_MAP(IA2_ROLE_EMBEDDED_OBJECT) IA2_ROLE_MAP(IA2_ROLE_ENDNOTE) IA2_ROLE_MAP(IA2_ROLE_FILE_CHOOSER) IA2_ROLE_MAP(IA2_ROLE_FONT_CHOOSER) IA2_ROLE_MAP(IA2_ROLE_FOOTER) IA2_ROLE_MAP(IA2_ROLE_FOOTNOTE) IA2_ROLE_MAP(IA2_ROLE_FORM) IA2_ROLE_MAP(IA2_ROLE_FRAME) IA2_ROLE_MAP(IA2_ROLE_GLASS_PANE) IA2_ROLE_MAP(IA2_ROLE_HEADER) IA2_ROLE_MAP(IA2_ROLE_HEADING) IA2_ROLE_MAP(IA2_ROLE_ICON) IA2_ROLE_MAP(IA2_ROLE_IMAGE_MAP) IA2_ROLE_MAP(IA2_ROLE_INPUT_METHOD_WINDOW) IA2_ROLE_MAP(IA2_ROLE_INTERNAL_FRAME) IA2_ROLE_MAP(IA2_ROLE_LABEL) IA2_ROLE_MAP(IA2_ROLE_LAYERED_PANE) IA2_ROLE_MAP(IA2_ROLE_NOTE) IA2_ROLE_MAP(IA2_ROLE_OPTION_PANE) IA2_ROLE_MAP(IA2_ROLE_PAGE) IA2_ROLE_MAP(IA2_ROLE_PARAGRAPH) IA2_ROLE_MAP(IA2_ROLE_RADIO_MENU_ITEM) IA2_ROLE_MAP(IA2_ROLE_REDUNDANT_OBJECT) IA2_ROLE_MAP(IA2_ROLE_ROOT_PANE) IA2_ROLE_MAP(IA2_ROLE_RULER) IA2_ROLE_MAP(IA2_ROLE_SCROLL_PANE) IA2_ROLE_MAP(IA2_ROLE_SECTION) IA2_ROLE_MAP(IA2_ROLE_SHAPE) IA2_ROLE_MAP(IA2_ROLE_SPLIT_PANE) IA2_ROLE_MAP(IA2_ROLE_TEAR_OFF_MENU) IA2_ROLE_MAP(IA2_ROLE_TERMINAL) IA2_ROLE_MAP(IA2_ROLE_TEXT_FRAME) IA2_ROLE_MAP(IA2_ROLE_TOGGLE_BUTTON) IA2_ROLE_MAP(IA2_ROLE_UNKNOWN) IA2_ROLE_MAP(IA2_ROLE_VIEW_PORT) // MSAA / IAccessible states. Unlike roles, these are not also IA2 states. IA_STATE_MAP(ALERT_HIGH) IA_STATE_MAP(ALERT_LOW) IA_STATE_MAP(ALERT_MEDIUM) IA_STATE_MAP(ANIMATED) IA_STATE_MAP(BUSY) IA_STATE_MAP(CHECKED) IA_STATE_MAP(COLLAPSED) IA_STATE_MAP(DEFAULT) IA_STATE_MAP(EXPANDED) IA_STATE_MAP(EXTSELECTABLE) IA_STATE_MAP(FLOATING) IA_STATE_MAP(FOCUSABLE) IA_STATE_MAP(FOCUSED) IA_STATE_MAP(HASPOPUP) IA_STATE_MAP(HOTTRACKED) IA_STATE_MAP(INVISIBLE) IA_STATE_MAP(LINKED) IA_STATE_MAP(MARQUEED) IA_STATE_MAP(MIXED) IA_STATE_MAP(MOVEABLE) IA_STATE_MAP(MULTISELECTABLE) IA_STATE_MAP(PRESSED) IA_STATE_MAP(PROTECTED) IA_STATE_MAP(READONLY) IA_STATE_MAP(SELECTABLE) IA_STATE_MAP(SELECTED) IA_STATE_MAP(SELFVOICING) IA_STATE_MAP(SIZEABLE) IA_STATE_MAP(TRAVERSED) IA_STATE_MAP(UNAVAILABLE) // Untested states include those that would be repeated on nearly every node, // or would vary based on window size. // IA_STATE_MAP(OFFSCREEN) // Untested. // IAccessible2 states. IA2_STATE_MAP(IA2_STATE_ACTIVE) IA2_STATE_MAP(IA2_STATE_ARMED) IA2_STATE_MAP(IA2_STATE_DEFUNCT) IA2_STATE_MAP(IA2_STATE_EDITABLE) IA2_STATE_MAP(IA2_STATE_ICONIFIED) IA2_STATE_MAP(IA2_STATE_INVALID_ENTRY) IA2_STATE_MAP(IA2_STATE_MANAGES_DESCENDANTS) IA2_STATE_MAP(IA2_STATE_MODAL) IA2_STATE_MAP(IA2_STATE_MULTI_LINE) IA2_STATE_MAP(IA2_STATE_REQUIRED) IA2_STATE_MAP(IA2_STATE_SELECTABLE_TEXT) IA2_STATE_MAP(IA2_STATE_SINGLE_LINE) IA2_STATE_MAP(IA2_STATE_STALE) IA2_STATE_MAP(IA2_STATE_SUPPORTS_AUTOCOMPLETION) IA2_STATE_MAP(IA2_STATE_TRANSIENT) // Untested states include those that would be repeated on nearly every node, // or would vary based on window size. // IA2_STATE_MAP(IA2_STATE_HORIZONTAL) // Untested. // IA2_STATE_MAP(IA2_STATE_OPAQUE) // Untested. // IA2_STATE_MAP(IA2_STATE_VERTICAL) // Untested. } } // namespace. string16 IAccessibleRoleToString(int32 ia_role) { return AccessibilityRoleStateMap::GetInstance()->ia_role_string_map[ia_role]; } string16 IAccessible2RoleToString(int32 ia_role) { return AccessibilityRoleStateMap::GetInstance()->ia2_role_string_map[ia_role]; } string16 IAccessibleStateToString(int32 ia_state) { string16 state_str; const std::map<int32, string16>& state_string_map = AccessibilityRoleStateMap::GetInstance()->ia_state_string_map; std::map<int32, string16>::const_iterator it; for (it = state_string_map.begin(); it != state_string_map.end(); ++it) { if (it->first & ia_state) { if (!state_str.empty()) state_str += L","; state_str += it->second; } } return state_str; } string16 IAccessible2StateToString(int32 ia2_state) { string16 state_str; const std::map<int32, string16>& state_string_map = AccessibilityRoleStateMap::GetInstance()->ia2_state_string_map; std::map<int32, string16>::const_iterator it; for (it = state_string_map.begin(); it != state_string_map.end(); ++it) { if (it->first & ia2_state) { if (!state_str.empty()) state_str += L","; state_str += it->second; } } return state_str; } <|endoftext|>
<commit_before>/* * Licensed under the MIT License (MIT) * * Copyright (c) 2013 AudioScience Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * net_interface_imp.cpp * * Network interface implementation class */ #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <sys/sysctl.h> #include <net/if.h> #include <net/if_dl.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/time.h> #include <sys/ioctl.h> #include <net/bpf.h> #include <algorithm> #include "util.h" #include "enumeration.h" #include "log_imp.h" #include "jdksavdecc_pdu.h" #include "net_interface_imp.h" namespace avdecc_lib { net_interface * STDCALL create_net_interface() { return (new net_interface_imp()); } net_interface_imp::net_interface_imp() { if (pcap_findalldevs(&all_devs, err_buf) == -1) // Retrieve the device list on the local machine. { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "pcap_findalldevs error %s", err_buf); exit(EXIT_FAILURE); } for (dev = all_devs, total_devs = 0; dev; dev = dev->next) { // store the valid IPv4 addresses associated with the device std::vector<std::string> device_ip_addresses; pcap_addr_t * dev_addr; for (dev_addr = dev->addresses; dev_addr != NULL; dev_addr = dev_addr->next) { if (dev_addr->addr->sa_family == AF_INET && dev_addr->addr) { char ip_str[INET_ADDRSTRLEN] = {0}; inet_ntop(AF_INET, &((struct sockaddr_in *)dev_addr->addr)->sin_addr, ip_str, INET_ADDRSTRLEN); device_ip_addresses.push_back(std::string(ip_str)); } } all_ip_addresses.push_back(device_ip_addresses); // store the MAC addr associated with device find_and_store_device_mac_addr(dev->name); total_devs++; } if (total_devs == 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "No interfaces found! Make sure WinPcap is installed."); exit(EXIT_FAILURE); } } net_interface_imp::~net_interface_imp() { pcap_freealldevs(all_devs); // Free the device list pcap_close(pcap_interface); } void net_interface_imp::find_and_store_device_mac_addr(char * dev_name) { uint64_t mac; int mib[6]; size_t len; char * buf; unsigned char * ptr; struct if_msghdr * ifm; struct sockaddr_dl * sdl; mib[0] = CTL_NET; mib[1] = AF_ROUTE; mib[2] = 0; mib[3] = AF_LINK; mib[4] = NET_RT_IFLIST; if ((mib[5] = if_nametoindex(dev_name)) == 0) { perror("if_nametoindex error"); exit(EXIT_FAILURE); } if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { perror("sysctl 1 error"); exit(EXIT_FAILURE); } if ((buf = (char *)malloc(len)) == NULL) { perror("malloc error"); exit(EXIT_FAILURE); } if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { perror("sysctl 2 error"); exit(EXIT_FAILURE); } ifm = (struct if_msghdr *)buf; sdl = (struct sockaddr_dl *)(ifm + 1); ptr = (unsigned char *)LLADDR(sdl); utility::convert_eui48_to_uint64(ptr, mac); all_mac_addresses.push_back(mac); free(buf); } void STDCALL net_interface_imp::destroy() { delete this; } uint32_t STDCALL net_interface_imp::devs_count() { return total_devs; } size_t STDCALL net_interface_imp::device_ip_address_count(size_t dev_index) { if (dev_index < all_ip_addresses.size()) return all_ip_addresses.at(dev_index).size(); return -1; } uint64_t net_interface_imp::mac_addr() { return selected_dev_mac; } char * STDCALL net_interface_imp::get_dev_desc_by_index(size_t dev_index) { uint32_t index_i; // Get the selected interface for (dev = all_devs, index_i = 0; (index_i < dev_index) && (dev_index < total_devs); dev = dev->next, index_i++) ; if (!dev->name) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Interface name is blank."); } return dev->name; } const char * STDCALL net_interface_imp::get_dev_ip_address_by_index(size_t dev_index, size_t ip_index) { if (dev_index < all_ip_addresses.size()) { if (ip_index < all_ip_addresses.at(dev_index).size()) return all_ip_addresses.at(dev_index).at(ip_index).c_str(); } return NULL; } bool STDCALL net_interface_imp::does_interface_have_ip_address(size_t dev_index, char * ip_addr_str) { if (dev_index < all_ip_addresses.size()) { if (std::find(all_ip_addresses.at(dev_index).begin(), all_ip_addresses.at(dev_index).end(), std::string(ip_addr_str)) != all_ip_addresses.at(dev_index).end()) return true; } return false; } bool STDCALL net_interface_imp::does_interface_have_mac_address(size_t dev_index, uint64_t mac_addr) { if (dev_index < all_mac_addresses.size()) { if (all_mac_addresses.at(dev_index) == mac_addr) return true; } return false; } char * STDCALL net_interface_imp::get_dev_name_by_index(size_t dev_index) { return get_dev_desc_by_index(dev_index); } int net_interface_imp::get_fd() { return pcap_get_selectable_fd(pcap_interface); } uint64_t net_interface_imp::get_dev_mac_addr_by_index(size_t dev_index) { if (dev_index < all_mac_addresses.size()) return all_mac_addresses.at(dev_index); return 0; } int STDCALL net_interface_imp::select_interface_by_num(uint32_t interface_num) { uint32_t index; int timeout_ms = 1; if (interface_num < 1 || interface_num > total_devs) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Interface number out of range."); pcap_freealldevs(all_devs); // Free the device list exit(EXIT_FAILURE); } for (dev = all_devs, index = 0; index < interface_num - 1; dev = dev->next, index++) ; // Jump to the selected adapter /************* Open the device **************/ if ((pcap_interface = pcap_open_live(dev->name, // Name of the device 65536, // Portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers 1, // In promiscuous mode, all packets including packets of other hosts are captured timeout_ms, // Read timeout in ms err_buf // Error buffer )) == NULL) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Unable to open the adapter. %s is not supported by pcap.", dev->name); pcap_freealldevs(all_devs); // Free the device list exit(EXIT_FAILURE); } if (pcap_setnonblock(pcap_interface, 1, err_buf) < 0) { perror("pcap_setnonblock"); exit(EXIT_FAILURE); } int fd = pcap_fileno(pcap_interface); if (fd == -1) { perror("Can't get file descriptor for pcap_t"); exit(EXIT_FAILURE); } int on = 1; if (ioctl(fd, BIOCIMMEDIATE, &on) == -1) { perror("BIOCIMMEDIATE error"); exit(EXIT_FAILURE); } if (index >= all_mac_addresses.size()) { perror("Cannot find selected interface MAC address"); exit(EXIT_FAILURE); } selected_dev_mac = all_mac_addresses.at(index); uint16_t ether_type[1]; ether_type[0] = JDKSAVDECC_AVTP_ETHERTYPE; set_capture_ether_type(ether_type, 1); // Set the filter return 0; } int net_interface_imp::set_capture_ether_type(uint16_t * ether_type, uint32_t count) { struct bpf_program fcode; char ether_type_string[512]; char ether_type_single[64]; const unsigned char * ether_packet = NULL; struct pcap_pkthdr pcap_header; ether_type_string[0] = 0; for (uint32_t index_i = 0; index_i < count; index_i++) { sprintf(ether_type_single, "ether proto 0x%04x", ether_type[index_i]); strcat(ether_type_string, ether_type_single); if ((index_i + 1) < count) { strcat(ether_type_string, " or "); } } /******************************************************* Compile a filter ************************************************/ if (pcap_compile(pcap_interface, &fcode, ether_type_string, 1, 0) < 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Unable to compile the packet filter."); pcap_freealldevs(all_devs); // Free the device list return -1; } /*************************************************** Set the filter *******************************************/ if (pcap_setfilter(pcap_interface, &fcode) < 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Error setting the filter."); pcap_freealldevs(all_devs); // Free the device list return -1; } /*********** Flush any packets that might be present **********/ for (uint32_t index_j = 0; index_j < 1; index_j++) { ether_packet = pcap_next(pcap_interface, &pcap_header); if (!ether_packet) { break; } } return 0; } int STDCALL net_interface_imp::capture_frame(const uint8_t ** frame, uint16_t * mem_buf_len) { struct pcap_pkthdr * header; int error = 0; *mem_buf_len = 0; error = pcap_next_ex(pcap_interface, &header, frame); if (error > 0) { ether_frame = *frame; *mem_buf_len = (uint16_t)header->len; return 1; } return error; } int net_interface_imp::send_frame(uint8_t * frame, uint16_t mem_buf_len) { if (pcap_sendpacket(pcap_interface, frame, mem_buf_len) != 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "pcap_sendpacket error %s", pcap_geterr(pcap_interface)); return -1; } return 0; } } <commit_msg>osx - net interface - use return code rather than exit(); log callback instead of perror<commit_after>/* * Licensed under the MIT License (MIT) * * Copyright (c) 2013 AudioScience Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * net_interface_imp.cpp * * Network interface implementation class */ #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <sys/sysctl.h> #include <net/if.h> #include <net/if_dl.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/time.h> #include <sys/ioctl.h> #include <net/bpf.h> #include <algorithm> #include "util.h" #include "enumeration.h" #include "log_imp.h" #include "jdksavdecc_pdu.h" #include "net_interface_imp.h" namespace avdecc_lib { net_interface * STDCALL create_net_interface() { return (new net_interface_imp()); } net_interface_imp::net_interface_imp() { if (pcap_findalldevs(&all_devs, err_buf) == -1) // Retrieve the device list on the local machine. { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "pcap_findalldevs error %s", err_buf); } for (dev = all_devs, total_devs = 0; dev; dev = dev->next) { // store the valid IPv4 addresses associated with the device std::vector<std::string> device_ip_addresses; pcap_addr_t * dev_addr; for (dev_addr = dev->addresses; dev_addr != NULL; dev_addr = dev_addr->next) { if (dev_addr->addr->sa_family == AF_INET && dev_addr->addr) { char ip_str[INET_ADDRSTRLEN] = {0}; inet_ntop(AF_INET, &((struct sockaddr_in *)dev_addr->addr)->sin_addr, ip_str, INET_ADDRSTRLEN); device_ip_addresses.push_back(std::string(ip_str)); } } all_ip_addresses.push_back(device_ip_addresses); // store the MAC addr associated with device find_and_store_device_mac_addr(dev->name); total_devs++; } if (total_devs == 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "No interfaces found! Make sure WinPcap is installed."); } } net_interface_imp::~net_interface_imp() { pcap_freealldevs(all_devs); // Free the device list pcap_close(pcap_interface); } void net_interface_imp::find_and_store_device_mac_addr(char * dev_name) { uint64_t mac; int mib[6]; size_t len; char * buf; unsigned char * ptr; struct if_msghdr * ifm; struct sockaddr_dl * sdl; mib[0] = CTL_NET; mib[1] = AF_ROUTE; mib[2] = 0; mib[3] = AF_LINK; mib[4] = NET_RT_IFLIST; if ((mib[5] = if_nametoindex(dev_name)) == 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "if_nametoindex error"); return; } if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "sysctl 1 error"); return; } if ((buf = (char *)malloc(len)) == NULL) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "malloc error"); return; } if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "sysctl 2 error"); return; } ifm = (struct if_msghdr *)buf; sdl = (struct sockaddr_dl *)(ifm + 1); ptr = (unsigned char *)LLADDR(sdl); utility::convert_eui48_to_uint64(ptr, mac); all_mac_addresses.push_back(mac); free(buf); } void STDCALL net_interface_imp::destroy() { delete this; } uint32_t STDCALL net_interface_imp::devs_count() { return total_devs; } size_t STDCALL net_interface_imp::device_ip_address_count(size_t dev_index) { if (dev_index < all_ip_addresses.size()) return all_ip_addresses.at(dev_index).size(); return -1; } uint64_t net_interface_imp::mac_addr() { return selected_dev_mac; } char * STDCALL net_interface_imp::get_dev_desc_by_index(size_t dev_index) { uint32_t index_i; // Get the selected interface for (dev = all_devs, index_i = 0; (index_i < dev_index) && (dev_index < total_devs); dev = dev->next, index_i++) ; if (!dev->name) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Interface name is blank."); } return dev->name; } const char * STDCALL net_interface_imp::get_dev_ip_address_by_index(size_t dev_index, size_t ip_index) { if (dev_index < all_ip_addresses.size()) { if (ip_index < all_ip_addresses.at(dev_index).size()) return all_ip_addresses.at(dev_index).at(ip_index).c_str(); } return NULL; } bool STDCALL net_interface_imp::does_interface_have_ip_address(size_t dev_index, char * ip_addr_str) { if (dev_index < all_ip_addresses.size()) { if (std::find(all_ip_addresses.at(dev_index).begin(), all_ip_addresses.at(dev_index).end(), std::string(ip_addr_str)) != all_ip_addresses.at(dev_index).end()) return true; } return false; } bool STDCALL net_interface_imp::does_interface_have_mac_address(size_t dev_index, uint64_t mac_addr) { if (dev_index < all_mac_addresses.size()) { if (all_mac_addresses.at(dev_index) == mac_addr) return true; } return false; } char * STDCALL net_interface_imp::get_dev_name_by_index(size_t dev_index) { return get_dev_desc_by_index(dev_index); } int net_interface_imp::get_fd() { return pcap_get_selectable_fd(pcap_interface); } uint64_t net_interface_imp::get_dev_mac_addr_by_index(size_t dev_index) { if (dev_index < all_mac_addresses.size()) return all_mac_addresses.at(dev_index); return 0; } int STDCALL net_interface_imp::select_interface_by_num(uint32_t interface_num) { uint32_t index; int timeout_ms = 1; if (interface_num < 1 || interface_num > total_devs) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Interface number out of range."); pcap_freealldevs(all_devs); // Free the device list return -1; } for (dev = all_devs, index = 0; index < interface_num - 1; dev = dev->next, index++) ; // Jump to the selected adapter /************* Open the device **************/ if ((pcap_interface = pcap_open_live(dev->name, // Name of the device 65536, // Portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers 1, // In promiscuous mode, all packets including packets of other hosts are captured timeout_ms, // Read timeout in ms err_buf // Error buffer )) == NULL) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Unable to open the adapter. %s is not supported by pcap.", dev->name); pcap_freealldevs(all_devs); // Free the device list return -1; } if (pcap_setnonblock(pcap_interface, 1, err_buf) < 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "pcap_setnonblock"); return -1; } int fd = pcap_fileno(pcap_interface); if (fd == -1) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Can't get file descriptor for pcap_t"); return -1; } int on = 1; if (ioctl(fd, BIOCIMMEDIATE, &on) == -1) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "BIOCIMMEDIATE error"); return -1; } if (index >= all_mac_addresses.size()) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Cannot find selected interface MAC address"); return -1; } selected_dev_mac = all_mac_addresses.at(index); uint16_t ether_type[1]; ether_type[0] = JDKSAVDECC_AVTP_ETHERTYPE; if (set_capture_ether_type(ether_type, 1) < 0) // Set the filter return -1; return 0; } int net_interface_imp::set_capture_ether_type(uint16_t * ether_type, uint32_t count) { struct bpf_program fcode; char ether_type_string[512]; char ether_type_single[64]; const unsigned char * ether_packet = NULL; struct pcap_pkthdr pcap_header; ether_type_string[0] = 0; for (uint32_t index_i = 0; index_i < count; index_i++) { sprintf(ether_type_single, "ether proto 0x%04x", ether_type[index_i]); strcat(ether_type_string, ether_type_single); if ((index_i + 1) < count) { strcat(ether_type_string, " or "); } } /******************************************************* Compile a filter ************************************************/ if (pcap_compile(pcap_interface, &fcode, ether_type_string, 1, 0) < 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Unable to compile the packet filter."); pcap_freealldevs(all_devs); // Free the device list return -1; } /*************************************************** Set the filter *******************************************/ if (pcap_setfilter(pcap_interface, &fcode) < 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Error setting the filter."); pcap_freealldevs(all_devs); // Free the device list return -1; } /*********** Flush any packets that might be present **********/ for (uint32_t index_j = 0; index_j < 1; index_j++) { ether_packet = pcap_next(pcap_interface, &pcap_header); if (!ether_packet) { break; } } return 0; } int STDCALL net_interface_imp::capture_frame(const uint8_t ** frame, uint16_t * mem_buf_len) { struct pcap_pkthdr * header; int error = 0; *mem_buf_len = 0; error = pcap_next_ex(pcap_interface, &header, frame); if (error > 0) { ether_frame = *frame; *mem_buf_len = (uint16_t)header->len; return 1; } return error; } int net_interface_imp::send_frame(uint8_t * frame, uint16_t mem_buf_len) { if (pcap_sendpacket(pcap_interface, frame, mem_buf_len) != 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "pcap_sendpacket error %s", pcap_geterr(pcap_interface)); return -1; } return 0; } } <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/elementaryFluxModes/CEFMAlgorithm.cpp,v $ $Revision: 1.10 $ $Name: $ $Author: shoops $ $Date: 2003/10/16 16:23:13 $ End CVS Header */ /** * CEFMAlgorithm class. * Used to calculate elementary flux modes * * Created for Copasi by Stefan Hoops 2002-05-08 * (C) Stefan Hoops 2002 */ // #define COPASI_TRACE_CONSTRUCTION #include "copasi.h" #include "CEFMAlgorithm.h" #include "CFluxMode.h" #include "CTableauMatrix.h" CEFMAlgorithm::CEFMAlgorithm() { CONSTRUCTOR_TRACE; mCurrentTableau = NULL; mNextTableau = NULL; } CEFMAlgorithm::~CEFMAlgorithm() { DESTRUCTOR_TRACE; pdelete(mCurrentTableau); pdelete(mNextTableau); } bool CEFMAlgorithm::calculate(const std::vector < std::vector < C_FLOAT64 > > & stoi, const unsigned C_INT32 &reversibleNumber, std::vector < CFluxMode > & fluxModes) { bool Success = true; unsigned C_INT32 Step, MaxSteps = stoi[0].size(); /* initialize the current tableu matrix */ mCurrentTableau = new CTableauMatrix(stoi, reversibleNumber); /* Do the iteration */ for (Step = 0; Step < MaxSteps; Step++) calculateNextTableau(); /* Build the elementary flux modes to be returned */ buildFluxModes(fluxModes); /* Delete the current / final tableu matrix */ pdelete(mCurrentTableau); return Success; } void CEFMAlgorithm::calculateNextTableau() { std::list< const CTableauLine * >::iterator a; std::list< const CTableauLine * >::iterator b; C_FLOAT64 ma, mb; mNextTableau = new CTableauMatrix(); /* Move all lines with zeros in the step column to the new tableu matrix */ /* and remove them from the current tableau matrix */ a = mCurrentTableau->getFirst(); while (a != mCurrentTableau->getEnd()) if ((*a)->getReaction(0) == 0.0) { /* We have to make sure that "a" points to the next element in the */ /* list after the removal of itself */ if (a == mCurrentTableau->getFirst()) { mNextTableau->addLine(*a); mCurrentTableau->removeLine(a); a = mCurrentTableau->getFirst(); } else { /* We have to remember the previous element so that a++ points to */ /* past the removed one */ b = a--; mNextTableau->addLine(*b); mCurrentTableau->removeLine(b); a++; } } else a++; /* Now we create all linear combinations of the remaining lines in the */ /* current tableau */ a = mCurrentTableau->getFirst(); while (a != mCurrentTableau->getEnd()) { b = a; b++; while (b != mCurrentTableau->getEnd()) { mb = (*a)->getReaction(0); /* We make sure that "mb" is positive */ if (mb < 0.0) { mb *= -1; ma = (*b)->getReaction(0); } else ma = - (*b)->getReaction(0); /* The multiplier "ma" for irreversible reactions must be positive */ if ((*a)->isReversible() || ma > 0.0) mNextTableau->addLine(new CTableauLine(ma, **a, mb, **b)); b++; } a++; } /* Assigne the next tableau to the current tableau and cleanup */ pdelete(mCurrentTableau); mCurrentTableau = mNextTableau; mNextTableau = NULL; } void CEFMAlgorithm::buildFluxModes(std::vector < CFluxMode > & fluxModes) { fluxModes.clear(); std::list< const CTableauLine * >::iterator a = mCurrentTableau->getFirst(); std::list< const CTableauLine * >::iterator end = mCurrentTableau->getEnd(); while (a != end) { fluxModes.push_back(CFluxMode(*a)); a++; } } <commit_msg>Rectified the bug that caused the application to crash on pressing the run button on Elementary Flux Modes.<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/elementaryFluxModes/CEFMAlgorithm.cpp,v $ $Revision: 1.11 $ $Name: $ $Author: gasingh $ $Date: 2004/03/10 04:19:33 $ End CVS Header */ /** * CEFMAlgorithm class. * Used to calculate elementary flux modes * * Created for Copasi by Stefan Hoops 2002-05-08 * (C) Stefan Hoops 2002 */ // #define COPASI_TRACE_CONSTRUCTION #include "copasi.h" #include "CEFMAlgorithm.h" #include "CFluxMode.h" #include "CTableauMatrix.h" CEFMAlgorithm::CEFMAlgorithm() { CONSTRUCTOR_TRACE; mCurrentTableau = NULL; mNextTableau = NULL; } CEFMAlgorithm::~CEFMAlgorithm() { DESTRUCTOR_TRACE; pdelete(mCurrentTableau); pdelete(mNextTableau); } bool CEFMAlgorithm::calculate(const std::vector < std::vector < C_FLOAT64 > > & stoi, const unsigned C_INT32 &reversibleNumber, std::vector < CFluxMode > & fluxModes) { bool Success = true; if (stoi.size()) { unsigned C_INT32 Step, MaxSteps = stoi[0].size(); /* initialize the current tableu matrix */ mCurrentTableau = new CTableauMatrix(stoi, reversibleNumber); /* Do the iteration */ for (Step = 0; Step < MaxSteps; Step++) calculateNextTableau(); /* Build the elementary flux modes to be returned */ buildFluxModes(fluxModes); /* Delete the current / final tableu matrix */ pdelete(mCurrentTableau); } return Success; } void CEFMAlgorithm::calculateNextTableau() { std::list< const CTableauLine * >::iterator a; std::list< const CTableauLine * >::iterator b; C_FLOAT64 ma, mb; mNextTableau = new CTableauMatrix(); /* Move all lines with zeros in the step column to the new tableu matrix */ /* and remove them from the current tableau matrix */ a = mCurrentTableau->getFirst(); while (a != mCurrentTableau->getEnd()) if ((*a)->getReaction(0) == 0.0) { /* We have to make sure that "a" points to the next element in the */ /* list after the removal of itself */ if (a == mCurrentTableau->getFirst()) { mNextTableau->addLine(*a); mCurrentTableau->removeLine(a); a = mCurrentTableau->getFirst(); } else { /* We have to remember the previous element so that a++ points to */ /* past the removed one */ b = a--; mNextTableau->addLine(*b); mCurrentTableau->removeLine(b); a++; } } else a++; /* Now we create all linear combinations of the remaining lines in the */ /* current tableau */ a = mCurrentTableau->getFirst(); while (a != mCurrentTableau->getEnd()) { b = a; b++; while (b != mCurrentTableau->getEnd()) { mb = (*a)->getReaction(0); /* We make sure that "mb" is positive */ if (mb < 0.0) { mb *= -1; ma = (*b)->getReaction(0); } else ma = - (*b)->getReaction(0); /* The multiplier "ma" for irreversible reactions must be positive */ if ((*a)->isReversible() || ma > 0.0) mNextTableau->addLine(new CTableauLine(ma, **a, mb, **b)); b++; } a++; } /* Assigne the next tableau to the current tableau and cleanup */ pdelete(mCurrentTableau); mCurrentTableau = mNextTableau; mNextTableau = NULL; } void CEFMAlgorithm::buildFluxModes(std::vector < CFluxMode > & fluxModes) { fluxModes.clear(); std::list< const CTableauLine * >::iterator a = mCurrentTableau->getFirst(); std::list< const CTableauLine * >::iterator end = mCurrentTableau->getEnd(); while (a != end) { fluxModes.push_back(CFluxMode(*a)); a++; } } <|endoftext|>
<commit_before>// Copyright (C) 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include <copasi/optimization/COptPopulationMethod.h> #include <copasi/randomGenerator/CRandom.h> #include <copasi/utilities/CProcessReport.h> #include <copasi/report/CCopasiObject.h> #include <copasi/report/CCopasiObjectReference.h> COptPopulationMethod::COptPopulationMethod(const CCopasiContainer * pParent, const CTaskEnum::Method & methodType, const CTaskEnum::Task & taskType /*= CTaskEnum::optimization*/) : COptMethod(pParent, methodType, taskType) , mPopulationSize(0) , mGenerations(0) , mCurrentGeneration(0) , mhGenerations(C_INVALID_INDEX) , mVariableSize(0) , mIndividuals() , mValues() , mpRandom(NULL) { initObjects(); } COptPopulationMethod::COptPopulationMethod(const COptPopulationMethod & src, const CCopasiContainer * pParent) : COptMethod(src, pParent) , mPopulationSize(0) , mGenerations(0) , mCurrentGeneration(0) , mhGenerations(C_INVALID_INDEX) , mVariableSize(0) , mIndividuals() , mValues() , mpRandom(NULL) { initObjects(); } COptPopulationMethod::~COptPopulationMethod() { cleanup(); } void COptPopulationMethod::initObjects() { if (getSubType() != CTaskEnum::ParticleSwarm && getSubType() != CTaskEnum::ScatterSearch) addObjectReference("Current Generation", mCurrentGeneration, CCopasiObject::ValueInt); } #include <iostream> bool COptPopulationMethod::initialize() { cleanup(); if (!COptMethod::initialize()) return false; mCurrentGeneration = 0; mGenerations = 0; if (getParameter("Number of Generations") != NULL) mGenerations = getValue< unsigned C_INT32 >("Number of Generations"); if (mpCallBack && (getSubType() != CTaskEnum::ParticleSwarm && getSubType() != CTaskEnum::ScatterSearch)) { mhGenerations = mpCallBack->addItem("Current Generation", mCurrentGeneration, &mGenerations); } mCurrentGeneration++; if (getParameter("Population Size") != NULL) mPopulationSize = getValue< unsigned C_INT32 >("Population Size"); else mPopulationSize = 0; if (getParameter("Random Number Generator") != NULL && getParameter("Seed") != NULL) mpRandom = CRandom::createGenerator((CRandom::Type) getValue< unsigned C_INT32 >("Random Number Generator"), getValue< unsigned C_INT32 >("Seed")); mVariableSize = mpOptItem->size(); return true; } bool COptPopulationMethod::cleanup() { size_t i; pdelete(mpRandom); for (i = 0; i < mIndividuals.size(); i++) pdelete(mIndividuals[i]); mIndividuals.clear(); return true; } void COptPopulationMethod::print(std::ostream * ostream) const { *ostream << *this; } std::ostream &operator<<(std::ostream &os, const COptPopulationMethod & o) { os << "Population Information: " << std::endl; os << "Population Size: " << o.mPopulationSize << std::endl; os << "# Generations / Iterations: " << o.mGenerations << std::endl; os << "Current Generation / Iteration: " << o.mCurrentGeneration << std::endl; os << "Population Values: " << std::endl << " " << o.mValues << std::endl << std::endl; os << "Population:" << std::endl; std::vector< CVector < C_FLOAT64 > * >::const_iterator it = o.mIndividuals.begin(); for (; it != o.mIndividuals.end(); ++it) { os << " " << **it << std::endl; } return os; } <commit_msg>- additionally print regular results from coptmethod<commit_after>// Copyright (C) 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include <copasi/optimization/COptPopulationMethod.h> #include <copasi/randomGenerator/CRandom.h> #include <copasi/utilities/CProcessReport.h> #include <copasi/report/CCopasiObject.h> #include <copasi/report/CCopasiObjectReference.h> COptPopulationMethod::COptPopulationMethod(const CCopasiContainer * pParent, const CTaskEnum::Method & methodType, const CTaskEnum::Task & taskType /*= CTaskEnum::optimization*/) : COptMethod(pParent, methodType, taskType) , mPopulationSize(0) , mGenerations(0) , mCurrentGeneration(0) , mhGenerations(C_INVALID_INDEX) , mVariableSize(0) , mIndividuals() , mValues() , mpRandom(NULL) { initObjects(); } COptPopulationMethod::COptPopulationMethod(const COptPopulationMethod & src, const CCopasiContainer * pParent) : COptMethod(src, pParent) , mPopulationSize(0) , mGenerations(0) , mCurrentGeneration(0) , mhGenerations(C_INVALID_INDEX) , mVariableSize(0) , mIndividuals() , mValues() , mpRandom(NULL) { initObjects(); } COptPopulationMethod::~COptPopulationMethod() { cleanup(); } void COptPopulationMethod::initObjects() { if (getSubType() != CTaskEnum::ParticleSwarm && getSubType() != CTaskEnum::ScatterSearch) addObjectReference("Current Generation", mCurrentGeneration, CCopasiObject::ValueInt); } #include <iostream> bool COptPopulationMethod::initialize() { cleanup(); if (!COptMethod::initialize()) return false; mCurrentGeneration = 0; mGenerations = 0; if (getParameter("Number of Generations") != NULL) mGenerations = getValue< unsigned C_INT32 >("Number of Generations"); if (mpCallBack && (getSubType() != CTaskEnum::ParticleSwarm && getSubType() != CTaskEnum::ScatterSearch)) { mhGenerations = mpCallBack->addItem("Current Generation", mCurrentGeneration, &mGenerations); } mCurrentGeneration++; if (getParameter("Population Size") != NULL) mPopulationSize = getValue< unsigned C_INT32 >("Population Size"); else mPopulationSize = 0; if (getParameter("Random Number Generator") != NULL && getParameter("Seed") != NULL) mpRandom = CRandom::createGenerator((CRandom::Type) getValue< unsigned C_INT32 >("Random Number Generator"), getValue< unsigned C_INT32 >("Seed")); mVariableSize = mpOptItem->size(); return true; } bool COptPopulationMethod::cleanup() { size_t i; pdelete(mpRandom); for (i = 0; i < mIndividuals.size(); i++) pdelete(mIndividuals[i]); mIndividuals.clear(); return true; } void COptPopulationMethod::print(std::ostream * ostream) const { COptMethod::print(ostream); *ostream << std::endl << *this; } std::ostream &operator<<(std::ostream &os, const COptPopulationMethod & o) { os << "Population Information: " << std::endl; os << "Population Size: " << o.mPopulationSize << std::endl; os << "# Generations / Iterations: " << o.mGenerations << std::endl; os << "Current Generation / Iteration: " << o.mCurrentGeneration << std::endl; os << "Population Values: " << std::endl << " " << o.mValues << std::endl << std::endl; os << "Population:" << std::endl; std::vector< CVector < C_FLOAT64 > * >::const_iterator it = o.mIndividuals.begin(); for (; it != o.mIndividuals.end(); ++it) { os << " " << **it << std::endl; } return os; } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexScriptol.cxx ** Lexer for Scriptol. **/ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #include <ctype.h> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif static void ClassifyWordSol(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, char *prevWord) { char s[100] = ""; bool wordIsNumber = isdigit(styler[start]) != 0; for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) { s[i] = styler[start + i]; s[i + 1] = '\0'; } char chAttr = SCE_SCRIPTOL_IDENTIFIER; if (0 == strcmp(prevWord, "class")) chAttr = SCE_SCRIPTOL_CLASSNAME; else if (wordIsNumber) chAttr = SCE_SCRIPTOL_NUMBER; else if (keywords.InList(s)) chAttr = SCE_SCRIPTOL_KEYWORD; else for (unsigned int i = 0; i < end - start + 1; i++) // test dotted idents { if (styler[start + i] == '.') { styler.ColourTo(start + i - 1, chAttr); styler.ColourTo(start + i, SCE_SCRIPTOL_OPERATOR); } } styler.ColourTo(end, chAttr); strcpy(prevWord, s); } static bool IsSolComment(Accessor &styler, int pos, int len) { if(len > 0) { char c = styler[pos]; if(c == '`') return true; if(len > 1) { if(c == '/') { c = styler[pos + 1]; if(c == '/') return true; if(c == '*') return true; } } } return false; } static bool IsSolStringStart(char ch) { if (ch == '\'' || ch == '"') return true; return false; } static bool IsSolWordStart(char ch) { return (iswordchar(ch) && !IsSolStringStart(ch)); } static int GetSolStringState(Accessor &styler, int i, int *nextIndex) { char ch = styler.SafeGetCharAt(i); char chNext = styler.SafeGetCharAt(i + 1); if (ch != '\"' && ch != '\'') { *nextIndex = i + 1; return SCE_SCRIPTOL_DEFAULT; } // ch is either single or double quotes in string // code below seem non-sense but is here for future extensions if (ch == chNext && ch == styler.SafeGetCharAt(i + 2)) { *nextIndex = i + 3; if(ch == '\"') return SCE_SCRIPTOL_TRIPLE; if(ch == '\'') return SCE_SCRIPTOL_TRIPLE; return SCE_SCRIPTOL_STRING; } else { *nextIndex = i + 1; if (ch == '"') return SCE_SCRIPTOL_STRING; else return SCE_SCRIPTOL_STRING; } } static void ColouriseSolDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { int lengthDoc = startPos + length; char stringType = '\"'; if (startPos > 0) { int lineCurrent = styler.GetLine(startPos); if (lineCurrent > 0) { startPos = styler.LineStart(lineCurrent-1); if (startPos == 0) initStyle = SCE_SCRIPTOL_DEFAULT; else initStyle = styler.StyleAt(startPos-1); } } styler.StartAt(startPos, 127); WordList &keywords = *keywordlists[0]; int whingeLevel = styler.GetPropertyInt("tab.timmy.whinge.level"); char prevWord[200]; prevWord[0] = '\0'; if (length == 0) return; int state = initStyle & 31; int nextIndex = 0; char chPrev = ' '; char chPrev2 = ' '; char chNext = styler[startPos]; styler.StartSegment(startPos); bool atStartLine = true; int spaceFlags = 0; for (int i = startPos; i < lengthDoc; i++) { if (atStartLine) { char chBad = static_cast<char>(64); char chGood = static_cast<char>(0); char chFlags = chGood; if (whingeLevel == 1) { chFlags = (spaceFlags & wsInconsistent) ? chBad : chGood; } else if (whingeLevel == 2) { chFlags = (spaceFlags & wsSpaceTab) ? chBad : chGood; } else if (whingeLevel == 3) { chFlags = (spaceFlags & wsSpace) ? chBad : chGood; } else if (whingeLevel == 4) { chFlags = (spaceFlags & wsTab) ? chBad : chGood; } styler.SetFlags(chFlags, static_cast<char>(state)); atStartLine = false; } char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc)) { if ((state == SCE_SCRIPTOL_DEFAULT) || (state == SCE_SCRIPTOL_TRIPLE) || (state == SCE_SCRIPTOL_COMMENTBLOCK)) { styler.ColourTo(i, state); } atStartLine = true; } if (styler.IsLeadByte(ch)) { chNext = styler.SafeGetCharAt(i + 2); chPrev = ' '; chPrev2 = ' '; i += 1; continue; } if (state == SCE_SCRIPTOL_STRINGEOL) { if (ch != '\r' && ch != '\n') { styler.ColourTo(i - 1, state); state = SCE_SCRIPTOL_DEFAULT; } } if (state == SCE_SCRIPTOL_DEFAULT) { if (IsSolWordStart(ch)) { styler.ColourTo(i - 1, state); state = SCE_SCRIPTOL_KEYWORD; } else if (ch == '`') { styler.ColourTo(i - 1, state); state = SCE_SCRIPTOL_COMMENTLINE; } else if (ch == '/') { styler.ColourTo(i - 1, state); if(chNext == '/') state = SCE_SCRIPTOL_CSTYLE; if(chNext == '*') state = SCE_SCRIPTOL_COMMENTBLOCK; } else if (IsSolStringStart(ch)) { styler.ColourTo(i - 1, state); state = GetSolStringState(styler, i, &nextIndex); if(state == SCE_SCRIPTOL_STRING) { stringType = ch; } if (nextIndex != i + 1) { i = nextIndex - 1; ch = ' '; chPrev = ' '; chNext = styler.SafeGetCharAt(i + 1); } } else if (isoperator(ch)) { styler.ColourTo(i - 1, state); styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR); } } else if (state == SCE_SCRIPTOL_KEYWORD) { if (!iswordchar(ch)) { ClassifyWordSol(styler.GetStartSegment(), i - 1, keywords, styler, prevWord); state = SCE_SCRIPTOL_DEFAULT; if (ch == '`') { state = chNext == '`' ? SCE_SCRIPTOL_PERSISTENT : SCE_SCRIPTOL_COMMENTLINE; } else if (IsSolStringStart(ch)) { styler.ColourTo(i - 1, state); state = GetSolStringState(styler, i, &nextIndex); if (nextIndex != i + 1) { i = nextIndex - 1; ch = ' '; chPrev = ' '; chNext = styler.SafeGetCharAt(i + 1); } } else if (isoperator(ch)) { styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR); } } } else { if (state == SCE_SCRIPTOL_COMMENTLINE || state == SCE_SCRIPTOL_PERSISTENT || state == SCE_SCRIPTOL_CSTYLE) { if (ch == '\r' || ch == '\n') { styler.ColourTo(i - 1, state); state = SCE_SCRIPTOL_DEFAULT; } } else if(state == SCE_SCRIPTOL_COMMENTBLOCK) { if(chPrev == '*' && ch == '/') { styler.ColourTo(i, state); state = SCE_SCRIPTOL_DEFAULT; } } else if ((state == SCE_SCRIPTOL_STRING) || (state == SCE_SCRIPTOL_CHARACTER)) { if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { styler.ColourTo(i - 1, state); state = SCE_SCRIPTOL_STRINGEOL; } else if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if ((ch == '\"') || (ch == '\'')) { // must match the entered quote type if(ch == stringType) { styler.ColourTo(i, state); state = SCE_SCRIPTOL_DEFAULT; } } } else if (state == SCE_SCRIPTOL_TRIPLE) { if ((ch == '\'' && chPrev == '\'' && chPrev2 == '\'') || (ch == '\"' && chPrev == '\"' && chPrev2 == '\"')) { styler.ColourTo(i, state); state = SCE_SCRIPTOL_DEFAULT; } } } chPrev2 = chPrev; chPrev = ch; } if (state == SCE_SCRIPTOL_KEYWORD) { ClassifyWordSol(styler.GetStartSegment(), lengthDoc-1, keywords, styler, prevWord); } else { styler.ColourTo(lengthDoc-1, state); } } static void FoldSolDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { int lengthDoc = startPos + length; int lineCurrent = styler.GetLine(startPos); if (startPos > 0) { if (lineCurrent > 0) { lineCurrent--; startPos = styler.LineStart(lineCurrent); if (startPos == 0) initStyle = SCE_SCRIPTOL_DEFAULT; else initStyle = styler.StyleAt(startPos-1); } } int state = initStyle & 31; int spaceFlags = 0; int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsSolComment); if (state == SCE_SCRIPTOL_TRIPLE) indentCurrent |= SC_FOLDLEVELWHITEFLAG; char chNext = styler[startPos]; for (int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styler.StyleAt(i) & 31; if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc)) { int lev = indentCurrent; int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsSolComment); if (style == SCE_SCRIPTOL_TRIPLE) indentNext |= SC_FOLDLEVELWHITEFLAG; if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) { // Only non whitespace lines can be headers if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } else if (indentNext & SC_FOLDLEVELWHITEFLAG) { // Line after is blank so check the next - maybe should continue further? int spaceFlags2 = 0; int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsSolComment); if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } } } indentCurrent = indentNext; styler.SetLevel(lineCurrent, lev); lineCurrent++; } } } LexerModule lmScriptol(SCLEX_SCRIPTOL, ColouriseSolDoc, "scriptol", FoldSolDoc); <commit_msg>Removing use of style byte indicator in Scriptol lexer.<commit_after>// Scintilla source code edit control /** @file LexScriptol.cxx ** Lexer for Scriptol. **/ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #include <ctype.h> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif static void ClassifyWordSol(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, char *prevWord) { char s[100] = ""; bool wordIsNumber = isdigit(styler[start]) != 0; for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) { s[i] = styler[start + i]; s[i + 1] = '\0'; } char chAttr = SCE_SCRIPTOL_IDENTIFIER; if (0 == strcmp(prevWord, "class")) chAttr = SCE_SCRIPTOL_CLASSNAME; else if (wordIsNumber) chAttr = SCE_SCRIPTOL_NUMBER; else if (keywords.InList(s)) chAttr = SCE_SCRIPTOL_KEYWORD; else for (unsigned int i = 0; i < end - start + 1; i++) // test dotted idents { if (styler[start + i] == '.') { styler.ColourTo(start + i - 1, chAttr); styler.ColourTo(start + i, SCE_SCRIPTOL_OPERATOR); } } styler.ColourTo(end, chAttr); strcpy(prevWord, s); } static bool IsSolComment(Accessor &styler, int pos, int len) { if(len > 0) { char c = styler[pos]; if(c == '`') return true; if(len > 1) { if(c == '/') { c = styler[pos + 1]; if(c == '/') return true; if(c == '*') return true; } } } return false; } static bool IsSolStringStart(char ch) { if (ch == '\'' || ch == '"') return true; return false; } static bool IsSolWordStart(char ch) { return (iswordchar(ch) && !IsSolStringStart(ch)); } static int GetSolStringState(Accessor &styler, int i, int *nextIndex) { char ch = styler.SafeGetCharAt(i); char chNext = styler.SafeGetCharAt(i + 1); if (ch != '\"' && ch != '\'') { *nextIndex = i + 1; return SCE_SCRIPTOL_DEFAULT; } // ch is either single or double quotes in string // code below seem non-sense but is here for future extensions if (ch == chNext && ch == styler.SafeGetCharAt(i + 2)) { *nextIndex = i + 3; if(ch == '\"') return SCE_SCRIPTOL_TRIPLE; if(ch == '\'') return SCE_SCRIPTOL_TRIPLE; return SCE_SCRIPTOL_STRING; } else { *nextIndex = i + 1; if (ch == '"') return SCE_SCRIPTOL_STRING; else return SCE_SCRIPTOL_STRING; } } static void ColouriseSolDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { int lengthDoc = startPos + length; char stringType = '\"'; if (startPos > 0) { int lineCurrent = styler.GetLine(startPos); if (lineCurrent > 0) { startPos = styler.LineStart(lineCurrent-1); if (startPos == 0) initStyle = SCE_SCRIPTOL_DEFAULT; else initStyle = styler.StyleAt(startPos-1); } } styler.StartAt(startPos); WordList &keywords = *keywordlists[0]; char prevWord[200]; prevWord[0] = '\0'; if (length == 0) return; int state = initStyle & 31; int nextIndex = 0; char chPrev = ' '; char chPrev2 = ' '; char chNext = styler[startPos]; styler.StartSegment(startPos); for (int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc)) { if ((state == SCE_SCRIPTOL_DEFAULT) || (state == SCE_SCRIPTOL_TRIPLE) || (state == SCE_SCRIPTOL_COMMENTBLOCK)) { styler.ColourTo(i, state); } } if (styler.IsLeadByte(ch)) { chNext = styler.SafeGetCharAt(i + 2); chPrev = ' '; chPrev2 = ' '; i += 1; continue; } if (state == SCE_SCRIPTOL_STRINGEOL) { if (ch != '\r' && ch != '\n') { styler.ColourTo(i - 1, state); state = SCE_SCRIPTOL_DEFAULT; } } if (state == SCE_SCRIPTOL_DEFAULT) { if (IsSolWordStart(ch)) { styler.ColourTo(i - 1, state); state = SCE_SCRIPTOL_KEYWORD; } else if (ch == '`') { styler.ColourTo(i - 1, state); state = SCE_SCRIPTOL_COMMENTLINE; } else if (ch == '/') { styler.ColourTo(i - 1, state); if(chNext == '/') state = SCE_SCRIPTOL_CSTYLE; if(chNext == '*') state = SCE_SCRIPTOL_COMMENTBLOCK; } else if (IsSolStringStart(ch)) { styler.ColourTo(i - 1, state); state = GetSolStringState(styler, i, &nextIndex); if(state == SCE_SCRIPTOL_STRING) { stringType = ch; } if (nextIndex != i + 1) { i = nextIndex - 1; ch = ' '; chPrev = ' '; chNext = styler.SafeGetCharAt(i + 1); } } else if (isoperator(ch)) { styler.ColourTo(i - 1, state); styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR); } } else if (state == SCE_SCRIPTOL_KEYWORD) { if (!iswordchar(ch)) { ClassifyWordSol(styler.GetStartSegment(), i - 1, keywords, styler, prevWord); state = SCE_SCRIPTOL_DEFAULT; if (ch == '`') { state = chNext == '`' ? SCE_SCRIPTOL_PERSISTENT : SCE_SCRIPTOL_COMMENTLINE; } else if (IsSolStringStart(ch)) { styler.ColourTo(i - 1, state); state = GetSolStringState(styler, i, &nextIndex); if (nextIndex != i + 1) { i = nextIndex - 1; ch = ' '; chPrev = ' '; chNext = styler.SafeGetCharAt(i + 1); } } else if (isoperator(ch)) { styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR); } } } else { if (state == SCE_SCRIPTOL_COMMENTLINE || state == SCE_SCRIPTOL_PERSISTENT || state == SCE_SCRIPTOL_CSTYLE) { if (ch == '\r' || ch == '\n') { styler.ColourTo(i - 1, state); state = SCE_SCRIPTOL_DEFAULT; } } else if(state == SCE_SCRIPTOL_COMMENTBLOCK) { if(chPrev == '*' && ch == '/') { styler.ColourTo(i, state); state = SCE_SCRIPTOL_DEFAULT; } } else if ((state == SCE_SCRIPTOL_STRING) || (state == SCE_SCRIPTOL_CHARACTER)) { if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { styler.ColourTo(i - 1, state); state = SCE_SCRIPTOL_STRINGEOL; } else if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if ((ch == '\"') || (ch == '\'')) { // must match the entered quote type if(ch == stringType) { styler.ColourTo(i, state); state = SCE_SCRIPTOL_DEFAULT; } } } else if (state == SCE_SCRIPTOL_TRIPLE) { if ((ch == '\'' && chPrev == '\'' && chPrev2 == '\'') || (ch == '\"' && chPrev == '\"' && chPrev2 == '\"')) { styler.ColourTo(i, state); state = SCE_SCRIPTOL_DEFAULT; } } } chPrev2 = chPrev; chPrev = ch; } if (state == SCE_SCRIPTOL_KEYWORD) { ClassifyWordSol(styler.GetStartSegment(), lengthDoc-1, keywords, styler, prevWord); } else { styler.ColourTo(lengthDoc-1, state); } } static void FoldSolDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { int lengthDoc = startPos + length; int lineCurrent = styler.GetLine(startPos); if (startPos > 0) { if (lineCurrent > 0) { lineCurrent--; startPos = styler.LineStart(lineCurrent); if (startPos == 0) initStyle = SCE_SCRIPTOL_DEFAULT; else initStyle = styler.StyleAt(startPos-1); } } int state = initStyle & 31; int spaceFlags = 0; int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsSolComment); if (state == SCE_SCRIPTOL_TRIPLE) indentCurrent |= SC_FOLDLEVELWHITEFLAG; char chNext = styler[startPos]; for (int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styler.StyleAt(i) & 31; if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc)) { int lev = indentCurrent; int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsSolComment); if (style == SCE_SCRIPTOL_TRIPLE) indentNext |= SC_FOLDLEVELWHITEFLAG; if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) { // Only non whitespace lines can be headers if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } else if (indentNext & SC_FOLDLEVELWHITEFLAG) { // Line after is blank so check the next - maybe should continue further? int spaceFlags2 = 0; int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsSolComment); if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } } } indentCurrent = indentNext; styler.SetLevel(lineCurrent, lev); lineCurrent++; } } } LexerModule lmScriptol(SCLEX_SCRIPTOL, ColouriseSolDoc, "scriptol", FoldSolDoc); <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/controls/tabbed_pane/tabbed_pane.h" #include "base/logging.h" #include "views/controls/tabbed_pane/native_tabbed_pane_wrapper.h" namespace views { // static const char TabbedPane::kViewClassName[] = "views/TabbedPane"; TabbedPane::TabbedPane() : native_tabbed_pane_(NULL), listener_(NULL) { SetFocusable(true); } TabbedPane::~TabbedPane() { } void TabbedPane::SetListener(Listener* listener) { listener_ = listener; } void TabbedPane::AddTab(const std::wstring& title, View* contents) { native_tabbed_pane_->AddTab(title, contents); } void TabbedPane::AddTabAtIndex(int index, const std::wstring& title, View* contents, bool select_if_first_tab) { native_tabbed_pane_->AddTabAtIndex(index, title, contents, select_if_first_tab); } int TabbedPane::GetSelectedTabIndex() { return native_tabbed_pane_->GetSelectedTabIndex(); } View* TabbedPane::GetSelectedTab() { return native_tabbed_pane_->GetSelectedTab(); } View* TabbedPane::RemoveTabAtIndex(int index) { return native_tabbed_pane_->RemoveTabAtIndex(index); } void TabbedPane::SelectTabAt(int index) { native_tabbed_pane_->SelectTabAt(index); } int TabbedPane::GetTabCount() { return native_tabbed_pane_->GetTabCount(); } void TabbedPane::CreateWrapper() { native_tabbed_pane_ = NativeTabbedPaneWrapper::CreateNativeWrapper(this); } // View overrides: std::string TabbedPane::GetClassName() const { return kViewClassName; } void TabbedPane::ViewHierarchyChanged(bool is_add, View* parent, View* child) { if (is_add && !native_tabbed_pane_ && GetWidget()) { CreateWrapper(); AddChildView(native_tabbed_pane_->GetView()); LoadAccelerators(); } } bool TabbedPane::AcceleratorPressed(const views::Accelerator& accelerator) { // We only accept Ctrl+Tab keyboard events. DCHECK(accelerator.GetKeyCode() == VK_TAB && accelerator.IsCtrlDown()); int tab_count = GetTabCount(); if (tab_count <= 1) return false; int selected_tab_index = GetSelectedTabIndex(); int next_tab_index = accelerator.IsShiftDown() ? (selected_tab_index - 1) % tab_count : (selected_tab_index + 1) % tab_count; // Wrap around. if (next_tab_index < 0) next_tab_index += tab_count; SelectTabAt(next_tab_index); return true; } void TabbedPane::LoadAccelerators() { // Ctrl+Shift+Tab AddAccelerator(views::Accelerator(VK_TAB, true, true, false)); // Ctrl+Tab AddAccelerator(views::Accelerator(VK_TAB, false, true, false)); } void TabbedPane::Layout() { if (native_tabbed_pane_) { native_tabbed_pane_->GetView()->SetBounds(0, 0, width(), height()); native_tabbed_pane_->GetView()->Layout(); } } void TabbedPane::Focus() { // Forward the focus to the wrapper. if (native_tabbed_pane_) native_tabbed_pane_->SetFocus(); else View::Focus(); // Will focus the RootView window (so we still get keyboard // messages). } } // namespace views <commit_msg>Fixing a compilation error in toolkit_views.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/controls/tabbed_pane/tabbed_pane.h" #include "base/keyboard_codes.h" #include "base/logging.h" #include "views/controls/tabbed_pane/native_tabbed_pane_wrapper.h" namespace views { // static const char TabbedPane::kViewClassName[] = "views/TabbedPane"; TabbedPane::TabbedPane() : native_tabbed_pane_(NULL), listener_(NULL) { SetFocusable(true); } TabbedPane::~TabbedPane() { } void TabbedPane::SetListener(Listener* listener) { listener_ = listener; } void TabbedPane::AddTab(const std::wstring& title, View* contents) { native_tabbed_pane_->AddTab(title, contents); } void TabbedPane::AddTabAtIndex(int index, const std::wstring& title, View* contents, bool select_if_first_tab) { native_tabbed_pane_->AddTabAtIndex(index, title, contents, select_if_first_tab); } int TabbedPane::GetSelectedTabIndex() { return native_tabbed_pane_->GetSelectedTabIndex(); } View* TabbedPane::GetSelectedTab() { return native_tabbed_pane_->GetSelectedTab(); } View* TabbedPane::RemoveTabAtIndex(int index) { return native_tabbed_pane_->RemoveTabAtIndex(index); } void TabbedPane::SelectTabAt(int index) { native_tabbed_pane_->SelectTabAt(index); } int TabbedPane::GetTabCount() { return native_tabbed_pane_->GetTabCount(); } void TabbedPane::CreateWrapper() { native_tabbed_pane_ = NativeTabbedPaneWrapper::CreateNativeWrapper(this); } // View overrides: std::string TabbedPane::GetClassName() const { return kViewClassName; } void TabbedPane::ViewHierarchyChanged(bool is_add, View* parent, View* child) { if (is_add && !native_tabbed_pane_ && GetWidget()) { CreateWrapper(); AddChildView(native_tabbed_pane_->GetView()); LoadAccelerators(); } } bool TabbedPane::AcceleratorPressed(const views::Accelerator& accelerator) { // We only accept Ctrl+Tab keyboard events. DCHECK(accelerator.GetKeyCode() == base::VKEY_TAB && accelerator.IsCtrlDown()); int tab_count = GetTabCount(); if (tab_count <= 1) return false; int selected_tab_index = GetSelectedTabIndex(); int next_tab_index = accelerator.IsShiftDown() ? (selected_tab_index - 1) % tab_count : (selected_tab_index + 1) % tab_count; // Wrap around. if (next_tab_index < 0) next_tab_index += tab_count; SelectTabAt(next_tab_index); return true; } void TabbedPane::LoadAccelerators() { // Ctrl+Shift+Tab AddAccelerator(views::Accelerator(base::VKEY_TAB, true, true, false)); // Ctrl+Tab AddAccelerator(views::Accelerator(base::VKEY_TAB, false, true, false)); } void TabbedPane::Layout() { if (native_tabbed_pane_) { native_tabbed_pane_->GetView()->SetBounds(0, 0, width(), height()); native_tabbed_pane_->GetView()->Layout(); } } void TabbedPane::Focus() { // Forward the focus to the wrapper. if (native_tabbed_pane_) native_tabbed_pane_->SetFocus(); else View::Focus(); // Will focus the RootView window (so we still get keyboard // messages). } } // namespace views <|endoftext|>
<commit_before>// Copyright 2012-2013 Samplecount S.L. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef METHCLA_FILE_HPP_INCLUDED #define METHCLA_FILE_HPP_INCLUDED #include <methcla/detail.hpp> #include <methcla/engine.hpp> #include <methcla/file.h> #include <methcla/plugin.h> #include <stdexcept> namespace Methcla { class SoundFileInfo : public Methcla_SoundFileInfo { public: SoundFileInfo() { frames = 0; channels = 0; samplerate = 0; file_type = kMethcla_SoundFileTypeUnknown; file_format = kMethcla_SoundFileFormatUnknown; } SoundFileInfo(const Methcla_SoundFileInfo& info) { frames = info.frames; channels = info.channels; samplerate = info.samplerate; file_type = info.file_type; file_format = info.file_format; } int64_t samples() const { return channels * frames; } template <typename T> T duration() const { return (T)frames/(T)samplerate; } }; class SoundFile { Methcla_SoundFile* m_file; SoundFileInfo m_info; inline void ensureInitialized() const { if (!m_file) throw std::logic_error("SoundFile has not been initialized"); } public: SoundFile() : m_file(nullptr) {} SoundFile(Methcla_SoundFile* file, const Methcla_SoundFileInfo& info) : m_file(file) , m_info(info) {} SoundFile(const Engine& engine, const std::string& path) { detail::checkReturnCode( methcla_engine_soundfile_open(engine, path.c_str(), kMethcla_FileModeRead, &m_file, &m_info) ); } SoundFile(const Engine& engine, const std::string& path, const SoundFileInfo& info) : m_info(info) { detail::checkReturnCode( methcla_engine_soundfile_open(engine, path.c_str(), kMethcla_FileModeWrite, &m_file, &m_info) ); } SoundFile(const Methcla_Host* host, const std::string& path) { detail::checkReturnCode( methcla_host_soundfile_open(host, path.c_str(), kMethcla_FileModeRead, &m_file, &m_info) ); } SoundFile(const Methcla_Host* host, const std::string& path, const SoundFileInfo& info) : m_info(info) { detail::checkReturnCode( methcla_host_soundfile_open(host, path.c_str(), kMethcla_FileModeWrite, &m_file, &m_info) ); } // SoundFile is moveable SoundFile(SoundFile&& other) : m_file(std::move(other.m_file)) , m_info(std::move(other.m_info)) { other.m_file = nullptr; } SoundFile& operator=(SoundFile&& other) { m_file = std::move(other.m_file); m_info = std::move(other.m_info); other.m_file = nullptr; return *this; } // SoundFile is not copyable SoundFile(const SoundFile&) = delete; SoundFile& operator=(const SoundFile&) = delete; ~SoundFile() { if (m_file != nullptr) methcla_soundfile_close(m_file); } const SoundFileInfo& info() const { return m_info; } void seek(int64_t numFrames) { ensureInitialized(); detail::checkReturnCode(methcla_soundfile_seek(m_file, numFrames)); } int64_t tell() { ensureInitialized(); int64_t numFrames; detail::checkReturnCode(methcla_soundfile_tell(m_file, &numFrames)); return numFrames; } size_t read(float* buffer, size_t numFrames) { ensureInitialized(); size_t outNumFrames; detail::checkReturnCode(methcla_soundfile_read_float(m_file, buffer, numFrames, &outNumFrames)); return outNumFrames; } size_t write(const float* buffer, size_t numFrames) { ensureInitialized(); size_t outNumFrames; detail::checkReturnCode(methcla_soundfile_write_float(m_file, buffer, numFrames, &outNumFrames)); return outNumFrames; } }; } #endif // METHCLA_FILE_HPP_INCLUDED<commit_msg>Add operator bool to Methcla::SoundFile for checking whether it is valid<commit_after>// Copyright 2012-2013 Samplecount S.L. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef METHCLA_FILE_HPP_INCLUDED #define METHCLA_FILE_HPP_INCLUDED #include <methcla/detail.hpp> #include <methcla/engine.hpp> #include <methcla/file.h> #include <methcla/plugin.h> #include <stdexcept> namespace Methcla { class SoundFileInfo : public Methcla_SoundFileInfo { public: SoundFileInfo() { frames = 0; channels = 0; samplerate = 0; file_type = kMethcla_SoundFileTypeUnknown; file_format = kMethcla_SoundFileFormatUnknown; } SoundFileInfo(const Methcla_SoundFileInfo& info) { frames = info.frames; channels = info.channels; samplerate = info.samplerate; file_type = info.file_type; file_format = info.file_format; } int64_t samples() const { return channels * frames; } template <typename T> T duration() const { return (T)frames/(T)samplerate; } }; class SoundFile { Methcla_SoundFile* m_file; SoundFileInfo m_info; inline void ensureInitialized() const { if (!m_file) throw std::logic_error("SoundFile has not been initialized"); } public: SoundFile() : m_file(nullptr) {} SoundFile(Methcla_SoundFile* file, const Methcla_SoundFileInfo& info) : m_file(file) , m_info(info) {} SoundFile(const Engine& engine, const std::string& path) { detail::checkReturnCode( methcla_engine_soundfile_open(engine, path.c_str(), kMethcla_FileModeRead, &m_file, &m_info) ); } SoundFile(const Engine& engine, const std::string& path, const SoundFileInfo& info) : m_info(info) { detail::checkReturnCode( methcla_engine_soundfile_open(engine, path.c_str(), kMethcla_FileModeWrite, &m_file, &m_info) ); } SoundFile(const Methcla_Host* host, const std::string& path) { detail::checkReturnCode( methcla_host_soundfile_open(host, path.c_str(), kMethcla_FileModeRead, &m_file, &m_info) ); } SoundFile(const Methcla_Host* host, const std::string& path, const SoundFileInfo& info) : m_info(info) { detail::checkReturnCode( methcla_host_soundfile_open(host, path.c_str(), kMethcla_FileModeWrite, &m_file, &m_info) ); } // SoundFile is moveable SoundFile(SoundFile&& other) : m_file(std::move(other.m_file)) , m_info(std::move(other.m_info)) { other.m_file = nullptr; } SoundFile& operator=(SoundFile&& other) { m_file = std::move(other.m_file); m_info = std::move(other.m_info); other.m_file = nullptr; return *this; } // SoundFile is not copyable SoundFile(const SoundFile&) = delete; SoundFile& operator=(const SoundFile&) = delete; ~SoundFile() { if (m_file != nullptr) methcla_soundfile_close(m_file); } operator bool() const { return m_file != nullptr; } const SoundFileInfo& info() const { return m_info; } void seek(int64_t numFrames) { ensureInitialized(); detail::checkReturnCode(methcla_soundfile_seek(m_file, numFrames)); } int64_t tell() { ensureInitialized(); int64_t numFrames; detail::checkReturnCode(methcla_soundfile_tell(m_file, &numFrames)); return numFrames; } size_t read(float* buffer, size_t numFrames) { ensureInitialized(); size_t outNumFrames; detail::checkReturnCode(methcla_soundfile_read_float(m_file, buffer, numFrames, &outNumFrames)); return outNumFrames; } size_t write(const float* buffer, size_t numFrames) { ensureInitialized(); size_t outNumFrames; detail::checkReturnCode(methcla_soundfile_write_float(m_file, buffer, numFrames, &outNumFrames)); return outNumFrames; } }; } #endif // METHCLA_FILE_HPP_INCLUDED<|endoftext|>
<commit_before>#include <cstdlib> #include <iostream> using namespace std; int c(int a, int b) { if(a >= 0) { return a * b; } else if(b <= 0) { return b * b; } else if(a >= 0 && b <= 0) { return a * a * a; } else { return 0; } } int main() { int a, b; while(cin >> a >> b){ cout << c(a, b) << endl; } return 0; } <commit_msg>:Add sum/mult sample<commit_after>#include <cstdlib> #include <iostream> using namespace std; int y(int x){ int y; if(x >= 0){ y = 0; for(int i = 0; i < x; i++){ y += i; } } else { y = 1; for(int i = x; i < 0; i++){ y *= i; } } return y; } int c(int a, int b) { if(a >= 0) { return a * b; } else if(b <= 0) { return b * b; } else if(a >= 0 && b <= 0) { return a * a * a; } else { return 0; } } int main() { int a, b; while(cin >> a >> b){ cout << c(a, b) << ", " << y(a) << endl; } return 0; } <|endoftext|>
<commit_before>// Copyright (C) 2015, Baidu Inc. // Author: Sun Junyi (sunjunyi01@baidu.com) #include "partitioner.h" #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <iostream> #include <string> int main(int argc, char* argv[]) { if (argc < 2) { fprintf(stderr, "partitioner [reducer total] \n"); return 1; } std::string record; uint32_t reducer_total = atoi( argv[1] ); Partitioner* partition = new HashPartitioner(); partition->SetReducerTotal(reducer_total); while (getline(std::cin, record)) { size_t key_span = strcspn(record.c_str(), "\t "); //tab or whitespace std::string key(record.c_str(), key_span); uint32_t reducer_slot = partition->GetReducerSlot(key.c_str()); std::cout << reducer_slot << "\1\1\1" << record << std::endl; } return 0; } <commit_msg>fix memory leak<commit_after>// Copyright (C) 2015, Baidu Inc. // Author: Sun Junyi (sunjunyi01@baidu.com) #include "partitioner.h" #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <iostream> #include <string> int main(int argc, char* argv[]) { if (argc < 2) { fprintf(stderr, "partitioner [reducer total] \n"); return 1; } std::string record; uint32_t reducer_total = atoi( argv[1] ); Partitioner* partition = new HashPartitioner(); partition->SetReducerTotal(reducer_total); while (getline(std::cin, record)) { size_t key_span = strcspn(record.c_str(), "\t "); //tab or whitespace std::string key(record.c_str(), key_span); uint32_t reducer_slot = partition->GetReducerSlot(key.c_str()); std::cout << reducer_slot << "\1\1\1" << record << std::endl; } delete partition; return 0; } <|endoftext|>
<commit_before>#include "Statistics.hpp" auto to_json(nlohmann::json& json, const GameStatistics& stats) -> void { for (hlt::PlayerId player_id = 0; player_id < stats.player_statistics.size(); player_id++) { auto& player_stats = stats.player_statistics[player_id]; json[std::to_string(static_cast<int>(player_id))] = nlohmann::json{ { "rank", player_stats.rank }, { "last_frame_alive", player_stats.last_frame_alive }, { "total_ship_count", player_stats.total_ship_count }, { "damage_dealt", player_stats.damage_dealt }, { "init_response_time", player_stats.init_response_time }, { "average_frame_response_time", player_stats.average_frame_response_time }, }; } } <commit_msg>Add max_frame_response_time<commit_after>#include "Statistics.hpp" auto to_json(nlohmann::json& json, const GameStatistics& stats) -> void { for (hlt::PlayerId player_id = 0; player_id < stats.player_statistics.size(); player_id++) { auto& player_stats = stats.player_statistics[player_id]; json[std::to_string(static_cast<int>(player_id))] = nlohmann::json{ { "rank", player_stats.rank }, { "last_frame_alive", player_stats.last_frame_alive }, { "total_ship_count", player_stats.total_ship_count }, { "damage_dealt", player_stats.damage_dealt }, { "init_response_time", player_stats.init_response_time }, { "average_frame_response_time", player_stats.average_frame_response_time }, { "max_frame_response_time", player_stats.max_frame_response_time }, }; } } <|endoftext|>
<commit_before>#include "UnrealCVPrivate.h" #include "ViewMode.h" #include "BufferVisualizationData.h" /** FViewMode is a helper class to tweak render options. Important options are Tonemapper EyeAdaptation TemporalAA MotionBlur Lighting Bloom ColorGrading GammaCorrection DepthOfField LensFlare Vignette */ void BasicSetting(FEngineShowFlags& ShowFlags) { ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_All0); ShowFlags.SetRendering(true); ShowFlags.SetStaticMeshes(true); ShowFlags.SetLandscape(true); ShowFlags.SetInstancedFoliage(true); ShowFlags.SetInstancedGrass(true); ShowFlags.SetInstancedStaticMeshes(true); } void FViewMode::Lit(FEngineShowFlags& ShowFlags) { BasicSetting(ShowFlags); ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_Game); ApplyViewMode(VMI_Lit, true, ShowFlags); ShowFlags.SetMaterials(true); ShowFlags.SetLighting(true); ShowFlags.SetPostProcessing(true); // ToneMapper needs to be enabled, otherwise the screen will be very dark ShowFlags.SetTonemapper(true); // TemporalAA needs to be disabled, otherwise the previous frame might contaminate current frame. // Check: https://answers.unrealengine.com/questions/436060/low-quality-screenshot-after-setting-the-actor-pos.html for detail // ShowFlags.SetTemporalAA(true); ShowFlags.SetTemporalAA(false); ShowFlags.SetAntiAliasing(true); ShowFlags.SetEyeAdaptation(false); // Eye adaption is a slow temporal procedure, not useful for image capture } void FViewMode::BufferVisualization(FEngineShowFlags& ShowFlags) { ApplyViewMode(EViewModeIndex::VMI_VisualizeBuffer, true, ShowFlags); // This did more than just SetVisualizeBuffer(true); // EngineShowFlagOverride() // From ShowFlags.cpp ShowFlags.SetPostProcessing(true); ShowFlags.SetMaterials(true); ShowFlags.SetVisualizeBuffer(true); // ToneMapper needs to be disabled ShowFlags.SetTonemapper(false); // TemporalAA needs to be disabled, or it will contaminate the following frame ShowFlags.SetTemporalAA(false); } /** ViewMode showing post process */ void FViewMode::PostProcess(FEngineShowFlags& ShowFlags) { BasicSetting(ShowFlags); // These are minimal setting ShowFlags.SetPostProcessing(true); ShowFlags.SetPostProcessMaterial(true); // ShowFlags.SetVertexColors(true); // This option will change object material to vertex color material, which don't produce surface normal GVertexColorViewMode = EVertexColorViewMode::Color; } void FViewMode::Wireframe(FEngineShowFlags& ShowFlags) { // ApplyViewMode(VMI_Wireframe, true, ShowFlags); ShowFlags.SetPostProcessing(true); ShowFlags.SetWireframe(true); } void FViewMode::VertexColor(FEngineShowFlags& ShowFlags) { ApplyViewMode(VMI_Lit, true, ShowFlags); // From MeshPaintEdMode.cpp:2942 ShowFlags.SetMaterials(false); ShowFlags.SetLighting(false); ShowFlags.SetBSPTriangles(true); ShowFlags.SetVertexColors(true); ShowFlags.SetPostProcessing(false); ShowFlags.SetHMDDistortion(false); ShowFlags.SetTonemapper(false); // This won't take effect here GVertexColorViewMode = EVertexColorViewMode::Color; } void FViewMode::Unlit(FEngineShowFlags& ShowFlags) { ApplyViewMode(VMI_Unlit, true, ShowFlags); ShowFlags.SetMaterials(false); ShowFlags.SetVertexColors(false); ShowFlags.SetLightFunctions(false); ShowFlags.SetLighting(false); ShowFlags.SetAtmosphericFog(false); } <commit_msg>SkeletalMesh is not displayed in depth mode.<commit_after>#include "UnrealCVPrivate.h" #include "ViewMode.h" #include "BufferVisualizationData.h" /** FViewMode is a helper class to tweak render options. Important options are Tonemapper EyeAdaptation TemporalAA MotionBlur Lighting Bloom ColorGrading GammaCorrection DepthOfField LensFlare Vignette */ void BasicSetting(FEngineShowFlags& ShowFlags) { ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_All0); ShowFlags.SetRendering(true); ShowFlags.SetStaticMeshes(true); ShowFlags.SetLandscape(true); ShowFlags.SetInstancedFoliage(true); ShowFlags.SetInstancedGrass(true); ShowFlags.SetInstancedStaticMeshes(true); ShowFlags.SetSkeletalMeshes(true); } void FViewMode::Lit(FEngineShowFlags& ShowFlags) { BasicSetting(ShowFlags); ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_Game); ApplyViewMode(VMI_Lit, true, ShowFlags); ShowFlags.SetMaterials(true); ShowFlags.SetLighting(true); ShowFlags.SetPostProcessing(true); // ToneMapper needs to be enabled, otherwise the screen will be very dark ShowFlags.SetTonemapper(true); // TemporalAA needs to be disabled, otherwise the previous frame might contaminate current frame. // Check: https://answers.unrealengine.com/questions/436060/low-quality-screenshot-after-setting-the-actor-pos.html for detail // ShowFlags.SetTemporalAA(true); ShowFlags.SetTemporalAA(false); ShowFlags.SetAntiAliasing(true); ShowFlags.SetEyeAdaptation(false); // Eye adaption is a slow temporal procedure, not useful for image capture } void FViewMode::BufferVisualization(FEngineShowFlags& ShowFlags) { ApplyViewMode(EViewModeIndex::VMI_VisualizeBuffer, true, ShowFlags); // This did more than just SetVisualizeBuffer(true); // EngineShowFlagOverride() // From ShowFlags.cpp ShowFlags.SetPostProcessing(true); ShowFlags.SetMaterials(true); ShowFlags.SetVisualizeBuffer(true); // ToneMapper needs to be disabled ShowFlags.SetTonemapper(false); // TemporalAA needs to be disabled, or it will contaminate the following frame ShowFlags.SetTemporalAA(false); } /** ViewMode showing post process */ void FViewMode::PostProcess(FEngineShowFlags& ShowFlags) { BasicSetting(ShowFlags); // These are minimal setting ShowFlags.SetPostProcessing(true); ShowFlags.SetPostProcessMaterial(true); // ShowFlags.SetVertexColors(true); // This option will change object material to vertex color material, which don't produce surface normal GVertexColorViewMode = EVertexColorViewMode::Color; } void FViewMode::Wireframe(FEngineShowFlags& ShowFlags) { // ApplyViewMode(VMI_Wireframe, true, ShowFlags); ShowFlags.SetPostProcessing(true); ShowFlags.SetWireframe(true); } void FViewMode::VertexColor(FEngineShowFlags& ShowFlags) { ApplyViewMode(VMI_Lit, true, ShowFlags); // From MeshPaintEdMode.cpp:2942 ShowFlags.SetMaterials(false); ShowFlags.SetLighting(false); ShowFlags.SetBSPTriangles(true); ShowFlags.SetVertexColors(true); ShowFlags.SetPostProcessing(false); ShowFlags.SetHMDDistortion(false); ShowFlags.SetTonemapper(false); // This won't take effect here GVertexColorViewMode = EVertexColorViewMode::Color; } void FViewMode::Unlit(FEngineShowFlags& ShowFlags) { ApplyViewMode(VMI_Unlit, true, ShowFlags); ShowFlags.SetMaterials(false); ShowFlags.SetVertexColors(false); ShowFlags.SetLightFunctions(false); ShowFlags.SetLighting(false); ShowFlags.SetAtmosphericFog(false); } <|endoftext|>
<commit_before>//===--- CFGPrinter.cpp - Pretty-printing of CFGs ----------------*- C++ -*-==// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines the logic to pretty-print CFGs, Instructions, etc. // //===----------------------------------------------------------------------===// #include "swift/CFG/CFGVisitor.h" #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/OwningPtr.h" using namespace swift; //===----------------------------------------------------------------------===// // Pretty-printing //===----------------------------------------------------------------------===// namespace { /// CFGPrinter class - This is the internal implementation details of printing /// for CFG structures. class CFGPrinter : public CFGVisitor<CFGPrinter> { raw_ostream &OS; typedef llvm::DenseMap<const BasicBlock *, unsigned> BlocksToIdsTy; llvm::OwningPtr<BlocksToIdsTy> BlocksToIDs; raw_ostream &printID(const Instruction *I, bool includeBBPrefix = true); raw_ostream &printID(const BasicBlock *B); raw_ostream &printID(const BasicBlockArg *BBarg); raw_ostream &printID(const CFGValue &V); public: CFGPrinter(raw_ostream &OS) : OS(OS) { } void print(const BasicBlock *BB) { printID(BB) << ":\n"; for (const Instruction &I : *BB) print(&I); OS << " Preds:"; for (const BasicBlock *B : BB->getPreds()) { OS << ' '; printID(B); } OS << '\n'; OS << " Succs:"; for (const BasicBlock *B : BB->getSuccs()) { OS << ' '; printID(B); } OS << '\n'; } //===--------------------------------------------------------------------===// // Instruction Printing Logic void print(const Instruction *I) { OS << " "; printID(I, false) << " = "; visit(const_cast<Instruction*>(I)); OS << '\n'; } void visitInstruction(Instruction *I) { assert(0 && "CFGPrinter not implemented for this instruction!"); } void visitCallInst(CallInst *CI) { OS << "Call(fn="; printID(CI->function); auto args = CI->arguments(); if (!args.empty()) { bool first = true; OS << ",args=("; for (auto arg : args) { if (first) first = false; else OS << ' '; printID(arg); } OS << ')'; } OS << ')'; } void visitDeclRefInst(DeclRefInst *DRI) { OS << "DeclRef(decl=" << DRI->expr->getDecl()->getName() << ')'; } void visitIntegerLiteralInst(IntegerLiteralInst *ILI) { const auto &lit = ILI->literal->getValue(); OS << "Integer(val=" << lit << ",width=" << lit.getBitWidth() << ')'; } void visitLoadInst(LoadInst *LI) { OS << "Load(lvalue="; printID(LI->lvalue); OS << ')'; } void visitThisApplyInst(ThisApplyInst *TAI) { OS << "ThisApply(fn="; printID(TAI->function); OS << ",arg="; printID(TAI->argument); OS << ')'; } void visitTupleInst(TupleInst *TI) { OS << "Tuple("; bool isFirst = true; for (const auto &Elem : TI->elements()) { if (isFirst) isFirst = false; else OS << ','; printID(Elem); } OS << ')'; } void visitTypeOfInst(TypeOfInst *TOI) { OS << "TypeOf(type=" << TOI->Expr->getType().getString() << ')'; } void visitReturnInst(ReturnInst *RI) { OS << "Return"; if (RI->returnValue) { OS << '('; printID(RI->returnValue); OS << ')'; } } void visitUncondBranchInst(UncondBranchInst *UBI) { OS << "br "; printID(UBI->targetBlock()); const UncondBranchInst::ArgsTy Args = UBI->blockArgs(); if (!Args.empty()) { OS << '('; for (auto Arg : Args) { OS << "%" << Arg; } OS << ')'; } } void visitCondBranchInst(CondBranchInst *CBI) { OS << "cond_br(cond="; OS << "?"; // printID(BI.condition); OS << ",branches=("; printID(CBI->branches()[0]); OS << ','; printID(CBI->branches()[1]); OS << "))"; } }; } // end anonymous namespace raw_ostream &CFGPrinter::printID(const BasicBlock *Block) { // Lazily initialize the Blocks-to-IDs mapping. if (!BlocksToIDs) { BlocksToIDs.reset(new BlocksToIdsTy()); BlocksToIdsTy &Map = *BlocksToIDs; unsigned idx = 0; for (const BasicBlock &B : *Block->getParent()) Map[&B] = idx++; } BlocksToIdsTy &Map = *BlocksToIDs; auto I = Map.find(Block); assert(I != Map.end()); OS << "b" << I->second; return OS; } raw_ostream &CFGPrinter::printID(const Instruction *Inst, bool includeBBPrefix) { const BasicBlock *Block = Inst->getParent(); unsigned count = 1; for (const Instruction &I : *Block) { if (&I == Inst) break; ++count; } OS << '%'; if (includeBBPrefix) { printID(Block); OS << '.'; } OS << "i" << count; return OS; } raw_ostream &CFGPrinter::printID(const BasicBlockArg *BBArg) { OS << "BBArg (unsupported)\n"; return OS; } raw_ostream &CFGPrinter::printID(const CFGValue &Val) { if (const Instruction *Inst = Val.dyn_cast<Instruction*>()) printID(Inst); else printID(Val.get<BasicBlockArg*>()); return OS; } //===----------------------------------------------------------------------===// // Printing for Instruction, BasicBlock, and CFG //===----------------------------------------------------------------------===// void Instruction::dump() const { print(llvm::errs()); } void Instruction::print(raw_ostream &OS) const { CFGPrinter(OS).print(this); } void BasicBlock::dump() const { print(llvm::errs()); } /// Pretty-print the BasicBlock with the designated stream. void BasicBlock::print(raw_ostream &OS) const { CFGPrinter(OS).print(this); } /// Pretty-print the basic block. void CFG::dump() const { print(llvm::errs()); } /// Pretty-print the basi block with the designated stream. void CFG::print(llvm::raw_ostream &OS) const { CFGPrinter Printer(OS); for (const BasicBlock &B : *this) Printer.print(&B); } <commit_msg>change basic block id printing to allow more natural use of ostreams instead of printID.<commit_after>//===--- CFGPrinter.cpp - Pretty-printing of CFGs ----------------*- C++ -*-==// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines the logic to pretty-print CFGs, Instructions, etc. // //===----------------------------------------------------------------------===// #include "swift/CFG/CFGVisitor.h" #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/OwningPtr.h" using namespace swift; struct ID { enum { BasicBlock, LocalVal } Kind; unsigned Number; }; raw_ostream &operator<<(raw_ostream &OS, ID i) { switch (i.Kind) { case ID::BasicBlock: OS << "b"; break; case ID::LocalVal: OS << '%'; break; } return OS << i.Number; } namespace { /// CFGPrinter class - This is the internal implementation details of printing /// for CFG structures. class CFGPrinter : public CFGVisitor<CFGPrinter> { raw_ostream &OS; llvm::DenseMap<const BasicBlock *, unsigned> BlocksToIDsMap; ID getID(const BasicBlock *B); raw_ostream &printID(const Instruction *I, bool includeBBPrefix = true); raw_ostream &printID(const BasicBlockArg *BBarg); raw_ostream &printID(const CFGValue &V); public: CFGPrinter(raw_ostream &OS) : OS(OS) { } void print(const BasicBlock *BB) { OS << getID(BB) << ":\n"; for (const Instruction &I : *BB) print(&I); OS << " Preds:"; for (const BasicBlock *B : BB->getPreds()) OS << ' ' << getID(B); OS << "\n Succs:"; for (const BasicBlock *B : BB->getSuccs()) OS << ' ' << getID(B); OS << '\n'; } //===--------------------------------------------------------------------===// // Instruction Printing Logic void print(const Instruction *I) { OS << " "; printID(I, false) << " = "; visit(const_cast<Instruction*>(I)); OS << '\n'; } void visitInstruction(Instruction *I) { assert(0 && "CFGPrinter not implemented for this instruction!"); } void visitCallInst(CallInst *CI) { OS << "Call(fn="; printID(CI->function); auto args = CI->arguments(); if (!args.empty()) { bool first = true; OS << ",args=("; for (auto arg : args) { if (first) first = false; else OS << ' '; printID(arg); } OS << ')'; } OS << ')'; } void visitDeclRefInst(DeclRefInst *DRI) { OS << "DeclRef(decl=" << DRI->expr->getDecl()->getName() << ')'; } void visitIntegerLiteralInst(IntegerLiteralInst *ILI) { const auto &lit = ILI->literal->getValue(); OS << "Integer(val=" << lit << ",width=" << lit.getBitWidth() << ')'; } void visitLoadInst(LoadInst *LI) { OS << "Load(lvalue="; printID(LI->lvalue); OS << ')'; } void visitThisApplyInst(ThisApplyInst *TAI) { OS << "ThisApply(fn="; printID(TAI->function); OS << ",arg="; printID(TAI->argument); OS << ')'; } void visitTupleInst(TupleInst *TI) { OS << "Tuple("; bool isFirst = true; for (const auto &Elem : TI->elements()) { if (isFirst) isFirst = false; else OS << ','; printID(Elem); } OS << ')'; } void visitTypeOfInst(TypeOfInst *TOI) { OS << "TypeOf(type=" << TOI->Expr->getType().getString() << ')'; } void visitReturnInst(ReturnInst *RI) { OS << "Return"; if (RI->returnValue) { OS << '('; printID(RI->returnValue); OS << ')'; } } void visitUncondBranchInst(UncondBranchInst *UBI) { OS << "br " << getID(UBI->targetBlock()); const UncondBranchInst::ArgsTy Args = UBI->blockArgs(); if (!Args.empty()) { OS << '('; for (auto Arg : Args) { OS << "%" << Arg; } OS << ')'; } } void visitCondBranchInst(CondBranchInst *CBI) { OS << "cond_br(cond="; OS << "?"; // printID(BI.condition); OS << ",branches=(" << getID(CBI->branches()[0]); OS << ',' << getID(CBI->branches()[1]); OS << "))"; } }; } // end anonymous namespace ID CFGPrinter::getID(const BasicBlock *Block) { // Lazily initialize the Blocks-to-IDs mapping. if (BlocksToIDsMap.empty()) { unsigned idx = 0; for (const BasicBlock &B : *Block->getParent()) BlocksToIDsMap[&B] = idx++; } ID R = { ID::BasicBlock, BlocksToIDsMap[Block] }; return R; } raw_ostream &CFGPrinter::printID(const Instruction *Inst, bool includeBBPrefix) { const BasicBlock *Block = Inst->getParent(); unsigned count = 1; for (const Instruction &I : *Block) { if (&I == Inst) break; ++count; } OS << '%'; if (includeBBPrefix) OS << getID(Block) << '.'; OS << "i" << count; return OS; } raw_ostream &CFGPrinter::printID(const BasicBlockArg *BBArg) { OS << "BBArg (unsupported)\n"; return OS; } raw_ostream &CFGPrinter::printID(const CFGValue &Val) { if (const Instruction *Inst = Val.dyn_cast<Instruction*>()) printID(Inst); else printID(Val.get<BasicBlockArg*>()); return OS; } //===----------------------------------------------------------------------===// // Printing for Instruction, BasicBlock, and CFG //===----------------------------------------------------------------------===// void Instruction::dump() const { print(llvm::errs()); } void Instruction::print(raw_ostream &OS) const { CFGPrinter(OS).print(this); } void BasicBlock::dump() const { print(llvm::errs()); } /// Pretty-print the BasicBlock with the designated stream. void BasicBlock::print(raw_ostream &OS) const { CFGPrinter(OS).print(this); } /// Pretty-print the basic block. void CFG::dump() const { print(llvm::errs()); } /// Pretty-print the basi block with the designated stream. void CFG::print(llvm::raw_ostream &OS) const { CFGPrinter Printer(OS); for (const BasicBlock &B : *this) Printer.print(&B); } <|endoftext|>
<commit_before>#include <sstream> #include "Tools/Exception/exception.hpp" #include "Module/Encoder/NO/Encoder_NO.hpp" #include "Module/Decoder/NO/Decoder_NO.hpp" #include "Codec_uncoded.hpp" using namespace aff3ct::module; using namespace aff3ct::tools; template <typename B, typename Q> Codec_uncoded<B,Q> ::Codec_uncoded(const parameters& params) : Codec_SISO<B,Q>(params) { if (params.code.K != params.code.N_code) { std::stringstream message; message << "'K' has to be equal to 'N_code' ('K' = " << params.code.K << ", 'N_code' = " << params.code.N_code << ")."; throw invalid_argument(__FILE__, __LINE__, __func__, message.str()); } } template <typename B, typename Q> Codec_uncoded<B,Q> ::~Codec_uncoded() { } template <typename B, typename Q> Encoder<B>* Codec_uncoded<B,Q> ::build_encoder(const int tid, const Interleaver<int>* itl) { return new Encoder_NO<B>(this->params.code.K, this->params.simulation.inter_frame_level); } template <typename B, typename Q> SISO<Q>* Codec_uncoded<B,Q> ::build_siso(const int tid, const Interleaver<int>* itl, CRC<B>* crc) { return new Decoder_NO<B,Q>(this->params.code.K, this->params.simulation.inter_frame_level); } template <typename B, typename Q> Decoder<B,Q>* Codec_uncoded<B,Q> ::build_decoder(const int tid, const Interleaver<int>* itl, CRC<B>* crc) { return new Decoder_NO<B,Q>(this->params.code.K, this->params.simulation.inter_frame_level); } template <typename B, typename Q> void Codec_uncoded<B,Q> ::extract_sys_par(const mipp::vector<Q> &Y_N, mipp::vector<Q> &sys, mipp::vector<Q> &par) { const auto K = this->params.code.K; if ((int)Y_N.size() != K * this->params.simulation.inter_frame_level) { std::stringstream message; message << "'Y_N.size()' has to be equal to 'K' * 'inter_frame_level' ('Y_N.size()' = " << Y_N.size() << ", 'K' = " << K << ", 'inter_frame_level' = " << this->params.simulation.inter_frame_level << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if ((int)sys.size() != K * this->params.simulation.inter_frame_level) { std::stringstream message; message << "'sys.size()' has to be equal to 'K' * 'inter_frame_level' ('sys.size()' = " << sys.size() << ", 'K' = " << K << ", 'inter_frame_level' = " << this->params.simulation.inter_frame_level << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if ((int)par.size() != 0) { std::stringstream message; message << "'par.size()' has to be equal to 0 ('par.size()' = " << 'par.size()' << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } std::copy(Y_N.begin(), Y_N.end(), sys.begin()); } // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template class aff3ct::tools::Codec_uncoded<B_8,Q_8>; template class aff3ct::tools::Codec_uncoded<B_16,Q_16>; template class aff3ct::tools::Codec_uncoded<B_32,Q_32>; template class aff3ct::tools::Codec_uncoded<B_64,Q_64>; #else template class aff3ct::tools::Codec_uncoded<B,Q>; #endif // ==================================================================================== explicit template instantiation <commit_msg>Fix exception.<commit_after>#include <sstream> #include "Tools/Exception/exception.hpp" #include "Module/Encoder/NO/Encoder_NO.hpp" #include "Module/Decoder/NO/Decoder_NO.hpp" #include "Codec_uncoded.hpp" using namespace aff3ct::module; using namespace aff3ct::tools; template <typename B, typename Q> Codec_uncoded<B,Q> ::Codec_uncoded(const parameters& params) : Codec_SISO<B,Q>(params) { if (params.code.K != params.code.N_code) { std::stringstream message; message << "'K' has to be equal to 'N_code' ('K' = " << params.code.K << ", 'N_code' = " << params.code.N_code << ")."; throw invalid_argument(__FILE__, __LINE__, __func__, message.str()); } } template <typename B, typename Q> Codec_uncoded<B,Q> ::~Codec_uncoded() { } template <typename B, typename Q> Encoder<B>* Codec_uncoded<B,Q> ::build_encoder(const int tid, const Interleaver<int>* itl) { return new Encoder_NO<B>(this->params.code.K, this->params.simulation.inter_frame_level); } template <typename B, typename Q> SISO<Q>* Codec_uncoded<B,Q> ::build_siso(const int tid, const Interleaver<int>* itl, CRC<B>* crc) { return new Decoder_NO<B,Q>(this->params.code.K, this->params.simulation.inter_frame_level); } template <typename B, typename Q> Decoder<B,Q>* Codec_uncoded<B,Q> ::build_decoder(const int tid, const Interleaver<int>* itl, CRC<B>* crc) { return new Decoder_NO<B,Q>(this->params.code.K, this->params.simulation.inter_frame_level); } template <typename B, typename Q> void Codec_uncoded<B,Q> ::extract_sys_par(const mipp::vector<Q> &Y_N, mipp::vector<Q> &sys, mipp::vector<Q> &par) { const auto K = this->params.code.K; if ((int)Y_N.size() != K * this->params.simulation.inter_frame_level) { std::stringstream message; message << "'Y_N.size()' has to be equal to 'K' * 'inter_frame_level' ('Y_N.size()' = " << Y_N.size() << ", 'K' = " << K << ", 'inter_frame_level' = " << this->params.simulation.inter_frame_level << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if ((int)sys.size() != K * this->params.simulation.inter_frame_level) { std::stringstream message; message << "'sys.size()' has to be equal to 'K' * 'inter_frame_level' ('sys.size()' = " << sys.size() << ", 'K' = " << K << ", 'inter_frame_level' = " << this->params.simulation.inter_frame_level << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if ((int)par.size() != 0) { std::stringstream message; message << "'par.size()' has to be equal to 0 ('par.size()' = " << par.size() << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } std::copy(Y_N.begin(), Y_N.end(), sys.begin()); } // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template class aff3ct::tools::Codec_uncoded<B_8,Q_8>; template class aff3ct::tools::Codec_uncoded<B_16,Q_16>; template class aff3ct::tools::Codec_uncoded<B_32,Q_32>; template class aff3ct::tools::Codec_uncoded<B_64,Q_64>; #else template class aff3ct::tools::Codec_uncoded<B,Q>; #endif // ==================================================================================== explicit template instantiation <|endoftext|>
<commit_before>#include "Iop_FileIoHandler2300.h" #include "Iop_Ioman.h" #include "../Log.h" #define LOG_NAME ("iop_fileio") using namespace Iop; CFileIoHandler2300::CFileIoHandler2300(CIoman* ioman, CSifMan& sifMan) : CHandler(ioman) , m_sifMan(sifMan) { memset(m_resultPtr, 0, sizeof(m_resultPtr)); } void CFileIoHandler2300::Invoke(uint32 method, uint32* args, uint32 argsSize, uint32* ret, uint32 retSize, uint8* ram) { switch(method) { case 0: { assert(retSize == 4); auto command = reinterpret_cast<OPENCOMMAND*>(args); *ret = m_ioman->Open(command->flags, command->fileName); //Send response if(m_resultPtr[0] != 0) { OPENREPLY reply; reply.header.commandId = 0; CopyHeader(reply.header, command->header); reply.result = *ret; reply.unknown2 = 0; reply.unknown3 = 0; reply.unknown4 = 0; memcpy(ram + m_resultPtr[0], &reply, sizeof(OPENREPLY)); } { size_t packetSize = sizeof(SIFCMDHEADER); uint8* callbackPacket = reinterpret_cast<uint8*>(alloca(packetSize)); auto header = reinterpret_cast<SIFCMDHEADER*>(callbackPacket); header->commandId = 0x80000011; header->size = packetSize; header->dest = 0; header->optional = 0; m_sifMan.SendPacket(callbackPacket, packetSize); } } break; case 1: { assert(retSize == 4); auto command = reinterpret_cast<CLOSECOMMAND*>(args); *ret = m_ioman->Close(command->fd); //Send response { CLOSEREPLY reply; reply.header.commandId = 1; CopyHeader(reply.header, command->header); reply.result = *ret; reply.unknown2 = 0; reply.unknown3 = 0; reply.unknown4 = 0; memcpy(ram + m_resultPtr[0], &reply, sizeof(reply)); } { size_t packetSize = sizeof(SIFCMDHEADER); uint8* callbackPacket = reinterpret_cast<uint8*>(alloca(packetSize)); auto header = reinterpret_cast<SIFCMDHEADER*>(callbackPacket); header->commandId = 0x80000011; header->size = packetSize; header->dest = 0; header->optional = 0; m_sifMan.SendPacket(callbackPacket, packetSize); } } break; case 2: { assert(retSize == 4); auto command = reinterpret_cast<READCOMMAND*>(args); *ret = m_ioman->Read(command->fd, command->size, reinterpret_cast<void*>(ram + command->buffer)); //Send response { READREPLY reply; reply.header.commandId = 2; CopyHeader(reply.header, command->header); reply.result = *ret; reply.unknown2 = 0; reply.unknown3 = 0; reply.unknown4 = 0; memcpy(ram + m_resultPtr[0], &reply, sizeof(reply)); } { size_t packetSize = sizeof(SIFCMDHEADER); uint8* callbackPacket = reinterpret_cast<uint8*>(alloca(packetSize)); auto header = reinterpret_cast<SIFCMDHEADER*>(callbackPacket); header->commandId = 0x80000011; header->size = packetSize; header->dest = 0; header->optional = 0; m_sifMan.SendPacket(callbackPacket, packetSize); } } break; case 4: { assert(retSize == 4); auto command = reinterpret_cast<SEEKCOMMAND*>(args); *ret = m_ioman->Seek(command->fd, command->offset, command->whence); //Send response { SEEKREPLY reply; reply.header.commandId = 4; CopyHeader(reply.header, command->header); reply.result = *ret; reply.unknown2 = 0; reply.unknown3 = 0; reply.unknown4 = 0; memcpy(ram + m_resultPtr[0], &reply, sizeof(reply)); } { size_t packetSize = sizeof(SIFCMDHEADER); uint8* callbackPacket = reinterpret_cast<uint8*>(alloca(packetSize)); auto header = reinterpret_cast<SIFCMDHEADER*>(callbackPacket); header->commandId = 0x80000011; header->size = packetSize; header->dest = 0; header->optional = 0; m_sifMan.SendPacket(callbackPacket, packetSize); } } break; case 23: { //No idea what that does... assert(retSize == 4); auto command = reinterpret_cast<ACTIVATECOMMAND*>(args); *ret = 0; { //Send response ACTIVATEREPLY reply; reply.header.commandId = 23; CopyHeader(reply.header, command->header); reply.result = *ret; reply.unknown2 = 0; reply.unknown3 = 0; reply.unknown4 = 0; memcpy(ram + m_resultPtr[0], &reply, sizeof(reply)); } { size_t packetSize = sizeof(SIFCMDHEADER); uint8* callbackPacket = reinterpret_cast<uint8*>(alloca(packetSize)); auto header = reinterpret_cast<SIFCMDHEADER*>(callbackPacket); header->commandId = 0x80000011; header->size = packetSize; header->dest = 0; header->optional = 0; m_sifMan.SendPacket(callbackPacket, packetSize); } } break; case 255: //Not really sure about that... if(retSize == 8) { memcpy(ret, "....rawr", 8); } else if(retSize == 4) { memcpy(ret, "....", 4); } else { assert(0); } m_resultPtr[0] = args[0]; m_resultPtr[1] = args[1]; break; default: CLog::GetInstance().Print(LOG_NAME, "Unknown function (%d) called.\r\n", method); break; } } void CFileIoHandler2300::CopyHeader(REPLYHEADER& reply, const COMMANDHEADER& command) { reply.semaphoreId = command.semaphoreId; reply.resultPtr = command.resultPtr; reply.resultSize = command.resultSize; } <commit_msg>Return proper value for FileIo Lseek.<commit_after>#include "Iop_FileIoHandler2300.h" #include "Iop_Ioman.h" #include "../Log.h" #define LOG_NAME ("iop_fileio") using namespace Iop; CFileIoHandler2300::CFileIoHandler2300(CIoman* ioman, CSifMan& sifMan) : CHandler(ioman) , m_sifMan(sifMan) { memset(m_resultPtr, 0, sizeof(m_resultPtr)); } void CFileIoHandler2300::Invoke(uint32 method, uint32* args, uint32 argsSize, uint32* ret, uint32 retSize, uint8* ram) { switch(method) { case 0: { assert(retSize == 4); auto command = reinterpret_cast<OPENCOMMAND*>(args); *ret = m_ioman->Open(command->flags, command->fileName); //Send response if(m_resultPtr[0] != 0) { OPENREPLY reply; reply.header.commandId = 0; CopyHeader(reply.header, command->header); reply.result = *ret; reply.unknown2 = 0; reply.unknown3 = 0; reply.unknown4 = 0; memcpy(ram + m_resultPtr[0], &reply, sizeof(OPENREPLY)); } { size_t packetSize = sizeof(SIFCMDHEADER); uint8* callbackPacket = reinterpret_cast<uint8*>(alloca(packetSize)); auto header = reinterpret_cast<SIFCMDHEADER*>(callbackPacket); header->commandId = 0x80000011; header->size = packetSize; header->dest = 0; header->optional = 0; m_sifMan.SendPacket(callbackPacket, packetSize); } } break; case 1: { assert(retSize == 4); auto command = reinterpret_cast<CLOSECOMMAND*>(args); *ret = m_ioman->Close(command->fd); //Send response { CLOSEREPLY reply; reply.header.commandId = 1; CopyHeader(reply.header, command->header); reply.result = *ret; reply.unknown2 = 0; reply.unknown3 = 0; reply.unknown4 = 0; memcpy(ram + m_resultPtr[0], &reply, sizeof(reply)); } { size_t packetSize = sizeof(SIFCMDHEADER); uint8* callbackPacket = reinterpret_cast<uint8*>(alloca(packetSize)); auto header = reinterpret_cast<SIFCMDHEADER*>(callbackPacket); header->commandId = 0x80000011; header->size = packetSize; header->dest = 0; header->optional = 0; m_sifMan.SendPacket(callbackPacket, packetSize); } } break; case 2: { assert(retSize == 4); auto command = reinterpret_cast<READCOMMAND*>(args); *ret = m_ioman->Read(command->fd, command->size, reinterpret_cast<void*>(ram + command->buffer)); //Send response { READREPLY reply; reply.header.commandId = 2; CopyHeader(reply.header, command->header); reply.result = *ret; reply.unknown2 = 0; reply.unknown3 = 0; reply.unknown4 = 0; memcpy(ram + m_resultPtr[0], &reply, sizeof(reply)); } { size_t packetSize = sizeof(SIFCMDHEADER); uint8* callbackPacket = reinterpret_cast<uint8*>(alloca(packetSize)); auto header = reinterpret_cast<SIFCMDHEADER*>(callbackPacket); header->commandId = 0x80000011; header->size = packetSize; header->dest = 0; header->optional = 0; m_sifMan.SendPacket(callbackPacket, packetSize); } } break; case 4: { assert(retSize == 4); auto command = reinterpret_cast<SEEKCOMMAND*>(args); auto result = m_ioman->Seek(command->fd, command->offset, command->whence); (*ret) = (static_cast<int32>(result) >= 0) ? 1 : 0; //Send response { SEEKREPLY reply; reply.header.commandId = 4; CopyHeader(reply.header, command->header); reply.result = result; reply.unknown2 = 0; reply.unknown3 = 0; reply.unknown4 = 0; memcpy(ram + m_resultPtr[0], &reply, sizeof(reply)); } { size_t packetSize = sizeof(SIFCMDHEADER); uint8* callbackPacket = reinterpret_cast<uint8*>(alloca(packetSize)); auto header = reinterpret_cast<SIFCMDHEADER*>(callbackPacket); header->commandId = 0x80000011; header->size = packetSize; header->dest = 0; header->optional = 0; m_sifMan.SendPacket(callbackPacket, packetSize); } } break; case 23: { //No idea what that does... assert(retSize == 4); auto command = reinterpret_cast<ACTIVATECOMMAND*>(args); *ret = 0; { //Send response ACTIVATEREPLY reply; reply.header.commandId = 23; CopyHeader(reply.header, command->header); reply.result = *ret; reply.unknown2 = 0; reply.unknown3 = 0; reply.unknown4 = 0; memcpy(ram + m_resultPtr[0], &reply, sizeof(reply)); } { size_t packetSize = sizeof(SIFCMDHEADER); uint8* callbackPacket = reinterpret_cast<uint8*>(alloca(packetSize)); auto header = reinterpret_cast<SIFCMDHEADER*>(callbackPacket); header->commandId = 0x80000011; header->size = packetSize; header->dest = 0; header->optional = 0; m_sifMan.SendPacket(callbackPacket, packetSize); } } break; case 255: //Not really sure about that... if(retSize == 8) { memcpy(ret, "....rawr", 8); } else if(retSize == 4) { memcpy(ret, "....", 4); } else { assert(0); } m_resultPtr[0] = args[0]; m_resultPtr[1] = args[1]; break; default: CLog::GetInstance().Print(LOG_NAME, "Unknown function (%d) called.\r\n", method); break; } } void CFileIoHandler2300::CopyHeader(REPLYHEADER& reply, const COMMANDHEADER& command) { reply.semaphoreId = command.semaphoreId; reply.resultPtr = command.resultPtr; reply.resultSize = command.resultSize; } <|endoftext|>
<commit_before>// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #include <Rosetta/Actions/PlayCard.hpp> #include <Rosetta/Actions/Targeting.hpp> #include <Rosetta/Games/Game.hpp> #include <Rosetta/Tasks/Tasks.hpp> namespace RosettaStone::Generic { void PlayCard(Player& player, Entity* source, Character* target, int fieldPos) { // Verify mana is sufficient if (source->GetCost() > player.currentMana) { return; } // Check if we can play this card and the target is valid if (!IsPlayableByCardReq(source) || !IsValidTarget(source, target)) { return; } // Spend mana to play cards if (source->GetCost() > 0) { player.currentMana -= source->GetCost(); } // Erase from player's hand player.GetHand().RemoveCard(*source); // Set card's owner source->SetOwner(player); // Pass to sub-logic switch (source->card.GetCardType()) { case CardType::MINION: { const auto minion = dynamic_cast<Minion*>(source); PlayMinion(player, minion, target, fieldPos); break; } case CardType::SPELL: { const auto spell = dynamic_cast<Spell*>(source); PlaySpell(player, spell, target); break; } case CardType::WEAPON: { const auto weapon = dynamic_cast<Weapon*>(source); PlayWeapon(player, weapon, target); break; } default: throw std::invalid_argument( "Generic::PlayCard() - Invalid card type!"); } } void PlayMinion(Player& player, Minion* minion, Character* target, int fieldPos) { (void)target; // Add minion to battlefield player.GetField().AddMinion(*minion, fieldPos); // Apply card mechanics tags for (const auto tags : minion->card.gameTags) { minion->SetGameTag(tags.first, tags.second); } // Process power tasks for (auto& powerTask : minion->card.power.GetPowerTask()) { if (powerTask == nullptr) { continue; } powerTask->SetSource(minion); powerTask->SetTarget(target); powerTask->Run(player); } player.GetGame()->ProcessDestroyAndUpdateAura(); } void PlaySpell(Player& player, Spell* spell, Character* target) { // Process power tasks for (auto& powerTask : spell->card.power.GetPowerTask()) { powerTask->SetSource(spell); powerTask->SetTarget(target); powerTask->Run(player); } player.GetGame()->ProcessDestroyAndUpdateAura(); } void PlayWeapon(Player& player, Weapon* weapon, Character* target) { (void)target; player.GetHero()->AddWeapon(*weapon); } bool IsPlayableByCardReq(Entity* source) { for (auto& requirement : source->card.playRequirements) { switch (requirement.first) { case PlayReq::REQ_MINIMUM_ENEMY_MINIONS: { auto& opField = source->GetOwner().GetOpponent().GetField(); if (static_cast<int>(opField.GetNumOfMinions()) < requirement.second) { return false; } break; } case PlayReq::REQ_MINION_TARGET: case PlayReq::REQ_ENEMY_TARGET: case PlayReq::REQ_NONSELF_TARGET: break; default: break; } } return true; } } // namespace RosettaStone::Generic <commit_msg>fix: Add code to move spell to graveyard<commit_after>// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #include <Rosetta/Actions/PlayCard.hpp> #include <Rosetta/Actions/Targeting.hpp> #include <Rosetta/Games/Game.hpp> #include <Rosetta/Tasks/Tasks.hpp> namespace RosettaStone::Generic { void PlayCard(Player& player, Entity* source, Character* target, int fieldPos) { // Verify mana is sufficient if (source->GetCost() > player.currentMana) { return; } // Check if we can play this card and the target is valid if (!IsPlayableByCardReq(source) || !IsValidTarget(source, target)) { return; } // Spend mana to play cards if (source->GetCost() > 0) { player.currentMana -= source->GetCost(); } // Erase from player's hand player.GetHand().RemoveCard(*source); // Set card's owner source->SetOwner(player); // Pass to sub-logic switch (source->card.GetCardType()) { case CardType::MINION: { const auto minion = dynamic_cast<Minion*>(source); PlayMinion(player, minion, target, fieldPos); break; } case CardType::SPELL: { const auto spell = dynamic_cast<Spell*>(source); PlaySpell(player, spell, target); break; } case CardType::WEAPON: { const auto weapon = dynamic_cast<Weapon*>(source); PlayWeapon(player, weapon, target); break; } default: throw std::invalid_argument( "Generic::PlayCard() - Invalid card type!"); } } void PlayMinion(Player& player, Minion* minion, Character* target, int fieldPos) { (void)target; // Add minion to battlefield player.GetField().AddMinion(*minion, fieldPos); // Apply card mechanics tags for (const auto tags : minion->card.gameTags) { minion->SetGameTag(tags.first, tags.second); } // Process power tasks for (auto& powerTask : minion->card.power.GetPowerTask()) { if (powerTask == nullptr) { continue; } powerTask->SetSource(minion); powerTask->SetTarget(target); powerTask->Run(player); } player.GetGame()->ProcessDestroyAndUpdateAura(); } void PlaySpell(Player& player, Spell* spell, Character* target) { // Process power tasks for (auto& powerTask : spell->card.power.GetPowerTask()) { powerTask->SetSource(spell); powerTask->SetTarget(target); powerTask->Run(player); } player.GetGraveyard().AddCard(*spell); player.GetGame()->ProcessDestroyAndUpdateAura(); } void PlayWeapon(Player& player, Weapon* weapon, Character* target) { (void)target; player.GetHero()->AddWeapon(*weapon); } bool IsPlayableByCardReq(Entity* source) { for (auto& requirement : source->card.playRequirements) { switch (requirement.first) { case PlayReq::REQ_MINIMUM_ENEMY_MINIONS: { auto& opField = source->GetOwner().GetOpponent().GetField(); if (static_cast<int>(opField.GetNumOfMinions()) < requirement.second) { return false; } break; } case PlayReq::REQ_MINION_TARGET: case PlayReq::REQ_ENEMY_TARGET: case PlayReq::REQ_NONSELF_TARGET: break; default: break; } } return true; } } // namespace RosettaStone::Generic <|endoftext|>
<commit_before>#include "core/tracery.h" #include "core/random.h" #include "catch.hpp" namespace tr = euphoria::core::tracery; TEST_CASE("tracery-all", "[tracery]") { const std::string test_file = "test-file"; auto random = euphoria::core::random{0}; tr::grammar g; g.register_english(); SECTION("empty json") { const auto loaded = g.load_from_string(test_file, R"( { } )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "test"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "test"); } SECTION("flatten single rule") { const auto loaded = g.load_from_string(test_file, R"( { "dog": "doggo" } )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#dog#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "doggo"); } SECTION("escape") { // need double backslashes to escape \ and // to actually enter a \ into the json string const auto loaded = g.load_from_string(test_file, R"( { "esc": "\\#" } )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#esc#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "#"); } SECTION("don't die on non ending rules") { // need double backslashes to escape \ and // to actually enter a \ into the json string const auto loaded = g.load_from_string(test_file, R"( { "esc": "#dog" } )"); REQUIRE(loaded.error_type == tr::result::rule_eof); } SECTION("rule call rule") { const auto loaded = g.load_from_string(test_file, R"( { "dog": "doggo", "animal": "#dog#" } )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#animal#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "doggo"); } SECTION("weird name rules") { const auto loaded = g.load_from_string(test_file, R"( { "animal-dog": "doggo", "animal": "#animal-dog#" } )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#animal#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "doggo"); } SECTION("func a") { const auto loaded = g.load_from_string(test_file, R"( { "dog": "dog", "animal": "#dog.a#" } )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#animal#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "a dog"); } SECTION("func s") { const auto loaded = g.load_from_string(test_file, R"( { "dog": "dog", "animal": "#dog.s#" } )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#animal#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "dogs"); } SECTION("push rules") { const auto loaded = g.load_from_string(test_file, R"( { "dog": "dog", "name": ["dog"], "story": ["#hero# is good"], "origin": ["#[hero:#name#]story#"] } )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#origin#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "dog is good"); } SECTION("advanced push") { const auto loaded = g.load_from_string(test_file, R"( { "origin":"I love #[animal:#cat#]say# and #[animal:POP]say#", "say":"#animal.s#", "animal": "dog", "cat":"cat" } )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#origin#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "I love cats and dogs"); } } <commit_msg>fix: tracery module is now only xml, reflected in test strings<commit_after>#include "core/tracery.h" #include "core/random.h" #include "catch.hpp" namespace tr = euphoria::core::tracery; TEST_CASE("tracery-all", "[tracery]") { const std::string test_file = "test-file"; auto random = euphoria::core::random{0}; tr::grammar g; g.register_english(); SECTION("empty json") { const auto loaded = g.load_from_string(test_file, R"( <tracery> </tracery> )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "test"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "test"); } SECTION("flatten single rule") { const auto loaded = g.load_from_string(test_file, R"( <tracery> <rule name="dog"> <text>doggo</text> </rule> </tracery> )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#dog#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "doggo"); } SECTION("escape") { const auto loaded = g.load_from_string(test_file, R"( <tracery> <rule name="esc"> <text>\#</text> </rule> </tracery> )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#esc#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "#"); } SECTION("don't die on non ending rules") { const auto loaded = g.load_from_string(test_file, R"( <tracery> <rule name="esc"> <text>#dog</text> </rule> </tracery> )"); REQUIRE(loaded.error_type == tr::result::rule_eof); } SECTION("rule call rule") { const auto loaded = g.load_from_string(test_file, R"( <tracery> <rule name="dog"> <text>doggo</text> </rule> <rule name="animal"> <text>#dog#</text> </rule> </tracery> )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#animal#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "doggo"); } SECTION("weird name rules") { const auto loaded = g.load_from_string(test_file, R"( <tracery> <rule name="animal-dog"> <text>doggo</text> </rule> <rule name="animal"> <text>#animal-dog#</text> </rule> </tracery> )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#animal#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "doggo"); } SECTION("func a") { const auto loaded = g.load_from_string(test_file, R"( <tracery> <rule name="dog"> <text>dog</text> </rule> <rule name="animal"> <text>#dog.a#</text> </rule> </tracery> )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#animal#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "a dog"); } SECTION("func s") { const auto loaded = g.load_from_string(test_file, R"( <tracery> <rule name="dog"> <text>dog</text> </rule> <rule name="animal"> <text>#dog.s#</text> </rule> </tracery> )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#animal#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "dogs"); } SECTION("push rules") { const auto loaded = g.load_from_string(test_file, R"( <tracery> <rule name="dog"> <text>dog</text> </rule> <rule name="name"> <text>dog</text> </rule> <rule name="story"> <text>#hero# is good</text> </rule> <rule name="origin"> <text>#[hero:#name#]story#</text> </rule> </tracery> )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#origin#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "dog is good"); } SECTION("advanced push") { const auto loaded = g.load_from_string(test_file, R"( <tracery> <rule name="origin"> <text>I love #[animal:#cat#]say# and #[animal:POP]say#</text> </rule> <rule name="say"> <text>#animal.s#</text> </rule> <rule name="animal"> <text>dog</text> </rule> <rule name="cat"> <text>cat</text> </rule> </tracery> )"); REQUIRE(loaded); const auto expansion_result = g.flatten(&random, "#origin#"); REQUIRE(expansion_result); CHECK(expansion_result.get_text() == "I love cats and dogs"); } } <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * https://lxqt.org * * Copyright: 2011 Razor team * Authors: * Alexander Sokoloff <sokoloff.a@gmail.com> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ /******************************************************************** Inspired by freedesktops tint2 ;) *********************************************************************/ #include <QApplication> #include <QDebug> #include <QTimer> #include <QX11Info> #include "trayicon.h" #include "../panel/ilxqtpanel.h" #include <LXQt/GridLayout> #include "lxqttray.h" #include "xfitman.h" #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include <X11/extensions/Xrender.h> #include <X11/extensions/Xdamage.h> #include <xcb/xcb.h> #include <xcb/damage.h> #undef Bool // defined as int in X11/Xlib.h #include "../panel/ilxqtpanelplugin.h" #define _NET_SYSTEM_TRAY_ORIENTATION_HORZ 0 #define _NET_SYSTEM_TRAY_ORIENTATION_VERT 1 #define SYSTEM_TRAY_REQUEST_DOCK 0 #define SYSTEM_TRAY_BEGIN_MESSAGE 1 #define SYSTEM_TRAY_CANCEL_MESSAGE 2 #define XEMBED_EMBEDDED_NOTIFY 0 #define XEMBED_MAPPED (1 << 0) /************************************************ ************************************************/ LXQtTray::LXQtTray(ILXQtPanelPlugin *plugin, QWidget *parent): QFrame(parent), mValid(false), mTrayId(0), mDamageEvent(0), mDamageError(0), mIconSize(TRAY_ICON_SIZE_DEFAULT, TRAY_ICON_SIZE_DEFAULT), mPlugin(plugin), mDisplay(QX11Info::display()) { mLayout = new LXQt::GridLayout(this); realign(); _NET_SYSTEM_TRAY_OPCODE = XfitMan::atom("_NET_SYSTEM_TRAY_OPCODE"); // Init the selection later just to ensure that no signals are sent until // after construction is done and the creating object has a chance to connect. QTimer::singleShot(0, this, SLOT(startTray())); } /************************************************ ************************************************/ LXQtTray::~LXQtTray() { stopTray(); } /************************************************ ************************************************/ bool LXQtTray::nativeEventFilter(const QByteArray &eventType, void *message, long *) { if (eventType != "xcb_generic_event_t") return false; xcb_generic_event_t* event = static_cast<xcb_generic_event_t *>(message); TrayIcon* icon; int event_type = event->response_type & ~0x80; switch (event_type) { case ClientMessage: clientMessageEvent(event); break; // case ConfigureNotify: // icon = findIcon(event->xconfigure.window); // if (icon) // icon->configureEvent(&(event->xconfigure)); // break; case DestroyNotify: { unsigned long event_window; event_window = reinterpret_cast<xcb_destroy_notify_event_t*>(event)->window; icon = findIcon(event_window); if (icon) { icon->windowDestroyed(event_window); mIcons.removeAll(icon); delete icon; } break; } default: if (event_type == mDamageEvent + XDamageNotify) { xcb_damage_notify_event_t* dmg = reinterpret_cast<xcb_damage_notify_event_t*>(event); icon = findIcon(dmg->drawable); if (icon) icon->update(); } break; } return false; } /************************************************ ************************************************/ void LXQtTray::realign() { mLayout->setEnabled(false); ILXQtPanel *panel = mPlugin->panel(); if (panel->isHorizontal()) { mLayout->setRowCount(panel->lineCount()); mLayout->setColumnCount(0); } else { mLayout->setColumnCount(panel->lineCount()); mLayout->setRowCount(0); } mLayout->setEnabled(true); } /************************************************ ************************************************/ void LXQtTray::clientMessageEvent(xcb_generic_event_t *e) { unsigned long opcode; unsigned long message_type; Window id; xcb_client_message_event_t* event = reinterpret_cast<xcb_client_message_event_t*>(e); uint32_t* data32 = event->data.data32; message_type = event->type; opcode = data32[1]; if(message_type != _NET_SYSTEM_TRAY_OPCODE) return; switch (opcode) { case SYSTEM_TRAY_REQUEST_DOCK: id = data32[2]; if (id) addIcon(id); break; case SYSTEM_TRAY_BEGIN_MESSAGE: case SYSTEM_TRAY_CANCEL_MESSAGE: qDebug() << "we don't show balloon messages."; break; default: // if (opcode == xfitMan().atom("_NET_SYSTEM_TRAY_MESSAGE_DATA")) // qDebug() << "message from dockapp:" << e->data.b; // else // qDebug() << "SYSTEM_TRAY : unknown message type" << opcode; break; } } /************************************************ ************************************************/ TrayIcon* LXQtTray::findIcon(Window id) { for(TrayIcon* icon : qAsConst(mIcons)) { if (icon->iconId() == id || icon->windowId() == id) return icon; } return 0; } /************************************************ ************************************************/ void LXQtTray::setIconSize(QSize iconSize) { mIconSize = iconSize; unsigned long size = qMin(mIconSize.width(), mIconSize.height()); XChangeProperty(mDisplay, mTrayId, XfitMan::atom("_NET_SYSTEM_TRAY_ICON_SIZE"), XA_CARDINAL, 32, PropModeReplace, (unsigned char*)&size, 1); } /************************************************ ************************************************/ VisualID LXQtTray::getVisual() { VisualID visualId = 0; Display* dsp = mDisplay; XVisualInfo templ; templ.screen=QX11Info::appScreen(); templ.depth=32; templ.c_class=TrueColor; int nvi; XVisualInfo* xvi = XGetVisualInfo(dsp, VisualScreenMask|VisualDepthMask|VisualClassMask, &templ, &nvi); if (xvi) { int i; XRenderPictFormat* format; for (i = 0; i < nvi; i++) { format = XRenderFindVisualFormat(dsp, xvi[i].visual); if (format && format->type == PictTypeDirect && format->direct.alphaMask) { visualId = xvi[i].visualid; break; } } XFree(xvi); } return visualId; } /************************************************ freedesktop systray specification ************************************************/ void LXQtTray::startTray() { Display* dsp = mDisplay; Window root = QX11Info::appRootWindow(); QString s = QString("_NET_SYSTEM_TRAY_S%1").arg(DefaultScreen(dsp)); Atom _NET_SYSTEM_TRAY_S = XfitMan::atom(s.toLatin1()); if (XGetSelectionOwner(dsp, _NET_SYSTEM_TRAY_S) != None) { qWarning() << "Another systray is running"; mValid = false; return; } // init systray protocol mTrayId = XCreateSimpleWindow(dsp, root, -1, -1, 1, 1, 0, 0, 0); XSetSelectionOwner(dsp, _NET_SYSTEM_TRAY_S, mTrayId, CurrentTime); if (XGetSelectionOwner(dsp, _NET_SYSTEM_TRAY_S) != mTrayId) { qWarning() << "Can't get systray manager"; stopTray(); mValid = false; return; } int orientation = _NET_SYSTEM_TRAY_ORIENTATION_HORZ; XChangeProperty(dsp, mTrayId, XfitMan::atom("_NET_SYSTEM_TRAY_ORIENTATION"), XA_CARDINAL, 32, PropModeReplace, (unsigned char *) &orientation, 1); // ** Visual ******************************** VisualID visualId = getVisual(); if (visualId) { XChangeProperty(mDisplay, mTrayId, XfitMan::atom("_NET_SYSTEM_TRAY_VISUAL"), XA_VISUALID, 32, PropModeReplace, (unsigned char*)&visualId, 1); } // ****************************************** setIconSize(mIconSize); XClientMessageEvent ev; ev.type = ClientMessage; ev.window = root; ev.message_type = XfitMan::atom("MANAGER"); ev.format = 32; ev.data.l[0] = CurrentTime; ev.data.l[1] = _NET_SYSTEM_TRAY_S; ev.data.l[2] = mTrayId; ev.data.l[3] = 0; ev.data.l[4] = 0; XSendEvent(dsp, root, False, StructureNotifyMask, (XEvent*)&ev); XDamageQueryExtension(mDisplay, &mDamageEvent, &mDamageError); qDebug() << "Systray started"; mValid = true; qApp->installNativeEventFilter(this); } /************************************************ ************************************************/ void LXQtTray::stopTray() { for (auto & icon : mIcons) disconnect(icon, &QObject::destroyed, this, &LXQtTray::onIconDestroyed); qDeleteAll(mIcons); if (mTrayId) { XDestroyWindow(mDisplay, mTrayId); mTrayId = 0; } mValid = false; } /************************************************ ************************************************/ void LXQtTray::onIconDestroyed(QObject * icon) { //in the time QOjbect::destroyed is emitted, the child destructor //is already finished, so the qobject_cast to child will return nullptr in all cases mIcons.removeAll(static_cast<TrayIcon *>(icon)); } /************************************************ ************************************************/ void LXQtTray::addIcon(Window winId) { // decline to add an icon for a window we already manage TrayIcon *icon = findIcon(winId); if(icon) return; icon = new TrayIcon(winId, mIconSize, this); mIcons.append(icon); QString name = icon->appName(); int insertIdx = mLayout->count(); int moveToIdx; // insert the icon sorted alphabetically, so that icons show up in a // predictable order (otherwise it varies depending on startup times) for (moveToIdx = 0; moveToIdx < insertIdx; moveToIdx++) { auto layoutItem = mLayout->itemAt(moveToIdx); auto existingIcon = static_cast<TrayIcon *>(layoutItem->widget()); if (name < existingIcon->appName()) break; } mLayout->addWidget(icon); mLayout->moveItem(insertIdx, moveToIdx); connect(icon, &QObject::destroyed, this, &LXQtTray::onIconDestroyed); } <commit_msg>Add a modest amount of spacing between system tray icons<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * https://lxqt.org * * Copyright: 2011 Razor team * Authors: * Alexander Sokoloff <sokoloff.a@gmail.com> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ /******************************************************************** Inspired by freedesktops tint2 ;) *********************************************************************/ #include <QApplication> #include <QDebug> #include <QTimer> #include <QX11Info> #include "trayicon.h" #include "../panel/ilxqtpanel.h" #include <LXQt/GridLayout> #include "lxqttray.h" #include "xfitman.h" #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include <X11/extensions/Xrender.h> #include <X11/extensions/Xdamage.h> #include <xcb/xcb.h> #include <xcb/damage.h> #undef Bool // defined as int in X11/Xlib.h #include "../panel/ilxqtpanelplugin.h" #define _NET_SYSTEM_TRAY_ORIENTATION_HORZ 0 #define _NET_SYSTEM_TRAY_ORIENTATION_VERT 1 #define SYSTEM_TRAY_REQUEST_DOCK 0 #define SYSTEM_TRAY_BEGIN_MESSAGE 1 #define SYSTEM_TRAY_CANCEL_MESSAGE 2 #define XEMBED_EMBEDDED_NOTIFY 0 #define XEMBED_MAPPED (1 << 0) /************************************************ ************************************************/ LXQtTray::LXQtTray(ILXQtPanelPlugin *plugin, QWidget *parent): QFrame(parent), mValid(false), mTrayId(0), mDamageEvent(0), mDamageError(0), mIconSize(TRAY_ICON_SIZE_DEFAULT, TRAY_ICON_SIZE_DEFAULT), mPlugin(plugin), mDisplay(QX11Info::display()) { mLayout = new LXQt::GridLayout(this); mLayout->setSpacing((TRAY_ICON_SIZE_DEFAULT + 4) / 8); realign(); _NET_SYSTEM_TRAY_OPCODE = XfitMan::atom("_NET_SYSTEM_TRAY_OPCODE"); // Init the selection later just to ensure that no signals are sent until // after construction is done and the creating object has a chance to connect. QTimer::singleShot(0, this, SLOT(startTray())); } /************************************************ ************************************************/ LXQtTray::~LXQtTray() { stopTray(); } /************************************************ ************************************************/ bool LXQtTray::nativeEventFilter(const QByteArray &eventType, void *message, long *) { if (eventType != "xcb_generic_event_t") return false; xcb_generic_event_t* event = static_cast<xcb_generic_event_t *>(message); TrayIcon* icon; int event_type = event->response_type & ~0x80; switch (event_type) { case ClientMessage: clientMessageEvent(event); break; // case ConfigureNotify: // icon = findIcon(event->xconfigure.window); // if (icon) // icon->configureEvent(&(event->xconfigure)); // break; case DestroyNotify: { unsigned long event_window; event_window = reinterpret_cast<xcb_destroy_notify_event_t*>(event)->window; icon = findIcon(event_window); if (icon) { icon->windowDestroyed(event_window); mIcons.removeAll(icon); delete icon; } break; } default: if (event_type == mDamageEvent + XDamageNotify) { xcb_damage_notify_event_t* dmg = reinterpret_cast<xcb_damage_notify_event_t*>(event); icon = findIcon(dmg->drawable); if (icon) icon->update(); } break; } return false; } /************************************************ ************************************************/ void LXQtTray::realign() { mLayout->setEnabled(false); ILXQtPanel *panel = mPlugin->panel(); if (panel->isHorizontal()) { mLayout->setRowCount(panel->lineCount()); mLayout->setColumnCount(0); } else { mLayout->setColumnCount(panel->lineCount()); mLayout->setRowCount(0); } mLayout->setEnabled(true); } /************************************************ ************************************************/ void LXQtTray::clientMessageEvent(xcb_generic_event_t *e) { unsigned long opcode; unsigned long message_type; Window id; xcb_client_message_event_t* event = reinterpret_cast<xcb_client_message_event_t*>(e); uint32_t* data32 = event->data.data32; message_type = event->type; opcode = data32[1]; if(message_type != _NET_SYSTEM_TRAY_OPCODE) return; switch (opcode) { case SYSTEM_TRAY_REQUEST_DOCK: id = data32[2]; if (id) addIcon(id); break; case SYSTEM_TRAY_BEGIN_MESSAGE: case SYSTEM_TRAY_CANCEL_MESSAGE: qDebug() << "we don't show balloon messages."; break; default: // if (opcode == xfitMan().atom("_NET_SYSTEM_TRAY_MESSAGE_DATA")) // qDebug() << "message from dockapp:" << e->data.b; // else // qDebug() << "SYSTEM_TRAY : unknown message type" << opcode; break; } } /************************************************ ************************************************/ TrayIcon* LXQtTray::findIcon(Window id) { for(TrayIcon* icon : qAsConst(mIcons)) { if (icon->iconId() == id || icon->windowId() == id) return icon; } return 0; } /************************************************ ************************************************/ void LXQtTray::setIconSize(QSize iconSize) { mIconSize = iconSize; unsigned long size = qMin(mIconSize.width(), mIconSize.height()); mLayout->setSpacing(((int)size + 4) / 8); XChangeProperty(mDisplay, mTrayId, XfitMan::atom("_NET_SYSTEM_TRAY_ICON_SIZE"), XA_CARDINAL, 32, PropModeReplace, (unsigned char*)&size, 1); } /************************************************ ************************************************/ VisualID LXQtTray::getVisual() { VisualID visualId = 0; Display* dsp = mDisplay; XVisualInfo templ; templ.screen=QX11Info::appScreen(); templ.depth=32; templ.c_class=TrueColor; int nvi; XVisualInfo* xvi = XGetVisualInfo(dsp, VisualScreenMask|VisualDepthMask|VisualClassMask, &templ, &nvi); if (xvi) { int i; XRenderPictFormat* format; for (i = 0; i < nvi; i++) { format = XRenderFindVisualFormat(dsp, xvi[i].visual); if (format && format->type == PictTypeDirect && format->direct.alphaMask) { visualId = xvi[i].visualid; break; } } XFree(xvi); } return visualId; } /************************************************ freedesktop systray specification ************************************************/ void LXQtTray::startTray() { Display* dsp = mDisplay; Window root = QX11Info::appRootWindow(); QString s = QString("_NET_SYSTEM_TRAY_S%1").arg(DefaultScreen(dsp)); Atom _NET_SYSTEM_TRAY_S = XfitMan::atom(s.toLatin1()); if (XGetSelectionOwner(dsp, _NET_SYSTEM_TRAY_S) != None) { qWarning() << "Another systray is running"; mValid = false; return; } // init systray protocol mTrayId = XCreateSimpleWindow(dsp, root, -1, -1, 1, 1, 0, 0, 0); XSetSelectionOwner(dsp, _NET_SYSTEM_TRAY_S, mTrayId, CurrentTime); if (XGetSelectionOwner(dsp, _NET_SYSTEM_TRAY_S) != mTrayId) { qWarning() << "Can't get systray manager"; stopTray(); mValid = false; return; } int orientation = _NET_SYSTEM_TRAY_ORIENTATION_HORZ; XChangeProperty(dsp, mTrayId, XfitMan::atom("_NET_SYSTEM_TRAY_ORIENTATION"), XA_CARDINAL, 32, PropModeReplace, (unsigned char *) &orientation, 1); // ** Visual ******************************** VisualID visualId = getVisual(); if (visualId) { XChangeProperty(mDisplay, mTrayId, XfitMan::atom("_NET_SYSTEM_TRAY_VISUAL"), XA_VISUALID, 32, PropModeReplace, (unsigned char*)&visualId, 1); } // ****************************************** setIconSize(mIconSize); XClientMessageEvent ev; ev.type = ClientMessage; ev.window = root; ev.message_type = XfitMan::atom("MANAGER"); ev.format = 32; ev.data.l[0] = CurrentTime; ev.data.l[1] = _NET_SYSTEM_TRAY_S; ev.data.l[2] = mTrayId; ev.data.l[3] = 0; ev.data.l[4] = 0; XSendEvent(dsp, root, False, StructureNotifyMask, (XEvent*)&ev); XDamageQueryExtension(mDisplay, &mDamageEvent, &mDamageError); qDebug() << "Systray started"; mValid = true; qApp->installNativeEventFilter(this); } /************************************************ ************************************************/ void LXQtTray::stopTray() { for (auto & icon : mIcons) disconnect(icon, &QObject::destroyed, this, &LXQtTray::onIconDestroyed); qDeleteAll(mIcons); if (mTrayId) { XDestroyWindow(mDisplay, mTrayId); mTrayId = 0; } mValid = false; } /************************************************ ************************************************/ void LXQtTray::onIconDestroyed(QObject * icon) { //in the time QOjbect::destroyed is emitted, the child destructor //is already finished, so the qobject_cast to child will return nullptr in all cases mIcons.removeAll(static_cast<TrayIcon *>(icon)); } /************************************************ ************************************************/ void LXQtTray::addIcon(Window winId) { // decline to add an icon for a window we already manage TrayIcon *icon = findIcon(winId); if(icon) return; icon = new TrayIcon(winId, mIconSize, this); mIcons.append(icon); QString name = icon->appName(); int insertIdx = mLayout->count(); int moveToIdx; // insert the icon sorted alphabetically, so that icons show up in a // predictable order (otherwise it varies depending on startup times) for (moveToIdx = 0; moveToIdx < insertIdx; moveToIdx++) { auto layoutItem = mLayout->itemAt(moveToIdx); auto existingIcon = static_cast<TrayIcon *>(layoutItem->widget()); if (name < existingIcon->appName()) break; } mLayout->addWidget(icon); mLayout->moveItem(insertIdx, moveToIdx); connect(icon, &QObject::destroyed, this, &LXQtTray::onIconDestroyed); } <|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/shell/common/webkit_test_helpers.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "content/public/common/content_switches.h" #include "content/shell/common/shell_switches.h" #include "content/shell/common/test_runner/WebPreferences.h" #include "webkit/common/webpreferences.h" namespace content { void ExportLayoutTestSpecificPreferences( const WebTestRunner::WebPreferences& from, WebPreferences* to) { to->allow_universal_access_from_file_urls = from.allowUniversalAccessFromFileURLs; to->dom_paste_enabled = from.DOMPasteAllowed; to->javascript_can_access_clipboard = from.javaScriptCanAccessClipboard; to->xss_auditor_enabled = from.XSSAuditorEnabled; to->editing_behavior = static_cast<webkit_glue::EditingBehavior>( from.editingBehavior); to->default_font_size = from.defaultFontSize; to->minimum_font_size = from.minimumFontSize; to->default_encoding = from.defaultTextEncodingName.utf8().data(); to->javascript_enabled = from.javaScriptEnabled; to->supports_multiple_windows = from.supportsMultipleWindows; to->loads_images_automatically = from.loadsImagesAutomatically; to->plugins_enabled = from.pluginsEnabled; to->java_enabled = from.javaEnabled; to->application_cache_enabled = from.offlineWebApplicationCacheEnabled; to->tabs_to_links = from.tabsToLinks; to->experimental_webgl_enabled = from.experimentalWebGLEnabled; // experimentalCSSRegionsEnabled is deprecated and ignored. to->hyperlink_auditing_enabled = from.hyperlinkAuditingEnabled; to->caret_browsing_enabled = from.caretBrowsingEnabled; to->allow_displaying_insecure_content = from.allowDisplayOfInsecureContent; to->allow_running_insecure_content = from.allowRunningOfInsecureContent; to->should_respect_image_orientation = from.shouldRespectImageOrientation; to->asynchronous_spell_checking_enabled = from.asynchronousSpellCheckingEnabled; to->allow_file_access_from_file_urls = from.allowFileAccessFromFileURLs; to->javascript_can_open_windows_automatically = from.javaScriptCanOpenWindowsAutomatically; } // Applies settings that differ between layout tests and regular mode. Some // of the defaults are controlled via command line flags which are // automatically set for layout tests. void ApplyLayoutTestDefaultPreferences(WebPreferences* prefs) { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); prefs->allow_universal_access_from_file_urls = true; prefs->dom_paste_enabled = true; prefs->javascript_can_access_clipboard = true; prefs->xslt_enabled = true; prefs->xss_auditor_enabled = false; #if defined(OS_MACOSX) prefs->editing_behavior = webkit_glue::EDITING_BEHAVIOR_MAC; #else prefs->editing_behavior = webkit_glue::EDITING_BEHAVIOR_WIN; #endif prefs->java_enabled = false; prefs->application_cache_enabled = true; prefs->tabs_to_links = false; prefs->hyperlink_auditing_enabled = false; prefs->allow_displaying_insecure_content = true; prefs->allow_running_insecure_content = true; prefs->webgl_errors_to_console_enabled = false; base::string16 serif; #if defined(OS_MACOSX) prefs->cursive_font_family_map[webkit_glue::kCommonScript] = base::ASCIIToUTF16("Apple Chancery"); prefs->fantasy_font_family_map[webkit_glue::kCommonScript] = base::ASCIIToUTF16("Papyrus"); serif = base::ASCIIToUTF16("Times"); #else prefs->cursive_font_family_map[webkit_glue::kCommonScript] = base::ASCIIToUTF16("Comic Sans MS"); prefs->fantasy_font_family_map[webkit_glue::kCommonScript] = base::ASCIIToUTF16("Impact"); serif = base::ASCIIToUTF16("times new roman"); #endif prefs->serif_font_family_map[webkit_glue::kCommonScript] = serif; prefs->standard_font_family_map[webkit_glue::kCommonScript] = serif; prefs->fixed_font_family_map[webkit_glue::kCommonScript] = base::ASCIIToUTF16("Courier"); prefs->sans_serif_font_family_map[ webkit_glue::kCommonScript] = base::ASCIIToUTF16("Helvetica"); prefs->minimum_logical_font_size = 9; prefs->asynchronous_spell_checking_enabled = false; prefs->threaded_html_parser = true; prefs->accelerated_2d_canvas_enabled = command_line.HasSwitch(switches::kEnableAccelerated2DCanvas); prefs->force_compositing_mode = command_line.HasSwitch(switches::kForceCompositingMode); prefs->accelerated_compositing_for_video_enabled = false; prefs->mock_scrollbars_enabled = false; prefs->fixed_position_creates_stacking_context = false; prefs->smart_insert_delete_enabled = true; prefs->minimum_accelerated_2d_canvas_size = 0; #if defined(OS_ANDROID) prefs->text_autosizing_enabled = false; #endif } base::FilePath GetWebKitRootDirFilePath() { base::FilePath base_path; PathService::Get(base::DIR_SOURCE_ROOT, &base_path); return base_path.Append(FILE_PATH_LITERAL("third_party/WebKit")); } } // namespace content <commit_msg>Revert "Support viewport in content_shell."<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/shell/common/webkit_test_helpers.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "content/public/common/content_switches.h" #include "content/shell/common/shell_switches.h" #include "content/shell/common/test_runner/WebPreferences.h" #include "webkit/common/webpreferences.h" namespace content { void ExportLayoutTestSpecificPreferences( const WebTestRunner::WebPreferences& from, WebPreferences* to) { to->allow_universal_access_from_file_urls = from.allowUniversalAccessFromFileURLs; to->dom_paste_enabled = from.DOMPasteAllowed; to->javascript_can_access_clipboard = from.javaScriptCanAccessClipboard; to->xss_auditor_enabled = from.XSSAuditorEnabled; to->editing_behavior = static_cast<webkit_glue::EditingBehavior>( from.editingBehavior); to->default_font_size = from.defaultFontSize; to->minimum_font_size = from.minimumFontSize; to->default_encoding = from.defaultTextEncodingName.utf8().data(); to->javascript_enabled = from.javaScriptEnabled; to->supports_multiple_windows = from.supportsMultipleWindows; to->loads_images_automatically = from.loadsImagesAutomatically; to->plugins_enabled = from.pluginsEnabled; to->java_enabled = from.javaEnabled; to->application_cache_enabled = from.offlineWebApplicationCacheEnabled; to->tabs_to_links = from.tabsToLinks; to->experimental_webgl_enabled = from.experimentalWebGLEnabled; // experimentalCSSRegionsEnabled is deprecated and ignored. to->hyperlink_auditing_enabled = from.hyperlinkAuditingEnabled; to->caret_browsing_enabled = from.caretBrowsingEnabled; to->allow_displaying_insecure_content = from.allowDisplayOfInsecureContent; to->allow_running_insecure_content = from.allowRunningOfInsecureContent; to->should_respect_image_orientation = from.shouldRespectImageOrientation; to->asynchronous_spell_checking_enabled = from.asynchronousSpellCheckingEnabled; to->allow_file_access_from_file_urls = from.allowFileAccessFromFileURLs; to->javascript_can_open_windows_automatically = from.javaScriptCanOpenWindowsAutomatically; } // Applies settings that differ between layout tests and regular mode. Some // of the defaults are controlled via command line flags which are // automatically set for layout tests. void ApplyLayoutTestDefaultPreferences(WebPreferences* prefs) { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); prefs->allow_universal_access_from_file_urls = true; prefs->dom_paste_enabled = true; prefs->javascript_can_access_clipboard = true; prefs->xslt_enabled = true; prefs->xss_auditor_enabled = false; #if defined(OS_MACOSX) prefs->editing_behavior = webkit_glue::EDITING_BEHAVIOR_MAC; #else prefs->editing_behavior = webkit_glue::EDITING_BEHAVIOR_WIN; #endif prefs->java_enabled = false; prefs->application_cache_enabled = true; prefs->tabs_to_links = false; prefs->hyperlink_auditing_enabled = false; prefs->allow_displaying_insecure_content = true; prefs->allow_running_insecure_content = true; prefs->webgl_errors_to_console_enabled = false; base::string16 serif; #if defined(OS_MACOSX) prefs->cursive_font_family_map[webkit_glue::kCommonScript] = base::ASCIIToUTF16("Apple Chancery"); prefs->fantasy_font_family_map[webkit_glue::kCommonScript] = base::ASCIIToUTF16("Papyrus"); serif = base::ASCIIToUTF16("Times"); #else prefs->cursive_font_family_map[webkit_glue::kCommonScript] = base::ASCIIToUTF16("Comic Sans MS"); prefs->fantasy_font_family_map[webkit_glue::kCommonScript] = base::ASCIIToUTF16("Impact"); serif = base::ASCIIToUTF16("times new roman"); #endif prefs->serif_font_family_map[webkit_glue::kCommonScript] = serif; prefs->standard_font_family_map[webkit_glue::kCommonScript] = serif; prefs->fixed_font_family_map[webkit_glue::kCommonScript] = base::ASCIIToUTF16("Courier"); prefs->sans_serif_font_family_map[ webkit_glue::kCommonScript] = base::ASCIIToUTF16("Helvetica"); prefs->minimum_logical_font_size = 9; prefs->asynchronous_spell_checking_enabled = false; prefs->threaded_html_parser = true; prefs->accelerated_2d_canvas_enabled = command_line.HasSwitch(switches::kEnableAccelerated2DCanvas); prefs->force_compositing_mode = command_line.HasSwitch(switches::kForceCompositingMode); prefs->accelerated_compositing_for_video_enabled = false; prefs->mock_scrollbars_enabled = false; prefs->fixed_position_creates_stacking_context = false; prefs->smart_insert_delete_enabled = true; prefs->minimum_accelerated_2d_canvas_size = 0; #if defined(OS_ANDROID) prefs->text_autosizing_enabled = false; #endif prefs->viewport_enabled = false; } base::FilePath GetWebKitRootDirFilePath() { base::FilePath base_path; PathService::Get(base::DIR_SOURCE_ROOT, &base_path); return base_path.Append(FILE_PATH_LITERAL("third_party/WebKit")); } } // namespace content <|endoftext|>
<commit_before>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011-2013 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa 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. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #ifndef CPPA_OPTION_HPP #define CPPA_OPTION_HPP #include <new> #include <utility> #include "cppa/config.hpp" namespace cppa { /** * @brief Represents an optional value of @p T. */ template<typename T> class option { public: /** * @brief Typdef for @p T. */ typedef T type; /** * @brief Default constructor. * @post <tt>valid() == false</tt> */ option() : m_valid(false) { } /** * @brief Creates an @p option from @p value. * @post <tt>valid() == true</tt> */ option(T value) : m_valid(false) { cr(std::move(value)); } option(const option& other) : m_valid(false) { if (other.m_valid) cr(other.m_value); } option(option&& other) : m_valid(false) { if (other.m_valid) cr(std::move(other.m_value)); } ~option() { destroy(); } option& operator=(const option& other) { if (m_valid) { if (other.m_valid) m_value = other.m_value; else destroy(); } else if (other.m_valid) { cr(other.m_value); } return *this; } option& operator=(option&& other) { if (m_valid) { if (other.m_valid) m_value = std::move(other.m_value); else destroy(); } else if (other.m_valid) { cr(std::move(other.m_value)); } return *this; } /** * @brief Returns @p true if this @p option has a valid value; * otherwise @p false. */ inline bool valid() const { return m_valid; } /** * @brief Returns <tt>!valid()</tt>. */ inline bool empty() const { return !m_valid; } /** * @copydoc valid() */ inline explicit operator bool() const { return valid(); } /** * @brief Returns <tt>!valid()</tt>. */ inline bool operator!() const { return empty(); } /** * @brief Returns the value. */ inline T& operator*() { CPPA_REQUIRE(valid()); return m_value; } /** * @brief Returns the value. */ inline const T& operator*() const { CPPA_REQUIRE(valid()); return m_value; } /** * @brief Returns the value. */ inline T& get() { CPPA_REQUIRE(valid()); return m_value; } /** * @brief Returns the value. */ inline const T& get() const { CPPA_REQUIRE(valid()); return m_value; } /** * @brief Returns the value. The value is set to @p default_value * if <tt>valid() == false</tt>. * @post <tt>valid() == true</tt> */ inline const T& get_or_else(const T& default_value) const { if (valid()) return get(); return default_value; } private: bool m_valid; union { T m_value; }; void destroy() { if (m_valid) { m_value.~T(); m_valid = false; } } template<typename V> void cr(V&& value) { CPPA_REQUIRE(!valid()); m_valid = true; new (&m_value) T (std::forward<V>(value)); } }; template<typename T> class option<T&> { public: typedef T type; option() : m_value(nullptr) { } option(T& value) : m_value(&value) { } option(const option& other) = default; option& operator=(const option& other) = default; inline bool valid() const { return m_value != nullptr; } inline bool empty() const { return !valid(); } inline explicit operator bool() const { return valid(); } inline bool operator!() const { return empty(); } inline T& operator*() { CPPA_REQUIRE(valid()); return *m_value; } inline const T& operator*() const { CPPA_REQUIRE(valid()); return *m_value; } inline T& get() { CPPA_REQUIRE(valid()); return *m_value; } inline const T& get() const { CPPA_REQUIRE(valid()); return *m_value; } inline const T& get_or_else(const T& default_value) const { if (valid()) return get(); return default_value; } private: T* m_value; }; /** @relates option */ template<typename T> struct is_option { static constexpr bool value = false; }; template<typename T> struct is_option<option<T>> { static constexpr bool value = true; }; /** @relates option */ template<typename T, typename U> bool operator==(const option<T>& lhs, const option<U>& rhs) { if ((lhs) && (rhs)) return *lhs == *rhs; return false; } /** @relates option */ template<typename T, typename U> bool operator==(const option<T>& lhs, const U& rhs) { if (lhs) return *lhs == rhs; return false; } /** @relates option */ template<typename T, typename U> bool operator==(const T& lhs, const option<U>& rhs) { return rhs == lhs; } /** @relates option */ template<typename T, typename U> bool operator!=(const option<T>& lhs, const option<U>& rhs) { return !(lhs == rhs); } /** @relates option */ template<typename T, typename U> bool operator!=(const option<T>& lhs, const U& rhs) { return !(lhs == rhs); } /** @relates option */ template<typename T, typename U> bool operator!=(const T& lhs, const option<U>& rhs) { return !(lhs == rhs); } } // namespace cppa #endif // CPPA_OPTION_HPP <commit_msg>added convenience constructor to `option`<commit_after>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011-2013 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa 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. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #ifndef CPPA_OPTION_HPP #define CPPA_OPTION_HPP #include <new> #include <utility> #include "cppa/config.hpp" namespace cppa { /** * @brief Represents an optional value of @p T. */ template<typename T> class option { public: /** * @brief Typdef for @p T. */ typedef T type; /** * @brief Default constructor. * @post <tt>valid() == false</tt> */ option() : m_valid(false) { } /** * @brief Creates an @p option from @p value. * @post <tt>valid() == true</tt> */ option(T value) : m_valid(false) { cr(std::move(value)); } template<typename T0, typename T1, typename... Ts> option(T0&& arg0, T1&& arg1, Ts&&... args) { cr(T(std::forward<T0>(arg0), std::forward<T1>(arg1), std::forward<Ts>(args)...)); } option(const option& other) : m_valid(false) { if (other.m_valid) cr(other.m_value); } option(option&& other) : m_valid(false) { if (other.m_valid) cr(std::move(other.m_value)); } ~option() { destroy(); } option& operator=(const option& other) { if (m_valid) { if (other.m_valid) m_value = other.m_value; else destroy(); } else if (other.m_valid) { cr(other.m_value); } return *this; } option& operator=(option&& other) { if (m_valid) { if (other.m_valid) m_value = std::move(other.m_value); else destroy(); } else if (other.m_valid) { cr(std::move(other.m_value)); } return *this; } /** * @brief Returns @p true if this @p option has a valid value; * otherwise @p false. */ inline bool valid() const { return m_valid; } /** * @brief Returns <tt>!valid()</tt>. */ inline bool empty() const { return !m_valid; } /** * @copydoc valid() */ inline explicit operator bool() const { return valid(); } /** * @brief Returns <tt>!valid()</tt>. */ inline bool operator!() const { return empty(); } /** * @brief Returns the value. */ inline T& operator*() { CPPA_REQUIRE(valid()); return m_value; } /** * @brief Returns the value. */ inline const T& operator*() const { CPPA_REQUIRE(valid()); return m_value; } /** * @brief Returns the value. */ inline T& get() { CPPA_REQUIRE(valid()); return m_value; } /** * @brief Returns the value. */ inline const T& get() const { CPPA_REQUIRE(valid()); return m_value; } /** * @brief Returns the value. The value is set to @p default_value * if <tt>valid() == false</tt>. * @post <tt>valid() == true</tt> */ inline const T& get_or_else(const T& default_value) const { if (valid()) return get(); return default_value; } private: bool m_valid; union { T m_value; }; void destroy() { if (m_valid) { m_value.~T(); m_valid = false; } } template<typename V> void cr(V&& value) { CPPA_REQUIRE(!valid()); m_valid = true; new (&m_value) T (std::forward<V>(value)); } }; template<typename T> class option<T&> { public: typedef T type; option() : m_value(nullptr) { } option(T& value) : m_value(&value) { } option(const option& other) = default; option& operator=(const option& other) = default; inline bool valid() const { return m_value != nullptr; } inline bool empty() const { return !valid(); } inline explicit operator bool() const { return valid(); } inline bool operator!() const { return empty(); } inline T& operator*() { CPPA_REQUIRE(valid()); return *m_value; } inline const T& operator*() const { CPPA_REQUIRE(valid()); return *m_value; } inline T& get() { CPPA_REQUIRE(valid()); return *m_value; } inline const T& get() const { CPPA_REQUIRE(valid()); return *m_value; } inline const T& get_or_else(const T& default_value) const { if (valid()) return get(); return default_value; } private: T* m_value; }; /** @relates option */ template<typename T> struct is_option { static constexpr bool value = false; }; template<typename T> struct is_option<option<T>> { static constexpr bool value = true; }; /** @relates option */ template<typename T, typename U> bool operator==(const option<T>& lhs, const option<U>& rhs) { if ((lhs) && (rhs)) return *lhs == *rhs; return false; } /** @relates option */ template<typename T, typename U> bool operator==(const option<T>& lhs, const U& rhs) { if (lhs) return *lhs == rhs; return false; } /** @relates option */ template<typename T, typename U> bool operator==(const T& lhs, const option<U>& rhs) { return rhs == lhs; } /** @relates option */ template<typename T, typename U> bool operator!=(const option<T>& lhs, const option<U>& rhs) { return !(lhs == rhs); } /** @relates option */ template<typename T, typename U> bool operator!=(const option<T>& lhs, const U& rhs) { return !(lhs == rhs); } /** @relates option */ template<typename T, typename U> bool operator!=(const T& lhs, const option<U>& rhs) { return !(lhs == rhs); } } // namespace cppa #endif // CPPA_OPTION_HPP <|endoftext|>
<commit_before>#include <core/executionmanager.h> #include <core/datamanager.h> #include <core/module.h> #include <core/loader.h> #include <queue> #include <iostream> #include <core/datamanager.h> #include <stdio.h> #include <memory> namespace lms{ ExecutionManager::ExecutionManager(logging::Logger &rootLogger) : rootLogger(rootLogger), logger("EXECMGR", &rootLogger), maxThreads(1), valid(false), loader(rootLogger), dataManager(rootLogger) { } ExecutionManager::~ExecutionManager () { //TODO } void ExecutionManager::loop() { //validate the ExecutionManager validate(); /* //Imagerecognition_mt //TODO copy cycleList so it can be modified while(cycleList.size() > 0){ for(std::vector<Module*>& moduleV:cycleList){ if(moduleV.size() == 1){ moduleV[0]->cycle(); //TODO remove module from others //TODO remove moduleV from cycleList } } } */ //HACK just for testing atm for(auto* it: enabledModules){ it->cycle(); } } void ExecutionManager::loadAvailabelModules(){ logger.info() << "load available Modules"; available = loader.getModules(); } void ExecutionManager::enableModule(const std::string &name){ //Check if module is already enabled for(auto* it:enabledModules){ if(it->getName() == name){ //TODO throw error return; } } for(auto& it:available){ if(it.name == name){ Module* module = loader.load(it); module->initializeBase(&dataManager,it, &rootLogger); module->initialize(); enabledModules.push_back(module); invalidate(); } } } /**Disable module with the given name, remove it from the cycle-queue */ void ExecutionManager::disableModule(const std::string &name){ for(size_t i = 0; i< enabledModules.size(); ++i){ if(enabledModules[i]->getName() == name){ enabledModules.erase(enabledModules.begin() + 1); invalidate(); return; } } //TODO print error that modules didn't run } /** * @brief ExecutionManager::invalidate calling that method will cause the executionmanager to run validate() in the next loop */ void ExecutionManager::invalidate(){ valid = false; } void ExecutionManager::validate(){ if(!valid){ valid = true; sort(); } } void ExecutionManager::sort(){ cycleList.clear(); //add modules to the list for(Module* it : enabledModules){ std::vector<Module*> tmp; tmp.push_back(it); cycleList.push_back(tmp); } sortByDataChannel(); sortByPriority(); //TODO //validate(); //validateDataChannels(); } void ExecutionManager::sortByDataChannel(){ // getChannels() returns const& -> you must use a const& here as well for(const std::pair<std::string, DataManager::DataChannel> &pair : dataManager.getChannels()){ // Module* here is ok, you will make a copy of the pointer for(Module* reader : pair.second.readers){ // usual & here for(std::vector<Module*> &list: cycleList){ for(Module* toAdd : list){ //add all writers to the needed modules for(Module* writer : pair.second.writers){ if(toAdd->getName() == reader->getName()){ list.push_back(writer); } } } } } } } void ExecutionManager::sortByPriority(){ // const& here again for(const std::pair<std::string, DataManager::DataChannel>& pair : dataManager.getChannels()){ for(Module* writer1 : pair.second.writers){ for(Module* writer2 : pair.second.writers){ if(writer1->getName() != writer2->getName()){ // usual & here for(std::vector<Module*> &list: cycleList){ for(Module* insert : list){ if(writer1->getPriority() >= writer2->getPriority()){ if(insert->getName() == writer2->getName()){ list.push_back(writer1); } }else{ if(insert->getName() == writer1->getName()){ list.push_back(writer2); } } } } } } } } } } <commit_msg>Fixed bug and added logging for ExecutionManager<commit_after>#include <core/executionmanager.h> #include <core/datamanager.h> #include <core/module.h> #include <core/loader.h> #include <queue> #include <iostream> #include <core/datamanager.h> #include <stdio.h> #include <memory> namespace lms{ ExecutionManager::ExecutionManager(logging::Logger &rootLogger) : rootLogger(rootLogger), logger("EXECMGR", &rootLogger), maxThreads(1), valid(false), loader(rootLogger), dataManager(rootLogger) { } ExecutionManager::~ExecutionManager () { //TODO } void ExecutionManager::loop() { //validate the ExecutionManager validate(); /* //Imagerecognition_mt //TODO copy cycleList so it can be modified while(cycleList.size() > 0){ for(std::vector<Module*>& moduleV:cycleList){ if(moduleV.size() == 1){ moduleV[0]->cycle(); //TODO remove module from others //TODO remove moduleV from cycleList } } } */ //HACK just for testing atm for(auto* it: enabledModules){ it->cycle(); } } void ExecutionManager::loadAvailabelModules(){ logger.info() << "load available Modules"; available = loader.getModules(); } void ExecutionManager::enableModule(const std::string &name){ //Check if module is already enabled for(auto* it:enabledModules){ if(it->getName() == name){ logger.error("enableModule") << "Module " << name << " is already enabled."; return; } } for(auto& it:available){ if(it.name == name){ Module* module = loader.load(it); module->initializeBase(&dataManager,it, &rootLogger); module->initialize(); enabledModules.push_back(module); invalidate(); } } } /**Disable module with the given name, remove it from the cycle-queue */ void ExecutionManager::disableModule(const std::string &name){ for(size_t i = 0; i< enabledModules.size(); ++i){ if(enabledModules[i]->getName() == name){ enabledModules.erase(enabledModules.begin() + i); invalidate(); return; } } logger.error("disableModule") << "Module " << name << " was not enabled."; } /** * @brief ExecutionManager::invalidate calling that method will cause the executionmanager to run validate() in the next loop */ void ExecutionManager::invalidate(){ valid = false; } void ExecutionManager::validate(){ if(!valid){ valid = true; sort(); } } void ExecutionManager::sort(){ cycleList.clear(); //add modules to the list for(Module* it : enabledModules){ std::vector<Module*> tmp; tmp.push_back(it); cycleList.push_back(tmp); } sortByDataChannel(); sortByPriority(); //TODO //validate(); //validateDataChannels(); } void ExecutionManager::sortByDataChannel(){ // getChannels() returns const& -> you must use a const& here as well for(const std::pair<std::string, DataManager::DataChannel> &pair : dataManager.getChannels()){ // Module* here is ok, you will make a copy of the pointer for(Module* reader : pair.second.readers){ // usual & here for(std::vector<Module*> &list: cycleList){ for(Module* toAdd : list){ //add all writers to the needed modules for(Module* writer : pair.second.writers){ if(toAdd->getName() == reader->getName()){ list.push_back(writer); } } } } } } } void ExecutionManager::sortByPriority(){ // const& here again for(const std::pair<std::string, DataManager::DataChannel>& pair : dataManager.getChannels()){ for(Module* writer1 : pair.second.writers){ for(Module* writer2 : pair.second.writers){ if(writer1->getName() != writer2->getName()){ // usual & here for(std::vector<Module*> &list: cycleList){ for(Module* insert : list){ if(writer1->getPriority() >= writer2->getPriority()){ if(insert->getName() == writer2->getName()){ list.push_back(writer1); } }else{ if(insert->getName() == writer1->getName()){ list.push_back(writer2); } } } } } } } } } } <|endoftext|>