text
stringlengths
54
60.6k
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/tools/convert_dict/dic_reader.h" #include <algorithm> #include <set> #include "base/file_util.h" #include "base/string_util.h" #include "chrome/tools/convert_dict/aff_reader.h" #include "chrome/tools/convert_dict/hunspell_reader.h" namespace convert_dict { namespace { // Maps each unique word to the unique affix group IDs associated with it. typedef std::map<std::string, std::set<int> > WordSet; void SplitDicLine(const std::string& line, std::vector<std::string>* output) { // We split the line on a slash not preceeded by a backslash. A slash at the // beginning of the line is not a separator either. size_t slash_index = line.size(); for (size_t i = 0; i < line.size(); i++) { if (line[i] == '/' && i > 0 && line[i - 1] != '\\') { slash_index = i; break; } } output->clear(); // Everything before the slash index is the first term. We also need to // convert all escaped slashes ("\/" sequences) to regular slashes. std::string word = line.substr(0, slash_index); ReplaceSubstringsAfterOffset(&word, 0, "\\/", "/"); output->push_back(word); // Everything (if anything) after the slash is the second. if (slash_index < line.size() - 1) output->push_back(line.substr(slash_index + 1)); } // This function reads words from a .dic file, or a .dic_delta file. Note that // we read 'all' the words in the file, irrespective of the word count given // in the first non empty line of a .dic file. Also note that, for a .dic_delta // file, the first line actually does _not_ have the number of words. In order // to control this, we use the |file_has_word_count_in_the_first_line| // parameter to tell this method whether the first non empty line in the file // contains the number of words or not. If it does, skip the first line. If it // does not, then the first line contains a word. bool PopulateWordSet(WordSet* word_set, FILE* file, AffReader* aff_reader, const char* file_type, bool file_has_word_count_in_the_first_line) { printf("Extracting words from %s file...\n", file_type); int line_number = 0; while (!feof(file)) { std::string line = ReadLine(file); line_number++; StripComment(&line); if (line.empty()) continue; if (file_has_word_count_in_the_first_line) { // Skip the first nonempty line, this is the line count. We don't bother // with it and just read all the lines. file_has_word_count_in_the_first_line = false; continue; } std::vector<std::string> split; SplitDicLine(line, &split); if (split.size() == 0 || split.size() > 2) { printf("Line %d has extra slashes in the %s file\n", line_number, file_type); return false; } // The first part is the word, the second (optional) part is the affix. We // always use UTF-8 as the encoding to simplify life. std::string utf8word; if (!aff_reader->EncodingToUTF8(split[0], &utf8word)) { printf("Unable to convert line %d from %s to UTF-8 in the %s file\n", line_number, aff_reader->encoding(), file_type); return false; } // We always convert the affix to an index. 0 means no affix. int affix_index = 0; if (split.size() == 2) { // Got a rule, which is the stuff after the slash. The line may also have // an optional term separated by a tab. This is the morphological // description. We don't care about this (it is used in the tests to // generate a nice dump), so we remove it. size_t split1_tab_offset = split[1].find('\t'); if (split1_tab_offset != std::string::npos) split[1] = split[1].substr(0, split1_tab_offset); if (aff_reader->has_indexed_affixes()) affix_index = atoi(split[1].c_str()); else affix_index = aff_reader->GetAFIndexForAFString(split[1]); } WordSet::iterator found = word_set->find(utf8word); if (found == word_set->end()) { std::set<int> affix_vector; affix_vector.insert(affix_index); word_set->insert(std::make_pair(utf8word, affix_vector)); } else { found->second.insert(affix_index); } } return true; } } // namespace DicReader::DicReader(const std::string& filename) { file_ = file_util::OpenFile(filename, "r"); additional_words_file_ = file_util::OpenFile(filename + "_delta", "r"); } DicReader::~DicReader() { if (file_) file_util::CloseFile(file_); if (additional_words_file_) file_util::CloseFile(additional_words_file_); } bool DicReader::Read(AffReader* aff_reader) { if (!file_) return false; WordSet word_set; // Add words from the dic file to the word set. // Note that the first line is the word count in the file. if (!PopulateWordSet(&word_set, file_, aff_reader, "dic", true)) return false; // Add words from the dic delta file to the word set, if it exists. // The first line is the first word to add. Word count line is not present. if (additional_words_file_ != NULL) { PopulateWordSet(&word_set, additional_words_file_, aff_reader, "dic delta", false); } // Make sure the words are sorted, they may be unsorted in the input. for (WordSet::iterator word = word_set.begin(); word != word_set.end(); ++word) { std::vector<int> affixes; for (std::set<int>::iterator aff = word->second.begin(); aff != word->second.end(); ++aff) affixes.push_back(*aff); // Double check that the affixes are sorted. This isn't strictly necessary // but it's nice for the file to have a fixed layout. std::sort(affixes.begin(), affixes.end()); words_.push_back(std::make_pair(word->first, affixes)); } // Double-check that the words are sorted. std::sort(words_.begin(), words_.end()); return true; } } // namespace convert_dict <commit_msg>Fix the dic reader so that it now accepts additional words from dic_delta files encoded as UTF-8. <commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/tools/convert_dict/dic_reader.h" #include <algorithm> #include <set> #include "base/file_util.h" #include "base/string_util.h" #include "chrome/tools/convert_dict/aff_reader.h" #include "chrome/tools/convert_dict/hunspell_reader.h" namespace convert_dict { namespace { // Maps each unique word to the unique affix group IDs associated with it. typedef std::map<std::string, std::set<int> > WordSet; void SplitDicLine(const std::string& line, std::vector<std::string>* output) { // We split the line on a slash not preceeded by a backslash. A slash at the // beginning of the line is not a separator either. size_t slash_index = line.size(); for (size_t i = 0; i < line.size(); i++) { if (line[i] == '/' && i > 0 && line[i - 1] != '\\') { slash_index = i; break; } } output->clear(); // Everything before the slash index is the first term. We also need to // convert all escaped slashes ("\/" sequences) to regular slashes. std::string word = line.substr(0, slash_index); ReplaceSubstringsAfterOffset(&word, 0, "\\/", "/"); output->push_back(word); // Everything (if anything) after the slash is the second. if (slash_index < line.size() - 1) output->push_back(line.substr(slash_index + 1)); } // This function reads words from a .dic file, or a .dic_delta file. Note that // we read 'all' the words in the file, irrespective of the word count given // in the first non empty line of a .dic file. Also note that, for a .dic_delta // file, the first line actually does _not_ have the number of words. In order // to control this, we use the |file_has_word_count_in_the_first_line| // parameter to tell this method whether the first non empty line in the file // contains the number of words or not. If it does, skip the first line. If it // does not, then the first line contains a word. bool PopulateWordSet(WordSet* word_set, FILE* file, AffReader* aff_reader, const char* file_type, const char* encoding, bool file_has_word_count_in_the_first_line) { printf("Extracting words from %s file\nEncoding: %s\n", file_type, encoding); int line_number = 0; while (!feof(file)) { std::string line = ReadLine(file); line_number++; StripComment(&line); if (line.empty()) continue; if (file_has_word_count_in_the_first_line) { // Skip the first nonempty line, this is the line count. We don't bother // with it and just read all the lines. file_has_word_count_in_the_first_line = false; continue; } std::vector<std::string> split; SplitDicLine(line, &split); if (split.size() == 0 || split.size() > 2) { printf("Line %d has extra slashes in the %s file\n", line_number, file_type); return false; } // The first part is the word, the second (optional) part is the affix. We // always use UTF-8 as the encoding to simplify life. std::string utf8word; std::string encoding_string(encoding); if (encoding_string == "UTF-8") { utf8word = split[0]; } else if (!aff_reader->EncodingToUTF8(split[0], &utf8word)) { printf("Unable to convert line %d from %s to UTF-8 in the %s file\n", line_number, encoding, file_type); return false; } // We always convert the affix to an index. 0 means no affix. int affix_index = 0; if (split.size() == 2) { // Got a rule, which is the stuff after the slash. The line may also have // an optional term separated by a tab. This is the morphological // description. We don't care about this (it is used in the tests to // generate a nice dump), so we remove it. size_t split1_tab_offset = split[1].find('\t'); if (split1_tab_offset != std::string::npos) split[1] = split[1].substr(0, split1_tab_offset); if (aff_reader->has_indexed_affixes()) affix_index = atoi(split[1].c_str()); else affix_index = aff_reader->GetAFIndexForAFString(split[1]); } WordSet::iterator found = word_set->find(utf8word); if (found == word_set->end()) { std::set<int> affix_vector; affix_vector.insert(affix_index); word_set->insert(std::make_pair(utf8word, affix_vector)); } else { found->second.insert(affix_index); } } return true; } } // namespace DicReader::DicReader(const std::string& filename) { file_ = file_util::OpenFile(filename, "r"); additional_words_file_ = file_util::OpenFile(filename + "_delta", "r"); } DicReader::~DicReader() { if (file_) file_util::CloseFile(file_); if (additional_words_file_) file_util::CloseFile(additional_words_file_); } bool DicReader::Read(AffReader* aff_reader) { if (!file_) return false; WordSet word_set; // Add words from the dic file to the word set. // Note that the first line is the word count in the file. if (!PopulateWordSet(&word_set, file_, aff_reader, "dic", aff_reader->encoding(), true)) return false; // Add words from the .dic_delta file to the word set, if it exists. // The first line is the first word to add. Word count line is not present. // NOTE: These additional words should be encoded as UTF-8. if (additional_words_file_ != NULL) { PopulateWordSet(&word_set, additional_words_file_, aff_reader, "dic delta", "UTF-8", false); } // Make sure the words are sorted, they may be unsorted in the input. for (WordSet::iterator word = word_set.begin(); word != word_set.end(); ++word) { std::vector<int> affixes; for (std::set<int>::iterator aff = word->second.begin(); aff != word->second.end(); ++aff) affixes.push_back(*aff); // Double check that the affixes are sorted. This isn't strictly necessary // but it's nice for the file to have a fixed layout. std::sort(affixes.begin(), affixes.end()); words_.push_back(std::make_pair(word->first, affixes)); } // Double-check that the words are sorted. std::sort(words_.begin(), words_.end()); return true; } } // namespace convert_dict <|endoftext|>
<commit_before>#include "mainClass.h" #include "defs.h" #include "methodsTesterForQrxcAndQrmc.h" #include "methodsTesterForQrxcAndInterpreter.h" #include "methodsCheckerForTravis.h" #include "../../qrgui/pluginManager/interpreterEditorManager.h" #include "../../qrgui/pluginManager/editorManagerInterface.h" #include "../../qrgui/pluginManager/editorManager.h" #include "../../qrutils/xmlUtils.h" #include <QtCore/QDir> #include <QtCore/QFileInfo> using namespace qReal; using namespace editorPluginTestingFramework; using namespace qrRepo; MainClass::MainClass( QString const &fileName , QString const &pathToQrmc , QString const &applicationPath , bool const &travisMode) : mTempOldValue(SettingsManager::value("temp").toString()) , mApplicationPath(applicationPath) { setTempValueInSettingsManager(); deleteOldBinaries(binariesDir); createNewFolders(); QString const normalizedFileName = normalizedName(fileName); if (travisMode) { copyTestMetamodel(fileName); } parseConfigurationFile(travisMode); launchQrxc(normalizedFileName); compilePlugin(pathToQrxcGeneratedCode); EditorInterface* const qrxcGeneratedPlugin = loadedPlugin(normalizedFileName, pathToQrxcGeneratedPlugin); appendPluginNames(); launchQrmc(fileName, pathToQrmc); compilePlugin(pathToQrmcGeneratedCode); EditorInterface* const qrmcGeneratedPlugin = loadedPlugin(normalizedFileName, pathToQrmcGeneratedPlugin); InterpreterEditorManager interpreterEditorManager(fileName); EditorManager qrxcEditorManager(destDirForQrxc, mQrxcGeneratedPluginsList); // we cast qrxc plugin to Editor Manager MethodsTesterForQrxcAndInterpreter* const interpreterMethodsTester = new MethodsTesterForQrxcAndInterpreter( &qrxcEditorManager ,&interpreterEditorManager); QList<QPair<QString, QPair<QString, QString> > > interpreterMethodsTesterOutput = interpreterMethodsTester->generatedResult(); if ((qrxcGeneratedPlugin != NULL) && (qrmcGeneratedPlugin != NULL)) { MethodsTesterForQrxcAndQrmc* const methodsTester = new MethodsTesterForQrxcAndQrmc( qrmcGeneratedPlugin, qrxcGeneratedPlugin); QList<QPair<QString, QPair<QString, QString> > > methodsTesterOutput = methodsTester->generatedOutput(); if (!travisMode) { createHtml(methodsTesterOutput, interpreterMethodsTesterOutput); } else { mResultOfTesting = MethodsCheckerForTravis::calculateResult(methodsTesterOutput , interpreterMethodsTesterOutput); } } else { qDebug() << "Generation of plugins failed"; } returnOldValueOfTemp(); delete qrxcGeneratedPlugin; delete qrmcGeneratedPlugin; delete interpreterMethodsTester; } int MainClass::travisTestResult() const { return mResultOfTesting; } void MainClass::createFolder(QString const &path) { QDir dir; if (!dir.exists(path)) { dir.mkdir(path); } } void MainClass::createNewFolders() { createFolder(binariesDir); createFolder(pluginsDir); createFolder(sourcesDir); createFolder(pathToQrmcGeneratedPlugin); createFolder(pathToQrxcGeneratedPlugin); } QString MainClass::normalizedName(QString const &fileName) { QString normalizedName = fileName; if (fileName.contains("/")) { QStringList splittedName = normalizedName.split("/"); normalizedName = splittedName.last(); } if (normalizedName.contains(".qrs")) { normalizedName.chop(4); } return normalizedName; } void MainClass::deleteOldBinaries(QString const &directory) { QDir dir(directory); if (!dir.exists()) { return; } foreach (QFileInfo const &fileInfo, dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)) { if (fileInfo.isDir()) { deleteOldBinaries(fileInfo.filePath()); dir.rmdir(fileInfo.fileName()); } else { dir.remove(fileInfo.fileName()); } } } void MainClass::copyTestMetamodel(QString const &fileName) { QString const workingDirName = pathToTestMetamodel; QDir sourceDir(workingDirName); QFileInfo const destDirInfo; QDir destDir = destDirInfo.dir(); QFile::copy(sourceDir.absolutePath() + "/" + fileName, destDir.absolutePath() + "/" + fileName); } void MainClass::setTempValueInSettingsManager() { mApplicationPath.chop(4); SettingsManager::setValue("temp", mApplicationPath + tempValueForSettingsManager); } void MainClass::returnOldValueOfTemp() const { SettingsManager::setValue("temp", mTempOldValue); } void MainClass::launchQrmc(QString const &fileName, QString const &pathToQrmc) { mQrmcLauncher.launchQrmc(fileName, pathToQrmc); } void MainClass::compilePlugin(QString const &directoryToCodeToCompile) { mPluginCompiler.compilePlugin( directoryToCodeToCompile , mQmakeParameter , mMakeParameter , mConfigurationParameter ); } void MainClass::launchQrxc(QString const &fileName) { mQrxcLauncher.launchQrxc(fileName, mApplicationPath); } EditorInterface* MainClass::loadedPlugin(QString const &fileName, QString const &pathToFile) { return mPluginLoader.loadedPlugin(fileName, pathToFile, mPluginExtension, mPrefix); } void MainClass::createHtml(QList<QPair<QString, QPair<QString, QString> > > qrxcAndQrmcResult , QList<QPair<QString, QPair<QString, QString> > > qrxcAndInterpreterResult) { mHtmlMaker.makeHtml(qrxcAndQrmcResult, qrxcAndInterpreterResult); } void MainClass::appendPluginNames() { mQrxcGeneratedPluginsList.append(mPluginLoader.pluginNames()); } void MainClass::parseConfigurationFile(const bool &travisMode) { if (travisMode) { mConfigurationFileParser.parseConfigurationFile(travisConfigurationFileName); } else { mConfigurationFileParser.parseConfigurationFile(configurationFileName); } mQmakeParameter = mConfigurationFileParser.qmakeParameter(); mMakeParameter = mConfigurationFileParser.makeParameter(); mConfigurationParameter = mConfigurationFileParser.configurationParameter(); mPluginExtension = mConfigurationFileParser.pluginExtension(); mPrefix = mConfigurationFileParser.prefix(); } <commit_msg>deletion removed<commit_after>#include "mainClass.h" #include "defs.h" #include "methodsTesterForQrxcAndQrmc.h" #include "methodsTesterForQrxcAndInterpreter.h" #include "methodsCheckerForTravis.h" #include "../../qrgui/pluginManager/interpreterEditorManager.h" #include "../../qrgui/pluginManager/editorManagerInterface.h" #include "../../qrgui/pluginManager/editorManager.h" #include "../../qrutils/xmlUtils.h" #include <QtCore/QDir> #include <QtCore/QFileInfo> using namespace qReal; using namespace editorPluginTestingFramework; using namespace qrRepo; MainClass::MainClass( QString const &fileName , QString const &pathToQrmc , QString const &applicationPath , bool const &travisMode) : mTempOldValue(SettingsManager::value("temp").toString()) , mApplicationPath(applicationPath) { setTempValueInSettingsManager(); deleteOldBinaries(binariesDir); createNewFolders(); QString const normalizedFileName = normalizedName(fileName); if (travisMode) { copyTestMetamodel(fileName); } parseConfigurationFile(travisMode); launchQrxc(normalizedFileName); compilePlugin(pathToQrxcGeneratedCode); EditorInterface* const qrxcGeneratedPlugin = loadedPlugin(normalizedFileName, pathToQrxcGeneratedPlugin); appendPluginNames(); launchQrmc(fileName, pathToQrmc); compilePlugin(pathToQrmcGeneratedCode); EditorInterface* const qrmcGeneratedPlugin = loadedPlugin(normalizedFileName, pathToQrmcGeneratedPlugin); InterpreterEditorManager interpreterEditorManager(fileName); EditorManager qrxcEditorManager(destDirForQrxc, mQrxcGeneratedPluginsList); // we cast qrxc plugin to Editor Manager MethodsTesterForQrxcAndInterpreter* const interpreterMethodsTester = new MethodsTesterForQrxcAndInterpreter( &qrxcEditorManager ,&interpreterEditorManager); QList<QPair<QString, QPair<QString, QString> > > interpreterMethodsTesterOutput = interpreterMethodsTester->generatedResult(); if ((qrxcGeneratedPlugin != NULL) && (qrmcGeneratedPlugin != NULL)) { MethodsTesterForQrxcAndQrmc* const methodsTester = new MethodsTesterForQrxcAndQrmc( qrmcGeneratedPlugin, qrxcGeneratedPlugin); QList<QPair<QString, QPair<QString, QString> > > methodsTesterOutput = methodsTester->generatedOutput(); if (!travisMode) { createHtml(methodsTesterOutput, interpreterMethodsTesterOutput); } else { mResultOfTesting = MethodsCheckerForTravis::calculateResult(methodsTesterOutput , interpreterMethodsTesterOutput); } } else { qDebug() << "Generation of plugins failed"; } returnOldValueOfTemp(); } int MainClass::travisTestResult() const { return mResultOfTesting; } void MainClass::createFolder(QString const &path) { QDir dir; if (!dir.exists(path)) { dir.mkdir(path); } } void MainClass::createNewFolders() { createFolder(binariesDir); createFolder(pluginsDir); createFolder(sourcesDir); createFolder(pathToQrmcGeneratedPlugin); createFolder(pathToQrxcGeneratedPlugin); } QString MainClass::normalizedName(QString const &fileName) { QString normalizedName = fileName; if (fileName.contains("/")) { QStringList splittedName = normalizedName.split("/"); normalizedName = splittedName.last(); } if (normalizedName.contains(".qrs")) { normalizedName.chop(4); } return normalizedName; } void MainClass::deleteOldBinaries(QString const &directory) { QDir dir(directory); if (!dir.exists()) { return; } foreach (QFileInfo const &fileInfo, dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)) { if (fileInfo.isDir()) { deleteOldBinaries(fileInfo.filePath()); dir.rmdir(fileInfo.fileName()); } else { dir.remove(fileInfo.fileName()); } } } void MainClass::copyTestMetamodel(QString const &fileName) { QString const workingDirName = pathToTestMetamodel; QDir sourceDir(workingDirName); QFileInfo const destDirInfo; QDir destDir = destDirInfo.dir(); QFile::copy(sourceDir.absolutePath() + "/" + fileName, destDir.absolutePath() + "/" + fileName); } void MainClass::setTempValueInSettingsManager() { mApplicationPath.chop(4); SettingsManager::setValue("temp", mApplicationPath + tempValueForSettingsManager); } void MainClass::returnOldValueOfTemp() const { SettingsManager::setValue("temp", mTempOldValue); } void MainClass::launchQrmc(QString const &fileName, QString const &pathToQrmc) { mQrmcLauncher.launchQrmc(fileName, pathToQrmc); } void MainClass::compilePlugin(QString const &directoryToCodeToCompile) { mPluginCompiler.compilePlugin( directoryToCodeToCompile , mQmakeParameter , mMakeParameter , mConfigurationParameter ); } void MainClass::launchQrxc(QString const &fileName) { mQrxcLauncher.launchQrxc(fileName, mApplicationPath); } EditorInterface* MainClass::loadedPlugin(QString const &fileName, QString const &pathToFile) { return mPluginLoader.loadedPlugin(fileName, pathToFile, mPluginExtension, mPrefix); } void MainClass::createHtml(QList<QPair<QString, QPair<QString, QString> > > qrxcAndQrmcResult , QList<QPair<QString, QPair<QString, QString> > > qrxcAndInterpreterResult) { mHtmlMaker.makeHtml(qrxcAndQrmcResult, qrxcAndInterpreterResult); } void MainClass::appendPluginNames() { mQrxcGeneratedPluginsList.append(mPluginLoader.pluginNames()); } void MainClass::parseConfigurationFile(const bool &travisMode) { if (travisMode) { mConfigurationFileParser.parseConfigurationFile(travisConfigurationFileName); } else { mConfigurationFileParser.parseConfigurationFile(configurationFileName); } mQmakeParameter = mConfigurationFileParser.qmakeParameter(); mMakeParameter = mConfigurationFileParser.makeParameter(); mConfigurationParameter = mConfigurationFileParser.configurationParameter(); mPluginExtension = mConfigurationFileParser.pluginExtension(); mPrefix = mConfigurationFileParser.prefix(); } <|endoftext|>
<commit_before><commit_msg>[util] VectorAccessor to be useful<commit_after>#pragma once #include <vector> namespace nova::renderer { /*! * \brief Allows one to access a thing at a location in a vector, even after the vector has been reallocated * * How this isn't in the standard library, idk */ template<typename T> class VectorAccessor { public: VectorAccessor(const std::vector<T>& vec, const std::size_t idx) : vec(vec), idx(idx) {} T* operator->() { return &vec[idx]; } private: std::vector<T>& vec; std::size_t idx; }; } <|endoftext|>
<commit_before>#define FOVY 30.0 #define ZNEAR 0.0001 #define ZFAR 10.0 #define FPS_TIME_WINDOW 1 #define MAX_DEPTH 1.0 int g_numPasses = 4; GLuint g_quadDisplayList; float g_opacity = 0.6; unsigned g_numGeoPasses = 0; float g_white[3] = { 1.0, 1.0, 1.0 }; float *g_backgroundColor = g_white; GLSLProgramObject initProgram; GLSLProgramObject peelProgram; GLSLProgramObject blendProgram; GLSLProgramObject finalProgram; //-------------------------------------------------------------------------- void BuildShaders() { initProgram.attachVertexShader(SHADER_PATH "shade_vertex.glsl"); initProgram.attachVertexShader(SHADER_PATH "front_peeling_init_vertex.glsl"); initProgram.attachFragmentShader(SHADER_PATH "shade_fragment.glsl"); initProgram.attachFragmentShader(SHADER_PATH "front_peeling_init_fragment.glsl"); initProgram.link(); peelProgram.attachVertexShader(SHADER_PATH "shade_vertex.glsl"); peelProgram.attachVertexShader(SHADER_PATH "front_peeling_peel_vertex.glsl"); peelProgram.attachFragmentShader(SHADER_PATH "shade_fragment.glsl"); peelProgram.attachFragmentShader(SHADER_PATH "front_peeling_peel_fragment.glsl"); peelProgram.link(); blendProgram.attachVertexShader(SHADER_PATH "front_peeling_blend_vertex.glsl"); blendProgram.attachFragmentShader(SHADER_PATH "front_peeling_blend_fragment.glsl"); blendProgram.link(); finalProgram.attachVertexShader(SHADER_PATH "front_peeling_final_vertex.glsl"); finalProgram.attachFragmentShader(SHADER_PATH "front_peeling_final_fragment.glsl"); finalProgram.link(); } //-------------------------------------------------------------------------- void DestroyShaders() { initProgram.destroy(); peelProgram.destroy(); blendProgram.destroy(); finalProgram.destroy(); } //-------------------------------------------------------------------------- void RenderFrontToBackPeeling() { // --------------------------------------------------------------------- // 1. Initialize Min Depth Buffer // --------------------------------------------------------------------- glBindFramebuffer(GL_FRAMEBUFFER, blenderFBO); glDrawBuffer(drawBufferIndexes[0]); glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); initProgram.bind(); initProgram.setUniform("Alpha", (float*)&g_opacity, 1); DrawModel(); initProgram.unbind(); CHECK_GL_ERRORS; // --------------------------------------------------------------------- // 2. Depth Peeling + Blending // --------------------------------------------------------------------- int numLayers = (g_numPasses - 1) * 2; for (int layer = 1; g_useOQ || layer < numLayers; layer++) { int currId = layer % 2; int prevId = 1 - currId; glBindFramebuffer(GL_FRAMEBUFFER, FBOs[currId]); glDrawBuffer(drawBufferIndexes[0]); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); if (g_useOQ) { glBeginQuery(GL_SAMPLES_PASSED, g_queryId); } peelProgram.bind(); peelProgram.bindTextureRECT("DepthTex", depthTextures[prevId], 0); peelProgram.setUniform("Alpha", (float*)&g_opacity, 1); DrawModel(); peelProgram.unbind(); if (g_useOQ) { glEndQuery(GL_SAMPLES_PASSED); } CHECK_GL_ERRORS; glBindFramebuffer(GL_FRAMEBUFFER, blenderFBO); glDrawBuffer(drawBufferIndexes[0]); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFuncSeparate(GL_DST_ALPHA, GL_ONE, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA); blendProgram.bind(); blendProgram.bindTextureRECT("TempTex", colorTextures[currId], 0); glCallList(g_quadDisplayList); blendProgram.unbind(); glDisable(GL_BLEND); CHECK_GL_ERRORS; if (g_useOQ) { GLuint sample_count; glGetQueryObjectuiv(g_queryId, GL_QUERY_RESULT, &sample_count); if (sample_count == 0) { break; } } } // --------------------------------------------------------------------- // 3. Final Pass // --------------------------------------------------------------------- glBindFramebuffer(GL_FRAMEBUFFER, 0); glDrawBuffer(GL_BACK); glDisable(GL_DEPTH_TEST); finalProgram.bind(); finalProgram.setUniform("BackgroundColor", g_backgroundColor, 3); finalProgram.bindTextureRECT("ColorTex", blenderTexture, 0); glCallList(g_quadDisplayList); finalProgram.unbind(); CHECK_GL_ERRORS; } //-------------------------------------------------------------------------- void MakeFullScreenQuad() { g_quadDisplayList = glGenLists(1); glNewList(g_quadDisplayList, GL_COMPILE); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0.0, 1.0, 0.0, 1.0); glBegin(GL_QUADS); { glVertex2f(0.0, 0.0); glVertex2f(1.0, 0.0); glVertex2f(1.0, 1.0); glVertex2f(0.0, 1.0); } glEnd(); glPopMatrix(); glEndList(); } GLuint FBOs[2]; GLuint colorTextures[2]; GLuint depthTextures[2]; GLuint blenderFBO; GLuint blenderTexture; GLenum drawBufferIndexes[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3, GL_COLOR_ATTACHMENT4, GL_COLOR_ATTACHMENT5, GL_COLOR_ATTACHMENT6 }; //-------------------------------------------------------------------------- void InitFrontPeelingRenderTargets(int width, int height) { glGenTextures(2, depthTextures); glGenTextures(2, colorTextures); glGenFramebuffers(2, FBOs); for (int i = 0; i < 2; i++) { glBindTexture(TextureRect, depthTextures[i]); glTexParameteri(TextureRect, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(TextureRect, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(TextureRect, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(TextureRect, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(TextureRect, 0, GL_DEPTH_COMPONENT32F_NV, width, width, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glBindTexture(TextureRect, colorTextures[i]); glTexParameteri(TextureRect, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(TextureRect, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(TextureRect, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(TextureRect, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(TextureRect, 0, GL_RGBA, width, width, 0, GL_RGBA, GL_FLOAT, 0); glBindFramebuffer(GL_FRAMEBUFFER, FBOs[i]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, TextureRect, depthTextures[i], 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, TextureRect, colorTextures[i], 0); } // init front blender fbo. glGenTextures(1, &blenderTexture); glBindTexture(TextureRect, blenderTexture); glTexParameteri(TextureRect, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(TextureRect, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(TextureRect, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(TextureRect, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(TextureRect, 0, GL_RGBA, width, width, 0, GL_RGBA, GL_FLOAT, 0); glGenFramebuffers(1, &blenderFBO); glBindFramebuffer(GL_FRAMEBUFFER, blenderFBO); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, TextureRect, depthTextures[0], 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, TextureRect, blenderTexture, 0); CHECK_GL_ERRORS; } <commit_msg>update<commit_after>#define FOVY 30.0 #define ZNEAR 0.0001 #define ZFAR 10.0 #define FPS_TIME_WINDOW 1 #define MAX_DEPTH 1.0 int g_numPasses = 4; GLuint g_quadDisplayList; float g_opacity = 0.6; unsigned g_numGeoPasses = 0; float g_white[3] = { 1.0, 1.0, 1.0 }; float *g_backgroundColor = g_white; GLSLProgramObject initProgram; GLSLProgramObject peelProgram; GLSLProgramObject blendProgram; GLSLProgramObject finalProgram; //-------------------------------------------------------------------------- void BuildShaders() { initProgram.attachVertexShader(SHADER_PATH "shade_vertex.glsl"); initProgram.attachVertexShader(SHADER_PATH "front_peeling_init_vertex.glsl"); initProgram.attachFragmentShader(SHADER_PATH "shade_fragment.glsl"); initProgram.attachFragmentShader(SHADER_PATH "front_peeling_init_fragment.glsl"); initProgram.link(); peelProgram.attachVertexShader(SHADER_PATH "shade_vertex.glsl"); peelProgram.attachVertexShader(SHADER_PATH "front_peeling_peel_vertex.glsl"); peelProgram.attachFragmentShader(SHADER_PATH "shade_fragment.glsl"); peelProgram.attachFragmentShader(SHADER_PATH "front_peeling_peel_fragment.glsl"); peelProgram.link(); blendProgram.attachVertexShader(SHADER_PATH "front_peeling_blend_vertex.glsl"); blendProgram.attachFragmentShader(SHADER_PATH "front_peeling_blend_fragment.glsl"); blendProgram.link(); finalProgram.attachVertexShader(SHADER_PATH "front_peeling_final_vertex.glsl"); finalProgram.attachFragmentShader(SHADER_PATH "front_peeling_final_fragment.glsl"); finalProgram.link(); } //-------------------------------------------------------------------------- void DestroyShaders() { initProgram.destroy(); peelProgram.destroy(); blendProgram.destroy(); finalProgram.destroy(); } //-------------------------------------------------------------------------- void RenderFrontToBackPeeling() { // --------------------------------------------------------------------- // 1. Initialize Min Depth Buffer // --------------------------------------------------------------------- glBindFramebuffer(GL_FRAMEBUFFER, blenderFBO); glDrawBuffer(drawBufferIndexes[0]); glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); initProgram.bind(); initProgram.setUniform("Alpha", (float*)&g_opacity, 1); DrawModel(); initProgram.unbind(); CHECK_GL_ERRORS; // --------------------------------------------------------------------- // 2. Depth Peeling + Blending // --------------------------------------------------------------------- int numLayers = (g_numPasses - 1) * 2; for (int layer = 1; g_useOQ || layer < numLayers; layer++) { int currId = layer % 2; int prevId = 1 - currId; glBindFramebuffer(GL_FRAMEBUFFER, FBOs[currId]); glDrawBuffer(drawBufferIndexes[0]); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); if (g_useOQ) { glBeginQuery(GL_SAMPLES_PASSED, g_queryId); } peelProgram.bind(); peelProgram.bindTextureRECT("DepthTex", depthTextures[prevId], 0); peelProgram.setUniform("Alpha", (float*)&g_opacity, 1); DrawModel(); peelProgram.unbind(); if (g_useOQ) { glEndQuery(GL_SAMPLES_PASSED); } CHECK_GL_ERRORS; glBindFramebuffer(GL_FRAMEBUFFER, blenderFBO); glDrawBuffer(drawBufferIndexes[0]); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFuncSeparate(GL_DST_ALPHA, GL_ONE, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA); blendProgram.bind(); blendProgram.bindTextureRECT("TempTex", colorTextures[currId], 0); glCallList(g_quadDisplayList); blendProgram.unbind(); glDisable(GL_BLEND); CHECK_GL_ERRORS; if (g_useOQ) { GLuint sample_count; glGetQueryObjectuiv(g_queryId, GL_QUERY_RESULT, &sample_count); if (sample_count == 0) { break; } } } // --------------------------------------------------------------------- // 3. Final Pass // --------------------------------------------------------------------- glBindFramebuffer(GL_FRAMEBUFFER, 0); glDrawBuffer(GL_BACK); glDisable(GL_DEPTH_TEST); finalProgram.bind(); finalProgram.setUniform("BackgroundColor", g_backgroundColor, 3); finalProgram.bindTextureRECT("ColorTex", blenderTexture, 0); glCallList(g_quadDisplayList); finalProgram.unbind(); CHECK_GL_ERRORS; } //-------------------------------------------------------------------------- void MakeFullScreenQuad() { g_quadDisplayList = glGenLists(1); glNewList(g_quadDisplayList, GL_COMPILE); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0.0, 1.0, 0.0, 1.0); glBegin(GL_QUADS); { glVertex2f(0.0, 0.0); glVertex2f(1.0, 0.0); glVertex2f(1.0, 1.0); glVertex2f(0.0, 1.0); } glEnd(); glPopMatrix(); glEndList(); } GLuint FBOs[2]; GLuint colorTextures[2]; GLuint depthTextures[2]; GLuint blenderFBO; GLuint blenderTexture; GLenum drawBufferIndexes[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3, GL_COLOR_ATTACHMENT4, GL_COLOR_ATTACHMENT5, GL_COLOR_ATTACHMENT6 }; //-------------------------------------------------------------------------- void InitFrontPeelingRenderTargets(int width, int height) { glGenTextures(2, depthTextures); glGenTextures(2, colorTextures); glGenFramebuffers(2, FBOs); for (int i = 0; i < 2; i++) { glBindTexture(TextureRect, depthTextures[i]); glTexParameteri(TextureRect, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(TextureRect, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(TextureRect, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(TextureRect, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(TextureRect, 0, GL_DEPTH_COMPONENT32F_NV, width, width, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glBindTexture(TextureRect, colorTextures[i]); glTexParameteri(TextureRect, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(TextureRect, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(TextureRect, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(TextureRect, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(TextureRect, 0, GL_RGBA, width, width, 0, GL_RGBA, GL_FLOAT, 0); glBindFramebuffer(GL_FRAMEBUFFER, FBOs[i]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, TextureRect, depthTextures[i], 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, TextureRect, colorTextures[i], 0); } // init front blender fbo. glGenTextures(1, &blenderTexture); glBindTexture(TextureRect, blenderTexture); glTexParameteri(TextureRect, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(TextureRect, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(TextureRect, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(TextureRect, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(TextureRect, 0, GL_RGBA, width, width, 0, GL_RGBA, GL_FLOAT, 0); glGenFramebuffers(1, &blenderFBO); glBindFramebuffer(GL_FRAMEBUFFER, blenderFBO); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, TextureRect, depthTextures[0], 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, TextureRect, blenderTexture, 0); CHECK_GL_ERRORS; } <|endoftext|>
<commit_before>#include "Player.h" #include <SFML/Graphics.hpp> #include <cstdint> #include "../Maths/General_Maths.h" #include "../World/Block/D_Blocks.h" #include "../World/Chunk/Chunk_Map.h" #include "../Util/Debug_Display.h" #include "../Util/Display.h" #include "../Input/Key_Binds.h" Player::Player() : m_p_heldBlock (&Block::grass) { m_camera.position = {20000, 250, 20000}; Debug_Display::addheldBlock (*m_p_heldBlock); } /** */ const Camera& Player::getCamera() const { return m_camera; } /** */ void Player::setPosition(const Vector3& position) { m_camera.position = position; } void Player::input (const sf::Event& e) { if (e.type == sf::Event::KeyPressed) { if (e.key.code == sf::Keyboard::Left) changeBlock(-1); if (e.key.code == sf::Keyboard::Right) changeBlock(1); } } void Player::input() { m_velocity += m_camera.keyboardInput(SPEED); m_camera.mouseInput(); } void Player::update(float dt, Camera& camera, Chunk_Map& chunkMap) { if (!m_isOnGround) m_velocity.y -= 10 * dt; collision(chunkMap, dt); m_camera.position += m_velocity * dt; m_velocity *= 0.95; camera = m_camera; Debug_Display::addLookVector(camera.rotation); Debug_Display::addheldBlock (*m_p_heldBlock); } const Block::Block_Type& Player::getBlock() const { return *m_p_heldBlock; } void Player::changeBlock(int increment) { constexpr static auto BLOCK_TYPES = (uint32_t)(Block::ID::NUM_BLOCK_TYPES); auto currId = (uint32_t)(m_p_heldBlock->getData().getID()); currId += increment; //Seeing as "0" is an air block, we just skip over it if (currId == 0) currId = BLOCK_TYPES - 1; else if (currId == BLOCK_TYPES) currId = 1; auto* newBlock = &Block::get(static_cast<Block::ID>(currId)); //We don't want to place liquid and gas as blocks, so skip. if (newBlock->getData().getPhysicalState() == Block::Physical_State::Liquid || newBlock->getData().getPhysicalState() == Block::Physical_State::Gas) { currId += increment; } m_p_heldBlock = &Block::get(static_cast<Block::ID>(currId)); } <commit_msg>Shameless quick fix<commit_after>#include "Player.h" #include <SFML/Graphics.hpp> #include <cstdint> #include "../Maths/General_Maths.h" #include "../World/Block/D_Blocks.h" #include "../World/Chunk/Chunk_Map.h" #include "../Util/Debug_Display.h" #include "../Util/Display.h" #include "../Input/Key_Binds.h" Player::Player() : m_p_heldBlock (&Block::grass) { m_camera.position = {20000, 250, 20000}; Debug_Display::addheldBlock (*m_p_heldBlock); } /** */ const Camera& Player::getCamera() const { return m_camera; } /** */ void Player::setPosition(const Vector3& position) { m_camera.position = position; } void Player::input (const sf::Event& e) { if (e.type == sf::Event::KeyPressed) { if (e.key.code == sf::Keyboard::Left) changeBlock(-1); if (e.key.code == sf::Keyboard::Right) changeBlock(1); } } void Player::input() { m_velocity += m_camera.keyboardInput(SPEED); m_camera.mouseInput(); } void Player::update(float dt, Camera& camera, Chunk_Map& chunkMap) { if (!m_isOnGround) m_velocity.y -= 10 * dt; m_camera.position += m_velocity * dt; m_velocity *= 0.95; camera = m_camera; Debug_Display::addLookVector(camera.rotation); Debug_Display::addheldBlock (*m_p_heldBlock); } const Block::Block_Type& Player::getBlock() const { return *m_p_heldBlock; } void Player::changeBlock(int increment) { constexpr static auto BLOCK_TYPES = (uint32_t)(Block::ID::NUM_BLOCK_TYPES); auto currId = (uint32_t)(m_p_heldBlock->getData().getID()); currId += increment; //Seeing as "0" is an air block, we just skip over it if (currId == 0) currId = BLOCK_TYPES - 1; else if (currId == BLOCK_TYPES) currId = 1; auto* newBlock = &Block::get(static_cast<Block::ID>(currId)); //We don't want to place liquid and gas as blocks, so skip. if (newBlock->getData().getPhysicalState() == Block::Physical_State::Liquid || newBlock->getData().getPhysicalState() == Block::Physical_State::Gas) { currId += increment; } m_p_heldBlock = &Block::get(static_cast<Block::ID>(currId)); } <|endoftext|>
<commit_before>#include "testing/testing.hpp" #include "indexer/data_header.hpp" #include "indexer/index.hpp" #include "indexer/classificator_loader.hpp" #include "search/locality_finder.hpp" #include "platform/country_file.hpp" #include "platform/local_country_file.hpp" #include "platform/local_country_file_utils.hpp" #include "platform/platform.hpp" #include "base/scope_guard.hpp" namespace { void doTests(search::LocalityFinder & finder, vector<m2::PointD> const & input, char const * results[]) { for (size_t i = 0; i < input.size(); ++i) { string result; finder.GetLocalityInViewport(MercatorBounds::FromLatLon(input[i].y, input[i].x), result); TEST_EQUAL(result, results[i], ()); } } void doTests2(search::LocalityFinder & finder, vector<m2::PointD> const & input, char const * results[]) { for (size_t i = 0; i < input.size(); ++i) { string result; finder.GetLocalityCreateCache(MercatorBounds::FromLatLon(input[i].y, input[i].x), result); TEST_EQUAL(result, results[i], ()); } } } UNIT_TEST(LocalityFinder) { classificator::Load(); Index index; m2::RectD rect; auto world = platform::LocalCountryFile::MakeForTesting("World"); auto cleanup = [&world]() { platform::CountryIndexes::DeleteFromDisk(world); }; MY_SCOPE_GUARD(cleanupOnExit, cleanup); cleanup(); try { auto const p = index.Register(world); TEST_EQUAL(MwmSet::RegResult::Success, p.second, ()); MwmSet::MwmId const & id = p.first; TEST(id.IsAlive(), ()); rect = id.GetInfo()->m_limitRect; } catch (RootException const & ex) { LOG(LERROR, ("Read World.mwm error:", ex.Msg())); } search::LocalityFinder finder(&index); finder.SetLanguage(StringUtf8Multilang::GetLangIndex("en")); finder.SetViewportByIndex(MercatorBounds::FullRect(), 0); vector<m2::PointD> input; input.push_back(m2::PointD(27.5433964, 53.8993094)); // Minsk input.push_back(m2::PointD(2.3521, 48.856517)); // Paris input.push_back(m2::PointD(13.3908289, 52.5193859)); // Berlin char const * results[] = { "Minsk", "Paris", "Berlin" }; // Tets one viewport based on whole map doTests(finder, input, results); // Test two viewport based on quaters of world map m2::RectD rect1; rect1.setMinX(rect.minX()); rect1.setMinY(rect.minY()); rect1.setMaxX(rect.Center().x); rect1.setMaxY(rect.Center().y); m2::RectD rect2; rect2.setMinX(rect.Center().x); rect2.setMinY(rect.Center().y); rect2.setMaxY(rect.maxY()); rect2.setMaxX(rect.maxX()); input.clear(); input.push_back(m2::PointD(-87.624367, 41.875)); // Chicago input.push_back(m2::PointD(-43.209384, -22.911225)); // Rio de Janeiro input.push_back(m2::PointD(144.96, -37.8142)); // Melbourne (Australia) input.push_back(m2::PointD(27.69341, 53.883931)); // Parkin Minsk (near MKAD) input.push_back(m2::PointD(27.707875, 53.917306)); // Lipki airport (Minsk) input.push_back(m2::PointD(18.834407, 42.285901)); // Budva (Montenegro) input.push_back(m2::PointD(12.452854, 41.903479)); // Vaticano (Rome) input.push_back(m2::PointD(8.531262, 47.3345002)); // Zurich finder.SetViewportByIndex(rect1, 0); finder.SetViewportByIndex(rect2, 1); char const * results2[] = { "", "Rio de Janeiro", "", "Minsk", "Minsk", "Budva", "Rome", "Zurich" }; doTests(finder, input, results2); finder.ClearCacheAll(); char const * results3[] = { "Chicago", "Rio de Janeiro", "Melbourne", "Minsk", "Minsk", "Budva", "Rome", "Zurich" }; doTests2(finder, input, results3); } <commit_msg>[search] Added test for correct Moscow locality checking.<commit_after>#include "testing/testing.hpp" #include "indexer/data_header.hpp" #include "indexer/index.hpp" #include "indexer/classificator_loader.hpp" #include "search/locality_finder.hpp" #include "platform/country_file.hpp" #include "platform/local_country_file.hpp" #include "platform/local_country_file_utils.hpp" #include "platform/platform.hpp" namespace { class LocalityFinderTest { platform::LocalCountryFile m_worldFile; Index m_index; search::LocalityFinder m_finder; m2::RectD m_worldRect; public: LocalityFinderTest() : m_finder(&m_index) { classificator::Load(); m_worldFile = platform::LocalCountryFile::MakeForTesting("World"); try { auto const p = m_index.Register(m_worldFile); TEST_EQUAL(MwmSet::RegResult::Success, p.second, ()); MwmSet::MwmId const & id = p.first; TEST(id.IsAlive(), ()); m_worldRect = id.GetInfo()->m_limitRect; } catch (RootException const & ex) { LOG(LERROR, ("Read World.mwm error:", ex.Msg())); } m_finder.SetLanguage(StringUtf8Multilang::GetLangIndex("en")); } ~LocalityFinderTest() { platform::CountryIndexes::DeleteFromDisk(m_worldFile); } void RunTestsViewport(vector<ms::LatLon> const & input, char const * results[]) { for (size_t i = 0; i < input.size(); ++i) { string result; m_finder.GetLocalityInViewport(MercatorBounds::FromLatLon(input[i]), result); TEST_EQUAL(result, results[i], ()); } } void RunTestsEverywhere(vector<ms::LatLon> const & input, char const * results[]) { for (size_t i = 0; i < input.size(); ++i) { string result; m_finder.GetLocalityCreateCache(MercatorBounds::FromLatLon(input[i]), result); TEST_EQUAL(result, results[i], ()); } } m2::RectD const & GetWorldRect() const { return m_worldRect; } void SetViewportByIndex(m2::RectD const & viewport, size_t ind) { m_finder.SetViewportByIndex(viewport, ind); } void ClearCaches() { m_finder.ClearCacheAll(); } }; } // namespace /* UNIT_CLASS_TEST(LocalityFinderTest, Smoke) { m2::RectD const & rect = GetWorldRect(); SetViewportByIndex(rect, 0); vector<ms::LatLon> input; input.emplace_back(53.8993094, 27.5433964); // Minsk input.emplace_back(48.856517, 2.3521); // Paris input.emplace_back(52.5193859, 13.3908289); // Berlin char const * results[] = { "Minsk", "Paris", "Berlin" }; // Tets one viewport based on whole map RunTestsViewport(input, results); // Test two viewport based on quaters of world map m2::RectD rect1; rect1.setMinX(rect.minX()); rect1.setMinY(rect.minY()); rect1.setMaxX(rect.Center().x); rect1.setMaxY(rect.Center().y); m2::RectD rect2; rect2.setMinX(rect.Center().x); rect2.setMinY(rect.Center().y); rect2.setMaxY(rect.maxY()); rect2.setMaxX(rect.maxX()); input.clear(); input.emplace_back(41.875, -87.624367); // Chicago input.emplace_back(-22.911225, -43.209384); // Rio de Janeiro input.emplace_back(-37.8142, 144.96); // Melbourne (Australia) input.emplace_back(53.883931, 27.69341); // Parkin Minsk (near MKAD) input.emplace_back(53.917306, 27.707875); // Lipki airport (Minsk) input.emplace_back(42.285901, 18.834407); // Budva (Montenegro) input.emplace_back(41.903479, 12.452854); // Vaticano (Rome) input.emplace_back(47.3345002, 8.531262); // Zurich SetViewportByIndex(rect1, 0); SetViewportByIndex(rect2, 1); char const * results2[] = { "", "Rio de Janeiro", "", "Minsk", "Minsk", "Budva", "Rome", "Zurich" }; RunTestsViewport(input, results2); ClearCaches(); char const * results3[] = { "Chicago", "Rio de Janeiro", "Melbourne", "Minsk", "Minsk", "Budva", "Rome", "Zurich" }; RunTestsEverywhere(input, results3); } */ UNIT_CLASS_TEST(LocalityFinderTest, Moscow) { vector<ms::LatLon> input; input.emplace_back(55.80166, 37.54066); // Krasnoarmeyskaya 30 char const * results[] = { "Moscow" }; RunTestsEverywhere(input, results); } <|endoftext|>
<commit_before>#include "testing/testing.hpp" #include "indexer/data_header.hpp" #include "indexer/index.hpp" #include "indexer/classificator_loader.hpp" #include "search/categories_cache.hpp" #include "search/locality_finder.hpp" #include "platform/country_file.hpp" #include "platform/local_country_file.hpp" #include "platform/local_country_file_utils.hpp" #include "platform/platform.hpp" #include "base/cancellable.hpp" namespace { struct TestWithClassificator { TestWithClassificator() { classificator::Load(); } }; class LocalityFinderTest : public TestWithClassificator { platform::LocalCountryFile m_worldFile; Index m_index; my::Cancellable m_cancellable; search::VillagesCache m_villagesCache; search::LocalityFinder m_finder; m2::RectD m_worldRect; public: LocalityFinderTest() : m_villagesCache(m_cancellable), m_finder(m_index, m_villagesCache) { m_worldFile = platform::LocalCountryFile::MakeForTesting("World"); try { auto const p = m_index.Register(m_worldFile); TEST_EQUAL(MwmSet::RegResult::Success, p.second, ()); MwmSet::MwmId const & id = p.first; TEST(id.IsAlive(), ()); m_worldRect = id.GetInfo()->m_limitRect; } catch (RootException const & ex) { LOG(LERROR, ("Read World.mwm error:", ex.Msg())); } m_finder.SetLanguage(StringUtf8Multilang::kEnglishCode); } ~LocalityFinderTest() { platform::CountryIndexes::DeleteFromDisk(m_worldFile); } void RunTests(vector<ms::LatLon> const & input, char const * results[]) { for (size_t i = 0; i < input.size(); ++i) { string result; m_finder.GetLocality(MercatorBounds::FromLatLon(input[i]), result); TEST_EQUAL(result, results[i], ()); } } m2::RectD const & GetWorldRect() const { return m_worldRect; } void ClearCaches() { m_finder.ClearCache(); } }; } // namespace UNIT_CLASS_TEST(LocalityFinderTest, Smoke) { vector<ms::LatLon> input; input.emplace_back(53.8993094, 27.5433964); // Minsk input.emplace_back(48.856517, 2.3521); // Paris input.emplace_back(52.5193859, 13.3908289); // Berlin char const * results[] = { "Minsk", "Paris", "Berlin" }; RunTests(input, results); ClearCaches(); input.clear(); input.emplace_back(41.875, -87.624367); // Chicago input.emplace_back(-22.911225, -43.209384); // Rio de Janeiro input.emplace_back(-37.8142, 144.96); // Melbourne (Australia) input.emplace_back(53.883931, 27.69341); // Parking Minsk (near MKAD) input.emplace_back(53.917306, 27.707875); // Lipki airport (Minsk) input.emplace_back(42.285901, 18.834407); // Budva (Montenegro) input.emplace_back(41.903479, 12.452854); // Vaticano (Rome) input.emplace_back(47.3345002, 8.531262); // Zurich char const * results3[] = { "Chicago", "Rio de Janeiro", "Melbourne", "Minsk", "Minsk", "Budva", "Vatican City", "Zurich" }; RunTests(input, results3); } UNIT_CLASS_TEST(LocalityFinderTest, Moscow) { vector<ms::LatLon> input; input.emplace_back(55.80166, 37.54066); // Krasnoarmeyskaya 30 char const * results[] = { "Moscow" }; RunTests(input, results); } <commit_msg>Replaced Vatican City back to Rome<commit_after>#include "testing/testing.hpp" #include "indexer/data_header.hpp" #include "indexer/index.hpp" #include "indexer/classificator_loader.hpp" #include "search/categories_cache.hpp" #include "search/locality_finder.hpp" #include "platform/country_file.hpp" #include "platform/local_country_file.hpp" #include "platform/local_country_file_utils.hpp" #include "platform/platform.hpp" #include "base/cancellable.hpp" namespace { struct TestWithClassificator { TestWithClassificator() { classificator::Load(); } }; class LocalityFinderTest : public TestWithClassificator { platform::LocalCountryFile m_worldFile; Index m_index; my::Cancellable m_cancellable; search::VillagesCache m_villagesCache; search::LocalityFinder m_finder; m2::RectD m_worldRect; public: LocalityFinderTest() : m_villagesCache(m_cancellable), m_finder(m_index, m_villagesCache) { m_worldFile = platform::LocalCountryFile::MakeForTesting("World"); try { auto const p = m_index.Register(m_worldFile); TEST_EQUAL(MwmSet::RegResult::Success, p.second, ()); MwmSet::MwmId const & id = p.first; TEST(id.IsAlive(), ()); m_worldRect = id.GetInfo()->m_limitRect; } catch (RootException const & ex) { LOG(LERROR, ("Read World.mwm error:", ex.Msg())); } m_finder.SetLanguage(StringUtf8Multilang::kEnglishCode); } ~LocalityFinderTest() { platform::CountryIndexes::DeleteFromDisk(m_worldFile); } void RunTests(vector<ms::LatLon> const & input, char const * results[]) { for (size_t i = 0; i < input.size(); ++i) { string result; m_finder.GetLocality(MercatorBounds::FromLatLon(input[i]), result); TEST_EQUAL(result, results[i], ()); } } m2::RectD const & GetWorldRect() const { return m_worldRect; } void ClearCaches() { m_finder.ClearCache(); } }; } // namespace UNIT_CLASS_TEST(LocalityFinderTest, Smoke) { vector<ms::LatLon> input; input.emplace_back(53.8993094, 27.5433964); // Minsk input.emplace_back(48.856517, 2.3521); // Paris input.emplace_back(52.5193859, 13.3908289); // Berlin char const * results[] = { "Minsk", "Paris", "Berlin" }; RunTests(input, results); ClearCaches(); input.clear(); input.emplace_back(41.875, -87.624367); // Chicago input.emplace_back(-22.911225, -43.209384); // Rio de Janeiro input.emplace_back(-37.8142, 144.96); // Melbourne (Australia) input.emplace_back(53.883931, 27.69341); // Parking Minsk (near MKAD) input.emplace_back(53.917306, 27.707875); // Lipki airport (Minsk) input.emplace_back(42.285901, 18.834407); // Budva (Montenegro) input.emplace_back(43.9363996, 12.4466991); // City of San Marino input.emplace_back(47.3345002, 8.531262); // Zurich char const * results3[] = { "Chicago", "Rio de Janeiro", "Melbourne", "Minsk", "Minsk", "Budva", "City of San Marino", "Zurich" }; RunTests(input, results3); } UNIT_CLASS_TEST(LocalityFinderTest, Moscow) { vector<ms::LatLon> input; input.emplace_back(55.80166, 37.54066); // Krasnoarmeyskaya 30 char const * results[] = { "Moscow" }; RunTests(input, results); } <|endoftext|>
<commit_before>/* * despot1hifi.cpp * * Created by Tobias Wood on 17/10/2011. * Copyright (c) 2011-2013 Tobias Wood. * * Based on code by Sean Deoni * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <iostream> #include <Eigen/Dense> #include "ceres/ceres.h" #include "QI/Util.h" #include "QI/Sequences/Sequences.h" #include "QI/Args.h" #include "QI/IO.h" #include "Filters/ApplyAlgorithmFilter.h" class SPGRCost : public ceres::CostFunction { protected: const QI::SPGRSimple &m_seq; const Eigen::ArrayXd m_data; public: SPGRCost(const QI::SPGRSimple &s, const Eigen::ArrayXd &data) : m_seq(s), m_data(data) { mutable_parameter_block_sizes()->push_back(3); set_num_residuals(data.size()); } virtual bool Evaluate(double const* const* p, double* resids, double** jacobians) const override { const double &M0 = p[0][0]; const double &T1 = p[0][1]; const double &B1 = p[0][2]; const Eigen::ArrayXd sa = sin(B1 * m_seq.m_flip); const Eigen::ArrayXd ca = cos(B1 * m_seq.m_flip); const double E1 = exp(-m_seq.m_TR / T1); const Eigen::ArrayXd denom = (1.-E1*ca); Eigen::Map<Eigen::ArrayXd> r(resids, m_data.size()); r = M0*sa*(1-E1)/denom - m_data; // std::cout << "SPGR RESIDS" << std::endl; // std::cout << r.transpose() << std::endl; if (jacobians && jacobians[0]) { Eigen::Map<Eigen::Matrix<double, -1, -1, Eigen::RowMajor>> j(jacobians[0], m_data.size(), 3); j.col(0) = (1-E1)*sa/denom; j.col(1) = E1*M0*m_seq.m_TR*(ca-1.)*sa/((denom*T1).square()); j.col(2) = M0*m_seq.m_flip*(1.-E1)*(ca-E1)/denom.square(); } return true; } }; // Use AutoDiff for this class IRCostFunction { protected: const QI::MPRAGE &m_seq; const Eigen::ArrayXd m_data; public: IRCostFunction(const QI::MPRAGE &s, const Eigen::ArrayXd &data) : m_seq(s), m_data(data) { } template<typename T> bool operator() (const T* const p1, T* r) const { const T &M0 = p1[0]; const T &T1 = p1[1]; const T &B1 = p1[2]; const double eta = -1.0; // Inversion efficiency defined as -1 < eta < 0 const double TIs = m_seq.m_TI[0] - m_seq.m_TR*m_seq.m_Nk0; // Adjust TI for k0 const T T1s = 1. / (1./T1 - log(cos(m_seq.m_flip[0] * B1))/m_seq.m_TR); const T M0s = M0 * (1. - exp(-m_seq.m_TR/T1)) / (1. - exp(-m_seq.m_TR/T1s)); const T A_1 = M0s*(1. - exp(-(m_seq.m_Nseg*m_seq.m_TR)/T1s)); const T A_2 = M0*(1. - exp(-m_seq.m_TD[0]/T1)); const T A_3 = M0*(1. - exp(-TIs/T1)); const T B_1 = exp(-(m_seq.m_Nseg*m_seq.m_TR)/T1s); const T B_2 = exp(-m_seq.m_TD[0]/T1); const T B_3 = eta*exp(-TIs/T1); const T A = A_3 + A_2*B_3 + A_1*B_2*B_3; const T B = B_1*B_2*B_3; const T M1 = A / (1. - B); r[0] = m_data[0] - (M0s + (M1 - M0s)*exp(-(m_seq.m_Nk0*m_seq.m_TR)/T1s)) * sin(m_seq.m_flip[0] * B1); return true; } }; class HIFIAlgo : public QI::ApplyF::Algorithm { private: const QI::SPGRSimple &m_spgr; const QI::MPRAGE &m_mprage; double m_lo = 0; double m_hi = std::numeric_limits<double>::infinity(); public: HIFIAlgo(const QI::SPGRSimple &s, const QI::MPRAGE &m, const float hi) : m_spgr(s), m_mprage(m), m_hi(hi) {} size_t numInputs() const override { return 2; } size_t numConsts() const override { return 0; } size_t numOutputs() const override { return 3; } size_t dataSize() const override { return m_spgr.size() + m_mprage.size(); } const float &zero(const size_t i) const override { static float zero = 0; return zero; } virtual std::vector<float> defaultConsts() const override { // No constants for HIFI std::vector<float> def(0); return def; } virtual bool apply(const std::vector<TInput> &inputs, const std::vector<TConst> &, // No constants, remove name to silence compiler warnings std::vector<TOutput> &outputs, TConst &residual, TInput &resids, TIters &its) const override { Eigen::Map<const Eigen::ArrayXf> spgr_in(inputs[0].GetDataPointer(), inputs[0].Size()); Eigen::Map<const Eigen::ArrayXf> ir_in(inputs[1].GetDataPointer(), inputs[1].Size()); double scale = std::max(spgr_in.maxCoeff(), ir_in.maxCoeff()); const Eigen::ArrayXd spgr_data = spgr_in.cast<double>() / scale; const Eigen::ArrayXd ir_data = ir_in.cast<double>() / scale; double spgr_pars[] = {10., 1., 1.}; // PD, T1, B1 ceres::Problem problem; problem.AddResidualBlock(new SPGRCost(m_spgr, spgr_data), NULL, spgr_pars); ceres::CostFunction *IRCost = new ceres::AutoDiffCostFunction<IRCostFunction, 1, 3>(new IRCostFunction(m_mprage, ir_data)); problem.AddResidualBlock(IRCost, NULL, spgr_pars); problem.SetParameterLowerBound(spgr_pars, 0, 1.); problem.SetParameterLowerBound(spgr_pars, 1, 0.001); problem.SetParameterUpperBound(spgr_pars, 1, 5.0); problem.SetParameterLowerBound(spgr_pars, 2, 0.1); problem.SetParameterUpperBound(spgr_pars, 2, 2.0); ceres::Solver::Options options; ceres::Solver::Summary summary; options.max_num_iterations = 50; options.function_tolerance = 1e-5; options.gradient_tolerance = 1e-6; options.parameter_tolerance = 1e-4; // options.check_gradients = true; options.logging_type = ceres::SILENT; // std::cout << "START P: " << p.transpose() << std::endl; ceres::Solve(options, &problem, &summary); outputs[0] = spgr_pars[0] * scale; outputs[1] = QI::Clamp(spgr_pars[1], m_lo, m_hi); outputs[2] = spgr_pars[2]; if (!summary.IsSolutionUsable()) { std::cout << summary.FullReport() << std::endl; } its = summary.iterations.size(); residual = summary.final_cost * scale; if (resids.Size() > 0) { assert(resids.Size() == data.size()); std::vector<double> r_temp(spgr_data.size() + 1); problem.Evaluate(ceres::Problem::EvaluateOptions(), NULL, &r_temp, NULL, NULL); for (int i = 0; i < r_temp.size(); i++) { resids[i] = r_temp[i]; } } return true; } }; //****************************************************************************** // Main //****************************************************************************** int main(int argc, char **argv) { Eigen::initParallel(); args::ArgumentParser parser("Calculates T1 and B1 maps from SPGR & IR-SPGR or MP-RAGE data.\nhttp://github.com/spinicist/QUIT"); args::Positional<std::string> spgr_path(parser, "SPGR_FILE", "Input SPGR file"); args::Positional<std::string> ir_path(parser, "IRSPGR_FILE", "Input IR-SPGR or MP-RAGE file"); args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"}); args::Flag verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"}); args::Flag noprompt(parser, "NOPROMPT", "Suppress input prompts", {'n', "no-prompt"}); args::Flag mprage(parser, "MPRAGE", "2nd image is a generic MP-RAGE, not a GE IR-SPGR", {'M', "mprage"}); args::Flag all_resids(parser, "ALL RESIDUALS", "Output individual residuals in addition to the Sum-of-Squares", {'r',"resids"}); args::ValueFlag<float> clamp(parser, "CLAMP", "Clamp output T1 values to this value", {'c', "clamp"}, std::numeric_limits<float>::infinity()); args::ValueFlag<int> threads(parser, "THREADS", "Use N threads (default=4, 0=hardware limit)", {'T', "threads"}, 4); args::ValueFlag<std::string> outarg(parser, "OUTPREFIX", "Add a prefix to output filenames", {'o', "out"}); args::ValueFlag<std::string> mask(parser, "MASK", "Only process voxels within the mask", {'m', "mask"}); args::ValueFlag<std::string> subregion(parser, "SUBREGION", "Process subregion starting at voxel I,J,K with size SI,SJ,SK", {'s', "subregion"}); args::Flag resids(parser, "RESIDS", "Write out residuals for each data-point", {'r', "resids"}); QI::ParseArgs(parser, argc, argv); bool prompt = !noprompt; if (verbose) std::cout << "Reading SPGR file: " << QI::CheckPos(spgr_path) << std::endl; auto spgrImg = QI::ReadVectorImage(QI::CheckPos(spgr_path)); if (verbose) std::cout << "Reading " << (mprage ? "MPRAGE" : "IR-SPGR") << " file: " << QI::CheckPos(ir_path) << std::endl; auto irImg = QI::ReadVectorImage(QI::CheckPos(ir_path)); const QI::SPGRSimple *spgr_sequence = new QI::SPGRSimple(std::cin, prompt); const QI::MPRAGE *ir_sequence = mprage ? new QI::MPRAGE(std::cin, prompt) : new QI::IRSPGR(std::cin, prompt); if (verbose) std::cout << *spgr_sequence << std::endl << *ir_sequence << std::endl; auto apply = QI::ApplyF::New(); auto hifi = std::make_shared<HIFIAlgo>(*spgr_sequence, *ir_sequence, clamp.Get()); apply->SetAlgorithm(hifi); apply->SetOutputAllResiduals(all_resids); apply->SetPoolsize(threads.Get()); apply->SetSplitsPerThread(threads.Get()); apply->SetVerbose(verbose); apply->SetInput(0, spgrImg); apply->SetInput(1, irImg); if (subregion) apply->SetSubregion(QI::RegionOpt(args::get(subregion))); if (mask) apply->SetMask(QI::ReadImage(mask.Get())); if (verbose) std::cout << "Processing..." << std::endl; apply->Update(); if (verbose) { std::cout << "Elapsed time was " << apply->GetTotalTime() << "s" << std::endl; std::cout << "Writing results files." << std::endl; } std::string out_prefix = args::get(outarg) + "HIFI_"; QI::WriteImage(apply->GetOutput(0), out_prefix + "PD" + QI::OutExt()); QI::WriteImage(apply->GetOutput(1), out_prefix + "T1" + QI::OutExt()); QI::WriteImage(apply->GetOutput(2), out_prefix + "B1" + QI::OutExt()); QI::WriteScaledImage(apply->GetResidualOutput(), apply->GetOutput(0), out_prefix + "residual" + QI::OutExt()); if (all_resids) { QI::WriteVectorImage(apply->GetAllResidualsOutput(), out_prefix + "all_residuals" + QI::OutExt()); } if (verbose) std::cout << "Finished." << std::endl; return EXIT_SUCCESS; } <commit_msg>BUG: Changed RegionOpt to RegionArg<commit_after>/* * despot1hifi.cpp * * Created by Tobias Wood on 17/10/2011. * Copyright (c) 2011-2013 Tobias Wood. * * Based on code by Sean Deoni * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <iostream> #include <Eigen/Dense> #include "ceres/ceres.h" #include "QI/Util.h" #include "QI/Sequences/Sequences.h" #include "QI/Args.h" #include "QI/IO.h" #include "Filters/ApplyAlgorithmFilter.h" class SPGRCost : public ceres::CostFunction { protected: const QI::SPGRSimple &m_seq; const Eigen::ArrayXd m_data; public: SPGRCost(const QI::SPGRSimple &s, const Eigen::ArrayXd &data) : m_seq(s), m_data(data) { mutable_parameter_block_sizes()->push_back(3); set_num_residuals(data.size()); } virtual bool Evaluate(double const* const* p, double* resids, double** jacobians) const override { const double &M0 = p[0][0]; const double &T1 = p[0][1]; const double &B1 = p[0][2]; const Eigen::ArrayXd sa = sin(B1 * m_seq.m_flip); const Eigen::ArrayXd ca = cos(B1 * m_seq.m_flip); const double E1 = exp(-m_seq.m_TR / T1); const Eigen::ArrayXd denom = (1.-E1*ca); Eigen::Map<Eigen::ArrayXd> r(resids, m_data.size()); r = M0*sa*(1-E1)/denom - m_data; // std::cout << "SPGR RESIDS" << std::endl; // std::cout << r.transpose() << std::endl; if (jacobians && jacobians[0]) { Eigen::Map<Eigen::Matrix<double, -1, -1, Eigen::RowMajor>> j(jacobians[0], m_data.size(), 3); j.col(0) = (1-E1)*sa/denom; j.col(1) = E1*M0*m_seq.m_TR*(ca-1.)*sa/((denom*T1).square()); j.col(2) = M0*m_seq.m_flip*(1.-E1)*(ca-E1)/denom.square(); } return true; } }; // Use AutoDiff for this class IRCostFunction { protected: const QI::MPRAGE &m_seq; const Eigen::ArrayXd m_data; public: IRCostFunction(const QI::MPRAGE &s, const Eigen::ArrayXd &data) : m_seq(s), m_data(data) { } template<typename T> bool operator() (const T* const p1, T* r) const { const T &M0 = p1[0]; const T &T1 = p1[1]; const T &B1 = p1[2]; const double eta = -1.0; // Inversion efficiency defined as -1 < eta < 0 const double TIs = m_seq.m_TI[0] - m_seq.m_TR*m_seq.m_Nk0; // Adjust TI for k0 const T T1s = 1. / (1./T1 - log(cos(m_seq.m_flip[0] * B1))/m_seq.m_TR); const T M0s = M0 * (1. - exp(-m_seq.m_TR/T1)) / (1. - exp(-m_seq.m_TR/T1s)); const T A_1 = M0s*(1. - exp(-(m_seq.m_Nseg*m_seq.m_TR)/T1s)); const T A_2 = M0*(1. - exp(-m_seq.m_TD[0]/T1)); const T A_3 = M0*(1. - exp(-TIs/T1)); const T B_1 = exp(-(m_seq.m_Nseg*m_seq.m_TR)/T1s); const T B_2 = exp(-m_seq.m_TD[0]/T1); const T B_3 = eta*exp(-TIs/T1); const T A = A_3 + A_2*B_3 + A_1*B_2*B_3; const T B = B_1*B_2*B_3; const T M1 = A / (1. - B); r[0] = m_data[0] - (M0s + (M1 - M0s)*exp(-(m_seq.m_Nk0*m_seq.m_TR)/T1s)) * sin(m_seq.m_flip[0] * B1); return true; } }; class HIFIAlgo : public QI::ApplyF::Algorithm { private: const QI::SPGRSimple &m_spgr; const QI::MPRAGE &m_mprage; double m_lo = 0; double m_hi = std::numeric_limits<double>::infinity(); public: HIFIAlgo(const QI::SPGRSimple &s, const QI::MPRAGE &m, const float hi) : m_spgr(s), m_mprage(m), m_hi(hi) {} size_t numInputs() const override { return 2; } size_t numConsts() const override { return 0; } size_t numOutputs() const override { return 3; } size_t dataSize() const override { return m_spgr.size() + m_mprage.size(); } const float &zero(const size_t i) const override { static float zero = 0; return zero; } virtual std::vector<float> defaultConsts() const override { // No constants for HIFI std::vector<float> def(0); return def; } virtual bool apply(const std::vector<TInput> &inputs, const std::vector<TConst> &, // No constants, remove name to silence compiler warnings std::vector<TOutput> &outputs, TConst &residual, TInput &resids, TIters &its) const override { Eigen::Map<const Eigen::ArrayXf> spgr_in(inputs[0].GetDataPointer(), inputs[0].Size()); Eigen::Map<const Eigen::ArrayXf> ir_in(inputs[1].GetDataPointer(), inputs[1].Size()); double scale = std::max(spgr_in.maxCoeff(), ir_in.maxCoeff()); const Eigen::ArrayXd spgr_data = spgr_in.cast<double>() / scale; const Eigen::ArrayXd ir_data = ir_in.cast<double>() / scale; double spgr_pars[] = {10., 1., 1.}; // PD, T1, B1 ceres::Problem problem; problem.AddResidualBlock(new SPGRCost(m_spgr, spgr_data), NULL, spgr_pars); ceres::CostFunction *IRCost = new ceres::AutoDiffCostFunction<IRCostFunction, 1, 3>(new IRCostFunction(m_mprage, ir_data)); problem.AddResidualBlock(IRCost, NULL, spgr_pars); problem.SetParameterLowerBound(spgr_pars, 0, 1.); problem.SetParameterLowerBound(spgr_pars, 1, 0.001); problem.SetParameterUpperBound(spgr_pars, 1, 5.0); problem.SetParameterLowerBound(spgr_pars, 2, 0.1); problem.SetParameterUpperBound(spgr_pars, 2, 2.0); ceres::Solver::Options options; ceres::Solver::Summary summary; options.max_num_iterations = 50; options.function_tolerance = 1e-5; options.gradient_tolerance = 1e-6; options.parameter_tolerance = 1e-4; // options.check_gradients = true; options.logging_type = ceres::SILENT; // std::cout << "START P: " << p.transpose() << std::endl; ceres::Solve(options, &problem, &summary); outputs[0] = spgr_pars[0] * scale; outputs[1] = QI::Clamp(spgr_pars[1], m_lo, m_hi); outputs[2] = spgr_pars[2]; if (!summary.IsSolutionUsable()) { std::cout << summary.FullReport() << std::endl; } its = summary.iterations.size(); residual = summary.final_cost * scale; if (resids.Size() > 0) { assert(resids.Size() == data.size()); std::vector<double> r_temp(spgr_data.size() + 1); problem.Evaluate(ceres::Problem::EvaluateOptions(), NULL, &r_temp, NULL, NULL); for (int i = 0; i < r_temp.size(); i++) { resids[i] = r_temp[i]; } } return true; } }; //****************************************************************************** // Main //****************************************************************************** int main(int argc, char **argv) { Eigen::initParallel(); args::ArgumentParser parser("Calculates T1 and B1 maps from SPGR & IR-SPGR or MP-RAGE data.\nhttp://github.com/spinicist/QUIT"); args::Positional<std::string> spgr_path(parser, "SPGR_FILE", "Input SPGR file"); args::Positional<std::string> ir_path(parser, "IRSPGR_FILE", "Input IR-SPGR or MP-RAGE file"); args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"}); args::Flag verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"}); args::Flag noprompt(parser, "NOPROMPT", "Suppress input prompts", {'n', "no-prompt"}); args::Flag mprage(parser, "MPRAGE", "2nd image is a generic MP-RAGE, not a GE IR-SPGR", {'M', "mprage"}); args::Flag all_resids(parser, "ALL RESIDUALS", "Output individual residuals in addition to the Sum-of-Squares", {'r',"resids"}); args::ValueFlag<float> clamp(parser, "CLAMP", "Clamp output T1 values to this value", {'c', "clamp"}, std::numeric_limits<float>::infinity()); args::ValueFlag<int> threads(parser, "THREADS", "Use N threads (default=4, 0=hardware limit)", {'T', "threads"}, 4); args::ValueFlag<std::string> outarg(parser, "OUTPREFIX", "Add a prefix to output filenames", {'o', "out"}); args::ValueFlag<std::string> mask(parser, "MASK", "Only process voxels within the mask", {'m', "mask"}); args::ValueFlag<std::string> subregion(parser, "SUBREGION", "Process subregion starting at voxel I,J,K with size SI,SJ,SK", {'s', "subregion"}); args::Flag resids(parser, "RESIDS", "Write out residuals for each data-point", {'r', "resids"}); QI::ParseArgs(parser, argc, argv); bool prompt = !noprompt; if (verbose) std::cout << "Reading SPGR file: " << QI::CheckPos(spgr_path) << std::endl; auto spgrImg = QI::ReadVectorImage(QI::CheckPos(spgr_path)); if (verbose) std::cout << "Reading " << (mprage ? "MPRAGE" : "IR-SPGR") << " file: " << QI::CheckPos(ir_path) << std::endl; auto irImg = QI::ReadVectorImage(QI::CheckPos(ir_path)); const QI::SPGRSimple *spgr_sequence = new QI::SPGRSimple(std::cin, prompt); const QI::MPRAGE *ir_sequence = mprage ? new QI::MPRAGE(std::cin, prompt) : new QI::IRSPGR(std::cin, prompt); if (verbose) std::cout << *spgr_sequence << std::endl << *ir_sequence << std::endl; auto apply = QI::ApplyF::New(); auto hifi = std::make_shared<HIFIAlgo>(*spgr_sequence, *ir_sequence, clamp.Get()); apply->SetAlgorithm(hifi); apply->SetOutputAllResiduals(all_resids); apply->SetPoolsize(threads.Get()); apply->SetSplitsPerThread(threads.Get()); apply->SetVerbose(verbose); apply->SetInput(0, spgrImg); apply->SetInput(1, irImg); if (subregion) apply->SetSubregion(QI::RegionArg(args::get(subregion))); if (mask) apply->SetMask(QI::ReadImage(mask.Get())); if (verbose) std::cout << "Processing..." << std::endl; apply->Update(); if (verbose) { std::cout << "Elapsed time was " << apply->GetTotalTime() << "s" << std::endl; std::cout << "Writing results files." << std::endl; } std::string out_prefix = args::get(outarg) + "HIFI_"; QI::WriteImage(apply->GetOutput(0), out_prefix + "PD" + QI::OutExt()); QI::WriteImage(apply->GetOutput(1), out_prefix + "T1" + QI::OutExt()); QI::WriteImage(apply->GetOutput(2), out_prefix + "B1" + QI::OutExt()); QI::WriteScaledImage(apply->GetResidualOutput(), apply->GetOutput(0), out_prefix + "residual" + QI::OutExt()); if (all_resids) { QI::WriteVectorImage(apply->GetAllResidualsOutput(), out_prefix + "all_residuals" + QI::OutExt()); } if (verbose) std::cout << "Finished." << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <tackat@kde.org> // Copyright 2007 Inge Wallin <ingwa@kde.org> // Copyright 2008, 2009, 2010 Jens-Michael Hoffmann <jmho@c-xx.com> // Copyright 2010,2011 Bernhard Beschow <bbeschow@cs.tu-berlin.de>// #include "TextureLayer.h" #include <QtCore/qmath.h> #include <QtCore/QCache> #include <QtCore/QTimer> #include "SphericalScanlineTextureMapper.h" #include "EquirectScanlineTextureMapper.h" #include "MercatorScanlineTextureMapper.h" #include "TileScalingTextureMapper.h" #include "GeoPainter.h" #include "GeoSceneDocument.h" #include "GeoSceneFilter.h" #include "GeoSceneGroup.h" #include "GeoSceneHead.h" #include "GeoSceneMap.h" #include "GeoScenePalette.h" #include "GeoSceneSettings.h" #include "MarbleDebug.h" #include "MarbleDirs.h" #include "StackedTile.h" #include "StackedTileLoader.h" #include "TextureColorizer.h" #include "ViewParams.h" namespace Marble { class TextureLayer::Private { public: Private( MapThemeManager *mapThemeManager, HttpDownloadManager *downloadManager, SunLocator *sunLocator, TextureLayer *parent ); void mapChanged(); void updateTextureLayers(); const GeoSceneLayer *sceneLayer() const; GeoSceneGroup *textureLayerSettings() const; public: TextureLayer *const m_parent; StackedTileLoader m_tileLoader; QCache<TileId, QPixmap> m_pixmapCache; TextureMapperInterface *m_texmapper; TextureColorizer *m_texcolorizer; GeoSceneDocument *m_mapTheme; }; TextureLayer::Private::Private( MapThemeManager *mapThemeManager, HttpDownloadManager *downloadManager, SunLocator *sunLocator, TextureLayer *parent ) : m_parent( parent ) , m_tileLoader( downloadManager, mapThemeManager, sunLocator ) , m_pixmapCache( 100 ) , m_texmapper( 0 ) , m_texcolorizer( 0 ) , m_mapTheme( 0 ) { } void TextureLayer::Private::mapChanged() { if ( m_texmapper ) { m_texmapper->setRepaintNeeded(); } emit m_parent->repaintNeeded( QRegion() ); } void TextureLayer::Private::updateTextureLayers() { QVector<GeoSceneTexture const *> result; foreach ( const GeoSceneAbstractDataset *pos, sceneLayer()->datasets() ) { GeoSceneTexture const * const candidate = dynamic_cast<GeoSceneTexture const *>( pos ); if ( !candidate ) continue; bool enabled = true; if ( textureLayerSettings() ) { const bool propertyExists = textureLayerSettings()->propertyValue( candidate->name(), enabled ); enabled |= !propertyExists; // if property doesn't exist, enable texture nevertheless } if ( enabled ) result.append( candidate ); } m_tileLoader.setTextureLayers( result ); m_pixmapCache.clear(); } const GeoSceneLayer *TextureLayer::Private::sceneLayer() const { if ( !m_mapTheme ) return 0; GeoSceneHead const * head = m_mapTheme->head(); if ( !head ) return 0; GeoSceneMap const * map = m_mapTheme->map(); if ( !map ) return 0; const QString mapThemeId = head->target() + '/' + head->theme(); mDebug() << "StackedTileLoader::updateTextureLayers" << mapThemeId; return map->layer( head->theme() ); } GeoSceneGroup* TextureLayer::Private::textureLayerSettings() const { if ( !m_mapTheme ) return 0; if ( !m_mapTheme->settings() ) return 0; return m_mapTheme->settings()->group( "Texture Layers" ); } TextureLayer::TextureLayer( MapThemeManager *mapThemeManager, HttpDownloadManager *downloadManager, SunLocator *sunLocator ) : QObject() , d( new Private( mapThemeManager, downloadManager, sunLocator, this ) ) { } TextureLayer::~TextureLayer() { delete d; } void TextureLayer::paintGlobe( GeoPainter *painter, ViewParams *viewParams, const QRect& dirtyRect ) { if ( !d->m_mapTheme ) return; if ( !d->m_mapTheme->map()->hasTextureLayers() ) return; if ( !d->m_texmapper ) return; // As our tile resolution doubles with each level we calculate // the tile level from tilesize and the globe radius via log(2) qreal linearLevel = ( 4.0 * (qreal)( viewParams->radius() ) / (qreal)( d->m_tileLoader.tileSize().width() * d->m_tileLoader.tileColumnCount( 0 ) ) ); int tileLevel = 0; if ( linearLevel < 1.0 ) linearLevel = 1.0; // Dirty fix for invalid entry linearLevel qreal tileLevelF = log( linearLevel ) / log( 2.0 ); tileLevel = (int)( tileLevelF ); // mDebug() << "tileLevelF: " << tileLevelF << " tileLevel: " << tileLevel; if ( tileLevel > d->m_tileLoader.maximumTileLevel() ) tileLevel = d->m_tileLoader.maximumTileLevel(); const bool changedTileLevel = tileLevel != d->m_texmapper->tileZoomLevel(); // mDebug() << "Texture Level was set to: " << tileLevel; d->m_texmapper->setTileLevel( tileLevel ); if ( changedTileLevel ) { emit tileLevelChanged( tileLevel ); } d->m_texmapper->mapTexture( painter, viewParams, dirtyRect, d->m_texcolorizer ); } void TextureLayer::setShowTileId( bool show ) { d->m_tileLoader.setShowTileId( show ); } void TextureLayer::setupTextureMapper( Projection projection ) { if ( !d->m_mapTheme || !d->m_mapTheme->map()->hasTextureLayers() ) return; // FIXME: replace this with an approach based on the factory method pattern. delete d->m_texmapper; switch( projection ) { case Spherical: d->m_texmapper = new SphericalScanlineTextureMapper( &d->m_tileLoader, this ); break; case Equirectangular: d->m_texmapper = new EquirectScanlineTextureMapper( &d->m_tileLoader, this ); break; case Mercator: if ( d->m_tileLoader.tileProjection() == GeoSceneTexture::Mercator ) { d->m_texmapper = new TileScalingTextureMapper( &d->m_tileLoader, &d->m_pixmapCache, this ); } else { d->m_texmapper = new MercatorScanlineTextureMapper( &d->m_tileLoader, this ); } break; default: d->m_texmapper = 0; } Q_ASSERT( d->m_texmapper ); connect( d->m_texmapper, SIGNAL( tileUpdatesAvailable() ), SLOT( mapChanged() ) ); } void TextureLayer::setNeedsUpdate() { if ( d->m_texmapper ) { d->m_texmapper->setRepaintNeeded(); } } void TextureLayer::setVolatileCacheLimit( quint64 kilobytes ) { d->m_tileLoader.setVolatileCacheLimit( kilobytes ); } void TextureLayer::update() { mDebug() << "TextureLayer::update()"; d->m_tileLoader.clear(); d->mapChanged(); } void TextureLayer::reload() { d->m_tileLoader.reloadVisibleTiles(); } void TextureLayer::downloadTile( const TileId &tileId ) { d->m_tileLoader.downloadTile( tileId ); } void TextureLayer::setMapTheme(GeoSceneDocument* mapTheme) { if ( d->textureLayerSettings() ) { disconnect( d->textureLayerSettings(), SIGNAL( valueChanged( QString, bool ) ), this, SLOT( updateTextureLayers() ) ); } d->m_mapTheme = mapTheme; if ( d->textureLayerSettings() ) { connect( d->textureLayerSettings(), SIGNAL( valueChanged( QString, bool )), this, SLOT( updateTextureLayers() ) ); } d->updateTextureLayers(); delete d->m_texcolorizer; d->m_texcolorizer = 0; if( !d->m_mapTheme->map()->filters().isEmpty() ) { GeoSceneFilter *filter= d->m_mapTheme->map()->filters().first(); if( filter->type() == "colorize" ) { //no need to look up with MarbleDirs twice so they are left null for now QString seafile, landfile; QList<GeoScenePalette*> palette = filter->palette(); foreach ( GeoScenePalette *curPalette, palette ) { if( curPalette->type() == "sea" ) { seafile = MarbleDirs::path( curPalette->file() ); } else if( curPalette->type() == "land" ) { landfile = MarbleDirs::path( curPalette->file() ); } } //look up locations if they are empty if(seafile.isEmpty()) seafile = MarbleDirs::path( "seacolors.leg" ); if(landfile.isEmpty()) landfile = MarbleDirs::path( "landcolors.leg" ); d->m_texcolorizer = new TextureColorizer( seafile, landfile, this ); connect( d->m_texcolorizer, SIGNAL( datasetLoaded() ), SLOT( mapChanged() ) ); } } } int TextureLayer::tileZoomLevel() const { if (!d->m_texmapper) return -1; return d->m_texmapper->tileZoomLevel(); } QSize TextureLayer::tileSize() const { return d->m_tileLoader.tileSize(); } GeoSceneTexture::Projection TextureLayer::tileProjection() const { return d->m_tileLoader.tileProjection(); } int TextureLayer::tileColumnCount( int level ) const { return d->m_tileLoader.tileColumnCount( level ); } int TextureLayer::tileRowCount( int level ) const { return d->m_tileLoader.tileRowCount( level ); } qint64 TextureLayer::volatileCacheLimit() const { return d->m_tileLoader.volatileCacheLimit(); } int TextureLayer::preferredRadiusCeil( int radius ) const { const int tileWidth = d->m_tileLoader.tileSize().width(); const int levelZeroColumns = d->m_tileLoader.tileColumnCount( 0 ); const qreal linearLevel = 4.0 * (qreal)( radius ) / (qreal)( tileWidth * levelZeroColumns ); const qreal tileLevelF = log( linearLevel ) / log( 2.0 ); const int tileLevel = qCeil( tileLevelF ); if ( tileLevel < 0 ) return ( tileWidth * levelZeroColumns / 4 ) >> (-tileLevel); return ( tileWidth * levelZeroColumns / 4 ) << tileLevel; } int TextureLayer::preferredRadiusFloor( int radius ) const { const int tileWidth = d->m_tileLoader.tileSize().width(); const int levelZeroColumns = d->m_tileLoader.tileColumnCount( 0 ); const qreal linearLevel = 4.0 * (qreal)( radius ) / (qreal)( tileWidth * levelZeroColumns ); const qreal tileLevelF = log( linearLevel ) / log( 2.0 ); const int tileLevel = qFloor( tileLevelF ); if ( tileLevel < 0 ) return ( tileWidth * levelZeroColumns / 4 ) >> (-tileLevel); return ( tileWidth * levelZeroColumns / 4 ) << tileLevel; } } #include "TextureLayer.moc" <commit_msg>improve map quality when map width != height<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <tackat@kde.org> // Copyright 2007 Inge Wallin <ingwa@kde.org> // Copyright 2008, 2009, 2010 Jens-Michael Hoffmann <jmho@c-xx.com> // Copyright 2010,2011 Bernhard Beschow <bbeschow@cs.tu-berlin.de>// #include "TextureLayer.h" #include <QtCore/qmath.h> #include <QtCore/QCache> #include <QtCore/QTimer> #include "SphericalScanlineTextureMapper.h" #include "EquirectScanlineTextureMapper.h" #include "MercatorScanlineTextureMapper.h" #include "TileScalingTextureMapper.h" #include "GeoPainter.h" #include "GeoSceneDocument.h" #include "GeoSceneFilter.h" #include "GeoSceneGroup.h" #include "GeoSceneHead.h" #include "GeoSceneMap.h" #include "GeoScenePalette.h" #include "GeoSceneSettings.h" #include "MarbleDebug.h" #include "MarbleDirs.h" #include "StackedTile.h" #include "StackedTileLoader.h" #include "TextureColorizer.h" #include "ViewParams.h" namespace Marble { class TextureLayer::Private { public: Private( MapThemeManager *mapThemeManager, HttpDownloadManager *downloadManager, SunLocator *sunLocator, TextureLayer *parent ); void mapChanged(); void updateTextureLayers(); const GeoSceneLayer *sceneLayer() const; GeoSceneGroup *textureLayerSettings() const; public: TextureLayer *const m_parent; StackedTileLoader m_tileLoader; QCache<TileId, QPixmap> m_pixmapCache; TextureMapperInterface *m_texmapper; TextureColorizer *m_texcolorizer; GeoSceneDocument *m_mapTheme; }; TextureLayer::Private::Private( MapThemeManager *mapThemeManager, HttpDownloadManager *downloadManager, SunLocator *sunLocator, TextureLayer *parent ) : m_parent( parent ) , m_tileLoader( downloadManager, mapThemeManager, sunLocator ) , m_pixmapCache( 100 ) , m_texmapper( 0 ) , m_texcolorizer( 0 ) , m_mapTheme( 0 ) { } void TextureLayer::Private::mapChanged() { if ( m_texmapper ) { m_texmapper->setRepaintNeeded(); } emit m_parent->repaintNeeded( QRegion() ); } void TextureLayer::Private::updateTextureLayers() { QVector<GeoSceneTexture const *> result; foreach ( const GeoSceneAbstractDataset *pos, sceneLayer()->datasets() ) { GeoSceneTexture const * const candidate = dynamic_cast<GeoSceneTexture const *>( pos ); if ( !candidate ) continue; bool enabled = true; if ( textureLayerSettings() ) { const bool propertyExists = textureLayerSettings()->propertyValue( candidate->name(), enabled ); enabled |= !propertyExists; // if property doesn't exist, enable texture nevertheless } if ( enabled ) result.append( candidate ); } m_tileLoader.setTextureLayers( result ); m_pixmapCache.clear(); } const GeoSceneLayer *TextureLayer::Private::sceneLayer() const { if ( !m_mapTheme ) return 0; GeoSceneHead const * head = m_mapTheme->head(); if ( !head ) return 0; GeoSceneMap const * map = m_mapTheme->map(); if ( !map ) return 0; const QString mapThemeId = head->target() + '/' + head->theme(); mDebug() << "StackedTileLoader::updateTextureLayers" << mapThemeId; return map->layer( head->theme() ); } GeoSceneGroup* TextureLayer::Private::textureLayerSettings() const { if ( !m_mapTheme ) return 0; if ( !m_mapTheme->settings() ) return 0; return m_mapTheme->settings()->group( "Texture Layers" ); } TextureLayer::TextureLayer( MapThemeManager *mapThemeManager, HttpDownloadManager *downloadManager, SunLocator *sunLocator ) : QObject() , d( new Private( mapThemeManager, downloadManager, sunLocator, this ) ) { } TextureLayer::~TextureLayer() { delete d; } void TextureLayer::paintGlobe( GeoPainter *painter, ViewParams *viewParams, const QRect& dirtyRect ) { if ( !d->m_mapTheme ) return; if ( !d->m_mapTheme->map()->hasTextureLayers() ) return; if ( !d->m_texmapper ) return; // choose the smaller dimension for selecting the tile level, leading to higher-resolution results const int levelZeroWidth = d->m_tileLoader.tileSize().width() * d->m_tileLoader.tileColumnCount( 0 ); const int levelZeroHight = d->m_tileLoader.tileSize().height() * d->m_tileLoader.tileRowCount( 0 ); const int levelZeroMinDimension = ( levelZeroWidth < levelZeroHight ) ? levelZeroWidth : levelZeroHight; qreal linearLevel = ( 4.0 * (qreal)( viewParams->radius() ) / (qreal)( levelZeroMinDimension ) ); if ( linearLevel < 1.0 ) linearLevel = 1.0; // Dirty fix for invalid entry linearLevel // As our tile resolution doubles with each level we calculate // the tile level from tilesize and the globe radius via log(2) qreal tileLevelF = log( linearLevel ) / log( 2.0 ); int tileLevel = (int)( tileLevelF ); // mDebug() << "tileLevelF: " << tileLevelF << " tileLevel: " << tileLevel; if ( tileLevel > d->m_tileLoader.maximumTileLevel() ) tileLevel = d->m_tileLoader.maximumTileLevel(); const bool changedTileLevel = tileLevel != d->m_texmapper->tileZoomLevel(); // mDebug() << "Texture Level was set to: " << tileLevel; d->m_texmapper->setTileLevel( tileLevel ); if ( changedTileLevel ) { emit tileLevelChanged( tileLevel ); } d->m_texmapper->mapTexture( painter, viewParams, dirtyRect, d->m_texcolorizer ); } void TextureLayer::setShowTileId( bool show ) { d->m_tileLoader.setShowTileId( show ); } void TextureLayer::setupTextureMapper( Projection projection ) { if ( !d->m_mapTheme || !d->m_mapTheme->map()->hasTextureLayers() ) return; // FIXME: replace this with an approach based on the factory method pattern. delete d->m_texmapper; switch( projection ) { case Spherical: d->m_texmapper = new SphericalScanlineTextureMapper( &d->m_tileLoader, this ); break; case Equirectangular: d->m_texmapper = new EquirectScanlineTextureMapper( &d->m_tileLoader, this ); break; case Mercator: if ( d->m_tileLoader.tileProjection() == GeoSceneTexture::Mercator ) { d->m_texmapper = new TileScalingTextureMapper( &d->m_tileLoader, &d->m_pixmapCache, this ); } else { d->m_texmapper = new MercatorScanlineTextureMapper( &d->m_tileLoader, this ); } break; default: d->m_texmapper = 0; } Q_ASSERT( d->m_texmapper ); connect( d->m_texmapper, SIGNAL( tileUpdatesAvailable() ), SLOT( mapChanged() ) ); } void TextureLayer::setNeedsUpdate() { if ( d->m_texmapper ) { d->m_texmapper->setRepaintNeeded(); } } void TextureLayer::setVolatileCacheLimit( quint64 kilobytes ) { d->m_tileLoader.setVolatileCacheLimit( kilobytes ); } void TextureLayer::update() { mDebug() << "TextureLayer::update()"; d->m_tileLoader.clear(); d->mapChanged(); } void TextureLayer::reload() { d->m_tileLoader.reloadVisibleTiles(); } void TextureLayer::downloadTile( const TileId &tileId ) { d->m_tileLoader.downloadTile( tileId ); } void TextureLayer::setMapTheme(GeoSceneDocument* mapTheme) { if ( d->textureLayerSettings() ) { disconnect( d->textureLayerSettings(), SIGNAL( valueChanged( QString, bool ) ), this, SLOT( updateTextureLayers() ) ); } d->m_mapTheme = mapTheme; if ( d->textureLayerSettings() ) { connect( d->textureLayerSettings(), SIGNAL( valueChanged( QString, bool )), this, SLOT( updateTextureLayers() ) ); } d->updateTextureLayers(); delete d->m_texcolorizer; d->m_texcolorizer = 0; if( !d->m_mapTheme->map()->filters().isEmpty() ) { GeoSceneFilter *filter= d->m_mapTheme->map()->filters().first(); if( filter->type() == "colorize" ) { //no need to look up with MarbleDirs twice so they are left null for now QString seafile, landfile; QList<GeoScenePalette*> palette = filter->palette(); foreach ( GeoScenePalette *curPalette, palette ) { if( curPalette->type() == "sea" ) { seafile = MarbleDirs::path( curPalette->file() ); } else if( curPalette->type() == "land" ) { landfile = MarbleDirs::path( curPalette->file() ); } } //look up locations if they are empty if(seafile.isEmpty()) seafile = MarbleDirs::path( "seacolors.leg" ); if(landfile.isEmpty()) landfile = MarbleDirs::path( "landcolors.leg" ); d->m_texcolorizer = new TextureColorizer( seafile, landfile, this ); connect( d->m_texcolorizer, SIGNAL( datasetLoaded() ), SLOT( mapChanged() ) ); } } } int TextureLayer::tileZoomLevel() const { if (!d->m_texmapper) return -1; return d->m_texmapper->tileZoomLevel(); } QSize TextureLayer::tileSize() const { return d->m_tileLoader.tileSize(); } GeoSceneTexture::Projection TextureLayer::tileProjection() const { return d->m_tileLoader.tileProjection(); } int TextureLayer::tileColumnCount( int level ) const { return d->m_tileLoader.tileColumnCount( level ); } int TextureLayer::tileRowCount( int level ) const { return d->m_tileLoader.tileRowCount( level ); } qint64 TextureLayer::volatileCacheLimit() const { return d->m_tileLoader.volatileCacheLimit(); } int TextureLayer::preferredRadiusCeil( int radius ) const { const int tileWidth = d->m_tileLoader.tileSize().width(); const int levelZeroColumns = d->m_tileLoader.tileColumnCount( 0 ); const qreal linearLevel = 4.0 * (qreal)( radius ) / (qreal)( tileWidth * levelZeroColumns ); const qreal tileLevelF = log( linearLevel ) / log( 2.0 ); const int tileLevel = qCeil( tileLevelF ); if ( tileLevel < 0 ) return ( tileWidth * levelZeroColumns / 4 ) >> (-tileLevel); return ( tileWidth * levelZeroColumns / 4 ) << tileLevel; } int TextureLayer::preferredRadiusFloor( int radius ) const { const int tileWidth = d->m_tileLoader.tileSize().width(); const int levelZeroColumns = d->m_tileLoader.tileColumnCount( 0 ); const qreal linearLevel = 4.0 * (qreal)( radius ) / (qreal)( tileWidth * levelZeroColumns ); const qreal tileLevelF = log( linearLevel ) / log( 2.0 ); const int tileLevel = qFloor( tileLevelF ); if ( tileLevel < 0 ) return ( tileWidth * levelZeroColumns / 4 ) >> (-tileLevel); return ( tileWidth * levelZeroColumns / 4 ) << tileLevel; } } #include "TextureLayer.moc" <|endoftext|>
<commit_before>#include <common/buffer.h> #include <common/endian.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/channel.h> #include <io/file_descriptor.h> #include <xcodec/xchash.h> #include <xcodec/xcodec.h> #include <xcodec/xcodec_decoder.h> #include <xcodec/xcodec_encoder.h> #include "proxy_pipe.h" ProxyPipe::ProxyPipe(XCodec *read_codec, Channel *read_channel, Channel *write_channel, XCodec *write_codec) : log_("/wanproxy/proxy/pipe"), read_action_(NULL), read_buffer_(), read_channel_(read_channel), read_decoder_(NULL), write_action_(NULL), write_buffer_(), write_channel_(write_channel), write_encoder_(NULL), flow_action_(NULL), flow_callback_(NULL) { if (read_codec != NULL) read_decoder_ = read_codec->decoder(); if (write_codec != NULL) write_encoder_ = write_codec->encoder(); } ProxyPipe::~ProxyPipe() { ASSERT(read_action_ == NULL); ASSERT(write_action_ == NULL); if (read_decoder_ != NULL) { delete read_decoder_; read_decoder_ = NULL; } if (write_encoder_ != NULL) { delete write_encoder_; write_encoder_ = NULL; } ASSERT(flow_action_ == NULL); } /* * XXX * This function needs more assertions to ensure it's doing the right thing. */ void ProxyPipe::drain(void) { if (read_channel_ != NULL) { if (read_action_ != NULL) { read_action_->cancel(); read_action_ = NULL; } read_channel_ = NULL; } if (write_action_ == NULL) { flow_close(); } } Action * ProxyPipe::flow(EventCallback *cb) { ASSERT(flow_callback_ == NULL); flow_callback_ = cb; schedule_read(); return (cancellation(this, &ProxyPipe::flow_cancel)); } void ProxyPipe::read_complete(Event e, void *) { read_action_->cancel(); read_action_ = NULL; switch (e.type_) { case Event::Done: case Event::EOS: break; default: ERROR(log_) << "Unexpected event: " << e; read_error(); return; } read_buffer_.append(e.buffer_); if (!read_buffer_.empty()) { Buffer output; if (read_decoder_ != NULL) { if (!read_decoder_->decode(&output, &read_buffer_)) { read_error(); return; } } else { output = read_buffer_; read_buffer_.clear(); } if (write_encoder_ != NULL) { write_encoder_->encode(&write_buffer_, &output); } else { write_buffer_.append(output); } schedule_write(); } if (e.type_ == Event::EOS) { read_channel_ = NULL; if (write_action_ == NULL) { flow_close(); } } else { schedule_read(); } } void ProxyPipe::write_complete(Event e, void *) { write_action_->cancel(); write_action_ = NULL; switch (e.type_) { case Event::Done: break; default: ERROR(log_) << "Unexpected event: " << e; write_error(); return; } /* * If the read channel is gone (due to EOS) and we've finished our * writing, then tear down this flow. */ if (write_buffer_.empty() && read_channel_ == NULL) { flow_close(); } else { schedule_write(); } } void ProxyPipe::schedule_read(void) { ASSERT(read_action_ == NULL); ASSERT(read_channel_ != NULL); EventCallback *cb = callback(this, &ProxyPipe::read_complete); read_action_ = read_channel_->read(cb); } void ProxyPipe::schedule_write(void) { if (write_action_ != NULL) return; if (write_buffer_.empty()) return; EventCallback *cb = callback(this, &ProxyPipe::write_complete); write_action_ = write_channel_->write(&write_buffer_, cb); } void ProxyPipe::read_error(void) { ASSERT(read_action_ == NULL); if (write_action_ != NULL) { write_action_->cancel(); write_action_ = NULL; } flow_error(); } void ProxyPipe::write_error(void) { ASSERT(write_action_ == NULL); if (read_action_ != NULL) { read_action_->cancel(); read_action_ = NULL; } flow_error(); } void ProxyPipe::flow_close(void) { ASSERT(read_action_ == NULL); ASSERT(write_action_ == NULL); ASSERT(flow_action_ == NULL); ASSERT(flow_callback_ != NULL); flow_callback_->event(Event(Event::Done, 0)); Action *a = EventSystem::instance()->schedule(flow_callback_); flow_action_ = a; flow_callback_ = NULL; } void ProxyPipe::flow_error(void) { ASSERT(read_action_ == NULL); ASSERT(write_action_ == NULL); ASSERT(flow_action_ == NULL); ASSERT(flow_callback_ != NULL); /* XXX Preserve error code. */ flow_callback_->event(Event(Event::Error, 0)); Action *a = EventSystem::instance()->schedule(flow_callback_); flow_action_ = a; flow_callback_ = NULL; } void ProxyPipe::flow_cancel(void) { if (flow_action_ != NULL) { flow_action_->cancel(); flow_action_ = NULL; ASSERT(read_action_ == NULL); ASSERT(write_action_ == NULL); ASSERT(flow_callback_ == NULL); } else { if (read_action_ != NULL) { read_action_->cancel(); read_action_ = NULL; } if (write_action_ != NULL) { write_action_->cancel(); write_action_ = NULL; } if (flow_callback_ != NULL) { delete flow_callback_; flow_callback_ = NULL; } } } <commit_msg>When drain() is called, return immediately if we're already performing a callback to tell ProxyClient why we'd like to disappear.<commit_after>#include <common/buffer.h> #include <common/endian.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/channel.h> #include <io/file_descriptor.h> #include <xcodec/xchash.h> #include <xcodec/xcodec.h> #include <xcodec/xcodec_decoder.h> #include <xcodec/xcodec_encoder.h> #include "proxy_pipe.h" ProxyPipe::ProxyPipe(XCodec *read_codec, Channel *read_channel, Channel *write_channel, XCodec *write_codec) : log_("/wanproxy/proxy/pipe"), read_action_(NULL), read_buffer_(), read_channel_(read_channel), read_decoder_(NULL), write_action_(NULL), write_buffer_(), write_channel_(write_channel), write_encoder_(NULL), flow_action_(NULL), flow_callback_(NULL) { if (read_codec != NULL) read_decoder_ = read_codec->decoder(); if (write_codec != NULL) write_encoder_ = write_codec->encoder(); } ProxyPipe::~ProxyPipe() { ASSERT(read_action_ == NULL); ASSERT(write_action_ == NULL); if (read_decoder_ != NULL) { delete read_decoder_; read_decoder_ = NULL; } if (write_encoder_ != NULL) { delete write_encoder_; write_encoder_ = NULL; } ASSERT(flow_action_ == NULL); } /* * XXX * This function needs more assertions to ensure it's doing the right thing. */ void ProxyPipe::drain(void) { /* * If we're already tearing ourselves down, we don't need to drain. * We'll tell ProxyClient of our state any minute now. */ if (flow_action_ != NULL) return; if (read_channel_ != NULL) { if (read_action_ != NULL) { read_action_->cancel(); read_action_ = NULL; } read_channel_ = NULL; } if (write_action_ == NULL) { flow_close(); } } Action * ProxyPipe::flow(EventCallback *cb) { ASSERT(flow_callback_ == NULL); flow_callback_ = cb; schedule_read(); return (cancellation(this, &ProxyPipe::flow_cancel)); } void ProxyPipe::read_complete(Event e, void *) { read_action_->cancel(); read_action_ = NULL; switch (e.type_) { case Event::Done: case Event::EOS: break; default: ERROR(log_) << "Unexpected event: " << e; read_error(); return; } read_buffer_.append(e.buffer_); if (!read_buffer_.empty()) { Buffer output; if (read_decoder_ != NULL) { if (!read_decoder_->decode(&output, &read_buffer_)) { read_error(); return; } } else { output = read_buffer_; read_buffer_.clear(); } if (write_encoder_ != NULL) { write_encoder_->encode(&write_buffer_, &output); } else { write_buffer_.append(output); } schedule_write(); } if (e.type_ == Event::EOS) { read_channel_ = NULL; if (write_action_ == NULL) { flow_close(); } } else { schedule_read(); } } void ProxyPipe::write_complete(Event e, void *) { write_action_->cancel(); write_action_ = NULL; switch (e.type_) { case Event::Done: break; default: ERROR(log_) << "Unexpected event: " << e; write_error(); return; } /* * If the read channel is gone (due to EOS) and we've finished our * writing, then tear down this flow. */ if (write_buffer_.empty() && read_channel_ == NULL) { flow_close(); } else { schedule_write(); } } void ProxyPipe::schedule_read(void) { ASSERT(read_action_ == NULL); ASSERT(read_channel_ != NULL); EventCallback *cb = callback(this, &ProxyPipe::read_complete); read_action_ = read_channel_->read(cb); } void ProxyPipe::schedule_write(void) { if (write_action_ != NULL) return; if (write_buffer_.empty()) return; EventCallback *cb = callback(this, &ProxyPipe::write_complete); write_action_ = write_channel_->write(&write_buffer_, cb); } void ProxyPipe::read_error(void) { ASSERT(read_action_ == NULL); if (write_action_ != NULL) { write_action_->cancel(); write_action_ = NULL; } flow_error(); } void ProxyPipe::write_error(void) { ASSERT(write_action_ == NULL); if (read_action_ != NULL) { read_action_->cancel(); read_action_ = NULL; } flow_error(); } void ProxyPipe::flow_close(void) { ASSERT(read_action_ == NULL); ASSERT(write_action_ == NULL); ASSERT(flow_action_ == NULL); ASSERT(flow_callback_ != NULL); flow_callback_->event(Event(Event::Done, 0)); Action *a = EventSystem::instance()->schedule(flow_callback_); flow_action_ = a; flow_callback_ = NULL; } void ProxyPipe::flow_error(void) { ASSERT(read_action_ == NULL); ASSERT(write_action_ == NULL); ASSERT(flow_action_ == NULL); ASSERT(flow_callback_ != NULL); /* XXX Preserve error code. */ flow_callback_->event(Event(Event::Error, 0)); Action *a = EventSystem::instance()->schedule(flow_callback_); flow_action_ = a; flow_callback_ = NULL; } void ProxyPipe::flow_cancel(void) { if (flow_action_ != NULL) { flow_action_->cancel(); flow_action_ = NULL; ASSERT(read_action_ == NULL); ASSERT(write_action_ == NULL); ASSERT(flow_callback_ == NULL); } else { if (read_action_ != NULL) { read_action_->cancel(); read_action_ = NULL; } if (write_action_ != NULL) { write_action_->cancel(); write_action_ = NULL; } if (flow_callback_ != NULL) { delete flow_callback_; flow_callback_ = NULL; } } } <|endoftext|>
<commit_before>#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "getopt.h" #include "bitio.h" #include "h264.h" #include "md5.h" #ifdef __RENESAS_VERSION__ #include <machine.h> extern "C" { #pragma section FILES #define O_RDONLY 1 #define O_WRONLY 2 #define MAX_FILESIZE 8 * 1024 * 1024 #define MAX_MD5SIZE 128 * 1024 char InputFile[MAX_FILESIZE]; char OutputFile[MAX_MD5SIZE]; #pragma section void abort() {while (1);} static int infilepos; static void exit(int err) { while (err) sleep(); } int fseek(FILE *fp, long offset, int whence) { return 0; } int open(char *name, int mode, int flg) { if (mode & O_RDONLY) { infilepos = 0; } else if (mode & O_WRONLY) { infilepos = 0; } return 4; } int close(int fineno) {return 0;} int read(int fileno, char *buf, unsigned int count) { if (sizeof(InputFile) < infilepos + count) { count = sizeof(InputFile) - infilepos; if ((signed)count <= 0) { return 0; } } memcpy(buf, InputFile + infilepos, count); infilepos += count; return count; } int lseek() {return 0;} int write(int fileno, char *buf, unsigned int count) {return count;} char *getenv(const char *name) {return 0;} } #endif /* __RENESAS_VERSION__ */ static int alloc_frames(m2d_frame_t **mem, int width, int height, int num_mem) { m2d_frame_t *m; int luma_len = ((width + 15) & ~15) * ((height + 15) & ~15) + 15; if (luma_len <= 0) { return -1; } *mem = m = new m2d_frame_t[num_mem]; for (int i = 0; i < num_mem; ++i) { m[i].luma = new uint8_t[luma_len]; m[i].chroma = new uint8_t[luma_len >> 1]; } return 0; } static void free_frames(m2d_frame_t *mem, int num_mem) { for (int i = 0; i < num_mem; ++i) { delete[] mem[i].luma; delete[] mem[i].chroma; } } static bool outfilename(char *infilename, char *outfilename, size_t size) { char *start; char *end; if (!(start = strrchr(infilename, '/')) && !(start = strrchr(infilename, '\\'))) { start = infilename; } else { start += 1; } end = strrchr(start, '.'); if (end) { *end = '\0'; } if (size <= strlen(start)) { return false; } sprintf(outfilename, "%s.out", start); return true; } struct input_data_t { uint8_t *data_; size_t len_; size_t pos_; void *var_; FILE *fo_; int dpb_; bool raw_; bool md5_; bool force_exec_; input_data_t(int argc, char *argv[], void *v) : pos_(0), var_(v), fo_(0), dpb_(-1), raw_(false), md5_(false), force_exec_(false) { FILE *fi; int opt; while ((opt = getopt(argc, argv, "xbd:oO")) != -1) { switch (opt) { case 'b': dpb_ = 1; break; case 'd': dpb_ = strtol(optarg, 0, 0); if (32 < (unsigned)dpb_) { BlameUser(); /* NOTREACHED */ } break; case 'O': md5_ = true; break; case 'o': raw_ = true; break; case 'x': force_exec_ = true; break; default: BlameUser(); /* NOTREACHED */ } } if ((argc <= optind) || !(fi = fopen(argv[optind], "rb"))) { BlameUser(); /* NOTREACHED */ } if (md5_ || raw_) { char outfile[256]; if (outfilename(argv[optind], outfile, sizeof(outfile))) { fo_ = fopen(outfile, "wb"); } } #ifdef __RENESAS_VERSION__ data_ = (uint8_t *)InputFile; len_ = sizeof(InputFile); #else fseek(fi, 0, SEEK_END); len_ = ftell(fi); fseek(fi, 0, SEEK_SET); data_ = new uint8_t[len_]; fread(data_, 1, len_, fi); #endif fclose(fi); } ~input_data_t() { #ifndef __RENESAS_VERSION__ delete[] data_; #endif if (fo_) { fclose(fo_); } } static size_t write_md5(void *dst, const uint8_t *src, size_t size) { md5_append((md5_state_t *)dst, (const md5_byte_t *)src, (int)size); return size; } static size_t write_raw(void *dst, const uint8_t *src, size_t size) { return fwrite((const void *)src, 1, size, (FILE *)dst); } static void write_cropping(const m2d_frame_t *frame, size_t (*writef)(void *dst, const uint8_t *src, size_t size), void *dst) { const uint8_t *src; int stride, height, width; stride = frame->width; src = frame->luma + stride * frame->crop[2] + frame->crop[0]; height = frame->height - frame->crop[2] - frame->crop[3]; width = stride - frame->crop[0] - frame->crop[1]; for (int y = 0; y < height; ++y) { writef(dst, src, width); src += stride; } src = frame->chroma + stride * (frame->crop[2] >> 1) + frame->crop[0]; height >>= 1; for (int y = 0; y < height; ++y) { writef(dst, src, width); src += stride; } } static void md5txt(const unsigned char *md5, char *txt) { for (int i = 0; i < 16; ++i) { sprintf(txt + i * 2, "%02xd", *md5++); } txt[32] = 0x0d; txt[33] = 0x0a; } size_t writeframe(const m2d_frame_t *frame) { if (fo_) { int luma_size = frame->width * frame->height; if (md5_) { md5_state_t md5; md5_byte_t digest[16]; char txt[16 * 2 + 2]; md5_init(&md5); write_cropping(frame, write_md5, (void *)&md5); md5_finish(&md5, digest); md5txt(digest, txt); fwrite(txt, 1, sizeof(txt), fo_); } else { write_cropping(frame, write_raw, (void *)fo_); } fflush(fo_); return luma_size; } return 0; } void BlameUser() { fprintf(stderr, "Usage:\n" "\th264dec [-b] [-d <dpb_size>] [-o|O ] <infile>\n" "\t\t-b: Bypass DPB\n" "\t\t-d <dpb_size>: Specify number of DPB frames -1, 1..16 (default: -1(auto))\n" "\t\t-o: RAW output\n" "\t\t-O: MD5 output\n" "\t\t-x: Mask SIGABRT on error." ); exit(-1); } }; static int reread_file(void *var) { input_data_t *d = (input_data_t *)var; if (d->pos_ < d->len_) { dec_bits_set_data(((h264d_context *)d->var_)->stream, d->data_ + d->pos_, d->len_); d->pos_ += d->len_; return 0; } else { return -1; } } #ifdef _M_IX86 #include <crtdbg.h> #elif defined(__linux__) #include <pthread.h> #include <signal.h> static void trap(int no) { fprintf(stderr, "trap %d\n", no); exit(0); } #endif int main(int argc, char *argv[]) { h264d_context *h2d; m2d_frame_t *mem; int err; #ifdef _M_IX86 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW); // _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_WNDW); _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF); #endif h2d = new h264d_context; input_data_t data(argc, argv, (void *)h2d); if (data.len_ <= 0) { return -1; } #ifdef __linux__ if (data.force_exec_) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = trap; sigaction(SIGABRT, &sa, 0); sigaction(SIGSEGV, &sa, 0); } #endif err = h264d_init(h2d, data.dpb_, 0, 0); if (err) { return err; } err = h264d_read_header(h2d, data.data_, data.len_); data.pos_ = data.len_; if (err) { return err; } m2d_info_t info; h264d_get_info(h2d, &info); fprintf(stderr, "length: %ld\n" "width x height x num: %d x %d x %d\n" "Context Size: %ld\n", data.len_, info.src_width, info.src_height, info.frame_num, sizeof(h264d_context)); info.frame_num = (info.frame_num < 3 ? 3 : info.frame_num) + (data.dpb_ < 0 ? 16 : data.dpb_); alloc_frames(&mem, info.src_width, info.src_height, info.frame_num); uint8_t *second_frame = new uint8_t[info.additional_size]; err = h264d_set_frames(h2d, info.frame_num, mem, second_frame, info.additional_size); if (err) { return err; } dec_bits_set_callback(h2d->stream, reread_file, &data); m2d_frame_t frame; for (int i = 0; i < INT_MAX; ++i) { err = h264d_decode_picture(h2d); if (err == -1) { break; } while (h264d_get_decoded_frame(h2d, &frame, (data.dpb_ == 1))) { data.writeframe(&frame); } if (err < 0) { break; } } while (h264d_get_decoded_frame(h2d, &frame, 1)) { data.writeframe(&frame); } delete[] second_frame; free_frames(mem, info.frame_num); delete[] mem; delete h2d; #ifdef _M_IX86 assert(_CrtCheckMemory()); #endif return (data.force_exec_) ? 0 : ((err == -2) ? 0 : err); } <commit_msg>Remove uncecessary code chunk.<commit_after>#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <vector> #include <algorithm> #include "getopt.h" #include "bitio.h" #include "h264.h" #include "md5.h" #ifdef __RENESAS_VERSION__ #include <machine.h> extern "C" { #pragma section FILES #define O_RDONLY 1 #define O_WRONLY 2 #define MAX_FILESIZE 8 * 1024 * 1024 #define MAX_MD5SIZE 128 * 1024 char InputFile[MAX_FILESIZE]; char OutputFile[MAX_MD5SIZE]; #pragma section void abort() {while (1);} static int infilepos; static void exit(int err) { while (err) sleep(); } int fseek(FILE *fp, long offset, int whence) { return 0; } int open(char *name, int mode, int flg) { if (mode & O_RDONLY) { infilepos = 0; } else if (mode & O_WRONLY) { infilepos = 0; } return 4; } int close(int fineno) {return 0;} int read(int fileno, char *buf, unsigned int count) { if (sizeof(InputFile) < infilepos + count) { count = sizeof(InputFile) - infilepos; if ((signed)count <= 0) { return 0; } } memcpy(buf, InputFile + infilepos, count); infilepos += count; return count; } int lseek() {return 0;} int write(int fileno, char *buf, unsigned int count) {return count;} char *getenv(const char *name) {return 0;} } #endif /* __RENESAS_VERSION__ */ struct Frames { typedef std::vector<m2d_frame_t> frame_t; frame_t frame; Frames(int width, int height, int num_mem) : frame(num_mem) { int luma_len = ((width + 15) & ~15) * ((height + 15) & ~15) + 15; if (num_mem <= 0 || luma_len <= 0) { return; } for (int i = 0; i < num_mem; ++i) { frame[i].luma = new uint8_t[luma_len]; frame[i].chroma = new uint8_t[luma_len >> 1]; } } ~Frames() { if (!frame.empty()) { for_each(frame.begin(), frame.end(), Delete()); frame.clear(); } } private: struct Delete { void operator()(m2d_frame_t& frm) { delete[] frm.luma; delete[] frm.chroma; } }; }; static bool outfilename(char *infilename, char *outfilename, size_t size) { char *start; char *end; if (!(start = strrchr(infilename, '/')) && !(start = strrchr(infilename, '\\'))) { start = infilename; } else { start += 1; } end = strrchr(start, '.'); if (end) { *end = '\0'; } if (size <= strlen(start)) { return false; } sprintf(outfilename, "%s.out", start); return true; } struct input_data_t { uint8_t *data_; size_t len_; size_t pos_; void *var_; FILE *fo_; int dpb_; bool raw_; bool md5_; bool force_exec_; input_data_t(int argc, char *argv[], void *v) : pos_(0), var_(v), fo_(0), dpb_(-1), raw_(false), md5_(false), force_exec_(false) { FILE *fi; int opt; while ((opt = getopt(argc, argv, "xbd:oO")) != -1) { switch (opt) { case 'b': dpb_ = 1; break; case 'd': dpb_ = strtol(optarg, 0, 0); if (32 < (unsigned)dpb_) { BlameUser(); /* NOTREACHED */ } break; case 'O': md5_ = true; break; case 'o': raw_ = true; break; case 'x': force_exec_ = true; break; default: BlameUser(); /* NOTREACHED */ } } if ((argc <= optind) || !(fi = fopen(argv[optind], "rb"))) { BlameUser(); /* NOTREACHED */ } if (md5_ || raw_) { char outfile[256]; if (outfilename(argv[optind], outfile, sizeof(outfile))) { fo_ = fopen(outfile, "wb"); } } #ifdef __RENESAS_VERSION__ data_ = (uint8_t *)InputFile; len_ = sizeof(InputFile); #else fseek(fi, 0, SEEK_END); len_ = ftell(fi); fseek(fi, 0, SEEK_SET); data_ = new uint8_t[len_]; fread(data_, 1, len_, fi); #endif fclose(fi); } ~input_data_t() { #ifndef __RENESAS_VERSION__ delete[] data_; #endif if (fo_) { fclose(fo_); } } static size_t write_md5(void *dst, const uint8_t *src, size_t size) { md5_append((md5_state_t *)dst, (const md5_byte_t *)src, (int)size); return size; } static size_t write_raw(void *dst, const uint8_t *src, size_t size) { return fwrite((const void *)src, 1, size, (FILE *)dst); } static void write_cropping(const m2d_frame_t *frame, size_t (*writef)(void *dst, const uint8_t *src, size_t size), void *dst) { const uint8_t *src; int stride, height, width; stride = frame->width; src = frame->luma + stride * frame->crop[2] + frame->crop[0]; height = frame->height - frame->crop[2] - frame->crop[3]; width = stride - frame->crop[0] - frame->crop[1]; for (int y = 0; y < height; ++y) { writef(dst, src, width); src += stride; } src = frame->chroma + stride * (frame->crop[2] >> 1) + frame->crop[0]; height >>= 1; for (int y = 0; y < height; ++y) { writef(dst, src, width); src += stride; } } static void md5txt(const unsigned char *md5, char *txt) { for (int i = 0; i < 16; ++i) { sprintf(txt + i * 2, "%02xd", *md5++); } txt[32] = 0x0d; txt[33] = 0x0a; } size_t writeframe(const m2d_frame_t *frame) { if (fo_) { int luma_size = frame->width * frame->height; if (md5_) { md5_state_t md5; md5_byte_t digest[16]; char txt[16 * 2 + 2]; md5_init(&md5); write_cropping(frame, write_md5, (void *)&md5); md5_finish(&md5, digest); md5txt(digest, txt); fwrite(txt, 1, sizeof(txt), fo_); } else { write_cropping(frame, write_raw, (void *)fo_); } fflush(fo_); return luma_size; } return 0; } void BlameUser() { fprintf(stderr, "Usage:\n" "\th264dec [-b] [-d <dpb_size>] [-o|O ] <infile>\n" "\t\t-b: Bypass DPB\n" "\t\t-d <dpb_size>: Specify number of DPB frames -1, 1..16 (default: -1(auto))\n" "\t\t-o: RAW output\n" "\t\t-O: MD5 output\n" "\t\t-x: Mask SIGABRT on error." ); exit(-1); } }; static int reread_file(void *var) { input_data_t *d = (input_data_t *)var; if (d->pos_ < d->len_) { dec_bits_set_data(((h264d_context *)d->var_)->stream, d->data_ + d->pos_, d->len_); d->pos_ += d->len_; return 0; } else { return -1; } } #ifdef _M_IX86 #include <crtdbg.h> #elif defined(__linux__) #include <pthread.h> #include <signal.h> static void trap(int no) { fprintf(stderr, "trap %d\n", no); exit(0); } #endif int main(int argc, char *argv[]) { h264d_context *h2d; int err; #ifdef _M_IX86 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW); // _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_WNDW); _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF); #endif h2d = new h264d_context; input_data_t data(argc, argv, (void *)h2d); if (data.len_ <= 0) { delete h2d; return -1; } #ifdef __linux__ if (data.force_exec_) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = trap; sigaction(SIGABRT, &sa, 0); sigaction(SIGSEGV, &sa, 0); } #endif err = h264d_init(h2d, data.dpb_, 0, 0); if (err) { return err; } err = h264d_read_header(h2d, data.data_, data.len_); data.pos_ = data.len_; if (err) { return err; } m2d_info_t info; h264d_get_info(h2d, &info); fprintf(stderr, "length: %ld\n" "width x height x num: %d x %d x %d\n" "Context Size: %ld\n", data.len_, info.src_width, info.src_height, info.frame_num, sizeof(h264d_context)); info.frame_num = (info.frame_num < 3 ? 3 : info.frame_num) + (data.dpb_ < 0 ? 16 : data.dpb_); Frames frm(info.src_width, info.src_height, info.frame_num); std::vector<uint8_t> second_frame(info.additional_size); err = h264d_set_frames(h2d, info.frame_num, &frm.frame[0], &second_frame[0], info.additional_size); if (err) { return err; } dec_bits_set_callback(h2d->stream, reread_file, &data); m2d_frame_t frame; for (int i = 0; i < INT_MAX; ++i) { err = h264d_decode_picture(h2d); if (err == -1) { break; } while (h264d_get_decoded_frame(h2d, &frame, (data.dpb_ == 1))) { data.writeframe(&frame); } if (err < 0) { break; } } while (h264d_get_decoded_frame(h2d, &frame, 1)) { data.writeframe(&frame); } delete h2d; #ifdef _M_IX86 assert(_CrtCheckMemory()); #endif return (data.force_exec_) ? 0 : ((err == -2) ? 0 : err); } <|endoftext|>
<commit_before>// // test-jit.cc // #include <cstdio> #include <cstdlib> #include <cstring> #include <cassert> #include <cinttypes> #include <csignal> #include <csetjmp> #include <cerrno> #include <cmath> #include <cctype> #include <cwchar> #include <climits> #include <cfloat> #include <cfenv> #include <cstddef> #include <limits> #include <array> #include <string> #include <vector> #include <algorithm> #include <memory> #include <random> #include <deque> #include <map> #include <thread> #include <atomic> #include <type_traits> #include <poll.h> #include <fcntl.h> #include <unistd.h> #include <termios.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/time.h> #include "histedit.h" #include "host-endian.h" #include "types.h" #include "fmt.h" #include "bits.h" #include "sha512.h" #include "format.h" #include "meta.h" #include "util.h" #include "host.h" #include "cmdline.h" #include "config-parser.h" #include "config-string.h" #include "codec.h" #include "strings.h" #include "disasm.h" #include "alu.h" #include "fpu.h" #include "pma.h" #include "amo.h" #include "processor-logging.h" #include "processor-base.h" #include "processor-impl.h" #include "interp.h" #include "processor-model.h" #include "mmu-proxy.h" #include "unknown-abi.h" #include "processor-proxy.h" #include "debug-cli.h" #include "asmjit.h" #include "fusion-decode.h" #include "fusion-emitter.h" #include "fusion-tracer.h" #include "fusion-runloop.h" #include "assembler.h" #include "jit.h" using namespace riscv; using proxy_jit_rv64imafdc = fusion_runloop<processor_proxy <processor_rv64imafdc_model<fusion_decode,processor_rv64imafd,mmu_proxy_rv64>>>; template <typename P> struct rv_test_jit { void run_test(const char* test_name, P &emulator, addr_t pc, size_t step) { printf("\n=========================================================\n"); printf("TEST: %s\n", test_name); typename P::ireg_t save_regs[P::ireg_count]; size_t regfile_size = sizeof(typename P::ireg_t) * P::ireg_count; /* clear registers */ memset(&emulator.ireg[0], 0, regfile_size); /* step the interpreter */ printf("\n--[ interp ]---------------\n"); emulator.log = proc_log_inst; emulator.pc = pc; emulator.step(step); /* save and reset registers */ memcpy(&save_regs[0], &emulator.ireg[0], regfile_size); memset(&emulator.ireg[0], 0, regfile_size); /* compile the program buffer trace */ printf("\n--[ jit ]------------------\n"); emulator.log = proc_log_jit_trace; emulator.pc = pc; emulator.start_trace(); /* reset registers */ memset(&emulator.ireg[0], 0, regfile_size); /* run compiled trace */ auto fn = emulator.trace_cache[pc]; fn(static_cast<processor_rv64imafd*>(&emulator)); /* print result */ printf("\n--[ result ]---------------\n"); bool pass = true; for (size_t i = 0; i < P::ireg_count; i++) { if (save_regs[i].r.xu.val != emulator.ireg[i].r.xu.val) { pass = false; printf("ERROR interp-%s=0x%016llx jit-%s=0x%016llx\n", rv_ireg_name_sym[i], save_regs[i].r.xu.val, rv_ireg_name_sym[i], emulator.ireg[i].r.xu.val); } } printf("%s\n", pass ? "PASS" : "FAIL"); } void test_addi_1() { P emulator; assembler as; asm_addi(as, rv_ireg_a0, rv_ireg_zero, 0xde); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 1); } void test_add_1() { P emulator; assembler as; asm_addi(as, rv_ireg_a1, rv_ireg_zero, 0x7ff); asm_add(as, rv_ireg_a0, rv_ireg_zero, rv_ireg_a1); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 2); } void test_add_2() { P emulator; assembler as; asm_addi(as, rv_ireg_a1, rv_ireg_zero, 0x7ff); asm_add(as, rv_ireg_a0, rv_ireg_a1, rv_ireg_zero); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 2); } void test_add_3() { P emulator; assembler as; asm_addi(as, rv_ireg_a1, rv_ireg_zero, 0x7ff); asm_addi(as, rv_ireg_a0, rv_ireg_zero, 0x1); asm_add(as, rv_ireg_a1, rv_ireg_a1, rv_ireg_a0); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 3); } void test_add_4() { P emulator; assembler as; asm_addi(as, rv_ireg_s10, rv_ireg_zero, 0x7ff); asm_add(as, rv_ireg_s10, rv_ireg_zero, rv_ireg_s11); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 2); } void test_add_5() { P emulator; assembler as; asm_addi(as, rv_ireg_s10, rv_ireg_zero, 0x7ff); asm_add(as, rv_ireg_s10, rv_ireg_s11, rv_ireg_zero); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 2); } void test_slli_1() { P emulator; assembler as; asm_addi(as, rv_ireg_a0, rv_ireg_a0, 0xde); asm_slli(as, rv_ireg_a0, rv_ireg_a0, 8); asm_addi(as, rv_ireg_a0, rv_ireg_a0, 0xad); asm_slli(as, rv_ireg_a0, rv_ireg_a0, 8); asm_addi(as, rv_ireg_a0, rv_ireg_a0, 0xbe); asm_slli(as, rv_ireg_a0, rv_ireg_a0, 8); asm_addi(as, rv_ireg_a0, rv_ireg_a0, 0xef); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 7); } void test_sll_1() { P emulator; assembler as; asm_addi(as, rv_ireg_s9, rv_ireg_zero, 12); asm_addi(as, rv_ireg_s10, rv_ireg_zero, 0x7ff); asm_add(as, rv_ireg_s11, rv_ireg_zero, rv_ireg_s10); asm_sll(as, rv_ireg_s11, rv_ireg_s11, rv_ireg_s9); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 4); } void test_load_imm_1() { P emulator; assembler as; as.load_imm(rv_ireg_a0, 0xfeedcafebabe); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 6); } }; int main(int argc, char *argv[]) { rv_test_jit<proxy_jit_rv64imafdc> test; test.test_addi_1(); test.test_add_1(); test.test_add_2(); test.test_add_3(); test.test_add_4(); test.test_add_5(); test.test_slli_1(); test.test_sll_1(); test.test_load_imm_1(); } <commit_msg>Add test result summary to test-jit<commit_after>// // test-jit.cc // #include <cstdio> #include <cstdlib> #include <cstring> #include <cassert> #include <cinttypes> #include <csignal> #include <csetjmp> #include <cerrno> #include <cmath> #include <cctype> #include <cwchar> #include <climits> #include <cfloat> #include <cfenv> #include <cstddef> #include <limits> #include <array> #include <string> #include <vector> #include <algorithm> #include <memory> #include <random> #include <deque> #include <map> #include <thread> #include <atomic> #include <type_traits> #include <poll.h> #include <fcntl.h> #include <unistd.h> #include <termios.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/time.h> #include "histedit.h" #include "host-endian.h" #include "types.h" #include "fmt.h" #include "bits.h" #include "sha512.h" #include "format.h" #include "meta.h" #include "util.h" #include "host.h" #include "cmdline.h" #include "config-parser.h" #include "config-string.h" #include "codec.h" #include "strings.h" #include "disasm.h" #include "alu.h" #include "fpu.h" #include "pma.h" #include "amo.h" #include "processor-logging.h" #include "processor-base.h" #include "processor-impl.h" #include "interp.h" #include "processor-model.h" #include "mmu-proxy.h" #include "unknown-abi.h" #include "processor-proxy.h" #include "debug-cli.h" #include "asmjit.h" #include "fusion-decode.h" #include "fusion-emitter.h" #include "fusion-tracer.h" #include "fusion-runloop.h" #include "assembler.h" #include "jit.h" using namespace riscv; using proxy_jit_rv64imafdc = fusion_runloop<processor_proxy <processor_rv64imafdc_model<fusion_decode,processor_rv64imafd,mmu_proxy_rv64>>>; template <typename P> struct rv_test_jit { int total_tests = 0; int tests_passed = 0; rv_test_jit() : total_tests(0), tests_passed(0) {} void run_test(const char* test_name, P &emulator, addr_t pc, size_t step) { printf("\n=========================================================\n"); printf("TEST: %s\n", test_name); typename P::ireg_t save_regs[P::ireg_count]; size_t regfile_size = sizeof(typename P::ireg_t) * P::ireg_count; /* clear registers */ memset(&emulator.ireg[0], 0, regfile_size); /* step the interpreter */ printf("\n--[ interp ]---------------\n"); emulator.log = proc_log_inst; emulator.pc = pc; emulator.step(step); /* save and reset registers */ memcpy(&save_regs[0], &emulator.ireg[0], regfile_size); memset(&emulator.ireg[0], 0, regfile_size); /* compile the program buffer trace */ printf("\n--[ jit ]------------------\n"); emulator.log = proc_log_jit_trace; emulator.pc = pc; emulator.start_trace(); /* reset registers */ memset(&emulator.ireg[0], 0, regfile_size); /* run compiled trace */ auto fn = emulator.trace_cache[pc]; fn(static_cast<processor_rv64imafd*>(&emulator)); /* print result */ printf("\n--[ result ]---------------\n"); bool pass = true; for (size_t i = 0; i < P::ireg_count; i++) { if (save_regs[i].r.xu.val != emulator.ireg[i].r.xu.val) { pass = false; printf("ERROR interp-%s=0x%016llx jit-%s=0x%016llx\n", rv_ireg_name_sym[i], save_regs[i].r.xu.val, rv_ireg_name_sym[i], emulator.ireg[i].r.xu.val); } } printf("%s\n", pass ? "PASS" : "FAIL"); if (pass) tests_passed++; total_tests++; } void test_addi_1() { P emulator; assembler as; asm_addi(as, rv_ireg_a0, rv_ireg_zero, 0xde); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 1); } void test_add_1() { P emulator; assembler as; asm_addi(as, rv_ireg_a1, rv_ireg_zero, 0x7ff); asm_add(as, rv_ireg_a0, rv_ireg_zero, rv_ireg_a1); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 2); } void test_add_2() { P emulator; assembler as; asm_addi(as, rv_ireg_a1, rv_ireg_zero, 0x7ff); asm_add(as, rv_ireg_a0, rv_ireg_a1, rv_ireg_zero); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 2); } void test_add_3() { P emulator; assembler as; asm_addi(as, rv_ireg_a1, rv_ireg_zero, 0x7ff); asm_addi(as, rv_ireg_a0, rv_ireg_zero, 0x1); asm_add(as, rv_ireg_a1, rv_ireg_a1, rv_ireg_a0); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 3); } void test_add_4() { P emulator; assembler as; asm_addi(as, rv_ireg_s10, rv_ireg_zero, 0x7ff); asm_add(as, rv_ireg_s10, rv_ireg_zero, rv_ireg_s11); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 2); } void test_add_5() { P emulator; assembler as; asm_addi(as, rv_ireg_s10, rv_ireg_zero, 0x7ff); asm_add(as, rv_ireg_s10, rv_ireg_s11, rv_ireg_zero); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 2); } void test_slli_1() { P emulator; assembler as; asm_addi(as, rv_ireg_a0, rv_ireg_a0, 0xde); asm_slli(as, rv_ireg_a0, rv_ireg_a0, 8); asm_addi(as, rv_ireg_a0, rv_ireg_a0, 0xad); asm_slli(as, rv_ireg_a0, rv_ireg_a0, 8); asm_addi(as, rv_ireg_a0, rv_ireg_a0, 0xbe); asm_slli(as, rv_ireg_a0, rv_ireg_a0, 8); asm_addi(as, rv_ireg_a0, rv_ireg_a0, 0xef); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 7); } void test_sll_1() { P emulator; assembler as; asm_addi(as, rv_ireg_s9, rv_ireg_zero, 12); asm_addi(as, rv_ireg_s10, rv_ireg_zero, 0x7ff); asm_add(as, rv_ireg_s11, rv_ireg_zero, rv_ireg_s10); asm_sll(as, rv_ireg_s11, rv_ireg_s11, rv_ireg_s9); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 4); } void test_load_imm_1() { P emulator; assembler as; as.load_imm(rv_ireg_a0, 0xfeedcafebabe); asm_ebreak(as); as.link(); run_test(__func__, emulator, (addr_t)as.get_section(".text")->buf.data(), 6); } void print_summary() { printf("\n%d/%d tests successful\n", tests_passed, total_tests); } }; int main(int argc, char *argv[]) { rv_test_jit<proxy_jit_rv64imafdc> test; test.test_addi_1(); test.test_add_1(); test.test_add_2(); test.test_add_3(); test.test_add_4(); test.test_add_5(); test.test_slli_1(); test.test_sll_1(); test.test_load_imm_1(); test.print_summary(); } <|endoftext|>
<commit_before>#include "application.hpp" #include <boost/log/attributes.hpp> #include <boost/log/core.hpp> #include <boost/log/expressions.hpp> #include <boost/log/support/date_time.hpp> #include <boost/log/trivial.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/utility/setup/console.hpp> #include <iostream> #include <cstdlib> #include "log.hpp" namespace asio = boost::asio; namespace logging = boost::log; namespace simplicity { bool check_xcb_connection(xcb_connection_t *pConnection); const string SimplicityApplication::ENV_VAR_DISPLAY_NAME = "DISPLAY"; SimplicityApplication &SimplicityApplication::get_instance(void) { static SimplicityApplication singleton; return singleton; } SimplicityApplication::SimplicityApplication(void) : m_bRunning(false), m_pXConnection(nullptr), m_GlobalLogger(), m_IOService(), m_Signals(m_IOService, SIGINT, SIGTERM, SIGHUP), m_sDisplayName("") { initialize_logging(); m_Signals.async_wait(boost::bind(&SimplicityApplication::handler_sig, this, _1, _2)); m_ServiceThread = boost::thread(boost::bind(&asio::io_service::run, &m_IOService)); } SimplicityApplication::~SimplicityApplication(void) { global_log_trace << "Destroying application singleton"; } logging::sources::severity_logger<logging::trivial::severity_level> &SimplicityApplication::get_global_logger(void) { return m_GlobalLogger; } bool SimplicityApplication::run(void) { global_log_trace << "Starting main application loop"; int nScreenNum = 0; m_pXConnection = xcb_connect(m_sDisplayName.c_str(), &nScreenNum); if (check_xcb_connection(m_pXConnection)) { xcb_disconnect(m_pXConnection); return 1; } xcb_screen_iterator_t iter = xcb_setup_roots_iterator(xcb_get_setup(m_pXConnection)); for (int i = 0; i != nScreenNum; i++) xcb_screen_next(&iter); m_pRootScreen = iter.data; if (m_pRootScreen == nullptr) { global_log_error << "Could not get the current screen. Exiting"; xcb_disconnect(m_pXConnection); return 1; } global_log_debug << "Root screen dimensions: " << m_pRootScreen->width_in_pixels << "x" << m_pRootScreen->height_in_pixels << "Root window: " << m_pRootScreen->root; xcb_generic_event_t *pEvent; m_bRunning = true; while (m_bRunning && (pEvent = xcb_wait_for_event(m_pXConnection))) { delete pEvent; // TODO: necessary? } if (m_bRunning && pEvent == nullptr) global_log_error << "A fatal error occurred"; xcb_disconnect(m_pXConnection); return 0; } void SimplicityApplication::quit(void) { global_log_trace << "Ending main application loop"; m_bRunning = false; m_IOService.stop(); } string SimplicityApplication::get_display_name(void) const { return m_sDisplayName; } void SimplicityApplication::set_display_name(string sDisplay) { if (sDisplay.empty()) { char *pEnvVar = std::getenv(SimplicityApplication::ENV_VAR_DISPLAY_NAME.c_str()); if (pEnvVar) m_sDisplayName = pEnvVar; else m_sDisplayName = ":0.0"; global_log_trace << "No display set. Defaulting to " << m_sDisplayName; } else { m_sDisplayName = sDisplay; global_log_trace << "Display set to " << sDisplay; } putenv((char *)(SimplicityApplication::ENV_VAR_DISPLAY_NAME + "=" + m_sDisplayName).c_str()); } void SimplicityApplication::handler_sig(const boost::system::error_code &error, int nSignal) { global_log_trace << "Received OS signal: " << nSignal; switch (nSignal) { case SIGHUP: global_log_trace << "Received OS SIGHUP"; handler_sig_hup(error, nSignal); break; case SIGINT: global_log_trace << "Received OS SIGINT"; handler_sig_int(error, nSignal); return; case SIGTERM: global_log_trace << "Received OS SIGTERM"; handler_sig_term(error, nSignal); return; default: global_log_debug << "Unhandled signal: " << nSignal; } m_Signals.async_wait(boost::bind(&SimplicityApplication::handler_sig, this, _1, _2)); } xcb_atom_t SimplicityApplication::get_atom(string sAtomName) { xcb_intern_atom_cookie_t xcbCookie = xcb_intern_atom( m_pXConnection, 0, sAtomName.length(), sAtomName.c_str() ); xcb_intern_atom_reply_t *pxcbReply = xcb_intern_atom_reply( m_pXConnection, xcbCookie, NULL ); if (pxcbReply == nullptr) return 0; xcb_atom_t xcbAtom = pxcbReply->atom; delete pxcbReply; return xcbAtom; } void SimplicityApplication::SimplicityApplication::initialize_logging(void) { logging::add_common_attributes(); logging::add_console_log( std::cerr, logging::keywords::format = ( logging::expressions::stream << "(" << logging::expressions::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M%S") << ") " << "[" << logging::trivial::severity << "]: " << logging::expressions::smessage ), logging::keywords::auto_flush = true ); } void SimplicityApplication::handler_sig_hup(const boost::system::error_code &error, int nSignal) { // TODO: reload config global_log_debug << "SIGHUP received"; } void SimplicityApplication::handler_sig_int(const boost::system::error_code &error, int nSignal) { quit(); } void SimplicityApplication::handler_sig_term(const boost::system::error_code &error, int nSignal) { quit(); } bool check_xcb_connection(xcb_connection_t *pConnection) { switch (xcb_connection_has_error(pConnection)) { case XCB_CONN_ERROR: global_log_error << "Socket, pipe, or stream error prevented connetion to X server"; return true; case XCB_CONN_CLOSED_EXT_NOTSUPPORTED: global_log_error << "Extension not supported. Could not connect to X server"; return true; case XCB_CONN_CLOSED_MEM_INSUFFICIENT: global_log_error << "Not enough memory. Could not connect to X server"; return true; case XCB_CONN_CLOSED_REQ_LEN_EXCEED: global_log_error << "Exceeded request length. Could not connect to X server"; return true; case XCB_CONN_CLOSED_PARSE_ERR: global_log_error << "Could not parse display string. Could not connect to X server"; return true; case XCB_CONN_CLOSED_INVALID_SCREEN: global_log_error << "Could not connect to X server because an invalid screen was selected"; return true; default: return false; } } } <commit_msg>Fix method definition<commit_after>#include "application.hpp" #include <boost/log/attributes.hpp> #include <boost/log/core.hpp> #include <boost/log/expressions.hpp> #include <boost/log/support/date_time.hpp> #include <boost/log/trivial.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/utility/setup/console.hpp> #include <iostream> #include <cstdlib> #include "log.hpp" namespace asio = boost::asio; namespace logging = boost::log; namespace simplicity { bool check_xcb_connection(xcb_connection_t *pConnection); const string SimplicityApplication::ENV_VAR_DISPLAY_NAME = "DISPLAY"; SimplicityApplication &SimplicityApplication::get_instance(void) { static SimplicityApplication singleton; return singleton; } SimplicityApplication::SimplicityApplication(void) : m_bRunning(false), m_pXConnection(nullptr), m_GlobalLogger(), m_IOService(), m_Signals(m_IOService, SIGINT, SIGTERM, SIGHUP), m_sDisplayName("") { initialize_logging(); m_Signals.async_wait(boost::bind(&SimplicityApplication::handler_sig, this, _1, _2)); m_ServiceThread = boost::thread(boost::bind(&asio::io_service::run, &m_IOService)); } SimplicityApplication::~SimplicityApplication(void) { global_log_trace << "Destroying application singleton"; } logging::sources::severity_logger<logging::trivial::severity_level> &SimplicityApplication::get_global_logger(void) { return m_GlobalLogger; } bool SimplicityApplication::run(void) { global_log_trace << "Starting main application loop"; int nScreenNum = 0; m_pXConnection = xcb_connect(m_sDisplayName.c_str(), &nScreenNum); if (check_xcb_connection(m_pXConnection)) { xcb_disconnect(m_pXConnection); return 1; } xcb_screen_iterator_t iter = xcb_setup_roots_iterator(xcb_get_setup(m_pXConnection)); for (int i = 0; i != nScreenNum; i++) xcb_screen_next(&iter); m_pRootScreen = iter.data; if (m_pRootScreen == nullptr) { global_log_error << "Could not get the current screen. Exiting"; xcb_disconnect(m_pXConnection); return 1; } global_log_debug << "Root screen dimensions: " << m_pRootScreen->width_in_pixels << "x" << m_pRootScreen->height_in_pixels << "Root window: " << m_pRootScreen->root; xcb_generic_event_t *pEvent; m_bRunning = true; while (m_bRunning && (pEvent = xcb_wait_for_event(m_pXConnection))) { delete pEvent; // TODO: necessary? } if (m_bRunning && pEvent == nullptr) global_log_error << "A fatal error occurred"; xcb_disconnect(m_pXConnection); return 0; } void SimplicityApplication::quit(void) { global_log_trace << "Ending main application loop"; m_bRunning = false; m_IOService.stop(); } string SimplicityApplication::get_display_name(void) const { return m_sDisplayName; } void SimplicityApplication::set_display_name(string sDisplay) { if (sDisplay.empty()) { char *pEnvVar = std::getenv(SimplicityApplication::ENV_VAR_DISPLAY_NAME.c_str()); if (pEnvVar) m_sDisplayName = pEnvVar; else m_sDisplayName = ":0.0"; global_log_trace << "No display set. Defaulting to " << m_sDisplayName; } else { m_sDisplayName = sDisplay; global_log_trace << "Display set to " << sDisplay; } putenv((char *)(SimplicityApplication::ENV_VAR_DISPLAY_NAME + "=" + m_sDisplayName).c_str()); } void SimplicityApplication::handler_sig(const boost::system::error_code &error, int nSignal) { global_log_trace << "Received OS signal: " << nSignal; switch (nSignal) { case SIGHUP: global_log_trace << "Received OS SIGHUP"; handler_sig_hup(error, nSignal); break; case SIGINT: global_log_trace << "Received OS SIGINT"; handler_sig_int(error, nSignal); return; case SIGTERM: global_log_trace << "Received OS SIGTERM"; handler_sig_term(error, nSignal); return; default: global_log_debug << "Unhandled signal: " << nSignal; } m_Signals.async_wait(boost::bind(&SimplicityApplication::handler_sig, this, _1, _2)); } xcb_atom_t SimplicityApplication::get_atom(string sAtomName) { xcb_intern_atom_cookie_t xcbCookie = xcb_intern_atom( m_pXConnection, 0, sAtomName.length(), sAtomName.c_str() ); xcb_intern_atom_reply_t *pxcbReply = xcb_intern_atom_reply( m_pXConnection, xcbCookie, NULL ); if (pxcbReply == nullptr) return 0; xcb_atom_t xcbAtom = pxcbReply->atom; delete pxcbReply; return xcbAtom; } void SimplicityApplication::initialize_logging(void) { logging::add_common_attributes(); logging::add_console_log( std::cerr, logging::keywords::format = ( logging::expressions::stream << "(" << logging::expressions::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M%S") << ") " << "[" << logging::trivial::severity << "]: " << logging::expressions::smessage ), logging::keywords::auto_flush = true ); } void SimplicityApplication::handler_sig_hup(const boost::system::error_code &error, int nSignal) { // TODO: reload config global_log_debug << "SIGHUP received"; } void SimplicityApplication::handler_sig_int(const boost::system::error_code &error, int nSignal) { quit(); } void SimplicityApplication::handler_sig_term(const boost::system::error_code &error, int nSignal) { quit(); } bool check_xcb_connection(xcb_connection_t *pConnection) { switch (xcb_connection_has_error(pConnection)) { case XCB_CONN_ERROR: global_log_error << "Socket, pipe, or stream error prevented connetion to X server"; return true; case XCB_CONN_CLOSED_EXT_NOTSUPPORTED: global_log_error << "Extension not supported. Could not connect to X server"; return true; case XCB_CONN_CLOSED_MEM_INSUFFICIENT: global_log_error << "Not enough memory. Could not connect to X server"; return true; case XCB_CONN_CLOSED_REQ_LEN_EXCEED: global_log_error << "Exceeded request length. Could not connect to X server"; return true; case XCB_CONN_CLOSED_PARSE_ERR: global_log_error << "Could not parse display string. Could not connect to X server"; return true; case XCB_CONN_CLOSED_INVALID_SCREEN: global_log_error << "Could not connect to X server because an invalid screen was selected"; return true; default: return false; } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2009 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #ifndef __ARCH_ARM_ISA_HH__ #define __ARCH_MRM_ISA_HH__ #include "arch/arm/registers.hh" #include "arch/arm/types.hh" class ThreadContext; class Checkpoint; class EventManager; namespace ArmISA { class ISA { protected: MiscReg miscRegs[NumMiscRegs]; const IntRegIndex *intRegMap; void updateRegMap(CPSR cpsr) { switch (cpsr.mode) { case MODE_USER: case MODE_SYSTEM: intRegMap = IntRegUsrMap; break; case MODE_FIQ: intRegMap = IntRegFiqMap; break; case MODE_IRQ: intRegMap = IntRegIrqMap; break; case MODE_SVC: intRegMap = IntRegSvcMap; break; case MODE_ABORT: intRegMap = IntRegAbtMap; break; case MODE_UNDEFINED: intRegMap = IntRegUndMap; break; default: panic("Unrecognized mode setting in CPSR.\n"); } } public: void clear() { memset(miscRegs, 0, sizeof(miscRegs)); CPSR cpsr = 0; cpsr.mode = MODE_SYSTEM; miscRegs[MISCREG_CPSR] = cpsr; updateRegMap(cpsr); //XXX We need to initialize the rest of the state. } MiscReg readMiscRegNoEffect(int misc_reg) { assert(misc_reg < NumMiscRegs); return miscRegs[misc_reg]; } MiscReg readMiscReg(int misc_reg, ThreadContext *tc) { assert(misc_reg < NumMiscRegs); return miscRegs[misc_reg]; } void setMiscRegNoEffect(int misc_reg, const MiscReg &val) { assert(misc_reg < NumMiscRegs); miscRegs[misc_reg] = val; } void setMiscReg(int misc_reg, const MiscReg &val, ThreadContext *tc) { if (misc_reg == MISCREG_CPSR) { updateRegMap(val); } assert(misc_reg < NumMiscRegs); miscRegs[misc_reg] = val; } int flattenIntIndex(int reg) { assert(reg >= 0); if (reg < NUM_ARCH_INTREGS) { return intRegMap[reg]; } else { assert(reg < NUM_INTREGS); return reg; } } int flattenFloatIndex(int reg) { return reg; } void serialize(EventManager *em, std::ostream &os) {} void unserialize(EventManager *em, Checkpoint *cp, const std::string &section) {} ISA() { clear(); } }; } #endif <commit_msg>ARM: Initialize processes in user mode.<commit_after>/* * Copyright (c) 2009 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #ifndef __ARCH_ARM_ISA_HH__ #define __ARCH_MRM_ISA_HH__ #include "arch/arm/registers.hh" #include "arch/arm/types.hh" class ThreadContext; class Checkpoint; class EventManager; namespace ArmISA { class ISA { protected: MiscReg miscRegs[NumMiscRegs]; const IntRegIndex *intRegMap; void updateRegMap(CPSR cpsr) { switch (cpsr.mode) { case MODE_USER: case MODE_SYSTEM: intRegMap = IntRegUsrMap; break; case MODE_FIQ: intRegMap = IntRegFiqMap; break; case MODE_IRQ: intRegMap = IntRegIrqMap; break; case MODE_SVC: intRegMap = IntRegSvcMap; break; case MODE_ABORT: intRegMap = IntRegAbtMap; break; case MODE_UNDEFINED: intRegMap = IntRegUndMap; break; default: panic("Unrecognized mode setting in CPSR.\n"); } } public: void clear() { memset(miscRegs, 0, sizeof(miscRegs)); CPSR cpsr = 0; cpsr.mode = MODE_USER; miscRegs[MISCREG_CPSR] = cpsr; updateRegMap(cpsr); //XXX We need to initialize the rest of the state. } MiscReg readMiscRegNoEffect(int misc_reg) { assert(misc_reg < NumMiscRegs); return miscRegs[misc_reg]; } MiscReg readMiscReg(int misc_reg, ThreadContext *tc) { assert(misc_reg < NumMiscRegs); return miscRegs[misc_reg]; } void setMiscRegNoEffect(int misc_reg, const MiscReg &val) { assert(misc_reg < NumMiscRegs); miscRegs[misc_reg] = val; } void setMiscReg(int misc_reg, const MiscReg &val, ThreadContext *tc) { if (misc_reg == MISCREG_CPSR) { updateRegMap(val); } assert(misc_reg < NumMiscRegs); miscRegs[misc_reg] = val; } int flattenIntIndex(int reg) { assert(reg >= 0); if (reg < NUM_ARCH_INTREGS) { return intRegMap[reg]; } else { assert(reg < NUM_INTREGS); return reg; } } int flattenFloatIndex(int reg) { return reg; } void serialize(EventManager *em, std::ostream &os) {} void unserialize(EventManager *em, Checkpoint *cp, const std::string &section) {} ISA() { clear(); } }; } #endif <|endoftext|>
<commit_before>#include "ast_printer.h" void ASTPrinter::append_line_to_output(std::ostringstream &line) { if (tab_level == 0) { node_output << line.str() << '\n'; } else { for (unsigned i = 0; i < tab_level; i++) node_output << '|' << " "; node_output << line.str() << '\n'; } line.str(""); line.clear(); } void ASTPrinter::process_prototype(const PrototypeAST &proto) { std::ostringstream tmp; tmp << "FUNCTION NAME: " << proto.name; append_line_to_output(tmp); tmp << "FUNCTION ARGS: "; for (auto arg : proto.args) tmp << arg << " "; append_line_to_output(tmp); } void ASTPrinter::print_node_output() { std::cout << node_output.str() << std::endl; node_output.str(""); node_output.clear(); tab_level = 0; } void ASTPrinter::apply(const ExternASTNode &extern_node) { std::ostringstream tmp; tmp << "EXTERN:"; append_line_to_output(tmp); tab_level++; process_prototype(*extern_node.prototype); print_node_output(); } void ASTPrinter::apply(const DefnASTNode &defn_node) { std::ostringstream tmp; tmp << "DEFN:"; append_line_to_output(tmp); tab_level++; process_prototype(*defn_node.prototype); tmp << "BODY:"; append_line_to_output(tmp); tab_level++; defn_node.body->inject(*this); print_node_output(); } void ASTPrinter::apply(const VariableASTExpr &var_expr) { std::ostringstream tmp; tmp << "VARIABLE: " << var_expr.name; append_line_to_output(tmp); } void ASTPrinter::apply(const LiteralDoubleASTExpr &double_expr) { std::ostringstream tmp; tmp << "DOUBLE: " << double_expr.value; append_line_to_output(tmp); } void ASTPrinter::apply(const BinOpASTExpr &bin_op_expr) { std::ostringstream tmp; tmp << "BINOP: " << bin_op_expr.binop; append_line_to_output(tmp); tab_level++; tmp << "LHS:"; bin_op_expr.LHS->inject(*this); tmp << "RHS:"; bin_op_expr.RHS->inject(*this); tab_level--; } void ASTPrinter::apply(const CallASTExpr &call_expr) { std::ostringstream tmp; tmp << "CALL:"; append_line_to_output(tmp); tab_level++; tmp << "FUNCTION: " << call_expr.callee; append_line_to_output(tmp); tmp << "ARGUMENTS: "; append_line_to_output(tmp); tab_level++; unsigned int i = 1; for (auto &a : call_expr.args) { tmp << "ARG " << i << ":"; append_line_to_output(tmp); i++; tab_level++; a->inject(*this); tab_level--; } tab_level -= 2; } <commit_msg>renaming methods<commit_after>#include "ast_printer.h" void ASTPrinter::append_line_to_output(std::ostringstream &line) { if (tab_level == 0) { node_output << line.str() << '\n'; } else { for (unsigned i = 0; i < tab_level; i++) node_output << '|' << " "; node_output << line.str() << '\n'; } line.str(""); line.clear(); } void ASTPrinter::process_prototype(const PrototypeAST &proto) { std::ostringstream tmp; tmp << "FUNCTION NAME: " << proto.name; append_line_to_output(tmp); tmp << "FUNCTION ARGS: "; for (auto arg : proto.args) tmp << arg << " "; append_line_to_output(tmp); } void ASTPrinter::print_node_output() { std::cout << node_output.str() << std::endl; node_output.str(""); node_output.clear(); tab_level = 0; } void ASTPrinter::apply_to(const ExternASTNode &extern_node) { std::ostringstream tmp; tmp << "EXTERN:"; append_line_to_output(tmp); tab_level++; process_prototype(*extern_node.prototype); print_node_output(); } void ASTPrinter::apply_to(const DefnASTNode &defn_node) { std::ostringstream tmp; tmp << "DEFN:"; append_line_to_output(tmp); tab_level++; process_prototype(*defn_node.prototype); tmp << "BODY:"; append_line_to_output(tmp); tab_level++; defn_node.body->inject(*this); print_node_output(); } void ASTPrinter::apply_to(const VariableASTExpr &var_expr) { std::ostringstream tmp; tmp << "VARIABLE: " << var_expr.name; append_line_to_output(tmp); } void ASTPrinter::apply_to(const LiteralDoubleASTExpr &double_expr) { std::ostringstream tmp; tmp << "DOUBLE: " << double_expr.value; append_line_to_output(tmp); } void ASTPrinter::apply_to(const BinOpASTExpr &bin_op_expr) { std::ostringstream tmp; tmp << "BINOP: " << bin_op_expr.binop; append_line_to_output(tmp); tab_level++; tmp << "LHS:"; bin_op_expr.LHS->inject(*this); tmp << "RHS:"; bin_op_expr.RHS->inject(*this); tab_level--; } void ASTPrinter::apply_to(const CallASTExpr &call_expr) { std::ostringstream tmp; tmp << "CALL:"; append_line_to_output(tmp); tab_level++; tmp << "FUNCTION: " << call_expr.callee; append_line_to_output(tmp); tmp << "ARGUMENTS: "; append_line_to_output(tmp); tab_level++; unsigned int i = 1; for (auto &a : call_expr.args) { tmp << "ARG " << i << ":"; append_line_to_output(tmp); i++; tab_level++; a->inject(*this); tab_level--; } tab_level -= 2; } <|endoftext|>
<commit_before>#include "Configuration.h" #include <Groundfloor/Atoms/Defines.h> #define pi1hostname "pi1wifi" #ifdef GF_OS_WIN32 #define pi2hostname "testpc" #else #define pi2hostname "pi2wifi" #endif AudacityRover::Configuration DefaultInstance; AudacityRover::Configuration::Configuration() { CommandServerPort = 13666; SensorServerPort = 13777; GoPiGo = pi2hostname; Accelerometer1 = { 11, pi1hostname }; Gyroscope1 = { 12, pi1hostname }; Magnometer1 = { 13, pi1hostname }; Temperature1 = { 14, pi1hostname }; Barometer1 = { 15, pi1hostname }; Humidity1 = { 16, pi1hostname }; Dummy1 = { 21, pi1hostname }; Dummy2 = { 22, pi2hostname }; CameraFrontLeft = pi2hostname; CameraFrontRight = pi1hostname; } AudacityRover::Configuration * AudacityRover::Configuration::Instance() { return &DefaultInstance; } <commit_msg>hostnames<commit_after>#include "Configuration.h" #include <Groundfloor/Atoms/Defines.h> #define pi1hostname "pi1" #ifdef GF_OS_WIN32 #define pi2hostname "testpc" #else #define pi2hostname "pi2" #endif AudacityRover::Configuration DefaultInstance; AudacityRover::Configuration::Configuration() { CommandServerPort = 13666; SensorServerPort = 13777; GoPiGo = pi2hostname; Accelerometer1 = { 11, pi1hostname }; Gyroscope1 = { 12, pi1hostname }; Magnometer1 = { 13, pi1hostname }; Temperature1 = { 14, pi1hostname }; Barometer1 = { 15, pi1hostname }; Humidity1 = { 16, pi1hostname }; Dummy1 = { 21, pi1hostname }; Dummy2 = { 22, pi2hostname }; CameraFrontLeft = pi2hostname; CameraFrontRight = pi1hostname; } AudacityRover::Configuration * AudacityRover::Configuration::Instance() { return &DefaultInstance; } <|endoftext|>
<commit_before>#include "Arduino.h" #include "LedManager.h" const uint8_t PROGMEM gammaCorrection[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25, 25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36, 37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68, 69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89, 90, 92, 93, 95, 96, 98, 99,101,102,104,105,107,109,110,112,114, 115,117,119,120,122,124,126,127,129,131,133,135,137,138,140,142, 144,146,148,150,152,154,156,158,160,162,164,167,169,171,173,175, 177,180,182,184,186,189,191,193,196,198,200,203,205,208,210,213, 215,218,220,223,225,228,231,233,236,239,241,244,247,249,252,255 }; LedManager::LedManager(Outputs& outputs): _outputs(outputs) { } void LedManager::setValue(int id, int value) { _outputs[id].setIntencity(pgm_read_byte(&gammaCorrection[value])); } <commit_msg>LedManager: only PWM outputs get gamma correction<commit_after>#include "Arduino.h" #include "LedManager.h" const uint8_t PROGMEM gammaCorrection[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25, 25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36, 37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68, 69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89, 90, 92, 93, 95, 96, 98, 99,101,102,104,105,107,109,110,112,114, 115,117,119,120,122,124,126,127,129,131,133,135,137,138,140,142, 144,146,148,150,152,154,156,158,160,162,164,167,169,171,173,175, 177,180,182,184,186,189,191,193,196,198,200,203,205,208,210,213, 215,218,220,223,225,228,231,233,236,239,241,244,247,249,252,255 }; LedManager::LedManager(Outputs& outputs): _outputs(outputs) { } void LedManager::setValue(int id, int value) { int outputValue = _outputs[id].isPwm() ? pgm_read_byte(&gammaCorrection[value]) : value; _outputs[id].setValue(outputValue); } <|endoftext|>
<commit_before>#include "astutil.h" #include "expr.h" #include "optimizations.h" #include "passes.h" #include "stmt.h" #include "stringutil.h" #include "symbol.h" #include "iterator.h" static void expandIteratorInline(CallExpr* call) { BlockStmt* body; Symbol* index = toSymExpr(call->get(1))->var; Symbol* ic = toSymExpr(call->get(2))->var; FnSymbol* iterator = ic->type->defaultConstructor; BlockStmt* ibody = iterator->body->copy(); CallExpr* yield = NULL; reset_line_info(ibody, call->lineno); body = toBlockStmt(call->parentExpr); call->remove(); body->replace(ibody); Vec<BaseAST*> asts; collect_asts(ibody, asts); forv_Vec(BaseAST, ast, asts) { if (CallExpr* call = toCallExpr(ast)) { if (call->isPrimitive(PRIMITIVE_YIELD)) { yield = call; call->replace(body); } if (call->isPrimitive(PRIMITIVE_RETURN)) // remove return call->remove(); } } body->insertAtHead(new CallExpr(PRIMITIVE_MOVE, index, yield->get(1))); int count = 1; for_formals(formal, iterator) { forv_Vec(BaseAST, ast, asts) { if (SymExpr* se = toSymExpr(ast)) { if (se->var == formal) { // count is used to get the nth field out of the iterator class; // it is replaced by the field once the iterator class is created Expr* stmt = se->getStmtExpr(); VarSymbol* tmp = new VarSymbol(formal->name, formal->type); tmp->isCompilerTemp = true; stmt->insertBefore(new DefExpr(tmp)); stmt->insertBefore(new CallExpr(PRIMITIVE_MOVE, tmp, new CallExpr(PRIMITIVE_GET_MEMBER, ic, new_IntSymbol(count)))); se->var = tmp; } } } count++; } } static bool canInlineIterator(FnSymbol* iterator) { Vec<BaseAST*> asts; collect_asts(iterator, asts); int count = 0; forv_Vec(BaseAST, ast, asts) { if (CallExpr* call = toCallExpr(ast)) if (call->isPrimitive(PRIMITIVE_YIELD)) count++; } if (count == 1) return true; return false; } static void setupSimultaneousIterators(Vec<Symbol*>& iterators, Vec<Symbol*>& indices, Symbol* gIterator, Symbol* gIndex, BlockStmt* loop) { if (gIterator->type->symbol->hasPragma("tuple")) { ClassType* iteratorType = toClassType(gIterator->type); ClassType* indexType = toClassType(gIndex->type); for (int i=1; i <= iteratorType->fields.length(); i++) { Symbol* iterator = new VarSymbol("_iterator", iteratorType->getField(i)->type); loop->insertBefore(new DefExpr(iterator)); loop->insertBefore(new CallExpr(PRIMITIVE_MOVE, iterator, new CallExpr(PRIMITIVE_GET_MEMBER_VALUE, gIterator, iteratorType->getField(i)))); Symbol* index = new VarSymbol("_index", indexType->getField(i)->type); loop->insertAtHead(new CallExpr(PRIMITIVE_SET_MEMBER, gIndex, indexType->getField(i), index)); loop->insertAtHead(new DefExpr(index)); setupSimultaneousIterators(iterators, indices, iterator, index, loop); } } else { iterators.add(gIterator); indices.add(gIndex); } } static bool isBoundedIterator(FnSymbol* fn) { if (fn->_this) { Type* type = fn->_this->type; if (type->symbol->hasPragma("ref")) type = getValueType(type); if (type->symbol->hasPragma("range")) { if (!strcmp(toSymbol(type->substitutions.v[1].value)->name, "bounded")) return true; else return false; } } return true; } static void expand_for_loop(CallExpr* call) { BlockStmt* block = toBlockStmt(call->parentExpr); if (!block || block->loopInfo != call) INT_FATAL(call, "bad for loop primitive"); SymExpr* se1 = toSymExpr(call->get(1)); SymExpr* se2 = toSymExpr(call->get(2)); if (!se1 || !se2) INT_FATAL(call, "bad for loop primitive"); VarSymbol* index = toVarSymbol(se1->var); VarSymbol* iterator = toVarSymbol(se2->var); if (!index || !iterator) INT_FATAL(call, "bad for loop primitive"); if (!fNoInlineIterators && iterator->type->defaultConstructor->iteratorInfo && canInlineIterator(iterator->type->defaultConstructor)) { expandIteratorInline(call); } else { currentLineno = call->lineno; Vec<Symbol*> iterators; Vec<Symbol*> indices; setupSimultaneousIterators(iterators, indices, iterator, index, block); VarSymbol* firstCond = NULL; for (int i = 0; i < iterators.n; i++) { IteratorInfo* ii = iterators.v[i]->type->defaultConstructor->iteratorInfo; VarSymbol* cond = new VarSymbol("_cond", dtBool); cond->isCompilerTemp = true; block->insertBefore(new CallExpr(ii->zip1, iterators.v[i])); block->insertBefore(new DefExpr(cond)); block->insertBefore(new CallExpr(PRIMITIVE_MOVE, cond, new CallExpr(ii->hasMore, iterators.v[i]))); block->insertAtHead(new CallExpr(PRIMITIVE_MOVE, indices.v[i], new CallExpr(ii->getValue, iterators.v[i]))); block->insertAtTail(new CallExpr(ii->zip3, iterators.v[i])); block->insertAtTail(new CallExpr(PRIMITIVE_MOVE, cond, new CallExpr(ii->hasMore, iterators.v[i]))); if (isBoundedIterator(iterators.v[i]->type->defaultConstructor)) { if (!firstCond) { firstCond = cond; } else { VarSymbol* tmp = new VarSymbol("_tmp", dtBool); block->insertAtHead(new CondStmt(new SymExpr(tmp), new CallExpr(PRIMITIVE_RT_ERROR, new_StringSymbol("zippered iterations have non-equal lengths")))); block->insertAtHead(new CallExpr(PRIMITIVE_MOVE, tmp, new CallExpr(PRIMITIVE_EQUAL, cond, new_IntSymbol(0)))); block->insertAtHead(new DefExpr(tmp)); block->insertAfter(new CondStmt(new SymExpr(cond), new CallExpr(PRIMITIVE_RT_ERROR, new_StringSymbol("zippered iterations have non-equal lengths")))); } } block->insertAtHead(new CallExpr(ii->zip2, iterators.v[i])); block->insertAfter(new CallExpr(ii->zip4, iterators.v[i])); } call->get(2)->remove(); call->get(1)->remove(); if (firstCond) call->insertAtTail(firstCond); else call->insertAtTail(gTrue); } } void lowerIterators() { forv_Vec(BaseAST, ast, gAsts) { if (CallExpr* call = toCallExpr(ast)) if (call->isPrimitive(PRIMITIVE_LOOP_FOR)) if (call->numActuals() > 1) expand_for_loop(call); } forv_Vec(FnSymbol, fn, gFns) { if (fn->fnTag == FN_ITERATOR) { collapseBlocks(fn->body); removeUnnecessaryGotos(fn); if (!fNoCopyPropagation) localCopyPropagation(fn); if (!fNoDeadCodeElimination) { deadVariableElimination(fn); deadExpressionElimination(fn); } } } forv_Vec(FnSymbol, fn, gFns) { if (fn->fnTag == FN_ITERATOR) { lowerIterator(fn); } } // fix GET_MEMBER primitives that access fields of an iterator class // via a number forv_Vec(BaseAST, ast, gAsts) { if (CallExpr* call = toCallExpr(ast)) { if (call->parentSymbol && call->isPrimitive(PRIMITIVE_GET_MEMBER)) { ClassType* ct = toClassType(call->get(1)->typeInfo()); if (ct->symbol->hasPragma("ref")) ct = toClassType(getValueType(ct)); long num; if (get_int(call->get(2), &num)) { Symbol* field = ct->getField(num); call->get(2)->replace(new SymExpr(field)); CallExpr* parent = toCallExpr(call->parentExpr); INT_ASSERT(parent->isPrimitive(PRIMITIVE_MOVE)); Symbol* local = toSymExpr(parent->get(1))->var; if (local->type == field->type) call->primitive = primitives[PRIMITIVE_GET_MEMBER_VALUE]; else if (local->type != field->type->refType) INT_FATAL(call, "unexpected case"); } } } } // // make _getIterator(ic: _iteratorClass) implement a shallow copy to // avoid clashing during simultaneous iterations of the same // iterator class // // see functions/deitz/iterators/test_generic_use_twice2.chpl // forv_Vec(FnSymbol, fn, gFns) { if (fn->hasPragma("iterator class copy")) { BlockStmt* block = new BlockStmt(); ArgSymbol* ic = fn->getFormal(1); INT_ASSERT(ic); ClassType* ct = toClassType(ic->type); INT_ASSERT(ct); VarSymbol* cp = new VarSymbol("ic_copy", ct); cp->isCompilerTemp = true; block->insertAtTail(new DefExpr(cp)); block->insertAtTail(new CallExpr(PRIMITIVE_MOVE, cp, new CallExpr(PRIMITIVE_CHPL_ALLOC, ct->symbol, new_StringSymbol("iterator class copy")))); for_fields(field, ct) { VarSymbol* tmp = new VarSymbol("_tmp", field->type); block->insertAtTail(new DefExpr(tmp)); block->insertAtTail(new CallExpr(PRIMITIVE_MOVE, tmp, new CallExpr(PRIMITIVE_GET_MEMBER_VALUE, ic, field))); block->insertAtTail(new CallExpr(PRIMITIVE_SET_MEMBER, cp, field, tmp)); } block->insertAtTail(new CallExpr(PRIMITIVE_RETURN, cp)); fn->body->replace(block); } } } <commit_msg>disabled zipper iteration checks with --no-bounds-checks<commit_after>#include "astutil.h" #include "expr.h" #include "optimizations.h" #include "passes.h" #include "stmt.h" #include "stringutil.h" #include "symbol.h" #include "iterator.h" static void expandIteratorInline(CallExpr* call) { BlockStmt* body; Symbol* index = toSymExpr(call->get(1))->var; Symbol* ic = toSymExpr(call->get(2))->var; FnSymbol* iterator = ic->type->defaultConstructor; BlockStmt* ibody = iterator->body->copy(); CallExpr* yield = NULL; reset_line_info(ibody, call->lineno); body = toBlockStmt(call->parentExpr); call->remove(); body->replace(ibody); Vec<BaseAST*> asts; collect_asts(ibody, asts); forv_Vec(BaseAST, ast, asts) { if (CallExpr* call = toCallExpr(ast)) { if (call->isPrimitive(PRIMITIVE_YIELD)) { yield = call; call->replace(body); } if (call->isPrimitive(PRIMITIVE_RETURN)) // remove return call->remove(); } } body->insertAtHead(new CallExpr(PRIMITIVE_MOVE, index, yield->get(1))); int count = 1; for_formals(formal, iterator) { forv_Vec(BaseAST, ast, asts) { if (SymExpr* se = toSymExpr(ast)) { if (se->var == formal) { // count is used to get the nth field out of the iterator class; // it is replaced by the field once the iterator class is created Expr* stmt = se->getStmtExpr(); VarSymbol* tmp = new VarSymbol(formal->name, formal->type); tmp->isCompilerTemp = true; stmt->insertBefore(new DefExpr(tmp)); stmt->insertBefore(new CallExpr(PRIMITIVE_MOVE, tmp, new CallExpr(PRIMITIVE_GET_MEMBER, ic, new_IntSymbol(count)))); se->var = tmp; } } } count++; } } static bool canInlineIterator(FnSymbol* iterator) { Vec<BaseAST*> asts; collect_asts(iterator, asts); int count = 0; forv_Vec(BaseAST, ast, asts) { if (CallExpr* call = toCallExpr(ast)) if (call->isPrimitive(PRIMITIVE_YIELD)) count++; } if (count == 1) return true; return false; } static void setupSimultaneousIterators(Vec<Symbol*>& iterators, Vec<Symbol*>& indices, Symbol* gIterator, Symbol* gIndex, BlockStmt* loop) { if (gIterator->type->symbol->hasPragma("tuple")) { ClassType* iteratorType = toClassType(gIterator->type); ClassType* indexType = toClassType(gIndex->type); for (int i=1; i <= iteratorType->fields.length(); i++) { Symbol* iterator = new VarSymbol("_iterator", iteratorType->getField(i)->type); loop->insertBefore(new DefExpr(iterator)); loop->insertBefore(new CallExpr(PRIMITIVE_MOVE, iterator, new CallExpr(PRIMITIVE_GET_MEMBER_VALUE, gIterator, iteratorType->getField(i)))); Symbol* index = new VarSymbol("_index", indexType->getField(i)->type); loop->insertAtHead(new CallExpr(PRIMITIVE_SET_MEMBER, gIndex, indexType->getField(i), index)); loop->insertAtHead(new DefExpr(index)); setupSimultaneousIterators(iterators, indices, iterator, index, loop); } } else { iterators.add(gIterator); indices.add(gIndex); } } static bool isBoundedIterator(FnSymbol* fn) { if (fn->_this) { Type* type = fn->_this->type; if (type->symbol->hasPragma("ref")) type = getValueType(type); if (type->symbol->hasPragma("range")) { if (!strcmp(toSymbol(type->substitutions.v[1].value)->name, "bounded")) return true; else return false; } } return true; } static void expand_for_loop(CallExpr* call) { BlockStmt* block = toBlockStmt(call->parentExpr); if (!block || block->loopInfo != call) INT_FATAL(call, "bad for loop primitive"); SymExpr* se1 = toSymExpr(call->get(1)); SymExpr* se2 = toSymExpr(call->get(2)); if (!se1 || !se2) INT_FATAL(call, "bad for loop primitive"); VarSymbol* index = toVarSymbol(se1->var); VarSymbol* iterator = toVarSymbol(se2->var); if (!index || !iterator) INT_FATAL(call, "bad for loop primitive"); if (!fNoInlineIterators && iterator->type->defaultConstructor->iteratorInfo && canInlineIterator(iterator->type->defaultConstructor)) { expandIteratorInline(call); } else { currentLineno = call->lineno; Vec<Symbol*> iterators; Vec<Symbol*> indices; setupSimultaneousIterators(iterators, indices, iterator, index, block); VarSymbol* firstCond = NULL; for (int i = 0; i < iterators.n; i++) { IteratorInfo* ii = iterators.v[i]->type->defaultConstructor->iteratorInfo; VarSymbol* cond = new VarSymbol("_cond", dtBool); cond->isCompilerTemp = true; block->insertBefore(new CallExpr(ii->zip1, iterators.v[i])); block->insertBefore(new DefExpr(cond)); block->insertBefore(new CallExpr(PRIMITIVE_MOVE, cond, new CallExpr(ii->hasMore, iterators.v[i]))); block->insertAtHead(new CallExpr(PRIMITIVE_MOVE, indices.v[i], new CallExpr(ii->getValue, iterators.v[i]))); block->insertAtTail(new CallExpr(ii->zip3, iterators.v[i])); block->insertAtTail(new CallExpr(PRIMITIVE_MOVE, cond, new CallExpr(ii->hasMore, iterators.v[i]))); if (isBoundedIterator(iterators.v[i]->type->defaultConstructor)) { if (!firstCond) { firstCond = cond; } else if (!fNoBoundsChecks) { VarSymbol* tmp = new VarSymbol("_tmp", dtBool); block->insertAtHead(new CondStmt(new SymExpr(tmp), new CallExpr(PRIMITIVE_RT_ERROR, new_StringSymbol("zippered iterations have non-equal lengths")))); block->insertAtHead(new CallExpr(PRIMITIVE_MOVE, tmp, new CallExpr(PRIMITIVE_EQUAL, cond, new_IntSymbol(0)))); block->insertAtHead(new DefExpr(tmp)); block->insertAfter(new CondStmt(new SymExpr(cond), new CallExpr(PRIMITIVE_RT_ERROR, new_StringSymbol("zippered iterations have non-equal lengths")))); } } block->insertAtHead(new CallExpr(ii->zip2, iterators.v[i])); block->insertAfter(new CallExpr(ii->zip4, iterators.v[i])); } call->get(2)->remove(); call->get(1)->remove(); if (firstCond) call->insertAtTail(firstCond); else call->insertAtTail(gTrue); } } void lowerIterators() { forv_Vec(BaseAST, ast, gAsts) { if (CallExpr* call = toCallExpr(ast)) if (call->isPrimitive(PRIMITIVE_LOOP_FOR)) if (call->numActuals() > 1) expand_for_loop(call); } forv_Vec(FnSymbol, fn, gFns) { if (fn->fnTag == FN_ITERATOR) { collapseBlocks(fn->body); removeUnnecessaryGotos(fn); if (!fNoCopyPropagation) localCopyPropagation(fn); if (!fNoDeadCodeElimination) { deadVariableElimination(fn); deadExpressionElimination(fn); } } } forv_Vec(FnSymbol, fn, gFns) { if (fn->fnTag == FN_ITERATOR) { lowerIterator(fn); } } // fix GET_MEMBER primitives that access fields of an iterator class // via a number forv_Vec(BaseAST, ast, gAsts) { if (CallExpr* call = toCallExpr(ast)) { if (call->parentSymbol && call->isPrimitive(PRIMITIVE_GET_MEMBER)) { ClassType* ct = toClassType(call->get(1)->typeInfo()); if (ct->symbol->hasPragma("ref")) ct = toClassType(getValueType(ct)); long num; if (get_int(call->get(2), &num)) { Symbol* field = ct->getField(num); call->get(2)->replace(new SymExpr(field)); CallExpr* parent = toCallExpr(call->parentExpr); INT_ASSERT(parent->isPrimitive(PRIMITIVE_MOVE)); Symbol* local = toSymExpr(parent->get(1))->var; if (local->type == field->type) call->primitive = primitives[PRIMITIVE_GET_MEMBER_VALUE]; else if (local->type != field->type->refType) INT_FATAL(call, "unexpected case"); } } } } // // make _getIterator(ic: _iteratorClass) implement a shallow copy to // avoid clashing during simultaneous iterations of the same // iterator class // // see functions/deitz/iterators/test_generic_use_twice2.chpl // forv_Vec(FnSymbol, fn, gFns) { if (fn->hasPragma("iterator class copy")) { BlockStmt* block = new BlockStmt(); ArgSymbol* ic = fn->getFormal(1); INT_ASSERT(ic); ClassType* ct = toClassType(ic->type); INT_ASSERT(ct); VarSymbol* cp = new VarSymbol("ic_copy", ct); cp->isCompilerTemp = true; block->insertAtTail(new DefExpr(cp)); block->insertAtTail(new CallExpr(PRIMITIVE_MOVE, cp, new CallExpr(PRIMITIVE_CHPL_ALLOC, ct->symbol, new_StringSymbol("iterator class copy")))); for_fields(field, ct) { VarSymbol* tmp = new VarSymbol("_tmp", field->type); block->insertAtTail(new DefExpr(tmp)); block->insertAtTail(new CallExpr(PRIMITIVE_MOVE, tmp, new CallExpr(PRIMITIVE_GET_MEMBER_VALUE, ic, field))); block->insertAtTail(new CallExpr(PRIMITIVE_SET_MEMBER, cp, field, tmp)); } block->insertAtTail(new CallExpr(PRIMITIVE_RETURN, cp)); fn->body->replace(block); } } } <|endoftext|>
<commit_before>#include "framework/logger.h" #include "framework/data.h" #include "game/apocresources/pck.h" #include "game/apocresources/apocpalette.h" #include "framework/palette.h" #include "framework/ignorecase.h" #include "library/strings.h" #include "framework/imageloader_interface.h" #include "framework/musicloader_interface.h" #include "framework/sampleloader_interface.h" using namespace OpenApoc; namespace { std::map<UString, std::unique_ptr<OpenApoc::ImageLoaderFactory>> *registeredImageBackends = nullptr; std::map<UString, std::unique_ptr<OpenApoc::MusicLoaderFactory>> *registeredMusicLoaders = nullptr; std::map<UString, std::unique_ptr<OpenApoc::SampleLoaderFactory>> *registeredSampleLoaders = nullptr; }; //anonymous namespace namespace OpenApoc { void registerImageLoader(ImageLoaderFactory* factory, UString name) { if (!registeredImageBackends) { registeredImageBackends = new std::map<UString, std::unique_ptr<OpenApoc::ImageLoaderFactory>>(); } registeredImageBackends->emplace(name, std::unique_ptr<ImageLoaderFactory>(factory)); } void registerSampleLoader(SampleLoaderFactory *factory, UString name) { if (!registeredSampleLoaders) { registeredSampleLoaders = new std::map<UString, std::unique_ptr<OpenApoc::SampleLoaderFactory>>(); } registeredSampleLoaders->emplace(name, std::unique_ptr<SampleLoaderFactory>(factory)); } void registerMusicLoader(MusicLoaderFactory *factory, UString name) { if (!registeredMusicLoaders) { registeredMusicLoaders = new std::map<UString, std::unique_ptr<OpenApoc::MusicLoaderFactory>>(); } registeredMusicLoaders->emplace(name, std::unique_ptr<MusicLoaderFactory>(factory)); } Data::Data(Framework &fw, std::vector<UString> paths, int imageCacheSize, int imageSetCacheSize) { for (auto &imageBackend : *registeredImageBackends) { auto t = imageBackend.first; ImageLoader *l = imageBackend.second->create(); if (l) { this->imageLoaders.emplace_back(l); LogInfo("Initialised image loader %s", t.str().c_str()); } else LogWarning("Failed to load image loader %s", t.str().c_str()); } for (auto &sampleBackend : *registeredSampleLoaders) { auto t = sampleBackend.first; SampleLoader *s = sampleBackend.second->create(fw); if (s) { this->sampleLoaders.emplace_back(s); LogInfo("Initialised sample loader %s", t.str().c_str()); } else LogWarning("Failed to load sample loader %s", t.str().c_str()); } for (auto &musicLoader : *registeredMusicLoaders) { auto t = musicLoader.first; MusicLoader *m = musicLoader.second->create(fw); if (m) { this->musicLoaders.emplace_back(m); LogInfo("Initialised music loader %s", t.str().c_str()); } else LogWarning("Failed to load music loader %s", t.str().c_str()); } this->writeDir = PHYSFS_getPrefDir(PROGRAM_ORGANISATION, PROGRAM_NAME); LogInfo("Setting write directory to \"%s\"", this->writeDir.str().c_str()); PHYSFS_setWriteDir(this->writeDir.str().c_str()); for (int i = 0; i < imageCacheSize; i++) pinnedImages.push(nullptr); for (int i = 0; i < imageSetCacheSize; i++) pinnedImageSets.push(nullptr); //Paths are supplied in inverse-search order (IE the last in 'paths' should be the first searched) for(auto &p : paths) { if (!PHYSFS_mount(p.str().c_str(), "/", 0)) { LogWarning("Failed to add resource dir \"%s\"", p.str().c_str()); continue; } else LogInfo("Resource dir \"%s\" mounted to \"%s\"", p.str().c_str(), PHYSFS_getMountPoint(p.str().c_str())); } //Finally, the write directory trumps all PHYSFS_mount(this->writeDir.str().c_str(), "/", 0); } Data::~Data() { } std::shared_ptr<ImageSet> Data::load_image_set(UString path) { UString cacheKey = path.toUpper(); std::shared_ptr<ImageSet> imgSet = this->imageSetCache[cacheKey].lock(); if (imgSet) { return imgSet; } //PCK resources come in the format: //"PCK:PCKFILE:TABFILE[:optional/ignored]" if (path.substr(0, 4) == "PCK:") { auto splitString = path.split(':'); imgSet = PCKLoader::load(*this, splitString[1], splitString[2]); } else { LogError("Unknown image set format \"%s\"", path.str().c_str()); return nullptr; } this->pinnedImageSets.push(imgSet); this->pinnedImageSets.pop(); this->imageSetCache[cacheKey] = imgSet; return imgSet; } std::shared_ptr<Sample> Data::load_sample(UString path) { UString cacheKey = path.toUpper(); std::shared_ptr<Sample> sample = this->sampleCache[cacheKey].lock(); if (sample) return sample; for (auto &loader : this->sampleLoaders) { sample = loader->loadSample(path); if (sample) break; } if (!sample) { LogInfo("Failed to load sample \"%s\"", path.str().c_str()); return nullptr; } this->sampleCache[cacheKey] = sample; return sample; } std::shared_ptr<MusicTrack> Data::load_music(UString path) { //No cache for music tracks, just stream of disk for (auto &loader : this->musicLoaders) { auto track = loader->loadMusic(path); if (track) return track; } LogInfo("Failed to load music track \"%s\"", path.str().c_str()); return nullptr; } std::shared_ptr<Image> Data::load_image(UString path) { //Use an uppercase version of the path for the cache key UString cacheKey = path.toUpper(); std::shared_ptr<Image> img = this->imageCache[cacheKey].lock(); if (img) { return img; } if (path.substr(0,4) == "PCK:") { auto splitString = path.split(':'); auto imageSet = this->load_image_set(splitString[0] + ":" + splitString[1] + ":" + splitString[2]); if (!imageSet) { return nullptr; } //PCK resources come in the format: //"PCK:PCKFILE:TABFILE:INDEX" //or //"PCK:PCKFILE:TABFILE:INDEX:PALETTE" if we want them already in rgb space switch (splitString.size()) { case 4: { img = imageSet->images[Strings::ToInteger(splitString[3])]; break; } case 5: { std::shared_ptr<PaletteImage> pImg = std::dynamic_pointer_cast<PaletteImage>( this->load_image("PCK:" + splitString[1] + ":" + splitString[2] + ":" + splitString[3])); assert(pImg); auto pal = this->load_palette(splitString[4]); assert(pal); img = pImg->toRGBImage(pal); break; } default: LogError("Invalid PCK resource string \"%s\"", path.str().c_str()); return nullptr; } } else { for (auto &loader : imageLoaders) { img = loader->loadImage(GetCorrectCaseFilename(path)); if (img) { break; } } if (!img) { LogInfo("Failed to load image \"%s\"", path.str().c_str()); return nullptr; } } this->pinnedImages.push(img); this->pinnedImages.pop(); this->imageCache[cacheKey] = img; return img; } PHYSFS_file* Data::load_file(UString path, Data::FileMode mode) { //FIXME: read/write/append modes if (mode != Data::FileMode::Read) { LogError("Non-readonly modes not yet supported"); } UString foundPath = GetCorrectCaseFilename(path); if (foundPath == "") { LogInfo("Failed to open file \"%s\" : \"%s\"", path.str().c_str(), PHYSFS_getLastError()); return nullptr; } PHYSFS_File *f = PHYSFS_openRead(foundPath.str().c_str()); if (!f) { LogError("Failed to open file \"%s\" despite being 'found' at \"%s\"? - error: \"%s\"", path.str().c_str(), foundPath.str().c_str(), PHYSFS_getLastError()); return nullptr; } return f; } std::shared_ptr<Palette> Data::load_palette(UString path) { std::shared_ptr<RGBImage> img = std::dynamic_pointer_cast<RGBImage>(this->load_image(path)); if (img) { unsigned int idx = 0; auto p = std::make_shared<Palette>(img->size.x * img->size.y); RGBImageLock src{img, ImageLockUse::Read}; for (unsigned int y = 0; y < img->size.y; y++) { for (unsigned int x = 0; x < img->size.x; x++) { Colour c = src.get(Vec2<int>{x,y}); p->SetColour(idx, c); idx++; } } return p; } else { std::shared_ptr<Palette> pal(loadApocPalette(*this, path)); if (!pal) { LogError("Failed to open palette \"%s\"", path.str().c_str()); return nullptr; } return pal; } } UString Data::GetCorrectCaseFilename(UString Filename) { std::string u8Filename = Filename.str(); std::unique_ptr<char[]> buf(new char[u8Filename.length() + 1]); strncpy(buf.get(), u8Filename.c_str(), u8Filename.length()); buf[Filename.length()] = '\0'; if (PHYSFSEXT_locateCorrectCase(buf.get())) { LogInfo("Failed to find file \"%s\"", Filename.str().c_str()); return ""; } return buf.get(); } UString Data::GetActualFilename(UString Filename) { UString foundPath = GetCorrectCaseFilename(Filename); LogError("Found \"%s\" at \"%s\"", Filename.str().c_str(), foundPath.str().c_str()); UString folder = PHYSFS_getRealDir(foundPath.str().c_str()); LogError("Found \"%s\" in \"%s\"", Filename.str().c_str(), folder.str().c_str()); return folder + "/" + foundPath; } }; //namespace OpenApoc <commit_msg>Only print error if GetActualFilename() fails<commit_after>#include "framework/logger.h" #include "framework/data.h" #include "game/apocresources/pck.h" #include "game/apocresources/apocpalette.h" #include "framework/palette.h" #include "framework/ignorecase.h" #include "library/strings.h" #include "framework/imageloader_interface.h" #include "framework/musicloader_interface.h" #include "framework/sampleloader_interface.h" using namespace OpenApoc; namespace { std::map<UString, std::unique_ptr<OpenApoc::ImageLoaderFactory>> *registeredImageBackends = nullptr; std::map<UString, std::unique_ptr<OpenApoc::MusicLoaderFactory>> *registeredMusicLoaders = nullptr; std::map<UString, std::unique_ptr<OpenApoc::SampleLoaderFactory>> *registeredSampleLoaders = nullptr; }; //anonymous namespace namespace OpenApoc { void registerImageLoader(ImageLoaderFactory* factory, UString name) { if (!registeredImageBackends) { registeredImageBackends = new std::map<UString, std::unique_ptr<OpenApoc::ImageLoaderFactory>>(); } registeredImageBackends->emplace(name, std::unique_ptr<ImageLoaderFactory>(factory)); } void registerSampleLoader(SampleLoaderFactory *factory, UString name) { if (!registeredSampleLoaders) { registeredSampleLoaders = new std::map<UString, std::unique_ptr<OpenApoc::SampleLoaderFactory>>(); } registeredSampleLoaders->emplace(name, std::unique_ptr<SampleLoaderFactory>(factory)); } void registerMusicLoader(MusicLoaderFactory *factory, UString name) { if (!registeredMusicLoaders) { registeredMusicLoaders = new std::map<UString, std::unique_ptr<OpenApoc::MusicLoaderFactory>>(); } registeredMusicLoaders->emplace(name, std::unique_ptr<MusicLoaderFactory>(factory)); } Data::Data(Framework &fw, std::vector<UString> paths, int imageCacheSize, int imageSetCacheSize) { for (auto &imageBackend : *registeredImageBackends) { auto t = imageBackend.first; ImageLoader *l = imageBackend.second->create(); if (l) { this->imageLoaders.emplace_back(l); LogInfo("Initialised image loader %s", t.str().c_str()); } else LogWarning("Failed to load image loader %s", t.str().c_str()); } for (auto &sampleBackend : *registeredSampleLoaders) { auto t = sampleBackend.first; SampleLoader *s = sampleBackend.second->create(fw); if (s) { this->sampleLoaders.emplace_back(s); LogInfo("Initialised sample loader %s", t.str().c_str()); } else LogWarning("Failed to load sample loader %s", t.str().c_str()); } for (auto &musicLoader : *registeredMusicLoaders) { auto t = musicLoader.first; MusicLoader *m = musicLoader.second->create(fw); if (m) { this->musicLoaders.emplace_back(m); LogInfo("Initialised music loader %s", t.str().c_str()); } else LogWarning("Failed to load music loader %s", t.str().c_str()); } this->writeDir = PHYSFS_getPrefDir(PROGRAM_ORGANISATION, PROGRAM_NAME); LogInfo("Setting write directory to \"%s\"", this->writeDir.str().c_str()); PHYSFS_setWriteDir(this->writeDir.str().c_str()); for (int i = 0; i < imageCacheSize; i++) pinnedImages.push(nullptr); for (int i = 0; i < imageSetCacheSize; i++) pinnedImageSets.push(nullptr); //Paths are supplied in inverse-search order (IE the last in 'paths' should be the first searched) for(auto &p : paths) { if (!PHYSFS_mount(p.str().c_str(), "/", 0)) { LogWarning("Failed to add resource dir \"%s\"", p.str().c_str()); continue; } else LogInfo("Resource dir \"%s\" mounted to \"%s\"", p.str().c_str(), PHYSFS_getMountPoint(p.str().c_str())); } //Finally, the write directory trumps all PHYSFS_mount(this->writeDir.str().c_str(), "/", 0); } Data::~Data() { } std::shared_ptr<ImageSet> Data::load_image_set(UString path) { UString cacheKey = path.toUpper(); std::shared_ptr<ImageSet> imgSet = this->imageSetCache[cacheKey].lock(); if (imgSet) { return imgSet; } //PCK resources come in the format: //"PCK:PCKFILE:TABFILE[:optional/ignored]" if (path.substr(0, 4) == "PCK:") { auto splitString = path.split(':'); imgSet = PCKLoader::load(*this, splitString[1], splitString[2]); } else { LogError("Unknown image set format \"%s\"", path.str().c_str()); return nullptr; } this->pinnedImageSets.push(imgSet); this->pinnedImageSets.pop(); this->imageSetCache[cacheKey] = imgSet; return imgSet; } std::shared_ptr<Sample> Data::load_sample(UString path) { UString cacheKey = path.toUpper(); std::shared_ptr<Sample> sample = this->sampleCache[cacheKey].lock(); if (sample) return sample; for (auto &loader : this->sampleLoaders) { sample = loader->loadSample(path); if (sample) break; } if (!sample) { LogInfo("Failed to load sample \"%s\"", path.str().c_str()); return nullptr; } this->sampleCache[cacheKey] = sample; return sample; } std::shared_ptr<MusicTrack> Data::load_music(UString path) { //No cache for music tracks, just stream of disk for (auto &loader : this->musicLoaders) { auto track = loader->loadMusic(path); if (track) return track; } LogInfo("Failed to load music track \"%s\"", path.str().c_str()); return nullptr; } std::shared_ptr<Image> Data::load_image(UString path) { //Use an uppercase version of the path for the cache key UString cacheKey = path.toUpper(); std::shared_ptr<Image> img = this->imageCache[cacheKey].lock(); if (img) { return img; } if (path.substr(0,4) == "PCK:") { auto splitString = path.split(':'); auto imageSet = this->load_image_set(splitString[0] + ":" + splitString[1] + ":" + splitString[2]); if (!imageSet) { return nullptr; } //PCK resources come in the format: //"PCK:PCKFILE:TABFILE:INDEX" //or //"PCK:PCKFILE:TABFILE:INDEX:PALETTE" if we want them already in rgb space switch (splitString.size()) { case 4: { img = imageSet->images[Strings::ToInteger(splitString[3])]; break; } case 5: { std::shared_ptr<PaletteImage> pImg = std::dynamic_pointer_cast<PaletteImage>( this->load_image("PCK:" + splitString[1] + ":" + splitString[2] + ":" + splitString[3])); assert(pImg); auto pal = this->load_palette(splitString[4]); assert(pal); img = pImg->toRGBImage(pal); break; } default: LogError("Invalid PCK resource string \"%s\"", path.str().c_str()); return nullptr; } } else { for (auto &loader : imageLoaders) { img = loader->loadImage(GetCorrectCaseFilename(path)); if (img) { break; } } if (!img) { LogInfo("Failed to load image \"%s\"", path.str().c_str()); return nullptr; } } this->pinnedImages.push(img); this->pinnedImages.pop(); this->imageCache[cacheKey] = img; return img; } PHYSFS_file* Data::load_file(UString path, Data::FileMode mode) { //FIXME: read/write/append modes if (mode != Data::FileMode::Read) { LogError("Non-readonly modes not yet supported"); } UString foundPath = GetCorrectCaseFilename(path); if (foundPath == "") { LogInfo("Failed to open file \"%s\" : \"%s\"", path.str().c_str(), PHYSFS_getLastError()); return nullptr; } PHYSFS_File *f = PHYSFS_openRead(foundPath.str().c_str()); if (!f) { LogError("Failed to open file \"%s\" despite being 'found' at \"%s\"? - error: \"%s\"", path.str().c_str(), foundPath.str().c_str(), PHYSFS_getLastError()); return nullptr; } return f; } std::shared_ptr<Palette> Data::load_palette(UString path) { std::shared_ptr<RGBImage> img = std::dynamic_pointer_cast<RGBImage>(this->load_image(path)); if (img) { unsigned int idx = 0; auto p = std::make_shared<Palette>(img->size.x * img->size.y); RGBImageLock src{img, ImageLockUse::Read}; for (unsigned int y = 0; y < img->size.y; y++) { for (unsigned int x = 0; x < img->size.x; x++) { Colour c = src.get(Vec2<int>{x,y}); p->SetColour(idx, c); idx++; } } return p; } else { std::shared_ptr<Palette> pal(loadApocPalette(*this, path)); if (!pal) { LogError("Failed to open palette \"%s\"", path.str().c_str()); return nullptr; } return pal; } } UString Data::GetCorrectCaseFilename(UString Filename) { std::string u8Filename = Filename.str(); std::unique_ptr<char[]> buf(new char[u8Filename.length() + 1]); strncpy(buf.get(), u8Filename.c_str(), u8Filename.length()); buf[Filename.length()] = '\0'; if (PHYSFSEXT_locateCorrectCase(buf.get())) { LogInfo("Failed to find file \"%s\"", Filename.str().c_str()); return ""; } return buf.get(); } UString Data::GetActualFilename(UString Filename) { UString foundPath = GetCorrectCaseFilename(Filename); if (foundPath == "") { LogError("Failed to get filename for \"%s\"", Filename.str().c_str()); return ""; } UString folder = PHYSFS_getRealDir(foundPath.str().c_str()); return folder + "/" + foundPath; } }; //namespace OpenApoc <|endoftext|>
<commit_before>/* * Copyright (c) 2014, 2017, 2019 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __BASE_LOGGING_HH__ #define __BASE_LOGGING_HH__ #include <cassert> #include <sstream> #include <utility> #include "base/compiler.hh" #include "base/cprintf.hh" class Logger { public: // Get a Logger for the specified type of message. static Logger &getPanic(); static Logger &getFatal(); static Logger &getWarn(); static Logger &getInfo(); static Logger &getHack(); enum LogLevel { PANIC, FATAL, WARN, INFO, HACK, NUM_LOG_LEVELS, }; static void setLevel(LogLevel ll) { getPanic().enabled = (ll >= PANIC); getFatal().enabled = (ll >= FATAL); getWarn().enabled = (ll >= WARN); getInfo().enabled = (ll >= INFO); getHack().enabled = (ll >= HACK); } struct Loc { Loc(const char *file, int line) : file(file), line(line) {} const char *file; int line; }; Logger(const char *prefix) : enabled(true), prefix(prefix) { assert(prefix); } virtual ~Logger() {}; void print(const Loc &loc, const std::string &str) { std::stringstream ss; ss << prefix << str; if (str.length() && str.back() != '\n' && str.back() != '\r') ss << std::endl; if (!enabled) return; log(loc, ss.str()); } template<typename ...Args> void print(const Loc &loc, const char *format, const Args &...args) { std::stringstream ss; ccprintf(ss, format, args...); print(loc, ss.str()); } template<typename ...Args> void print(const Loc &loc, const std::string &format, const Args &...args) { print(loc, format.c_str(), args...); } // This helper is necessary since noreturn isn't inherited by virtual // functions, and gcc will get mad if a function calls panic and then // doesn't return. void exit_helper() M5_ATTR_NORETURN { exit(); ::abort(); } protected: bool enabled; virtual void log(const Loc &loc, std::string s) = 0; virtual void exit() { /* Fall through to the abort in exit_helper. */ } const char *prefix; }; #define base_message(logger, ...) \ logger.print(::Logger::Loc(__FILE__, __LINE__), __VA_ARGS__) /* * Only print the message the first time this expression is * encountered. i.e. This doesn't check the string itself and * prevent duplicate strings, this prevents the statement from * happening more than once. So, even if the arguments change and that * would have resulted in a different message thoes messages would be * supressed. */ #define base_message_once(...) do { \ static bool once = false; \ if (!once) { \ base_message(__VA_ARGS__); \ once = true; \ } \ } while (0) #define exit_message(logger, ...) \ do { \ base_message(logger, __VA_ARGS__); \ logger.exit_helper(); \ } while (0) /** * This implements a cprintf based panic() function. panic() should * be called when something happens that should never ever happen * regardless of what the user does (i.e., an acutal m5 bug). panic() * might call abort which can dump core or enter the debugger. */ #define panic(...) exit_message(::Logger::getPanic(), __VA_ARGS__) /** * This implements a cprintf based fatal() function. fatal() should * be called when the simulation cannot continue due to some condition * that is the user's fault (bad configuration, invalid arguments, * etc.) and not a simulator bug. fatal() might call exit, unlike panic(). */ #define fatal(...) exit_message(::Logger::getFatal(), __VA_ARGS__) /** * Conditional panic macro that checks the supplied condition and only panics * if the condition is true and allows the programmer to specify diagnostic * printout. Useful to replace if + panic, or if + print + assert, etc. * * @param cond Condition that is checked; if true -> panic * @param ... Printf-based format string with arguments, extends printout. */ #define panic_if(cond, ...) \ do { \ if ((cond)) { \ panic("panic condition " # cond " occurred: %s", \ csprintf(__VA_ARGS__)); \ } \ } while (0) /** * Conditional fatal macro that checks the supplied condition and only causes a * fatal error if the condition is true and allows the programmer to specify * diagnostic printout. Useful to replace if + fatal, or if + print + assert, * etc. * * @param cond Condition that is checked; if true -> fatal * @param ... Printf-based format string with arguments, extends printout. */ #define fatal_if(cond, ...) \ do { \ if ((cond)) { \ fatal("fatal condition " # cond " occurred: %s", \ csprintf(__VA_ARGS__)); \ } \ } while (0) #define warn(...) base_message(::Logger::getWarn(), __VA_ARGS__) #define inform(...) base_message(::Logger::getInfo(), __VA_ARGS__) #define hack(...) base_message(::Logger::getHack(), __VA_ARGS__) #define warn_once(...) base_message_once(::Logger::getWarn(), __VA_ARGS__) #define inform_once(...) base_message_once(::Logger::getInfo(), __VA_ARGS__) #define hack_once(...) base_message_once(::Logger::getHack(), __VA_ARGS__) /** * Conditional warning macro that checks the supplied condition and * only prints a warning if the condition is true. Useful to replace * if + warn. * * @param cond Condition that is checked; if true -> warn * @param ... Printf-based format string with arguments, extends printout. */ #define warn_if(cond, ...) \ do { \ if ((cond)) \ warn(__VA_ARGS__); \ } while (0) #define warn_if_once(cond, ...) \ do { \ if ((cond)) \ warn_once(__VA_ARGS__); \ } while (0) /** * The chatty assert macro will function like a normal assert, but will allow * the specification of additional, helpful material to aid debugging why the * assertion actually failed. Like the normal assertion, the chatty_assert * will not be active in fast builds. * * @param cond Condition that is checked; if false -> assert * @param ... Printf-based format string with arguments, extends printout. */ #ifdef NDEBUG #define chatty_assert(cond, ...) #else //!NDEBUG #define chatty_assert(cond, ...) \ do { \ if (!(cond)) \ panic("assert(" # cond ") failed: %s", csprintf(__VA_ARGS__)); \ } while (0) #endif // NDEBUG #endif // __BASE_LOGGING_HH__ <commit_msg>base: Tag API methods and macros in logger.hh<commit_after>/* * Copyright (c) 2014, 2017, 2019 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __BASE_LOGGING_HH__ #define __BASE_LOGGING_HH__ #include <cassert> #include <sstream> #include <utility> #include "base/compiler.hh" #include "base/cprintf.hh" class Logger { public: /** * Get a Logger for the specified type of message. */ static Logger &getPanic(); static Logger &getFatal(); static Logger &getWarn(); static Logger &getInfo(); static Logger &getHack(); enum LogLevel { PANIC, FATAL, WARN, INFO, HACK, NUM_LOG_LEVELS, }; static void setLevel(LogLevel ll) { getPanic().enabled = (ll >= PANIC); getFatal().enabled = (ll >= FATAL); getWarn().enabled = (ll >= WARN); getInfo().enabled = (ll >= INFO); getHack().enabled = (ll >= HACK); } struct Loc { Loc(const char *file, int line) : file(file), line(line) {} const char *file; int line; }; Logger(const char *prefix) : enabled(true), prefix(prefix) { assert(prefix); } virtual ~Logger() {}; void print(const Loc &loc, const std::string &str) { std::stringstream ss; ss << prefix << str; if (str.length() && str.back() != '\n' && str.back() != '\r') ss << std::endl; if (!enabled) return; log(loc, ss.str()); } template<typename ...Args> void print(const Loc &loc, const char *format, const Args &...args) { std::stringstream ss; ccprintf(ss, format, args...); print(loc, ss.str()); } template<typename ...Args> void print(const Loc &loc, const std::string &format, const Args &...args) { print(loc, format.c_str(), args...); } /** * This helper is necessary since noreturn isn't inherited by virtual * functions, and gcc will get mad if a function calls panic and then * doesn't return. */ void exit_helper() M5_ATTR_NORETURN { exit(); ::abort(); } protected: bool enabled; virtual void log(const Loc &loc, std::string s) = 0; virtual void exit() { /* Fall through to the abort in exit_helper. */ } const char *prefix; }; #define base_message(logger, ...) \ logger.print(::Logger::Loc(__FILE__, __LINE__), __VA_ARGS__) /* * Only print the message the first time this expression is * encountered. i.e. This doesn't check the string itself and * prevent duplicate strings, this prevents the statement from * happening more than once. So, even if the arguments change and that * would have resulted in a different message thoes messages would be * supressed. */ #define base_message_once(...) do { \ static bool once = false; \ if (!once) { \ base_message(__VA_ARGS__); \ once = true; \ } \ } while (0) #define exit_message(logger, ...) \ do { \ base_message(logger, __VA_ARGS__); \ logger.exit_helper(); \ } while (0) /** * This implements a cprintf based panic() function. panic() should * be called when something happens that should never ever happen * regardless of what the user does (i.e., an acutal m5 bug). panic() * might call abort which can dump core or enter the debugger. * * \def panic(...) * * @ingroup api_logger */ #define panic(...) exit_message(::Logger::getPanic(), __VA_ARGS__) /** * This implements a cprintf based fatal() function. fatal() should * be called when the simulation cannot continue due to some condition * that is the user's fault (bad configuration, invalid arguments, * etc.) and not a simulator bug. fatal() might call exit, unlike panic(). * * \def fatal(...) * * @ingroup api_logger */ #define fatal(...) exit_message(::Logger::getFatal(), __VA_ARGS__) /** * Conditional panic macro that checks the supplied condition and only panics * if the condition is true and allows the programmer to specify diagnostic * printout. Useful to replace if + panic, or if + print + assert, etc. * * @param cond Condition that is checked; if true -> panic * @param ... Printf-based format string with arguments, extends printout. * * \def panic_if(...) * * @ingroup api_logger */ #define panic_if(cond, ...) \ do { \ if ((cond)) { \ panic("panic condition " # cond " occurred: %s", \ csprintf(__VA_ARGS__)); \ } \ } while (0) /** * Conditional fatal macro that checks the supplied condition and only causes a * fatal error if the condition is true and allows the programmer to specify * diagnostic printout. Useful to replace if + fatal, or if + print + assert, * etc. * * @param cond Condition that is checked; if true -> fatal * @param ... Printf-based format string with arguments, extends printout. * * \def fatal_if(...) * * @ingroup api_logger */ #define fatal_if(cond, ...) \ do { \ if ((cond)) { \ fatal("fatal condition " # cond " occurred: %s", \ csprintf(__VA_ARGS__)); \ } \ } while (0) /** * \def warn(...) * \def inform(...) * \def hack(...) * \def warn_once(...) * \def inform_once(...) * \def hack_once(...) * * @ingroup api_logger * @{ */ #define warn(...) base_message(::Logger::getWarn(), __VA_ARGS__) #define inform(...) base_message(::Logger::getInfo(), __VA_ARGS__) #define hack(...) base_message(::Logger::getHack(), __VA_ARGS__) #define warn_once(...) base_message_once(::Logger::getWarn(), __VA_ARGS__) #define inform_once(...) base_message_once(::Logger::getInfo(), __VA_ARGS__) #define hack_once(...) base_message_once(::Logger::getHack(), __VA_ARGS__) /** @} */ // end of api_logger /** * * Conditional warning macro that checks the supplied condition and * only prints a warning if the condition is true. Useful to replace * if + warn. * * @param cond Condition that is checked; if true -> warn * @param ... Printf-based format string with arguments, extends printout. * * \def warn_if(cond, ...) * \def warn_if_once(cond, ...) * * @ingroup api_logger * @{ */ #define warn_if(cond, ...) \ do { \ if ((cond)) \ warn(__VA_ARGS__); \ } while (0) #define warn_if_once(cond, ...) \ do { \ if ((cond)) \ warn_once(__VA_ARGS__); \ } while (0) /** @} */ // end of api_logger /** * The chatty assert macro will function like a normal assert, but will allow * the specification of additional, helpful material to aid debugging why the * assertion actually failed. Like the normal assertion, the chatty_assert * will not be active in fast builds. * * @param cond Condition that is checked; if false -> assert * @param ... Printf-based format string with arguments, extends printout. * * \def chatty_assert(cond, ...) * * @ingroup api_logger */ #ifdef NDEBUG #define chatty_assert(cond, ...) #else //!NDEBUG #define chatty_assert(cond, ...) \ do { \ if (!(cond)) \ panic("assert(" # cond ") failed: %s", csprintf(__VA_ARGS__)); \ } while (0) #endif // NDEBUG /** @} */ // end of api_logger #endif // __BASE_LOGGING_HH__ <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/proxy/proxy_resolver_mac.h" #include <CoreFoundation/CoreFoundation.h> #include <CoreServices/CoreServices.h> #include "base/logging.h" #include "base/mac/foundation_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/string_util.h" #include "base/sys_string_conversions.h" #include "net/base/net_errors.h" #include "net/proxy/proxy_info.h" #include "net/proxy/proxy_server.h" namespace { // Utility function to map a CFProxyType to a ProxyServer::Scheme. // If the type is unknown, returns ProxyServer::SCHEME_INVALID. net::ProxyServer::Scheme GetProxyServerScheme(CFStringRef proxy_type) { if (CFEqual(proxy_type, kCFProxyTypeNone)) return net::ProxyServer::SCHEME_DIRECT; if (CFEqual(proxy_type, kCFProxyTypeHTTP)) return net::ProxyServer::SCHEME_HTTP; if (CFEqual(proxy_type, kCFProxyTypeSOCKS)) { // We can't tell whether this was v4 or v5. We will assume it is // v5 since that is the only version OS X supports. return net::ProxyServer::SCHEME_SOCKS5; } return net::ProxyServer::SCHEME_INVALID; } // Callback for CFNetworkExecuteProxyAutoConfigurationURL. |client| is a pointer // to a CFTypeRef. This stashes either |error| or |proxies| in that location. void ResultCallback(void* client, CFArrayRef proxies, CFErrorRef error) { DCHECK((proxies != NULL) == (error == NULL)); CFTypeRef* result_ptr = reinterpret_cast<CFTypeRef*>(client); DCHECK(result_ptr != NULL); DCHECK(*result_ptr == NULL); if (error != NULL) { *result_ptr = CFRetain(error); } else { *result_ptr = CFRetain(proxies); } CFRunLoopStop(CFRunLoopGetCurrent()); } } // namespace namespace net { ProxyResolverMac::ProxyResolverMac() : ProxyResolver(false /*expects_pac_bytes*/) { } ProxyResolverMac::~ProxyResolverMac() {} // Gets the proxy information for a query URL from a PAC. Implementation // inspired by http://developer.apple.com/samplecode/CFProxySupportTool/ int ProxyResolverMac::GetProxyForURL(const GURL& query_url, ProxyInfo* results, CompletionCallback* /*callback*/, RequestHandle* /*request*/, const BoundNetLog& net_log) { base::mac::ScopedCFTypeRef<CFStringRef> query_ref( base::SysUTF8ToCFStringRef(query_url.spec())); base::mac::ScopedCFTypeRef<CFURLRef> query_url_ref( CFURLCreateWithString(kCFAllocatorDefault, query_ref.get(), NULL)); if (!query_url_ref.get()) return ERR_FAILED; base::mac::ScopedCFTypeRef<CFStringRef> pac_ref( base::SysUTF8ToCFStringRef( script_data_->type() == ProxyResolverScriptData::TYPE_AUTO_DETECT ? std::string() : script_data_->url().spec())); base::mac::ScopedCFTypeRef<CFURLRef> pac_url_ref( CFURLCreateWithString(kCFAllocatorDefault, pac_ref.get(), NULL)); if (!pac_url_ref.get()) return ERR_FAILED; // Work around <rdar://problem/5530166>. This dummy call to // CFNetworkCopyProxiesForURL initializes some state within CFNetwork that is // required by CFNetworkExecuteProxyAutoConfigurationURL. CFArrayRef dummy_result = CFNetworkCopyProxiesForURL(query_url_ref.get(), NULL); if (dummy_result) CFRelease(dummy_result); // We cheat here. We need to act as if we were synchronous, so we pump the // runloop ourselves. Our caller moved us to a new thread anyway, so this is // OK to do. (BTW, CFNetworkExecuteProxyAutoConfigurationURL returns a // runloop source we need to release despite its name.) CFTypeRef result = NULL; CFStreamClientContext context = { 0, &result, NULL, NULL, NULL }; base::mac::ScopedCFTypeRef<CFRunLoopSourceRef> runloop_source( CFNetworkExecuteProxyAutoConfigurationURL(pac_url_ref.get(), query_url_ref.get(), ResultCallback, &context)); if (!runloop_source) return ERR_FAILED; const CFStringRef private_runloop_mode = CFSTR("org.chromium.ProxyResolverMac"); CFRunLoopAddSource(CFRunLoopGetCurrent(), runloop_source.get(), private_runloop_mode); CFRunLoopRunInMode(private_runloop_mode, DBL_MAX, false); CFRunLoopRemoveSource(CFRunLoopGetCurrent(), runloop_source.get(), private_runloop_mode); DCHECK(result != NULL); if (CFGetTypeID(result) == CFErrorGetTypeID()) { // TODO(avi): do something better than this CFRelease(result); return ERR_FAILED; } DCHECK(CFGetTypeID(result) == CFArrayGetTypeID()); base::mac::ScopedCFTypeRef<CFArrayRef> proxy_array_ref((CFArrayRef)result); // This string will be an ordered list of <proxy-uri> entries, separated by // semi-colons. It is the format that ProxyInfo::UseNamedProxy() expects. // proxy-uri = [<proxy-scheme>"://"]<proxy-host>":"<proxy-port> // (This also includes entries for direct connection, as "direct://"). std::string proxy_uri_list; CFIndex proxy_array_count = CFArrayGetCount(proxy_array_ref.get()); for (CFIndex i = 0; i < proxy_array_count; ++i) { CFDictionaryRef proxy_dictionary = (CFDictionaryRef)CFArrayGetValueAtIndex(proxy_array_ref.get(), i); DCHECK(CFGetTypeID(proxy_dictionary) == CFDictionaryGetTypeID()); // The dictionary may have the following keys: // - kCFProxyTypeKey : The type of the proxy // - kCFProxyHostNameKey // - kCFProxyPortNumberKey : The meat we're after. // - kCFProxyUsernameKey // - kCFProxyPasswordKey : Despite the existence of these keys in the // documentation, they're never populated. Even if a // username/password were to be set in the network // proxy system preferences, we'd need to fetch it // from the Keychain ourselves. CFProxy is such a // tease. // - kCFProxyAutoConfigurationURLKey : If the PAC file specifies another // PAC file, I'm going home. CFStringRef proxy_type = (CFStringRef)base::mac::GetValueFromDictionary(proxy_dictionary, kCFProxyTypeKey, CFStringGetTypeID()); ProxyServer proxy_server = ProxyServer::FromDictionary( GetProxyServerScheme(proxy_type), proxy_dictionary, kCFProxyHostNameKey, kCFProxyPortNumberKey); if (!proxy_server.is_valid()) continue; if (!proxy_uri_list.empty()) proxy_uri_list += ";"; proxy_uri_list += proxy_server.ToURI(); } if (!proxy_uri_list.empty()) results->UseNamedProxy(proxy_uri_list); // Else do nothing (results is already guaranteed to be in the default state). return OK; } void ProxyResolverMac::CancelRequest(RequestHandle request) { NOTREACHED(); } void ProxyResolverMac::CancelSetPacScript() { NOTREACHED(); } int ProxyResolverMac::SetPacScript( const scoped_refptr<ProxyResolverScriptData>& script_data, CompletionCallback* /*callback*/) { script_data_ = script_data; return OK; } } // namespace net <commit_msg>Check for kCFProxyTypeHttps in ProxyResolverMac<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/proxy/proxy_resolver_mac.h" #include <CoreFoundation/CoreFoundation.h> #include <CoreServices/CoreServices.h> #include "base/logging.h" #include "base/mac/foundation_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/string_util.h" #include "base/sys_string_conversions.h" #include "net/base/net_errors.h" #include "net/proxy/proxy_info.h" #include "net/proxy/proxy_server.h" namespace { // Utility function to map a CFProxyType to a ProxyServer::Scheme. // If the type is unknown, returns ProxyServer::SCHEME_INVALID. net::ProxyServer::Scheme GetProxyServerScheme(CFStringRef proxy_type) { if (CFEqual(proxy_type, kCFProxyTypeNone)) return net::ProxyServer::SCHEME_DIRECT; if (CFEqual(proxy_type, kCFProxyTypeHTTP)) return net::ProxyServer::SCHEME_HTTP; if (CFEqual(proxy_type, kCFProxyTypeHTTPS)) { // The "HTTPS" on the Mac side here means "proxy applies to https://" URLs; // the proxy itself is still expected to be an HTTP proxy. return net::ProxyServer::SCHEME_HTTP; } if (CFEqual(proxy_type, kCFProxyTypeSOCKS)) { // We can't tell whether this was v4 or v5. We will assume it is // v5 since that is the only version OS X supports. return net::ProxyServer::SCHEME_SOCKS5; } return net::ProxyServer::SCHEME_INVALID; } // Callback for CFNetworkExecuteProxyAutoConfigurationURL. |client| is a pointer // to a CFTypeRef. This stashes either |error| or |proxies| in that location. void ResultCallback(void* client, CFArrayRef proxies, CFErrorRef error) { DCHECK((proxies != NULL) == (error == NULL)); CFTypeRef* result_ptr = reinterpret_cast<CFTypeRef*>(client); DCHECK(result_ptr != NULL); DCHECK(*result_ptr == NULL); if (error != NULL) { *result_ptr = CFRetain(error); } else { *result_ptr = CFRetain(proxies); } CFRunLoopStop(CFRunLoopGetCurrent()); } } // namespace namespace net { ProxyResolverMac::ProxyResolverMac() : ProxyResolver(false /*expects_pac_bytes*/) { } ProxyResolverMac::~ProxyResolverMac() {} // Gets the proxy information for a query URL from a PAC. Implementation // inspired by http://developer.apple.com/samplecode/CFProxySupportTool/ int ProxyResolverMac::GetProxyForURL(const GURL& query_url, ProxyInfo* results, CompletionCallback* /*callback*/, RequestHandle* /*request*/, const BoundNetLog& net_log) { base::mac::ScopedCFTypeRef<CFStringRef> query_ref( base::SysUTF8ToCFStringRef(query_url.spec())); base::mac::ScopedCFTypeRef<CFURLRef> query_url_ref( CFURLCreateWithString(kCFAllocatorDefault, query_ref.get(), NULL)); if (!query_url_ref.get()) return ERR_FAILED; base::mac::ScopedCFTypeRef<CFStringRef> pac_ref( base::SysUTF8ToCFStringRef( script_data_->type() == ProxyResolverScriptData::TYPE_AUTO_DETECT ? std::string() : script_data_->url().spec())); base::mac::ScopedCFTypeRef<CFURLRef> pac_url_ref( CFURLCreateWithString(kCFAllocatorDefault, pac_ref.get(), NULL)); if (!pac_url_ref.get()) return ERR_FAILED; // Work around <rdar://problem/5530166>. This dummy call to // CFNetworkCopyProxiesForURL initializes some state within CFNetwork that is // required by CFNetworkExecuteProxyAutoConfigurationURL. CFArrayRef dummy_result = CFNetworkCopyProxiesForURL(query_url_ref.get(), NULL); if (dummy_result) CFRelease(dummy_result); // We cheat here. We need to act as if we were synchronous, so we pump the // runloop ourselves. Our caller moved us to a new thread anyway, so this is // OK to do. (BTW, CFNetworkExecuteProxyAutoConfigurationURL returns a // runloop source we need to release despite its name.) CFTypeRef result = NULL; CFStreamClientContext context = { 0, &result, NULL, NULL, NULL }; base::mac::ScopedCFTypeRef<CFRunLoopSourceRef> runloop_source( CFNetworkExecuteProxyAutoConfigurationURL(pac_url_ref.get(), query_url_ref.get(), ResultCallback, &context)); if (!runloop_source) return ERR_FAILED; const CFStringRef private_runloop_mode = CFSTR("org.chromium.ProxyResolverMac"); CFRunLoopAddSource(CFRunLoopGetCurrent(), runloop_source.get(), private_runloop_mode); CFRunLoopRunInMode(private_runloop_mode, DBL_MAX, false); CFRunLoopRemoveSource(CFRunLoopGetCurrent(), runloop_source.get(), private_runloop_mode); DCHECK(result != NULL); if (CFGetTypeID(result) == CFErrorGetTypeID()) { // TODO(avi): do something better than this CFRelease(result); return ERR_FAILED; } DCHECK(CFGetTypeID(result) == CFArrayGetTypeID()); base::mac::ScopedCFTypeRef<CFArrayRef> proxy_array_ref((CFArrayRef)result); // This string will be an ordered list of <proxy-uri> entries, separated by // semi-colons. It is the format that ProxyInfo::UseNamedProxy() expects. // proxy-uri = [<proxy-scheme>"://"]<proxy-host>":"<proxy-port> // (This also includes entries for direct connection, as "direct://"). std::string proxy_uri_list; CFIndex proxy_array_count = CFArrayGetCount(proxy_array_ref.get()); for (CFIndex i = 0; i < proxy_array_count; ++i) { CFDictionaryRef proxy_dictionary = (CFDictionaryRef)CFArrayGetValueAtIndex(proxy_array_ref.get(), i); DCHECK(CFGetTypeID(proxy_dictionary) == CFDictionaryGetTypeID()); // The dictionary may have the following keys: // - kCFProxyTypeKey : The type of the proxy // - kCFProxyHostNameKey // - kCFProxyPortNumberKey : The meat we're after. // - kCFProxyUsernameKey // - kCFProxyPasswordKey : Despite the existence of these keys in the // documentation, they're never populated. Even if a // username/password were to be set in the network // proxy system preferences, we'd need to fetch it // from the Keychain ourselves. CFProxy is such a // tease. // - kCFProxyAutoConfigurationURLKey : If the PAC file specifies another // PAC file, I'm going home. CFStringRef proxy_type = (CFStringRef)base::mac::GetValueFromDictionary(proxy_dictionary, kCFProxyTypeKey, CFStringGetTypeID()); ProxyServer proxy_server = ProxyServer::FromDictionary( GetProxyServerScheme(proxy_type), proxy_dictionary, kCFProxyHostNameKey, kCFProxyPortNumberKey); if (!proxy_server.is_valid()) continue; if (!proxy_uri_list.empty()) proxy_uri_list += ";"; proxy_uri_list += proxy_server.ToURI(); } if (!proxy_uri_list.empty()) results->UseNamedProxy(proxy_uri_list); // Else do nothing (results is already guaranteed to be in the default state). return OK; } void ProxyResolverMac::CancelRequest(RequestHandle request) { NOTREACHED(); } void ProxyResolverMac::CancelSetPacScript() { NOTREACHED(); } int ProxyResolverMac::SetPacScript( const scoped_refptr<ProxyResolverScriptData>& script_data, CompletionCallback* /*callback*/) { script_data_ = script_data; return OK; } } // namespace net <|endoftext|>
<commit_before>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "netpp_internal.h" #include "primitive.h" #include "address.h" #include "buffer.h" #include "socket_service.h" #include "socket.h" namespace netpp { IP IP::v4(void) { return IP(AF_INET); } IP IP::v6(void) { return IP(AF_INET6); } IP IP::get_protocol(int family) { return IP(family); } Tcp Tcp::v4(void) { return Tcp(AF_INET); } Tcp Tcp::v6(void) { return Tcp(AF_INET6); } Tcp Tcp::get_protocol(int family) { return Tcp(family); } int Tcp::socket_type(void) const { return SOCK_STREAM; } int Tcp::protocol(void) const { return IPPROTO_TCP; } Udp Udp::v4(void) { return Udp(AF_INET); } Udp Udp::v6(void) { return Udp(AF_INET6); } Udp Udp::get_protocol(int family) { return Udp(family); } int Udp::socket_type(void) const { return SOCK_DGRAM; } int Udp::protocol(void) const { return IPPROTO_UDP; } BaseSocket::BaseSocket(SocketService& service) : service_(&service) { } BaseSocket::~BaseSocket(void) { } void BaseSocket::open(int family, int socket_type, int protocol) { std::error_code ec; fd_ = get_service().open(family, socket_type, protocol, ec); netpp::throw_error(ec, "open"); } void BaseSocket::open(int family, int socket_type, int protocol, std::error_code& ec) { fd_ = get_service().open(family, socket_type, protocol, ec); } void BaseSocket::close(void) { std::error_code ec; get_service().close(fd_, ec); netpp::throw_error(ec, "close"); } void BaseSocket::close(std::error_code& ec) { this->get_service().close(fd_, ec); } void BaseSocket::shutdown(int what) { std::error_code ec; get_service().shutdown(fd_, what, ec); netpp::throw_error(ec, "shutdown"); } void BaseSocket::shutdown(int what, std::error_code& ec) { get_service().shutdown(fd_, what, ec); } void BaseSocket::bind(const Address& addr) { std::error_code ec; get_service().bind(fd_, addr, ec); netpp::throw_error(ec, "bind"); } void BaseSocket::bind(const Address& addr, std::error_code& ec) { get_service().bind(fd_, addr, ec); } void BaseSocket::connect(const Address& addr) { std::error_code ec; get_service().connect(fd_, addr, ec); netpp::throw_error(ec, "connect"); } void BaseSocket::connect(const Address& addr, std::error_code& ec) { get_service().connect(fd_, addr, ec); } void BaseSocket::async_connect( const Address& addr, const ConnectHandler& handler) { get_service().async_connect(fd_, addr, handler); } void BaseSocket::async_connect(const Address& addr, ConnectHandler&& handler) { get_service().async_connect(fd_, addr, std::move(handler)); } void BaseSocket::set_non_blocking(bool mode) { std::error_code ec; if (get_service().set_non_blocking(fd_, mode, ec)) non_blocking_ = mode; netpp::throw_error(ec, "non_blocking"); } void BaseSocket::set_non_blocking(bool mode, std::error_code& ec) { if (get_service().set_non_blocking(fd_, mode, ec)) non_blocking_ = mode; } TcpSocket::TcpSocket(SocketService& service) : BaseSocket(service) { } TcpSocket::TcpSocket(SocketService& service, const ProtocolType& protocol) : BaseSocket(service) { std::error_code ec; open(protocol.family(), protocol.socket_type(), protocol.protocol(), ec); netpp::throw_error(ec, "open"); } TcpSocket::~TcpSocket(void) { } std::size_t TcpSocket::read(const MutableBuffer& buf) { std::error_code ec; auto nread = get_service().read(get_fd(), buf, is_non_blocking(), ec); netpp::throw_error(ec, "read"); return nread; } std::size_t TcpSocket::read(const MutableBuffer& buf, std::error_code& ec) { return get_service().read(get_fd(), buf, is_non_blocking(), ec); } void TcpSocket::async_read( const MutableBuffer& buf, const ReadHandler& handler) { get_service().async_read(get_fd(), buf, handler); } void TcpSocket::async_read(const MutableBuffer& buf, ReadHandler&& handler) { get_service().async_read(get_fd(), buf, std::move(handler)); } std::size_t TcpSocket::read_some(const MutableBuffer& buf) { std::error_code ec; auto nread = get_service().read(get_fd(), buf, is_non_blocking(), ec); netpp::throw_error(ec, "read_some"); return nread; } std::size_t TcpSocket::read_some( const MutableBuffer& buf, std::error_code& ec) { return get_service().read(get_fd(), buf, is_non_blocking(), ec); } void TcpSocket::async_read_some( const MutableBuffer& buf, const ReadHandler&& handler) { get_service().async_read_some(get_fd(), buf, handler); } void TcpSocket::async_read_some( const MutableBuffer& buf, ReadHandler&& handler) { get_service().async_read_some(get_fd(), buf, std::move(handler)); } std::size_t TcpSocket::write(const ConstBuffer& buf) { std::error_code ec; auto nwrote = get_service().write(get_fd(), buf, is_non_blocking(), ec); netpp::throw_error(ec, "write"); return nwrote; } std::size_t TcpSocket::write(const ConstBuffer& buf, std::error_code& ec) { return get_service().write(get_fd(), buf, is_non_blocking(), ec); } void TcpSocket::async_write( const ConstBuffer& buf, const WriteHandler& handler) { get_service().async_write(get_fd(), buf, handler); } void TcpSocket::async_write(const ConstBuffer& buf, WriteHandler&& handler) { get_service().async_write(get_fd(), buf, std::move(handler)); } std::size_t TcpSocket::write_some(const ConstBuffer& buf) { std::error_code ec; auto nwrote = get_service().write(get_fd(), buf, is_non_blocking(), ec); netpp::throw_error(ec, "write_some"); return nwrote; } std::size_t TcpSocket::write_some(const ConstBuffer& buf, std::error_code& ec) { return get_service().write(get_fd(), buf, is_non_blocking(), ec); } void TcpSocket::async_write_some( const ConstBuffer& buf, const WriteHandler& handler) { get_service().async_write_some(get_fd(), buf, handler); } void TcpSocket::async_write_some( const ConstBuffer& buf, WriteHandler&& handler) { get_service().async_write_some(get_fd(), buf, std::move(handler)); } UdpSocket::UdpSocket(SocketService& service) : BaseSocket(service) { } UdpSocket::UdpSocket(SocketService& service, const ProtocolType& protocol) : BaseSocket(service) { std::error_code ec; open(protocol.family(), protocol.socket_type(), protocol.protocol(), ec); netpp::throw_error(ec, "open"); } UdpSocket::UdpSocket(SocketService& service, const Address& addr) : BaseSocket(service) { const auto protocol = netpp::get_protocol<ProtocolType>(addr); std::error_code ec; open(protocol.family(), protocol.socket_type(), protocol.protocol(), ec); netpp::throw_error(ec, "open"); bind(addr, ec); netpp::throw_error(ec, "bind"); } UdpSocket::~UdpSocket(void) { } std::size_t UdpSocket::read(const MutableBuffer& buf) { std::error_code ec; auto nread = get_service().read(get_fd(), buf, is_non_blocking(), ec); netpp::throw_error(ec, "read"); return nread; } std::size_t UdpSocket::read(const MutableBuffer& buf, std::error_code& ec) { return get_service().read(get_fd(), buf, is_non_blocking(), ec); } void UdpSocket::async_read( const MutableBuffer& buf, const ReadHandler& handler) { get_service().async_read(get_fd(), buf, handler); } void UdpSocket::async_read(const MutableBuffer& buf, ReadHandler&& handler) { get_service().async_read(get_fd(), buf, std::move(handler)); } std::size_t UdpSocket::read_from(const MutableBuffer& buf, Address& addr) { std::error_code ec; auto nread = get_service().read_from(get_fd(), buf, addr, is_non_blocking(), ec); netpp::throw_error(ec, "read_from"); return nread; } std::size_t UdpSocket::read_from( const MutableBuffer& buf, Address& addr, std::error_code& ec) { return get_service().read_from(get_fd(), buf, addr, is_non_blocking(), ec); } void UdpSocket::async_read_from( const MutableBuffer& buf, Address& addr, const ReadHandler& handler) { get_service().async_read_from(get_fd(), buf, addr, handler); } void UdpSocket::async_read_from( const MutableBuffer& buf, Address& addr, ReadHandler&& handler) { get_service().async_read_from(get_fd(), buf, addr, std::move(handler)); } std::size_t UdpSocket::write(const ConstBuffer& buf) { std::error_code ec; auto nwrote = get_service().write(get_fd(), buf, is_non_blocking(), ec); netpp::throw_error(ec, "write"); return nwrote; } std::size_t UdpSocket::write(const ConstBuffer& buf, std::error_code& ec) { return get_service().write(get_fd(), buf, is_non_blocking(), ec); } void UdpSocket::async_write( const ConstBuffer& buf, const WriteHandler& handler) { get_service().async_write(get_fd(), buf, handler); } void UdpSocket::async_write(const ConstBuffer& buf, WriteHandler&& handler) { get_service().async_write(get_fd(), buf, std::move(handler)); } std::size_t UdpSocket::write_to(const ConstBuffer& buf, const Address& addr) { std::error_code ec; auto nwrote = get_service().write_to(get_fd(), buf, addr, is_non_blocking(), ec); netpp::throw_error(ec, "write_to"); return nwrote; } std::size_t UdpSocket::write_to( const ConstBuffer& buf, const Address& addr, std::error_code& ec) { return get_service().write_to(get_fd(), buf, addr, is_non_blocking(), ec); } void UdpSocket::async_write_to( const ConstBuffer& buf, const Address& addr, const WriteHandler& handler) { get_service().async_write_to(get_fd(), buf, addr, handler); } void UdpSocket::async_write_to( const ConstBuffer& buf, const Address& addr, WriteHandler&& handler) { get_service().async_write_to(get_fd(), buf, addr, std::move(handler)); } } <commit_msg>:construction: chore(socket): udpated the implementation of socket<commit_after>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "netpp_internal.h" #include "primitive.h" #include "address.h" #include "buffer.h" #include "socket_service.h" #include "socket.h" namespace netpp { IP IP::v4(void) { return IP(AF_INET); } IP IP::v6(void) { return IP(AF_INET6); } IP IP::get_protocol(int family) { return IP(family); } Tcp Tcp::v4(void) { return Tcp(AF_INET); } Tcp Tcp::v6(void) { return Tcp(AF_INET6); } Tcp Tcp::get_protocol(int family) { return Tcp(family); } int Tcp::socket_type(void) const { return SOCK_STREAM; } int Tcp::protocol(void) const { return IPPROTO_TCP; } Udp Udp::v4(void) { return Udp(AF_INET); } Udp Udp::v6(void) { return Udp(AF_INET6); } Udp Udp::get_protocol(int family) { return Udp(family); } int Udp::socket_type(void) const { return SOCK_DGRAM; } int Udp::protocol(void) const { return IPPROTO_UDP; } BaseSocket::BaseSocket(SocketService& service) : service_(&service) { } BaseSocket::~BaseSocket(void) { } void BaseSocket::open(int family, int socket_type, int protocol) { std::error_code ec; fd_ = get_service().open(family, socket_type, protocol, ec); netpp::throw_error(ec, "open"); } void BaseSocket::open(int family, int socket_type, int protocol, std::error_code& ec) { fd_ = get_service().open(family, socket_type, protocol, ec); } void BaseSocket::close(void) { std::error_code ec; get_service().close(fd_, ec); netpp::throw_error(ec, "close"); } void BaseSocket::close(std::error_code& ec) { this->get_service().close(fd_, ec); } void BaseSocket::shutdown(int what) { std::error_code ec; get_service().shutdown(fd_, what, ec); netpp::throw_error(ec, "shutdown"); } void BaseSocket::shutdown(int what, std::error_code& ec) { get_service().shutdown(fd_, what, ec); } void BaseSocket::bind(const Address& addr) { std::error_code ec; get_service().bind(fd_, addr, ec); netpp::throw_error(ec, "bind"); } void BaseSocket::bind(const Address& addr, std::error_code& ec) { get_service().bind(fd_, addr, ec); } void BaseSocket::connect(const Address& addr) { std::error_code ec; get_service().connect(fd_, addr, ec); netpp::throw_error(ec, "connect"); } void BaseSocket::connect(const Address& addr, std::error_code& ec) { get_service().connect(fd_, addr, ec); } void BaseSocket::async_connect( const Address& addr, const ConnectHandler& handler) { get_service().async_connect(fd_, addr, handler); } void BaseSocket::async_connect(const Address& addr, ConnectHandler&& handler) { get_service().async_connect(fd_, addr, std::move(handler)); } void BaseSocket::set_non_blocking(bool mode) { std::error_code ec; if (get_service().set_non_blocking(fd_, mode, ec)) non_blocking_ = mode; netpp::throw_error(ec, "non_blocking"); } void BaseSocket::set_non_blocking(bool mode, std::error_code& ec) { if (get_service().set_non_blocking(fd_, mode, ec)) non_blocking_ = mode; } TcpSocket::TcpSocket(SocketService& service) : BaseSocket(service) { } TcpSocket::TcpSocket(SocketService& service, const ProtocolType& protocol) : BaseSocket(service) { std::error_code ec; open(protocol.family(), protocol.socket_type(), protocol.protocol(), ec); netpp::throw_error(ec, "open"); } TcpSocket::~TcpSocket(void) { } std::size_t TcpSocket::read(const MutableBuffer& buf) { std::error_code ec; auto nread = get_service().read(get_fd(), buf, is_non_blocking(), ec); netpp::throw_error(ec, "read"); return nread; } std::size_t TcpSocket::read(const MutableBuffer& buf, std::error_code& ec) { return get_service().read(get_fd(), buf, is_non_blocking(), ec); } void TcpSocket::async_read( const MutableBuffer& buf, const ReadHandler& handler) { get_service().async_read(get_fd(), buf, handler); } void TcpSocket::async_read(const MutableBuffer& buf, ReadHandler&& handler) { get_service().async_read(get_fd(), buf, std::move(handler)); } std::size_t TcpSocket::read_some(const MutableBuffer& buf) { std::error_code ec; auto nread = get_service().read_some(get_fd(), buf, is_non_blocking(), ec); netpp::throw_error(ec, "read_some"); return nread; } std::size_t TcpSocket::read_some( const MutableBuffer& buf, std::error_code& ec) { return get_service().read_some(get_fd(), buf, is_non_blocking(), ec); } void TcpSocket::async_read_some( const MutableBuffer& buf, const ReadHandler&& handler) { get_service().async_read_some(get_fd(), buf, handler); } void TcpSocket::async_read_some( const MutableBuffer& buf, ReadHandler&& handler) { get_service().async_read_some(get_fd(), buf, std::move(handler)); } std::size_t TcpSocket::write(const ConstBuffer& buf) { std::error_code ec; auto nwrote = get_service().write(get_fd(), buf, is_non_blocking(), ec); netpp::throw_error(ec, "write"); return nwrote; } std::size_t TcpSocket::write(const ConstBuffer& buf, std::error_code& ec) { return get_service().write(get_fd(), buf, is_non_blocking(), ec); } void TcpSocket::async_write( const ConstBuffer& buf, const WriteHandler& handler) { get_service().async_write(get_fd(), buf, handler); } void TcpSocket::async_write(const ConstBuffer& buf, WriteHandler&& handler) { get_service().async_write(get_fd(), buf, std::move(handler)); } std::size_t TcpSocket::write_some(const ConstBuffer& buf) { std::error_code ec; auto nwrote = get_service().write_some(get_fd(), buf, is_non_blocking(), ec); netpp::throw_error(ec, "write_some"); return nwrote; } std::size_t TcpSocket::write_some(const ConstBuffer& buf, std::error_code& ec) { return get_service().write_some(get_fd(), buf, is_non_blocking(), ec); } void TcpSocket::async_write_some( const ConstBuffer& buf, const WriteHandler& handler) { get_service().async_write_some(get_fd(), buf, handler); } void TcpSocket::async_write_some( const ConstBuffer& buf, WriteHandler&& handler) { get_service().async_write_some(get_fd(), buf, std::move(handler)); } UdpSocket::UdpSocket(SocketService& service) : BaseSocket(service) { } UdpSocket::UdpSocket(SocketService& service, const ProtocolType& protocol) : BaseSocket(service) { std::error_code ec; open(protocol.family(), protocol.socket_type(), protocol.protocol(), ec); netpp::throw_error(ec, "open"); } UdpSocket::UdpSocket(SocketService& service, const Address& addr) : BaseSocket(service) { const auto protocol = netpp::get_protocol<ProtocolType>(addr); std::error_code ec; open(protocol.family(), protocol.socket_type(), protocol.protocol(), ec); netpp::throw_error(ec, "open"); bind(addr, ec); netpp::throw_error(ec, "bind"); } UdpSocket::~UdpSocket(void) { } std::size_t UdpSocket::read(const MutableBuffer& buf) { std::error_code ec; auto nread = get_service().read(get_fd(), buf, is_non_blocking(), ec); netpp::throw_error(ec, "read"); return nread; } std::size_t UdpSocket::read(const MutableBuffer& buf, std::error_code& ec) { return get_service().read(get_fd(), buf, is_non_blocking(), ec); } void UdpSocket::async_read( const MutableBuffer& buf, const ReadHandler& handler) { get_service().async_read(get_fd(), buf, handler); } void UdpSocket::async_read(const MutableBuffer& buf, ReadHandler&& handler) { get_service().async_read(get_fd(), buf, std::move(handler)); } std::size_t UdpSocket::read_from(const MutableBuffer& buf, Address& addr) { std::error_code ec; auto nread = get_service().read_from(get_fd(), buf, addr, is_non_blocking(), ec); netpp::throw_error(ec, "read_from"); return nread; } std::size_t UdpSocket::read_from( const MutableBuffer& buf, Address& addr, std::error_code& ec) { return get_service().read_from(get_fd(), buf, addr, is_non_blocking(), ec); } void UdpSocket::async_read_from( const MutableBuffer& buf, Address& addr, const ReadHandler& handler) { get_service().async_read_from(get_fd(), buf, addr, handler); } void UdpSocket::async_read_from( const MutableBuffer& buf, Address& addr, ReadHandler&& handler) { get_service().async_read_from(get_fd(), buf, addr, std::move(handler)); } std::size_t UdpSocket::write(const ConstBuffer& buf) { std::error_code ec; auto nwrote = get_service().write(get_fd(), buf, is_non_blocking(), ec); netpp::throw_error(ec, "write"); return nwrote; } std::size_t UdpSocket::write(const ConstBuffer& buf, std::error_code& ec) { return get_service().write(get_fd(), buf, is_non_blocking(), ec); } void UdpSocket::async_write( const ConstBuffer& buf, const WriteHandler& handler) { get_service().async_write(get_fd(), buf, handler); } void UdpSocket::async_write(const ConstBuffer& buf, WriteHandler&& handler) { get_service().async_write(get_fd(), buf, std::move(handler)); } std::size_t UdpSocket::write_to(const ConstBuffer& buf, const Address& addr) { std::error_code ec; auto nwrote = get_service().write_to(get_fd(), buf, addr, is_non_blocking(), ec); netpp::throw_error(ec, "write_to"); return nwrote; } std::size_t UdpSocket::write_to( const ConstBuffer& buf, const Address& addr, std::error_code& ec) { return get_service().write_to(get_fd(), buf, addr, is_non_blocking(), ec); } void UdpSocket::async_write_to( const ConstBuffer& buf, const Address& addr, const WriteHandler& handler) { get_service().async_write_to(get_fd(), buf, addr, handler); } void UdpSocket::async_write_to( const ConstBuffer& buf, const Address& addr, WriteHandler&& handler) { get_service().async_write_to(get_fd(), buf, addr, std::move(handler)); } } <|endoftext|>
<commit_before>#include <fstream> #include <boost/ref.hpp> #include <boost/python.hpp> #include <boost/python/make_constructor.hpp> #include <boost/python/raw_function.hpp> #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <numpy/ndarrayobject.h> #include "picpac.h" #include "picpac-cv.h" using namespace boost::python; using namespace picpac; namespace { template <typename T> T *get_ndarray_data (object &o) { PyArrayObject *nd = reinterpret_cast<PyArrayObject *>(o.ptr()); return reinterpret_cast<T*>(PyArray_DATA(nd)); } class NumpyBatchImageStream: public BatchImageStream { public: NumpyBatchImageStream (std::string const &path, Config const &c) : BatchImageStream(fs::path(path), c) { import_array(); } tuple next () { vector<npy_intp> images_dims; vector<npy_intp> labels_dims; next_shape(&images_dims, &labels_dims); object images = object(boost::python::handle<>(PyArray_SimpleNew(images_dims.size(), &images_dims[0], NPY_FLOAT))); CHECK(images.ptr()); float *images_buf = get_ndarray_data<float>(images); object labels = object(boost::python::handle<>(PyArray_SimpleNew(labels_dims.size(), &labels_dims[0], NPY_FLOAT))); CHECK(labels.ptr()); float *labels_buf = get_ndarray_data<float>(labels); unsigned padding; next_fill(images_buf, labels_buf, &padding); return make_tuple(images, labels, padding); } }; object create_image_stream (tuple args, dict kwargs) { object self = args[0]; CHECK(len(args) > 1); string path = extract<string>(args[1]); NumpyBatchImageStream::Config config; /* bool train = extract<bool>(kwargs.get("train", true)); unsigned K = extract<unsigned>(kwargs.get("K", 1)); unsigned fold = extract<unsigned>(kwargs.get("fold", 0)); if (K <= 1) { if (!train) { config.loop = false; config.reshuffle = false; } } else { config.kfold(K, fold, train); } */ #define PICPAC_CONFIG_UPDATE(C, P) \ C.P = extract<decltype(C.P)>(kwargs.get(#P, C.P)) PICPAC_CONFIG_UPDATE_ALL(config); #undef PICPAC_CONFIG_UPDATE return self.attr("__init__")(path, config); }; object return_iterator (tuple args, dict kwargs) { object self = args[0]; self.attr("reset")(); return self; }; class Writer: public FileWriter { public: Writer (string const &path): FileWriter(fs::path(path), FileWriter::COMPACT) { } void append (float label, string const &buf) { Record record(label, buf); FileWriter::append(record); } void append (string const &buf1, string const &buf2) { Record record(0, buf1, buf2); FileWriter::append(record); } void append (float label, string const &buf1, string const &buf2) { Record record(label, buf1, buf2); FileWriter::append(record); } }; class Reader: public IndexedFileReader { int _next; object ctor; public: Reader (string const &path): IndexedFileReader(path), _next(0) { auto collections = import("collections"); auto namedtuple = collections.attr("namedtuple"); list fields; fields.append("id"); fields.append("label"); fields.append("label2"); fields.append("fields"); ctor = namedtuple("Record", fields); } object next () { if (_next >= size()) { throw EoS(); } return read(_next++); } void reset () { _next = 0; } object read (int i) { Record rec; IndexedFileReader::read(i, &rec); list fields; for (unsigned i = 0; i < rec.size(); ++i) { fields.append(rec.field_string(i)); } auto const &meta = rec.meta(); return ctor(meta.id, meta.label, meta.label2, fields); } }; void serialize_raw_ndarray (object &obj, std::ostream &os) { PyArrayObject *image = reinterpret_cast<PyArrayObject *>(obj.ptr()); int nd = PyArray_NDIM(image); CHECK(nd == 2 || nd == 3); auto desc = PyArray_DESCR(image); CHECK(desc); CHECK(PyArray_EquivByteorders(desc->byteorder, NPY_NATIVE) || desc->byteorder == '|') << "Only support native/little endian"; int elemSize = desc->elsize; CHECK(elemSize > 0) << "Flex type not supported."; int ch = (nd == 2) ? 1 : PyArray_DIM(image, 2); elemSize *= ch; // opencv elements includes all channels //CHECK(image->strides[1] == elemSize) << "Image cols must be consecutive"; int rows = PyArray_DIM(image, 0); int cols = PyArray_DIM(image, 1); int t = PyArray_TYPE(image); int type = 0; switch (t) { case NPY_UINT8: type = CV_MAKETYPE(CV_8U, ch); break; case NPY_INT8: type = CV_MAKETYPE(CV_8S, ch); break; case NPY_UINT16: type = CV_MAKETYPE(CV_16U, ch); break; case NPY_INT16: type = CV_MAKETYPE(CV_16S, ch); break; case NPY_INT32: type = CV_MAKETYPE(CV_32S, ch); break; case NPY_FLOAT32: type = CV_MAKETYPE(CV_32F, ch); break; case NPY_FLOAT64: type = CV_MAKETYPE(CV_64F, ch); break; default: CHECK(0) << "type not supported: " << t; } int stride = PyArray_STRIDE(image, 0); CHECK(stride == cols * elemSize) << "bad stride"; os.write(reinterpret_cast<char const *>(&type), sizeof(type)); os.write(reinterpret_cast<char const *>(&rows), sizeof(rows)); os.write(reinterpret_cast<char const *>(&cols), sizeof(cols)); os.write(reinterpret_cast<char const *>(&elemSize), sizeof(elemSize)); char const *off = PyArray_BYTES(image); for (int i = 0; i < rows; ++i) { os.write(off, cols * elemSize); off += stride; } } string encode_raw_ndarray (object &obj) { std::ostringstream ss; serialize_raw_ndarray(obj, ss); return ss.str(); } void write_raw_ndarray (string const &path, object &obj) { std::ofstream os(path.c_str(), std::ios::binary); serialize_raw_ndarray(obj, os); } void (Writer::*append1) (float, string const &) = &Writer::append; void (Writer::*append2) (string const &, string const &) = &Writer::append; void (Writer::*append3) (float, string const &, string const &) = &Writer::append; void translate_eos (EoS const &) { // Use the Python 'C' API to set up an exception object PyErr_SetNone(PyExc_StopIteration); } } BOOST_PYTHON_MODULE(_picpac) { scope().attr("__doc__") = "PicPoc Python API"; register_exception_translator<EoS>(&translate_eos); class_<NumpyBatchImageStream::Config>("ImageStreamParams", init<>()); class_<NumpyBatchImageStream, boost::noncopyable>("ImageStream", no_init) .def("__init__", raw_function(create_image_stream), "exposed ctor") .def("__iter__", raw_function(return_iterator)) .def(init<string, NumpyBatchImageStream::Config const&>()) // C++ constructor not exposed .def("next", &NumpyBatchImageStream::next) .def("size", &NumpyBatchImageStream::size) .def("reset", &NumpyBatchImageStream::reset) .def("categories", &NumpyBatchImageStream::categories) ; class_<Reader>("Reader", init<string>()) .def("__iter__", raw_function(return_iterator)) .def("next", &Reader::next) .def("size", &Reader::size) .def("read", &Reader::read) .def("reset", &Reader::reset) ; class_<Writer>("Writer", init<string>()) .def("append", append1) .def("append", append2) .def("append", append3) ; def("encode_raw", ::encode_raw_ndarray); def("write_raw", ::write_raw_ndarray); } <commit_msg>update<commit_after>#include <fstream> #include <boost/ref.hpp> #include <boost/python.hpp> #include <boost/python/make_constructor.hpp> #include <boost/python/raw_function.hpp> #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <numpy/ndarrayobject.h> #include "picpac.h" #include "picpac-cv.h" using namespace boost::python; using namespace picpac; namespace { template <typename T> T *get_ndarray_data (object &o) { PyArrayObject *nd = reinterpret_cast<PyArrayObject *>(o.ptr()); return reinterpret_cast<T*>(PyArray_DATA(nd)); } class NumpyBatchImageStream: public BatchImageStream { public: NumpyBatchImageStream (std::string const &path, Config const &c) : BatchImageStream(fs::path(path), c) { } tuple next () { vector<npy_intp> images_dims; vector<npy_intp> labels_dims; next_shape(&images_dims, &labels_dims); object images = object(boost::python::handle<>(PyArray_SimpleNew(images_dims.size(), &images_dims[0], NPY_FLOAT))); CHECK(images.ptr()); float *images_buf = get_ndarray_data<float>(images); object labels = object(boost::python::handle<>(PyArray_SimpleNew(labels_dims.size(), &labels_dims[0], NPY_FLOAT))); CHECK(labels.ptr()); float *labels_buf = get_ndarray_data<float>(labels); unsigned padding; next_fill(images_buf, labels_buf, &padding); return make_tuple(images, labels, padding); } }; object create_image_stream (tuple args, dict kwargs) { object self = args[0]; CHECK(len(args) > 1); string path = extract<string>(args[1]); NumpyBatchImageStream::Config config; /* bool train = extract<bool>(kwargs.get("train", true)); unsigned K = extract<unsigned>(kwargs.get("K", 1)); unsigned fold = extract<unsigned>(kwargs.get("fold", 0)); if (K <= 1) { if (!train) { config.loop = false; config.reshuffle = false; } } else { config.kfold(K, fold, train); } */ #define PICPAC_CONFIG_UPDATE(C, P) \ C.P = extract<decltype(C.P)>(kwargs.get(#P, C.P)) PICPAC_CONFIG_UPDATE_ALL(config); #undef PICPAC_CONFIG_UPDATE return self.attr("__init__")(path, config); }; object return_iterator (tuple args, dict kwargs) { object self = args[0]; self.attr("reset")(); return self; }; class Writer: public FileWriter { public: Writer (string const &path): FileWriter(fs::path(path), FileWriter::COMPACT) { } void append (float label, string const &buf) { Record record(label, buf); FileWriter::append(record); } void append (string const &buf1, string const &buf2) { Record record(0, buf1, buf2); FileWriter::append(record); } void append (float label, string const &buf1, string const &buf2) { Record record(label, buf1, buf2); FileWriter::append(record); } }; class Reader: public IndexedFileReader { int _next; object ctor; public: Reader (string const &path): IndexedFileReader(path), _next(0) { auto collections = import("collections"); auto namedtuple = collections.attr("namedtuple"); list fields; fields.append("id"); fields.append("label"); fields.append("label2"); fields.append("fields"); ctor = namedtuple("Record", fields); } object next () { if (_next >= size()) { throw EoS(); } return read(_next++); } void reset () { _next = 0; } object read (int i) { Record rec; IndexedFileReader::read(i, &rec); list fields; for (unsigned i = 0; i < rec.size(); ++i) { fields.append(rec.field_string(i)); } auto const &meta = rec.meta(); return ctor(meta.id, meta.label, meta.label2, fields); } }; void serialize_raw_ndarray (object &obj, std::ostream &os) { PyArrayObject *image = reinterpret_cast<PyArrayObject *>(obj.ptr()); int nd = PyArray_NDIM(image); CHECK(nd == 2 || nd == 3); auto desc = PyArray_DESCR(image); CHECK(desc); CHECK(PyArray_EquivByteorders(desc->byteorder, NPY_NATIVE) || desc->byteorder == '|') << "Only support native/little endian"; int elemSize = desc->elsize; CHECK(elemSize > 0) << "Flex type not supported."; int ch = (nd == 2) ? 1 : PyArray_DIM(image, 2); elemSize *= ch; // opencv elements includes all channels //CHECK(image->strides[1] == elemSize) << "Image cols must be consecutive"; int rows = PyArray_DIM(image, 0); int cols = PyArray_DIM(image, 1); int t = PyArray_TYPE(image); int type = 0; switch (t) { case NPY_UINT8: type = CV_MAKETYPE(CV_8U, ch); break; case NPY_INT8: type = CV_MAKETYPE(CV_8S, ch); break; case NPY_UINT16: type = CV_MAKETYPE(CV_16U, ch); break; case NPY_INT16: type = CV_MAKETYPE(CV_16S, ch); break; case NPY_INT32: type = CV_MAKETYPE(CV_32S, ch); break; case NPY_FLOAT32: type = CV_MAKETYPE(CV_32F, ch); break; case NPY_FLOAT64: type = CV_MAKETYPE(CV_64F, ch); break; default: CHECK(0) << "type not supported: " << t; } int stride = PyArray_STRIDE(image, 0); CHECK(stride == cols * elemSize) << "bad stride"; os.write(reinterpret_cast<char const *>(&type), sizeof(type)); os.write(reinterpret_cast<char const *>(&rows), sizeof(rows)); os.write(reinterpret_cast<char const *>(&cols), sizeof(cols)); os.write(reinterpret_cast<char const *>(&elemSize), sizeof(elemSize)); char const *off = PyArray_BYTES(image); for (int i = 0; i < rows; ++i) { os.write(off, cols * elemSize); off += stride; } } string encode_raw_ndarray (object &obj) { std::ostringstream ss; serialize_raw_ndarray(obj, ss); return ss.str(); } void write_raw_ndarray (string const &path, object &obj) { std::ofstream os(path.c_str(), std::ios::binary); serialize_raw_ndarray(obj, os); } void (Writer::*append1) (float, string const &) = &Writer::append; void (Writer::*append2) (string const &, string const &) = &Writer::append; void (Writer::*append3) (float, string const &, string const &) = &Writer::append; void translate_eos (EoS const &) { // Use the Python 'C' API to set up an exception object PyErr_SetNone(PyExc_StopIteration); } } BOOST_PYTHON_MODULE(_picpac) { scope().attr("__doc__") = "PicPoc Python API"; register_exception_translator<EoS>(&translate_eos); class_<NumpyBatchImageStream::Config>("ImageStreamParams", init<>()); class_<NumpyBatchImageStream, boost::noncopyable>("ImageStream", no_init) .def("__init__", raw_function(create_image_stream), "exposed ctor") .def("__iter__", raw_function(return_iterator)) .def(init<string, NumpyBatchImageStream::Config const&>()) // C++ constructor not exposed .def("next", &NumpyBatchImageStream::next) .def("size", &NumpyBatchImageStream::size) .def("reset", &NumpyBatchImageStream::reset) .def("categories", &NumpyBatchImageStream::categories) ; class_<Reader>("Reader", init<string>()) .def("__iter__", raw_function(return_iterator)) .def("next", &Reader::next) .def("size", &Reader::size) .def("read", &Reader::read) .def("reset", &Reader::reset) ; class_<Writer>("Writer", init<string>()) .def("append", append1) .def("append", append2) .def("append", append3) ; def("encode_raw", ::encode_raw_ndarray); def("write_raw", ::write_raw_ndarray); #undef NUMPY_IMPORT_ARRAY_RETVAL #define NUMPY_IMPORT_ARRAY_RETVAL import_array(); } <|endoftext|>
<commit_before>/********************************************************************************************** * Arduino PID Library - Version 1.1.1 * by Brett Beauregard <br3ttb@gmail.com> brettbeauregard.com * * This Library is licensed under a GPLv3 License * * Modified by Romain Reignier * - use float instead of double for compatibility reasons (even if double == float on Arduino) * - does not use millis in Compute() because used with TimerOne Library **********************************************************************************************/ #include "Pid.h" /*Constructor (...)********************************************************* * The parameters specified here are those for for which we can't set up * reliable defaults, so we need to have the user set them. ***************************************************************************/ PID::PID(float* Input, float* Output, float* Setpoint, float Kp, float Ki, float Kd, int ControllerDirection) { myOutput = Output; myInput = Input; mySetpoint = Setpoint; inAuto = false; PID::SetOutputLimits(0, 255); //default output limit corresponds to //the arduino pwm limits SampleTime = 100; //default Controller Sample Time is 0.1 seconds PID::SetControllerDirection(ControllerDirection); PID::SetTunings(Kp, Ki, Kd); } /* Compute() ********************************************************************** * This, as they say, is where the magic happens. this function should be called * every time "void loop()" executes. the function will decide for itself whether a new * pid Output needs to be computed. returns true when the output is computed, * false when nothing has been done. **********************************************************************************/ bool PID::Compute() { if (!inAuto) return false; /*Compute all the working error variables*/ float input = *myInput; float error = *mySetpoint - input; ITerm += (ki * error); if (ITerm > outMax) ITerm = outMax; else if (ITerm < outMin) ITerm = outMin; float dInput = (input - lastInput); /*Compute PID Output*/ float output = kp * error + ITerm - kd * dInput; if (output > outMax) output = outMax; else if (output < outMin) output = outMin; *myOutput = output; /*Remember some variables for next time*/ lastInput = input; return true; } /* SetTunings(...)************************************************************* * This function allows the controller's dynamic performance to be adjusted. * it's called automatically from the constructor, but tunings can also * be adjusted on the fly during normal operation ******************************************************************************/ void PID::SetTunings(float Kp, float Ki, float Kd) { if (Kp < 0 || Ki < 0 || Kd < 0) return; dispKp = Kp; dispKi = Ki; dispKd = Kd; float SampleTimeInSec = ((float)SampleTime) / 1000; kp = Kp; ki = Ki * SampleTimeInSec; kd = Kd / SampleTimeInSec; if (controllerDirection == REVERSE) { kp = (0 - kp); ki = (0 - ki); kd = (0 - kd); } } /* SetSampleTime(...) ********************************************************* * sets the period, in Milliseconds, at which the calculation is performed ******************************************************************************/ void PID::SetSampleTime(int NewSampleTime) { if (NewSampleTime > 0) { float ratio = (float)NewSampleTime / (float)SampleTime; ki *= ratio; kd /= ratio; SampleTime = (unsigned long)NewSampleTime; } } /* SetOutputLimits(...)**************************************************** * This function will be used far more often than SetInputLimits. while * the input to the controller will generally be in the 0-1023 range (which is * the default already,) the output will be a little different. maybe they'll * be doing a time window and will need 0-8000 or something. or maybe they'll * want to clamp it from 0-125. who knows. at any rate, that can all be done * here. **************************************************************************/ void PID::SetOutputLimits(float Min, float Max) { if (Min >= Max) return; outMin = Min; outMax = Max; if (inAuto) { if (*myOutput > outMax) *myOutput = outMax; else if (*myOutput < outMin) *myOutput = outMin; if (ITerm > outMax) ITerm = outMax; else if (ITerm < outMin) ITerm = outMin; } } /* SetMode(...)**************************************************************** * Allows the controller Mode to be set to manual (0) or Automatic (non-zero) * when the transition from manual to auto occurs, the controller is * automatically initialized ******************************************************************************/ void PID::SetMode(int Mode) { bool newAuto = (Mode == AUTOMATIC); if (newAuto == !inAuto) { /*we just went from manual to auto*/ PID::Initialize(); } inAuto = newAuto; } /* Initialize()**************************************************************** * does all the things that need to happen to ensure a bumpless transfer * from manual to automatic mode. ******************************************************************************/ void PID::Initialize() { //ITerm = *myOutput; // Strange behaviour with that ITerm = 0; lastInput = *myInput; if (ITerm > outMax) ITerm = outMax; else if (ITerm < outMin) ITerm = outMin; } /* SetControllerDirection(...)************************************************* * The PID will either be connected to a DIRECT acting process (+Output leads * to +Input) or a REVERSE acting process(+Output leads to -Input.) we need to * know which one, because otherwise we may increase the output when we should * be decreasing. This is called from the constructor. ******************************************************************************/ void PID::SetControllerDirection(int Direction) { if (inAuto && Direction != controllerDirection) { kp = (0 - kp); ki = (0 - ki); kd = (0 - kd); } controllerDirection = Direction; } /* Status Funcions************************************************************* * Just because you set the Kp=-1 doesn't mean it actually happened. these * functions query the internal state of the PID. they're here for display * purposes. this are the functions the PID Front-end uses for example ******************************************************************************/ float PID::GetKp() { return dispKp; } float PID::GetKi() { return dispKi; } float PID::GetKd() { return dispKd; } int PID::GetMode() { return inAuto ? AUTOMATIC : MANUAL; } int PID::GetDirection() { return controllerDirection; } <commit_msg>Reset the ITerm when changing PID tunnings.<commit_after>/********************************************************************************************** * Arduino PID Library - Version 1.1.1 * by Brett Beauregard <br3ttb@gmail.com> brettbeauregard.com * * This Library is licensed under a GPLv3 License * * Modified by Romain Reignier * - use float instead of double for compatibility reasons (even if double == float on Arduino) * - does not use millis in Compute() because used with TimerOne Library **********************************************************************************************/ #include "Pid.h" /*Constructor (...)********************************************************* * The parameters specified here are those for for which we can't set up * reliable defaults, so we need to have the user set them. ***************************************************************************/ PID::PID(float* Input, float* Output, float* Setpoint, float Kp, float Ki, float Kd, int ControllerDirection) { myOutput = Output; myInput = Input; mySetpoint = Setpoint; inAuto = false; PID::SetOutputLimits(0, 255); //default output limit corresponds to //the arduino pwm limits SampleTime = 100; //default Controller Sample Time is 0.1 seconds PID::SetControllerDirection(ControllerDirection); PID::SetTunings(Kp, Ki, Kd); } /* Compute() ********************************************************************** * This, as they say, is where the magic happens. this function should be called * every time "void loop()" executes. the function will decide for itself whether a new * pid Output needs to be computed. returns true when the output is computed, * false when nothing has been done. **********************************************************************************/ bool PID::Compute() { if (!inAuto) return false; /*Compute all the working error variables*/ float input = *myInput; float error = *mySetpoint - input; ITerm += (ki * error); if (ITerm > outMax) ITerm = outMax; else if (ITerm < outMin) ITerm = outMin; float dInput = (input - lastInput); /*Compute PID Output*/ float output = kp * error + ITerm - kd * dInput; if (output > outMax) output = outMax; else if (output < outMin) output = outMin; *myOutput = output; /*Remember some variables for next time*/ lastInput = input; return true; } /* SetTunings(...)************************************************************* * This function allows the controller's dynamic performance to be adjusted. * it's called automatically from the constructor, but tunings can also * be adjusted on the fly during normal operation ******************************************************************************/ void PID::SetTunings(float Kp, float Ki, float Kd) { if (Kp < 0 || Ki < 0 || Kd < 0) return; dispKp = Kp; dispKi = Ki; dispKd = Kd; float SampleTimeInSec = ((float)SampleTime) / 1000; kp = Kp; ki = Ki * SampleTimeInSec; kd = Kd / SampleTimeInSec; if (controllerDirection == REVERSE) { kp = (0 - kp); ki = (0 - ki); kd = (0 - kd); } ITerm = 0; } /* SetSampleTime(...) ********************************************************* * sets the period, in Milliseconds, at which the calculation is performed ******************************************************************************/ void PID::SetSampleTime(int NewSampleTime) { if (NewSampleTime > 0) { float ratio = (float)NewSampleTime / (float)SampleTime; ki *= ratio; kd /= ratio; SampleTime = (unsigned long)NewSampleTime; } } /* SetOutputLimits(...)**************************************************** * This function will be used far more often than SetInputLimits. while * the input to the controller will generally be in the 0-1023 range (which is * the default already,) the output will be a little different. maybe they'll * be doing a time window and will need 0-8000 or something. or maybe they'll * want to clamp it from 0-125. who knows. at any rate, that can all be done * here. **************************************************************************/ void PID::SetOutputLimits(float Min, float Max) { if (Min >= Max) return; outMin = Min; outMax = Max; if (inAuto) { if (*myOutput > outMax) *myOutput = outMax; else if (*myOutput < outMin) *myOutput = outMin; if (ITerm > outMax) ITerm = outMax; else if (ITerm < outMin) ITerm = outMin; } } /* SetMode(...)**************************************************************** * Allows the controller Mode to be set to manual (0) or Automatic (non-zero) * when the transition from manual to auto occurs, the controller is * automatically initialized ******************************************************************************/ void PID::SetMode(int Mode) { bool newAuto = (Mode == AUTOMATIC); if (newAuto == !inAuto) { /*we just went from manual to auto*/ PID::Initialize(); } inAuto = newAuto; } /* Initialize()**************************************************************** * does all the things that need to happen to ensure a bumpless transfer * from manual to automatic mode. ******************************************************************************/ void PID::Initialize() { //ITerm = *myOutput; // Strange behaviour with that ITerm = 0; lastInput = *myInput; if (ITerm > outMax) ITerm = outMax; else if (ITerm < outMin) ITerm = outMin; } /* SetControllerDirection(...)************************************************* * The PID will either be connected to a DIRECT acting process (+Output leads * to +Input) or a REVERSE acting process(+Output leads to -Input.) we need to * know which one, because otherwise we may increase the output when we should * be decreasing. This is called from the constructor. ******************************************************************************/ void PID::SetControllerDirection(int Direction) { if (inAuto && Direction != controllerDirection) { kp = (0 - kp); ki = (0 - ki); kd = (0 - kd); } controllerDirection = Direction; } /* Status Funcions************************************************************* * Just because you set the Kp=-1 doesn't mean it actually happened. these * functions query the internal state of the PID. they're here for display * purposes. this are the functions the PID Front-end uses for example ******************************************************************************/ float PID::GetKp() { return dispKp; } float PID::GetKi() { return dispKi; } float PID::GetKd() { return dispKd; } int PID::GetMode() { return inAuto ? AUTOMATIC : MANUAL; } int PID::GetDirection() { return controllerDirection; } <|endoftext|>
<commit_before>// Copyright 2016, Dawid Kurek, <dawikur@gmail.com> #ifndef FIRMWARE_REPORT_POINTER_HPP_ #define FIRMWARE_REPORT_POINTER_HPP_ #include "report_base.hpp" namespace Crow { namespace Reports { union PointerRaw { PointerRaw() : _{0} {} struct { int8_t buttons; int8_t x; int8_t y; int8_t wheel; }; int8_t _[4]; }; class Pointer : public Base<1, PointerRaw> { using Base = Base<1, PointerRaw>; static constexpr int8_t Speed = 5; public: Pointer() : Base{} {} explicit operator bool() const override { return Base::operator bool() || raw.x != 0 || raw.y != 0; } #define update_move(V, P, C) \ do { \ if (raw.V C 0) { \ if (P(Speed << 1) C raw.V) \ raw.V P## = 1; \ else if (P(Speed * 5) C raw.V) \ raw.V P## = Speed; \ } \ } while (0) void commit() { update_move(x, +, >); update_move(x, -, <); update_move(y, +, >); update_move(y, -, <); Base::commit(); } #undef update_move void clear() { raw.buttons = 0; raw.x = 0; raw.y = 0; raw.wheel = 0; } void action(Index const id, bool const wasPressed) { wasPressed ? process_action_begin(id) : process_action_end(id); markChanged(); } private: void process_action_begin(Index const id) { switch (id) { case '+' ^ 'x': raw.x = Speed; break; case '-' ^ 'x': raw.x = -Speed; break; case '+' ^ 'y': raw.y = Speed; break; case '-' ^ 'y': raw.y = -Speed; break; case 'B' ^ 'L': raw.buttons |= 0x01; break; case 'B' ^ 'M': raw.buttons |= 0x04; break; case 'B' ^ 'R': raw.buttons |= 0x02; break; } } void process_action_end(Index const id) { switch (id) { case '+' ^ 'x': if (raw.x > 0) raw.x = 0x00; break; case '-' ^ 'x': if (raw.x < 0) raw.x = 0x00; break; case '+' ^ 'y': if (raw.y > 0) raw.y = 0x00; break; case '-' ^ 'y': if (raw.y < 0) raw.y = 0x00; break; case 'B' ^ 'L': raw.buttons &= ~0x01; break; case 'B' ^ 'M': raw.buttons &= ~0x04; break; case 'B' ^ 'R': raw.buttons &= ~0x02; break; } } }; static uint8_t const PointerDescriptor[] PROGMEM = { 0x05, 0x01, // USAGE_PAGE (Generic Desktop) 0x09, 0x02, // USAGE (Mouse) 0xa1, 0x01, // COLLECTION (Application) 0X85, Pointer::id(), // REPORT_ID (1) 0x05, 0x09, // USAGE_PAGE (Button) 0x19, 0x01, // USAGE_MINIMUM (Button 1) 0x29, 0x03, // USAGE_MAXIMUM (Button 3) 0x15, 0x00, // LOGICAL_MINIMUM (0) 0x25, 0x01, // LOGICAL_MAXIMUM (1) 0x95, 0x03, // REPORT_COUNT (3) 0x75, 0x01, // REPORT_SIZE (1) 0x81, 0x02, // INPUT (Data,Var,Abs) 0x95, 0x01, // REPORT_COUNT (1) 0x75, 0x05, // REPORT_SIZE (5) 0x81, 0x03, // INPUT (Cnst,Var,Abs) 0x05, 0x01, // USAGE_PAGE (Generic Desktop) 0x09, 0x30, // USAGE (X) 0x09, 0x31, // USAGE (Y) 0x09, 0x38, // USAGE (Wheel) 0x15, 0x81, // LOGICAL_MINIMUM (-127) 0x25, 0x7f, // LOGICAL_MAXIMUM (127) 0x75, 0x08, // REPORT_SIZE (8) 0x95, 0x03, // REPORT_COUNT (3) 0x81, 0x06, // INPUT (Data,Var,Rel) 0xc0, // END_COLLECTION }; } // namespace Reports } // namespace Crow #endif // FIRMWARE_REPORT_CUSTOMER_HPP_ <commit_msg>[report/pointer] Add two buttons to report<commit_after>// Copyright 2016, Dawid Kurek, <dawikur@gmail.com> #ifndef FIRMWARE_REPORT_POINTER_HPP_ #define FIRMWARE_REPORT_POINTER_HPP_ #include "report_base.hpp" namespace Crow { namespace Reports { union PointerRaw { PointerRaw() : _{0} {} struct Button { static constexpr int8_t Left = 0x1 << 0; static constexpr int8_t Right = 0x1 << 1; static constexpr int8_t Middle = 0x1 << 2; static constexpr int8_t Back = 0x1 << 3; static constexpr int8_t Forward = 0x1 << 4; }; struct { int8_t buttons; int8_t x; int8_t y; int8_t wheel; }; int8_t _[4]; }; class Pointer : public Base<1, PointerRaw> { using Base = Base<1, PointerRaw>; static constexpr int8_t Speed = 5; public: Pointer() : Base{} {} explicit operator bool() const override { return Base::operator bool() || raw.x != 0 || raw.y != 0; } #define update_move(V, P, C) \ do { \ if (raw.V C 0) { \ if (P(Speed << 1) C raw.V) \ raw.V P## = 1; \ else if (P(Speed * 5) C raw.V) \ raw.V P## = Speed; \ } \ } while (0) void commit() { update_move(x, +, >); update_move(x, -, <); update_move(y, +, >); update_move(y, -, <); Base::commit(); } #undef update_move void clear() { raw.buttons = 0; raw.x = 0; raw.y = 0; raw.wheel = 0; } void action(Index const id, bool const wasPressed) { wasPressed ? process_action_begin(id) : process_action_end(id); markChanged(); } private: void process_action_begin(Index const id) { switch (id) { case '+' ^ 'x': raw.x = Speed; break; case '-' ^ 'x': raw.x = -Speed; break; case '+' ^ 'y': raw.y = Speed; break; case '-' ^ 'y': raw.y = -Speed; break; case 'B' ^ 'L': raw.buttons |= PointerRaw::Button::Left; break; case 'B' ^ 'R': raw.buttons |= PointerRaw::Button::Right; break; case 'B' ^ 'M': raw.buttons |= PointerRaw::Button::Middle; break; } } void process_action_end(Index const id) { switch (id) { case '+' ^ 'x': if (raw.x > 0) raw.x = 0x00; break; case '-' ^ 'x': if (raw.x < 0) raw.x = 0x00; break; case '+' ^ 'y': if (raw.y > 0) raw.y = 0x00; break; case '-' ^ 'y': if (raw.y < 0) raw.y = 0x00; break; case 'B' ^ 'L': raw.buttons &= ~PointerRaw::Button::Left; break; case 'B' ^ 'R': raw.buttons &= ~PointerRaw::Button::Right; break; case 'B' ^ 'M': raw.buttons &= ~PointerRaw::Button::Middle; break; } } }; static uint8_t const PointerDescriptor[] PROGMEM = { 0x05, 0x01, // USAGE_PAGE (GENERIC DESKTOP) 0x09, 0x02, // USAGE (MOUSE) 0xa1, 0x01, // COLLECTION (APPLICATION) 0X85, Pointer::id(), // REPORT_ID (1) 0x05, 0x09, // USAGE_PAGE (BUTTON) 0x19, 0x01, // USAGE_MINIMUM (BUTTON 1) 0x29, 0x05, // USAGE_MAXIMUM (BUTTON 5) 0x15, 0x00, // LOGICAL_MINIMUM (0) 0x25, 0x01, // LOGICAL_MAXIMUM (1) 0x95, 0x05, // REPORT_COUNT (5) 0x75, 0x01, // REPORT_SIZE (1) 0x81, 0x02, // INPUT (DATA,VAR,ABS) 0x95, 0x01, // REPORT_COUNT (1) 0x75, 0x03, // REPORT_SIZE (3) 0x81, 0x03, // INPUT (CNST,VAR,ABS) 0x05, 0x01, // USAGE_PAGE (GENERIC DESKTOP) 0x09, 0x30, // USAGE (X) 0x09, 0x31, // USAGE (Y) 0x09, 0x38, // USAGE (WHEEL) 0x15, 0x81, // LOGICAL_MINIMUM (-127) 0x25, 0x7f, // LOGICAL_MAXIMUM (127) 0x75, 0x08, // REPORT_SIZE (8) 0x95, 0x03, // REPORT_COUNT (3) 0x81, 0x06, // INPUT (DATA,VAR,REL) 0xc0, // END_COLLECTION }; } // namespace Reports } // namespace Crow #endif // FIRMWARE_REPORT_CUSTOMER_HPP_ <|endoftext|>
<commit_before>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stddef.h> #include <stdint.h> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/optional.h" #include "riegeli/base/base.h" #include "riegeli/records/record_position.h" #include "riegeli/records/record_reader.h" #include "riegeli/records/skipped_region.h" #include "riegeli/tensorflow/io/file_reader.h" #include "tensorflow/core/framework/allocator.h" #include "tensorflow/core/framework/dataset.h" #include "tensorflow/core/framework/kernel_def_builder.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/op_requires.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/graph/graph.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/status.h" #include "tensorflow/core/platform/tstring.h" #include "tensorflow/core/protobuf/error_codes.pb.h" namespace riegeli { namespace tensorflow { namespace { class RiegeliDatasetOp : public ::tensorflow::data::DatasetOpKernel { public: using DatasetOpKernel::DatasetOpKernel; void MakeDataset(::tensorflow::OpKernelContext* ctx, ::tensorflow::data::DatasetBase** output) override { const ::tensorflow::Tensor* filenames_tensor; OP_REQUIRES_OK(ctx, ctx->input("filenames", &filenames_tensor)); OP_REQUIRES(ctx, filenames_tensor->dims() <= 1, ::tensorflow::errors::InvalidArgument( "`filenames` must be a scalar or a vector.")); std::vector<std::string> filenames; filenames.reserve(IntCast<size_t>(filenames_tensor->NumElements())); for (int i = 0; i < filenames_tensor->NumElements(); ++i) { filenames.emplace_back( filenames_tensor->flat<::tensorflow::tstring>()(i)); } int64_t min_buffer_size; OP_REQUIRES_OK(ctx, ::tensorflow::data::ParseScalarArgument<int64_t>( ctx, "min_buffer_size", &min_buffer_size)); OP_REQUIRES( ctx, min_buffer_size > 0, ::tensorflow::errors::InvalidArgument("`min_buffer_size` must be > 0")); int64_t max_buffer_size; OP_REQUIRES_OK(ctx, ::tensorflow::data::ParseScalarArgument<int64_t>( ctx, "max_buffer_size", &max_buffer_size)); OP_REQUIRES(ctx, max_buffer_size >= min_buffer_size, ::tensorflow::errors::InvalidArgument( "`max_buffer_size` must be >= `min_buffer_size`")); *output = new Dataset(ctx, std::move(filenames), min_buffer_size, max_buffer_size); } private: class Dataset : public ::tensorflow::data::DatasetBase { public: explicit Dataset(::tensorflow::OpKernelContext* ctx, std::vector<std::string> filenames, int64_t min_buffer_size, int64_t max_buffer_size) : DatasetBase(::tensorflow::data::DatasetContext(ctx)), filenames_(std::move(filenames)), min_buffer_size_(min_buffer_size), max_buffer_size_(max_buffer_size) {} std::unique_ptr<::tensorflow::data::IteratorBase> MakeIteratorInternal( const std::string& prefix) const override { return std::unique_ptr<::tensorflow::data::IteratorBase>( new Iterator({this, absl::StrCat(prefix, "::Riegeli")})); } const ::tensorflow::DataTypeVector& output_dtypes() const override { static const ::tensorflow::DataTypeVector* const dtypes = new ::tensorflow::DataTypeVector({::tensorflow::DT_STRING}); return *dtypes; } const std::vector<::tensorflow::PartialTensorShape>& output_shapes() const override { static const std::vector<::tensorflow::PartialTensorShape>* const shapes = new std::vector<::tensorflow::PartialTensorShape>({{}}); return *shapes; } std::string DebugString() const override { return "RiegeliDatasetOp::Dataset"; } ::tensorflow::Status CheckExternalState() const override { #if TF_GRAPH_DEF_VERSION >= 1137 return ::tensorflow::OkStatus(); #else return ::tensorflow::Status::OK(); #endif } ::tensorflow::Status InputDatasets( std::vector<const ::tensorflow::data::DatasetBase*>* inputs) const override { inputs->clear(); #if TF_GRAPH_DEF_VERSION >= 1137 return ::tensorflow::OkStatus(); #else return ::tensorflow::Status::OK(); #endif } protected: ::tensorflow::Status AsGraphDefInternal( ::tensorflow::data::SerializationContext* ctx, DatasetGraphDefBuilder* b, ::tensorflow::Node** output) const override { ::tensorflow::Node* filenames = nullptr; TF_RETURN_IF_ERROR(b->AddVector(filenames_, &filenames)); ::tensorflow::Node* min_buffer_size = nullptr; TF_RETURN_IF_ERROR(b->AddScalar(min_buffer_size_, &min_buffer_size)); ::tensorflow::Node* max_buffer_size = nullptr; TF_RETURN_IF_ERROR(b->AddScalar(max_buffer_size_, &max_buffer_size)); TF_RETURN_IF_ERROR(b->AddDataset( this, {filenames, min_buffer_size, max_buffer_size}, output)); #if TF_GRAPH_DEF_VERSION >= 1137 return ::tensorflow::OkStatus(); #else return ::tensorflow::Status::OK(); #endif } private: class Iterator : public ::tensorflow::data::DatasetIterator<Dataset> { public: explicit Iterator(const Params& params) : DatasetIterator<Dataset>(params) {} ::tensorflow::Status GetNextInternal( ::tensorflow::data::IteratorContext* ctx, std::vector<::tensorflow::Tensor>* out_tensors, bool* end_of_sequence) override ABSL_LOCKS_EXCLUDED(mu_) { absl::MutexLock l(&mu_); for (;;) { if (reader_ != absl::nullopt) { // We are currently processing a file, so try to read the next // record. ::tensorflow::Tensor result_tensor(::tensorflow::cpu_allocator(), ::tensorflow::DT_STRING, {}); absl::string_view value; if (TF_PREDICT_TRUE(reader_->ReadRecord(value))) { result_tensor.scalar<::tensorflow::tstring>()().assign( value.data(), value.size()); out_tensors->push_back(std::move(result_tensor)); *end_of_sequence = false; #if TF_GRAPH_DEF_VERSION >= 1137 return ::tensorflow::OkStatus(); #else return ::tensorflow::Status::OK(); #endif } SkippedRegion skipped_region; if (reader_->Recover(&skipped_region)) { // File has invalid contents: return an error. Further iteration // will resume reading the file after the invalid region has been // skipped. *end_of_sequence = false; return ::tensorflow::errors::InvalidArgument( "Skipping invalid region of a Riegeli/records file: ", skipped_region.ToString()); } if (TF_PREDICT_FALSE(!reader_->Close())) { // Failed to read the file: return an error. const absl::Status status = reader_->status(); // Further iteration will move on to the next file, if any. reader_.reset(); ++current_file_index_; *end_of_sequence = current_file_index_ == dataset()->filenames_.size(); return ::tensorflow::Status( static_cast<::tensorflow::error::Code>(status.code()), status.message()); } // We have reached the end of the current file, so move on to the // next file, if any. reader_.reset(); ++current_file_index_; } // Iteration ends when there are no more files to process. if (current_file_index_ == dataset()->filenames_.size()) { *end_of_sequence = true; #if TF_GRAPH_DEF_VERSION >= 1137 return ::tensorflow::OkStatus(); #else return ::tensorflow::Status::OK(); #endif } // Actually move on to next file. OpenFile(ctx); } } protected: ::tensorflow::Status SaveInternal( ::tensorflow::data::SerializationContext* ctx, ::tensorflow::data::IteratorStateWriter* writer) override ABSL_LOCKS_EXCLUDED(mu_) { absl::MutexLock l(&mu_); TF_RETURN_IF_ERROR( writer->WriteScalar(full_name("current_file_index"), IntCast<int64_t>(current_file_index_))); if (reader_ != absl::nullopt) { TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("current_pos"), reader_->pos().ToBytes())); } #if TF_GRAPH_DEF_VERSION >= 1137 return ::tensorflow::OkStatus(); #else return ::tensorflow::Status::OK(); #endif } ::tensorflow::Status RestoreInternal( ::tensorflow::data::IteratorContext* ctx, ::tensorflow::data::IteratorStateReader* reader) override ABSL_LOCKS_EXCLUDED(mu_) { absl::MutexLock l(&mu_); current_file_index_ = 0; reader_.reset(); int64_t current_file_index; TF_RETURN_IF_ERROR(reader->ReadScalar(full_name("current_file_index"), &current_file_index)); if (TF_PREDICT_FALSE(current_file_index < 0 || IntCast<uint64_t>(current_file_index) > dataset()->filenames_.size())) { return ::tensorflow::errors::Internal( "current_file_index out of range"); } current_file_index_ = IntCast<size_t>(current_file_index); if (reader->Contains(full_name("current_pos"))) { if (TF_PREDICT_FALSE(current_file_index_ == dataset()->filenames_.size())) { return ::tensorflow::errors::Internal( "current_file_index out of range"); } ::tensorflow::tstring current_pos; TF_RETURN_IF_ERROR( reader->ReadScalar(full_name("current_pos"), &current_pos)); RecordPosition pos; if (TF_PREDICT_FALSE(!pos.FromBytes(current_pos))) { return ::tensorflow::errors::Internal( "current_pos is not a valid RecordPosition"); } OpenFile(ctx); reader_->Seek(pos); // Any errors from seeking will be reported during reading. } #if TF_GRAPH_DEF_VERSION >= 1137 return ::tensorflow::OkStatus(); #else return ::tensorflow::Status::OK(); #endif } private: void OpenFile(::tensorflow::data::IteratorContext* ctx) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) { reader_.emplace(std::forward_as_tuple( dataset()->filenames_[current_file_index_], tensorflow::FileReaderBase::Options() .set_env(ctx->env()) .set_min_buffer_size( IntCast<size_t>(dataset()->min_buffer_size_)) .set_max_buffer_size( IntCast<size_t>(dataset()->max_buffer_size_)))); } // Invariants: // `current_file_index_ <= dataset()->filenames_.size()` // if `current_file_index_ == dataset()->filenames_.size()` then // `reader_ == absl::nullopt` absl::Mutex mu_; size_t current_file_index_ ABSL_GUARDED_BY(mu_) = 0; // `absl::nullopt` means not open yet. absl::optional<RecordReader<tensorflow::FileReader<>>> reader_ ABSL_GUARDED_BY(mu_); }; const std::vector<std::string> filenames_; const int64_t min_buffer_size_; const int64_t max_buffer_size_; }; }; REGISTER_KERNEL_BUILDER(Name("RiegeliDataset").Device(::tensorflow::DEVICE_CPU), RiegeliDatasetOp); } // namespace } // namespace tensorflow } // namespace riegeli <commit_msg>Remove obsolete precondition checks on `{min,max}_buffer_size`.<commit_after>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stddef.h> #include <stdint.h> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/optional.h" #include "riegeli/base/base.h" #include "riegeli/records/record_position.h" #include "riegeli/records/record_reader.h" #include "riegeli/records/skipped_region.h" #include "riegeli/tensorflow/io/file_reader.h" #include "tensorflow/core/framework/allocator.h" #include "tensorflow/core/framework/dataset.h" #include "tensorflow/core/framework/kernel_def_builder.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/op_requires.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/graph/graph.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/status.h" #include "tensorflow/core/platform/tstring.h" #include "tensorflow/core/protobuf/error_codes.pb.h" namespace riegeli { namespace tensorflow { namespace { class RiegeliDatasetOp : public ::tensorflow::data::DatasetOpKernel { public: using DatasetOpKernel::DatasetOpKernel; void MakeDataset(::tensorflow::OpKernelContext* ctx, ::tensorflow::data::DatasetBase** output) override { const ::tensorflow::Tensor* filenames_tensor; OP_REQUIRES_OK(ctx, ctx->input("filenames", &filenames_tensor)); OP_REQUIRES(ctx, filenames_tensor->dims() <= 1, ::tensorflow::errors::InvalidArgument( "`filenames` must be a scalar or a vector.")); std::vector<std::string> filenames; filenames.reserve(IntCast<size_t>(filenames_tensor->NumElements())); for (int i = 0; i < filenames_tensor->NumElements(); ++i) { filenames.emplace_back( filenames_tensor->flat<::tensorflow::tstring>()(i)); } int64_t min_buffer_size; OP_REQUIRES_OK(ctx, ::tensorflow::data::ParseScalarArgument<int64_t>( ctx, "min_buffer_size", &min_buffer_size)); int64_t max_buffer_size; OP_REQUIRES_OK(ctx, ::tensorflow::data::ParseScalarArgument<int64_t>( ctx, "max_buffer_size", &max_buffer_size)); *output = new Dataset(ctx, std::move(filenames), min_buffer_size, max_buffer_size); } private: class Dataset : public ::tensorflow::data::DatasetBase { public: explicit Dataset(::tensorflow::OpKernelContext* ctx, std::vector<std::string> filenames, int64_t min_buffer_size, int64_t max_buffer_size) : DatasetBase(::tensorflow::data::DatasetContext(ctx)), filenames_(std::move(filenames)), min_buffer_size_(min_buffer_size), max_buffer_size_(max_buffer_size) {} std::unique_ptr<::tensorflow::data::IteratorBase> MakeIteratorInternal( const std::string& prefix) const override { return std::unique_ptr<::tensorflow::data::IteratorBase>( new Iterator({this, absl::StrCat(prefix, "::Riegeli")})); } const ::tensorflow::DataTypeVector& output_dtypes() const override { static const ::tensorflow::DataTypeVector* const dtypes = new ::tensorflow::DataTypeVector({::tensorflow::DT_STRING}); return *dtypes; } const std::vector<::tensorflow::PartialTensorShape>& output_shapes() const override { static const std::vector<::tensorflow::PartialTensorShape>* const shapes = new std::vector<::tensorflow::PartialTensorShape>({{}}); return *shapes; } std::string DebugString() const override { return "RiegeliDatasetOp::Dataset"; } ::tensorflow::Status CheckExternalState() const override { #if TF_GRAPH_DEF_VERSION >= 1137 return ::tensorflow::OkStatus(); #else return ::tensorflow::Status::OK(); #endif } ::tensorflow::Status InputDatasets( std::vector<const ::tensorflow::data::DatasetBase*>* inputs) const override { inputs->clear(); #if TF_GRAPH_DEF_VERSION >= 1137 return ::tensorflow::OkStatus(); #else return ::tensorflow::Status::OK(); #endif } protected: ::tensorflow::Status AsGraphDefInternal( ::tensorflow::data::SerializationContext* ctx, DatasetGraphDefBuilder* b, ::tensorflow::Node** output) const override { ::tensorflow::Node* filenames = nullptr; TF_RETURN_IF_ERROR(b->AddVector(filenames_, &filenames)); ::tensorflow::Node* min_buffer_size = nullptr; TF_RETURN_IF_ERROR(b->AddScalar(min_buffer_size_, &min_buffer_size)); ::tensorflow::Node* max_buffer_size = nullptr; TF_RETURN_IF_ERROR(b->AddScalar(max_buffer_size_, &max_buffer_size)); TF_RETURN_IF_ERROR(b->AddDataset( this, {filenames, min_buffer_size, max_buffer_size}, output)); #if TF_GRAPH_DEF_VERSION >= 1137 return ::tensorflow::OkStatus(); #else return ::tensorflow::Status::OK(); #endif } private: class Iterator : public ::tensorflow::data::DatasetIterator<Dataset> { public: explicit Iterator(const Params& params) : DatasetIterator<Dataset>(params) {} ::tensorflow::Status GetNextInternal( ::tensorflow::data::IteratorContext* ctx, std::vector<::tensorflow::Tensor>* out_tensors, bool* end_of_sequence) override ABSL_LOCKS_EXCLUDED(mu_) { absl::MutexLock l(&mu_); for (;;) { if (reader_ != absl::nullopt) { // We are currently processing a file, so try to read the next // record. ::tensorflow::Tensor result_tensor(::tensorflow::cpu_allocator(), ::tensorflow::DT_STRING, {}); absl::string_view value; if (TF_PREDICT_TRUE(reader_->ReadRecord(value))) { result_tensor.scalar<::tensorflow::tstring>()().assign( value.data(), value.size()); out_tensors->push_back(std::move(result_tensor)); *end_of_sequence = false; #if TF_GRAPH_DEF_VERSION >= 1137 return ::tensorflow::OkStatus(); #else return ::tensorflow::Status::OK(); #endif } SkippedRegion skipped_region; if (reader_->Recover(&skipped_region)) { // File has invalid contents: return an error. Further iteration // will resume reading the file after the invalid region has been // skipped. *end_of_sequence = false; return ::tensorflow::errors::InvalidArgument( "Skipping invalid region of a Riegeli/records file: ", skipped_region.ToString()); } if (TF_PREDICT_FALSE(!reader_->Close())) { // Failed to read the file: return an error. const absl::Status status = reader_->status(); // Further iteration will move on to the next file, if any. reader_.reset(); ++current_file_index_; *end_of_sequence = current_file_index_ == dataset()->filenames_.size(); return ::tensorflow::Status( static_cast<::tensorflow::error::Code>(status.code()), status.message()); } // We have reached the end of the current file, so move on to the // next file, if any. reader_.reset(); ++current_file_index_; } // Iteration ends when there are no more files to process. if (current_file_index_ == dataset()->filenames_.size()) { *end_of_sequence = true; #if TF_GRAPH_DEF_VERSION >= 1137 return ::tensorflow::OkStatus(); #else return ::tensorflow::Status::OK(); #endif } // Actually move on to next file. OpenFile(ctx); } } protected: ::tensorflow::Status SaveInternal( ::tensorflow::data::SerializationContext* ctx, ::tensorflow::data::IteratorStateWriter* writer) override ABSL_LOCKS_EXCLUDED(mu_) { absl::MutexLock l(&mu_); TF_RETURN_IF_ERROR( writer->WriteScalar(full_name("current_file_index"), IntCast<int64_t>(current_file_index_))); if (reader_ != absl::nullopt) { TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("current_pos"), reader_->pos().ToBytes())); } #if TF_GRAPH_DEF_VERSION >= 1137 return ::tensorflow::OkStatus(); #else return ::tensorflow::Status::OK(); #endif } ::tensorflow::Status RestoreInternal( ::tensorflow::data::IteratorContext* ctx, ::tensorflow::data::IteratorStateReader* reader) override ABSL_LOCKS_EXCLUDED(mu_) { absl::MutexLock l(&mu_); current_file_index_ = 0; reader_.reset(); int64_t current_file_index; TF_RETURN_IF_ERROR(reader->ReadScalar(full_name("current_file_index"), &current_file_index)); if (TF_PREDICT_FALSE(current_file_index < 0 || IntCast<uint64_t>(current_file_index) > dataset()->filenames_.size())) { return ::tensorflow::errors::Internal( "current_file_index out of range"); } current_file_index_ = IntCast<size_t>(current_file_index); if (reader->Contains(full_name("current_pos"))) { if (TF_PREDICT_FALSE(current_file_index_ == dataset()->filenames_.size())) { return ::tensorflow::errors::Internal( "current_file_index out of range"); } ::tensorflow::tstring current_pos; TF_RETURN_IF_ERROR( reader->ReadScalar(full_name("current_pos"), &current_pos)); RecordPosition pos; if (TF_PREDICT_FALSE(!pos.FromBytes(current_pos))) { return ::tensorflow::errors::Internal( "current_pos is not a valid RecordPosition"); } OpenFile(ctx); reader_->Seek(pos); // Any errors from seeking will be reported during reading. } #if TF_GRAPH_DEF_VERSION >= 1137 return ::tensorflow::OkStatus(); #else return ::tensorflow::Status::OK(); #endif } private: void OpenFile(::tensorflow::data::IteratorContext* ctx) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) { reader_.emplace(std::forward_as_tuple( dataset()->filenames_[current_file_index_], tensorflow::FileReaderBase::Options() .set_env(ctx->env()) .set_min_buffer_size( IntCast<size_t>(dataset()->min_buffer_size_)) .set_max_buffer_size( IntCast<size_t>(dataset()->max_buffer_size_)))); } // Invariants: // `current_file_index_ <= dataset()->filenames_.size()` // if `current_file_index_ == dataset()->filenames_.size()` then // `reader_ == absl::nullopt` absl::Mutex mu_; size_t current_file_index_ ABSL_GUARDED_BY(mu_) = 0; // `absl::nullopt` means not open yet. absl::optional<RecordReader<tensorflow::FileReader<>>> reader_ ABSL_GUARDED_BY(mu_); }; const std::vector<std::string> filenames_; const int64_t min_buffer_size_; const int64_t max_buffer_size_; }; }; REGISTER_KERNEL_BUILDER(Name("RiegeliDataset").Device(::tensorflow::DEVICE_CPU), RiegeliDatasetOp); } // namespace } // namespace tensorflow } // namespace riegeli <|endoftext|>
<commit_before>#include "BasicPartitioner.h" #include "Node.h" #include "Camera.h" #include <memory> #include <algorithm> using namespace std; #define MIN_NODES 65536 #define MIN_LIGHTS 16 BasicPartitioner :: BasicPartitioner() { m_Nodes.resize(MIN_NODES); m_Lights.resize(MIN_LIGHTS); } void BasicPartitioner :: partition(const Node* root) { assert(m_pCamera); size_t sz = m_Nodes.size(); size_t lsz = m_Lights.size(); unsigned node_idx=0; unsigned light_idx=0; root->each([&](const Node* node){ if(!m_pCamera->is_visible(node)) return; if(K_UNLIKELY(node_idx >= sz)) { sz = max<unsigned>(MIN_NODES, sz*2); m_Nodes.resize(sz); } if(K_UNLIKELY(light_idx >= lsz)) { lsz = max<unsigned>(MIN_LIGHTS, lsz*2); m_Lights.resize(lsz); } if(not node->is_light()) { m_Nodes.at(node_idx) = node; ++node_idx; } else { m_Lights.at(light_idx) = (const Light*)node; ++light_idx; } }, Node::Each::RECURSIVE); if(K_UNLIKELY(node_idx >= sz)) m_Nodes.resize(max<unsigned>(MIN_NODES, sz*2)); if(K_UNLIKELY(light_idx >= lsz)) m_Lights.resize(max<unsigned>(MIN_LIGHTS, lsz*2)); stable_sort(m_Nodes.begin(), m_Nodes.begin() + node_idx, [](const Node* a, const Node* b){ if(not floatcmp(a->layer(), b->layer())) return a->layer() < b->layer(); return false; } ); m_Nodes.at(node_idx) = nullptr; m_Lights.at(light_idx) = nullptr; } void BasicPartitioner :: logic(Freq::Time t) { // check 1-to-1 collisions for( auto itr = m_Collisions.begin(); itr != m_Collisions.end(); ){ auto a = itr->a.lock(); if(not a) { itr = m_Collisions.erase(itr); continue; } auto b = itr->b.lock(); if(not b) { itr = m_Collisions.erase(itr); continue; } if(a->world_box().collision(b->world_box())) { (*itr->on_collision)(a.get(), b.get()); if(not itr->collision) { itr->collision = true; (*itr->on_enter)(a.get(), b.get()); } } else { (*itr->on_no_collision)(a.get(), b.get()); if(itr->collision) { itr->collision = false; (*itr->on_leave)(a.get(), b.get()); } } if(a.unique() || b.unique()) { itr = m_Collisions.erase(itr); continue; } ++itr; } // check type collisions for( auto itr = m_TypedCollisions.begin(); itr != m_TypedCollisions.end(); ){ auto a = itr->a.lock(); if(not a) { itr = m_TypedCollisions.erase(itr); continue; } unsigned type = itr->b; if(m_Objects.size() <= type) continue; for(auto jtr = m_Objects[type].begin(); jtr != m_Objects[type].end(); ){ auto b = jtr->lock(); if(not b) { jtr = m_Objects[type].erase(jtr); continue; } if(a->world_box().collision(b->world_box())) { (*itr->on_collision)(a.get(), b.get()); if(not itr->collision) { itr->collision = true; (*itr->on_enter)(a.get(), b.get()); } } else { (*itr->on_no_collision)(a.get(), b.get()); if(itr->collision) { itr->collision = false; (*itr->on_leave)(a.get(), b.get()); } } ++jtr; } if(a.unique()) { itr = m_TypedCollisions.erase(itr); continue; } ++itr; } // TODO: check intertype collisions } void BasicPartitioner :: on_collision( const std::shared_ptr<Node>& a, const std::shared_ptr<Node>& b, std::function<void(Node*, Node*)> col, std::function<void(Node*, Node*)> no_col, std::function<void(Node*, Node*)> enter, std::function<void(Node*, Node*)> leave ){ auto pair = Pair<weak_ptr<Node>, weak_ptr<Node>>(a,b); if(col) pair.on_collision->connect(col); if(no_col) pair.on_no_collision->connect(no_col); if(enter) pair.on_enter->connect(enter); if(leave) pair.on_leave->connect(leave); m_Collisions.push_back(std::move(pair)); } vector<Node*> BasicPartitioner :: get_collisions_for(Node* n) { vector<Node*> r; for( auto itr = m_Collisions.begin(); itr != m_Collisions.end(); ){ auto a = itr->a.lock(); if(not a) { itr = m_Collisions.erase(itr); continue; } if(a.get() == n) { auto b = itr->b.lock(); if(not b) { itr = m_Collisions.erase(itr); continue; } if(a->world_box().collision(b->world_box())) r.push_back(b.get()); } ++itr; } return r; } std::vector<Node*> BasicPartitioner :: get_collisions_for(Node* n, unsigned type) { return std::vector<Node*>(); } std::vector<Node*> BasicPartitioner :: get_collisions_for(unsigned type_a, unsigned type_b) { return std::vector<Node*>(); } void BasicPartitioner :: on_collision( const std::shared_ptr<Node>& a, unsigned type, std::function<void(Node*, Node*)> col, std::function<void(Node*, Node*)> no_col, std::function<void(Node*, Node*)> enter, std::function<void(Node*, Node*)> leave ){ auto pair = Pair<weak_ptr<Node>, unsigned>(a,type); if(col) pair.on_collision->connect(col); if(no_col) pair.on_no_collision->connect(no_col); if(enter) pair.on_enter->connect(enter); if(leave) pair.on_leave->connect(leave); m_TypedCollisions.push_back(std::move(pair)); } void BasicPartitioner :: on_collision( unsigned type_a, unsigned type_b, std::function<void(Node*, Node*)> col, std::function<void(Node*, Node*)> no_col, std::function<void(Node*, Node*)> enter, std::function<void(Node*, Node*)> leave ){ auto pair = Pair<unsigned, unsigned>(type_a,type_b); if(col) pair.on_collision->connect(col); if(no_col) pair.on_no_collision->connect(no_col); if(enter) pair.on_enter->connect(enter); if(leave) pair.on_leave->connect(leave); m_IntertypeCollisions.push_back(std::move(pair)); } void BasicPartitioner :: register_object( const std::shared_ptr<Node>& a, unsigned type ){ m_Objects[type].emplace_back(a); } void BasicPartitioner :: deregister_object( const std::shared_ptr<Node>& a, unsigned type ){ } void BasicPartitioner :: deregister_object( const std::shared_ptr<Node>& a ){ } <commit_msg>added intertype collision, done with new stuff -- needs testing<commit_after>#include "BasicPartitioner.h" #include "Node.h" #include "Camera.h" #include <memory> #include <algorithm> using namespace std; #define MIN_NODES 65536 #define MIN_LIGHTS 16 BasicPartitioner :: BasicPartitioner() { m_Nodes.resize(MIN_NODES); m_Lights.resize(MIN_LIGHTS); } void BasicPartitioner :: partition(const Node* root) { assert(m_pCamera); size_t sz = m_Nodes.size(); size_t lsz = m_Lights.size(); unsigned node_idx=0; unsigned light_idx=0; root->each([&](const Node* node){ if(!m_pCamera->is_visible(node)) return; if(K_UNLIKELY(node_idx >= sz)) { sz = max<unsigned>(MIN_NODES, sz*2); m_Nodes.resize(sz); } if(K_UNLIKELY(light_idx >= lsz)) { lsz = max<unsigned>(MIN_LIGHTS, lsz*2); m_Lights.resize(lsz); } if(not node->is_light()) { m_Nodes.at(node_idx) = node; ++node_idx; } else { m_Lights.at(light_idx) = (const Light*)node; ++light_idx; } }, Node::Each::RECURSIVE); if(K_UNLIKELY(node_idx >= sz)) m_Nodes.resize(max<unsigned>(MIN_NODES, sz*2)); if(K_UNLIKELY(light_idx >= lsz)) m_Lights.resize(max<unsigned>(MIN_LIGHTS, lsz*2)); stable_sort(m_Nodes.begin(), m_Nodes.begin() + node_idx, [](const Node* a, const Node* b){ if(not floatcmp(a->layer(), b->layer())) return a->layer() < b->layer(); return false; } ); m_Nodes.at(node_idx) = nullptr; m_Lights.at(light_idx) = nullptr; } void BasicPartitioner :: logic(Freq::Time t) { // check 1-to-1 collisions for( auto itr = m_Collisions.begin(); itr != m_Collisions.end(); ){ auto a = itr->a.lock(); if(not a) { itr = m_Collisions.erase(itr); continue; } auto b = itr->b.lock(); if(not b) { itr = m_Collisions.erase(itr); continue; } if(a->world_box().collision(b->world_box())) { (*itr->on_collision)(a.get(), b.get()); if(not itr->collision) { itr->collision = true; (*itr->on_enter)(a.get(), b.get()); } } else { (*itr->on_no_collision)(a.get(), b.get()); if(itr->collision) { itr->collision = false; (*itr->on_leave)(a.get(), b.get()); } } if(a.unique() || b.unique()) { itr = m_Collisions.erase(itr); continue; } ++itr; } // check type collisions for( auto itr = m_TypedCollisions.begin(); itr != m_TypedCollisions.end(); ){ auto a = itr->a.lock(); if(not a) { itr = m_TypedCollisions.erase(itr); continue; } unsigned type = itr->b; if(m_Objects.size() <= type) continue; for(auto jtr = m_Objects[type].begin(); jtr != m_Objects[type].end(); ){ auto b = jtr->lock(); if(not b) { jtr = m_Objects[type].erase(jtr); continue; } if(a->world_box().collision(b->world_box())) { (*itr->on_collision)(a.get(), b.get()); if(not itr->collision) { itr->collision = true; (*itr->on_enter)(a.get(), b.get()); } } else { (*itr->on_no_collision)(a.get(), b.get()); if(itr->collision) { itr->collision = false; (*itr->on_leave)(a.get(), b.get()); } } ++jtr; } if(a.unique()) { itr = m_TypedCollisions.erase(itr); continue; } ++itr; } // check intertype collisions for( auto itr = m_IntertypeCollisions.begin(); itr != m_IntertypeCollisions.end(); ){ auto type_a = itr->a; auto type_b = itr->b; for(auto jtr = m_Objects[type_a].begin(); jtr != m_Objects[type_a].end(); ){ auto a = jtr->lock(); if(not a) { jtr = m_Objects[type_a].erase(jtr); continue; } for(auto htr = m_Objects[type_b].begin(); htr != m_Objects[type_b].end(); ){ auto b = htr->lock(); if(not b) { htr = m_Objects[type_b].erase(htr); continue; } if(a == b) // same object continue; if(a->world_box().collision(b->world_box())) { (*itr->on_collision)(a.get(), b.get()); if(not itr->collision) { itr->collision = true; (*itr->on_enter)(a.get(), b.get()); } } else { (*itr->on_no_collision)(a.get(), b.get()); if(itr->collision) { itr->collision = false; (*itr->on_leave)(a.get(), b.get()); } } ++htr; } ++jtr; } ++itr; } } void BasicPartitioner :: on_collision( const std::shared_ptr<Node>& a, const std::shared_ptr<Node>& b, std::function<void(Node*, Node*)> col, std::function<void(Node*, Node*)> no_col, std::function<void(Node*, Node*)> enter, std::function<void(Node*, Node*)> leave ){ auto pair = Pair<weak_ptr<Node>, weak_ptr<Node>>(a,b); if(col) pair.on_collision->connect(col); if(no_col) pair.on_no_collision->connect(no_col); if(enter) pair.on_enter->connect(enter); if(leave) pair.on_leave->connect(leave); m_Collisions.push_back(std::move(pair)); } vector<Node*> BasicPartitioner :: get_collisions_for(Node* n) { vector<Node*> r; for( auto itr = m_Collisions.begin(); itr != m_Collisions.end(); ){ auto a = itr->a.lock(); if(not a) { itr = m_Collisions.erase(itr); continue; } if(a.get() == n) { auto b = itr->b.lock(); if(not b) { itr = m_Collisions.erase(itr); continue; } if(a->world_box().collision(b->world_box())) r.push_back(b.get()); } ++itr; } return r; } std::vector<Node*> BasicPartitioner :: get_collisions_for(Node* n, unsigned type) { return std::vector<Node*>(); } std::vector<Node*> BasicPartitioner :: get_collisions_for(unsigned type_a, unsigned type_b) { return std::vector<Node*>(); } void BasicPartitioner :: on_collision( const std::shared_ptr<Node>& a, unsigned type, std::function<void(Node*, Node*)> col, std::function<void(Node*, Node*)> no_col, std::function<void(Node*, Node*)> enter, std::function<void(Node*, Node*)> leave ){ auto pair = Pair<weak_ptr<Node>, unsigned>(a,type); if(col) pair.on_collision->connect(col); if(no_col) pair.on_no_collision->connect(no_col); if(enter) pair.on_enter->connect(enter); if(leave) pair.on_leave->connect(leave); m_TypedCollisions.push_back(std::move(pair)); } void BasicPartitioner :: on_collision( unsigned type_a, unsigned type_b, std::function<void(Node*, Node*)> col, std::function<void(Node*, Node*)> no_col, std::function<void(Node*, Node*)> enter, std::function<void(Node*, Node*)> leave ){ auto pair = Pair<unsigned, unsigned>(type_a,type_b); if(col) pair.on_collision->connect(col); if(no_col) pair.on_no_collision->connect(no_col); if(enter) pair.on_enter->connect(enter); if(leave) pair.on_leave->connect(leave); m_IntertypeCollisions.push_back(std::move(pair)); } void BasicPartitioner :: register_object( const std::shared_ptr<Node>& a, unsigned type ){ m_Objects[type].emplace_back(a); } void BasicPartitioner :: deregister_object( const std::shared_ptr<Node>& a, unsigned type ){ } void BasicPartitioner :: deregister_object( const std::shared_ptr<Node>& a ){ } <|endoftext|>
<commit_before>/*************************************************************************** Copyright (C) 2007 by Marco Gulino <marco@kmobiletools.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ***************************************************************************/ #include "sms.h" #include <qstringlist.h> #include <qdatetime.h> #include <kdebug.h> #include <qdir.h> #include <qfile.h> #include <klocale.h> #include <qregexp.h> #include <kcodecs.h> #include <QTextStream> #include "kmobiletoolshelper.h" class SMSPrivate { public: SMSPrivate() : i_folder(0), i_slot(0), i_type(SMS::All), b_unread(false) {}; QStringList sl_numbers; QString s_text; QDateTime dt_datetime; int i_folder; int i_slot; SMS::SMSType i_type; QList<int> v_id; QString s_rawSlot; bool b_unread; }; SMS::SMS(QObject *parent) : QObject(parent), d(new SMSPrivate) { } SMS::SMS(const QStringList & numbers, const QString & text, const QDateTime & datetime, QObject *parent) : QObject(parent), d(new SMSPrivate) { setNumbers(numbers); setText(text); setDateTime(datetime); setFolder(d->i_folder); } SMS::SMS(const QStringList & numbers, const QString & text, QObject *parent) : QObject(parent), d(new SMSPrivate) { setNumbers(numbers); setText(text); } void SMS::setDateTime(const QDateTime & datetime) { d->dt_datetime=datetime; } SMS::~SMS() { } QString SMS::getFrom() const { if (d->i_type==Unsent || d->i_type==Sent) { return QString(); } else { return QString( d->sl_numbers.first() ); } } QStringList SMS::getTo() const { if (d->i_type==Unsent || d->i_type==Sent) { return d->sl_numbers; } else { return QStringList(); } } QByteArray SMS::uid() const { KMD5 context; QByteArray ba; if (d->sl_numbers.isEmpty()) ba = d->s_text.toUtf8(); else ba = (d->s_text + d->sl_numbers.join(",")).toUtf8(); context.update(ba); return context.hexDigest(); } bool SMS::operator ==( SMS* compSMS) { return (compSMS->uid() == this->uid()); } int SMS::getMultiTextCount(const QString &text) { return getMultiTextCount(text.length()); } int SMS::getMultiTextCount(int length) { if(length <= 160) return 1; int textLength=0; if(length <= 1404 ) textLength=156; else textLength=154; if(length % textLength) return (length / textLength)+1; else return (length / textLength); } bool SMS::isIncoming() const { return ((type() & Unread) || (type() & Read)); } QStringList SMS::getMultiText(const QString &text) { if(text.length()<=160 ) return QStringList(text); QStringList out; /* Now some notes about total text calculation We're adding a separator at the beginning of each message: "n/m:" (without quotes, but WITH the semicolon). Now.. if m<10, the separator steal us 4 characters for each sms, so we must split the message in strings of 156 characters. So we should check if message length is <=1404 characters. If message length > 1404 characters, we should use a "nn/mm:" notation, and now the separarator steal us 6 characters. Each message part now should be 154 characters, and so our maximal length now is 15246 characters. I just hope that in this world nobody is so mad to send a multi-message made with more than 99 SMS ;-) */ int sepLength, textLength,minLength; const QString sep="%1/%2:"; int totalMessages; if(text.length() <= 1404 ) { sepLength=4; textLength=156; minLength=1; } else { sepLength=6; textLength=154; minLength=2; } if(text.length() % textLength) totalMessages=(text.length()/ textLength) +1; else totalMessages=text.length() / textLength; int j=0; for(int i=0; i<text.length(); i+=textLength) { j++; out+=text.mid( i, textLength ) .prepend( sep .arg( j, minLength ) .arg( totalMessages, minLength ) .replace( ' ','0') ); } return out; } // Convenience non-static method for the above one QStringList SMS::getMultiText() const { return getMultiText(d->s_text); } #include "sms.moc" /*! \fn SMS::export(const QString &dir) */ bool SMS::exportMD(const QString &dir) { bool retval=false; if (d->i_slot & SIM ) retval = retval | writeToSlot( dir + QDir::separator() + '.' + i18nc("SIM MailDir", "SIM") + ".directory"); if (d->i_slot & Phone ) retval = retval | writeToSlot( dir + QDir::separator() + '.' + i18nc("Phone MailDir", "Phone") + ".directory"); return retval; } bool SMS::writeToSlot(const QString &dir) { QString filename=dir+QDir::separator(); QString text; if((d->i_type & Unsent) || (d->i_type & Sent) ) { filename+=i18nc("Outgoing MailDir", "Outgoing"); text="To: "; for(QStringList::Iterator it=d->sl_numbers.begin(); it!=d->sl_numbers.end(); ++it) text+=KMobileTools::KMobiletoolsHelper::translateNumber(*it) + "\" <" + *it + ">\n"; text+="X-Status: RS\n"; } else { filename+=i18nc("Incoming MailDir", "Incoming"); text="From: \"" + KMobileTools::KMobiletoolsHelper::translateNumber( getFrom() ) + "\" <" + getFrom() + ">\n"; text+="X-Status: RC\n"; } QString subject=i18nc("SMS/Mail Subject", "[KMobileTools Imported Message]") + ' '; subject+=KCodecs::quotedPrintableEncode( getText().left( 20+ getText().indexOf( ( QRegExp("[\\s]"), 20 )) ).toUtf8() ); subject+="..."; subject=subject.replace( QRegExp("([^\\s]*=[\\dA-F]{2,2}[^\\s]*)"), "=?utf-8?q?\\1?="); text+=QString("Subject: %1\n").arg(subject); text+="Date: " + d->dt_datetime.toString( "%1, d %2 yyyy hh:mm:ss" ) .arg( KMobileTools::KMobiletoolsHelper::shortWeekDayNameEng( d->dt_datetime.date().dayOfWeek() ) ) .arg( KMobileTools::KMobiletoolsHelper::shortMonthNameEng( d->dt_datetime.date().month() ) ) + '\n'; text+="X-KMobileTools-IntType: " + QString::number(type() ) + '\n'; text+="X-KMobileTools-TextType: " + SMSTypeString(type() ) + '\n'; text+="X-KMobileTools-PhoneNumbersTo: " + d->sl_numbers.join(",") + '\n'; text+="X-KMobileTools-PhoneNumbersFrom: " + getFrom() + '\n'; text+="X-KMobileTools-RawSlot: " + rawSlot() + '\n'; text+="Content-Type: text/plain;\n \tcharset=\"utf-8\"\nContent-Transfer-Encoding: quoted-printable\n"; // text+="Content-Type: text/plain; charset=utf-8\n"; text+="\n\n" + KCodecs::quotedPrintableEncode( getText().toUtf8() )+ '\n'; filename=filename + QDir::separator() + "cur" + QDir::separator() + QString::number(d->dt_datetime.toTime_t()) + '.' + QString(uid()) + '.' + "kmobiletools"; kDebug() << "Writing sms to " << filename << endl; QFile file(filename); if(! file.open( QIODevice::WriteOnly | QIODevice::Truncate ) ) return false; QTextStream stream( &file ); stream << text; file.close(); return true; } /*! \fn SMS::exportCSV(const QString &dir) */ bool SMS::exportCSV(const QString &dir, const QString &filename) { kDebug() << "SMS::exportCSV(): " << endl; bool retval=false; if (d->i_slot & Phone ) retval = retval | writeToSlotCSV( dir, filename ); return retval; } bool SMS::writeToSlotCSV(const QString &dir, const QString &filename) { kDebug() << "SMS::writeToSlotCSV(): " << endl; QString text; QString filenameOut; filenameOut = dir + QDir::separator() + filename; if((d->i_type & Unsent) || (d->i_type & Sent) ) { text="\"OUTGOING\","; for(QStringList::Iterator it=d->sl_numbers.begin(); it!=d->sl_numbers.end(); ++it) text+="\"" + KMobileTools::KMobiletoolsHelper::translateNumber(*it) + "\",\"" + *it + "\","; //filenameOut = dir + QDir::separator() + "outbox_" + filename; } else { QString transNumber; //transNumber = KMobileTools::KMobiletoolsHelper::translateNumber( getFrom() ).utf8(); transNumber = KMobileTools::KMobiletoolsHelper::translateNumber( getFrom() ); //text="\"INCOMING\",\"" + KMobileTools::KMobiletoolsHelper::translateNumber( getFrom() ) + "\",\"" + getFrom() + "\","; text="\"INCOMING\",\"" + transNumber + "\",\"" + getFrom() + "\","; //filenameOut = dir + QDir::separator() + "inbox_" + filename; } text+="\"" + d->dt_datetime.toString( "%1, d %2 yyyy hh:mm:ss" ) .arg( KMobileTools::KMobiletoolsHelper::shortWeekDayNameEng( d->dt_datetime.date().dayOfWeek() ) ) .arg( KMobileTools::KMobiletoolsHelper::shortMonthNameEng( d->dt_datetime.date().month() ) ) + "\","; //text+="\"" + KCodecs::quotedPrintableEncode( getText().utf8() ) + "\""; //text+="\"" + getText().utf8() + "\""; text+="\"" + getText() + "\""; kDebug() << "Writing sms to " << filenameOut << endl; QFile file(filenameOut); QString lastFile = file.readAll(); if(! file.open( QIODevice::WriteOnly | QIODevice::Append ) ) return false; QTextStream stream( &file ); //stream << lastFile << text.utf8() << endl; stream << lastFile << text << endl; file.close(); return true; } void SMS::setText(const QString & text) { d->s_text=text; } QString SMS::getText() const { return d->s_text; } QString SMS::getDate() const { return d->dt_datetime.toString(); } QDateTime SMS::getDateTime() const { return d->dt_datetime; } void SMS::setRawSlot(const QString &rawSlot){ d->s_rawSlot=rawSlot;} QString SMS::rawSlot() const { return d->s_rawSlot;} void SMS::setNumbers(const QStringList & numbers) { d->sl_numbers=numbers; } void SMS::setFolder( int newFolder ) { d->i_folder = newFolder; } int SMS::folder() const { return d->i_folder; } QList<int> *SMS::idList() { return &(d->v_id); } void SMS::setSlot( int newSlot ) { d->i_slot=newSlot; emit updated(); } SMS::SMSType SMS::type() const { return d->i_type; } void SMS::setType( SMSType newType ) { d->i_type = newType; emit updated(); } int SMS::slot() const { return d->i_slot; } bool SMS::unread() const { return d->b_unread; } void SMS::setUnread(bool unread) { d->b_unread=unread;} <commit_msg>Fixing sms export.<commit_after>/*************************************************************************** Copyright (C) 2007 by Marco Gulino <marco@kmobiletools.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ***************************************************************************/ #include "sms.h" #include <qstringlist.h> #include <qdatetime.h> #include <kdebug.h> #include <qdir.h> #include <qfile.h> #include <klocale.h> #include <qregexp.h> #include <kcodecs.h> #include <QTextStream> #include "kmobiletoolshelper.h" class SMSPrivate { public: SMSPrivate() : i_folder(0), i_slot(0), i_type(SMS::All), b_unread(false) {}; QStringList sl_numbers; QString s_text; QDateTime dt_datetime; int i_folder; int i_slot; SMS::SMSType i_type; QList<int> v_id; QString s_rawSlot; bool b_unread; }; SMS::SMS(QObject *parent) : QObject(parent), d(new SMSPrivate) { } SMS::SMS(const QStringList & numbers, const QString & text, const QDateTime & datetime, QObject *parent) : QObject(parent), d(new SMSPrivate) { setNumbers(numbers); setText(text); setDateTime(datetime); setFolder(d->i_folder); } SMS::SMS(const QStringList & numbers, const QString & text, QObject *parent) : QObject(parent), d(new SMSPrivate) { setNumbers(numbers); setText(text); } void SMS::setDateTime(const QDateTime & datetime) { d->dt_datetime=datetime; } SMS::~SMS() { } QString SMS::getFrom() const { if (d->i_type==Unsent || d->i_type==Sent) { return QString(); } else { return QString( d->sl_numbers.first() ); } } QStringList SMS::getTo() const { if (d->i_type==Unsent || d->i_type==Sent) { return d->sl_numbers; } else { return QStringList(); } } QByteArray SMS::uid() const { KMD5 context; QByteArray ba; if (d->sl_numbers.isEmpty()) ba = d->s_text.toUtf8(); else ba = (d->s_text + d->sl_numbers.join(",")).toUtf8(); context.update(ba); return context.hexDigest(); } bool SMS::operator ==( SMS* compSMS) { return (compSMS->uid() == this->uid()); } int SMS::getMultiTextCount(const QString &text) { return getMultiTextCount(text.length()); } int SMS::getMultiTextCount(int length) { if(length <= 160) return 1; int textLength=0; if(length <= 1404 ) textLength=156; else textLength=154; if(length % textLength) return (length / textLength)+1; else return (length / textLength); } bool SMS::isIncoming() const { return ((type() & Unread) || (type() & Read)); } QStringList SMS::getMultiText(const QString &text) { if(text.length()<=160 ) return QStringList(text); QStringList out; /* Now some notes about total text calculation We're adding a separator at the beginning of each message: "n/m:" (without quotes, but WITH the semicolon). Now.. if m<10, the separator steal us 4 characters for each sms, so we must split the message in strings of 156 characters. So we should check if message length is <=1404 characters. If message length > 1404 characters, we should use a "nn/mm:" notation, and now the separarator steal us 6 characters. Each message part now should be 154 characters, and so our maximal length now is 15246 characters. I just hope that in this world nobody is so mad to send a multi-message made with more than 99 SMS ;-) */ int sepLength, textLength,minLength; const QString sep="%1/%2:"; int totalMessages; if(text.length() <= 1404 ) { sepLength=4; textLength=156; minLength=1; } else { sepLength=6; textLength=154; minLength=2; } if(text.length() % textLength) totalMessages=(text.length()/ textLength) +1; else totalMessages=text.length() / textLength; int j=0; for(int i=0; i<text.length(); i+=textLength) { j++; out+=text.mid( i, textLength ) .prepend( sep .arg( j, minLength ) .arg( totalMessages, minLength ) .replace( ' ','0') ); } return out; } // Convenience non-static method for the above one QStringList SMS::getMultiText() const { return getMultiText(d->s_text); } #include "sms.moc" /*! \fn SMS::export(const QString &dir) */ bool SMS::exportMD(const QString &dir) { bool retval=false; if (d->i_slot & SIM ) retval = retval | writeToSlot( dir + QDir::separator() + '.' + i18nc("SIM MailDir", "SIM") + ".directory"); if (d->i_slot & Phone ) retval = retval | writeToSlot( dir + QDir::separator() + '.' + i18nc("Phone MailDir", "Phone") + ".directory"); return retval; } bool SMS::writeToSlot(const QString &dir) { QString filename=dir+QDir::separator(); QString text; if((d->i_type & Unsent) || (d->i_type & Sent) ) { filename+=i18nc("Outgoing MailDir", "Outgoing"); text="To: \""; for(QStringList::Iterator it=d->sl_numbers.begin(); it!=d->sl_numbers.end(); ++it) text+=KMobileTools::KMobiletoolsHelper::translateNumber(*it) + "\" <" + *it + ">\n"; text+="X-Status: RS\n"; } else { filename+=i18nc("Incoming MailDir", "Incoming"); text="From: \"" + KMobileTools::KMobiletoolsHelper::translateNumber( getFrom() ) + "\" <" + getFrom() + ">\n"; text+="X-Status: RC\n"; } QString subject=i18nc("SMS/Mail Subject", "[KMobileTools Imported Message]") + ' '; subject+=KCodecs::quotedPrintableEncode( getText().left( 20+ getText().indexOf( ( QRegExp("[\\s]"), 20 )) ).toUtf8() ); subject+="..."; subject=subject.replace( QRegExp("([^\\s]*=[\\dA-F]{2,2}[^\\s]*)"), "=?utf-8?q?\\1?="); text+=QString("Subject: %1\n").arg(subject); text+="Date: " + d->dt_datetime.toString( "%1, d %2 yyyy hh:mm:ss" ) .arg( KMobileTools::KMobiletoolsHelper::shortWeekDayNameEng( d->dt_datetime.date().dayOfWeek() ) ) .arg( KMobileTools::KMobiletoolsHelper::shortMonthNameEng( d->dt_datetime.date().month() ) ) + '\n'; text+="X-KMobileTools-IntType: " + QString::number(type() ) + '\n'; text+="X-KMobileTools-TextType: " + SMSTypeString(type() ) + '\n'; text+="X-KMobileTools-PhoneNumbersTo: " + d->sl_numbers.join(",") + '\n'; text+="X-KMobileTools-PhoneNumbersFrom: " + getFrom() + '\n'; text+="X-KMobileTools-RawSlot: " + rawSlot() + '\n'; text+="Content-Type: text/plain;\n \tcharset=\"utf-8\"\nContent-Transfer-Encoding: quoted-printable\n"; // text+="Content-Type: text/plain; charset=utf-8\n"; text+="\n\n" + KCodecs::quotedPrintableEncode( getText().toUtf8() )+ '\n'; filename=filename + QDir::separator() + "cur" + QDir::separator() + QString::number(d->dt_datetime.toTime_t()) + '.' + QString(uid()) + '.' + "kmobiletools"; kDebug() << "Writing sms to " << filename << endl; QFile file(filename); if(! file.open( QIODevice::WriteOnly | QIODevice::Truncate ) ) return false; QTextStream stream( &file ); stream << text; file.close(); return true; } /*! \fn SMS::exportCSV(const QString &dir) */ bool SMS::exportCSV(const QString &dir, const QString &filename) { kDebug() << "SMS::exportCSV(): " << endl; bool retval=false; if (d->i_slot & Phone ) retval = retval | writeToSlotCSV( dir, filename ); return retval; } bool SMS::writeToSlotCSV(const QString &dir, const QString &filename) { kDebug() << "SMS::writeToSlotCSV(): " << endl; QString text; QString filenameOut; filenameOut = dir + QDir::separator() + filename; if((d->i_type & Unsent) || (d->i_type & Sent) ) { text="\"OUTGOING\","; for(QStringList::Iterator it=d->sl_numbers.begin(); it!=d->sl_numbers.end(); ++it) text+="\"" + KMobileTools::KMobiletoolsHelper::translateNumber(*it) + "\",\"" + *it + "\","; //filenameOut = dir + QDir::separator() + "outbox_" + filename; } else { QString transNumber; //transNumber = KMobileTools::KMobiletoolsHelper::translateNumber( getFrom() ).utf8(); transNumber = KMobileTools::KMobiletoolsHelper::translateNumber( getFrom() ); //text="\"INCOMING\",\"" + KMobileTools::KMobiletoolsHelper::translateNumber( getFrom() ) + "\",\"" + getFrom() + "\","; text="\"INCOMING\",\"" + transNumber + "\",\"" + getFrom() + "\","; //filenameOut = dir + QDir::separator() + "inbox_" + filename; } text+="\"" + d->dt_datetime.toString( "%1, d %2 yyyy hh:mm:ss" ) .arg( KMobileTools::KMobiletoolsHelper::shortWeekDayNameEng( d->dt_datetime.date().dayOfWeek() ) ) .arg( KMobileTools::KMobiletoolsHelper::shortMonthNameEng( d->dt_datetime.date().month() ) ) + "\","; //text+="\"" + KCodecs::quotedPrintableEncode( getText().utf8() ) + "\""; //text+="\"" + getText().utf8() + "\""; text+="\"" + getText() + "\""; kDebug() << "Writing sms to " << filenameOut << endl; QFile file(filenameOut); QString lastFile = file.readAll(); if(! file.open( QIODevice::WriteOnly | QIODevice::Append ) ) return false; QTextStream stream( &file ); //stream << lastFile << text.utf8() << endl; stream << lastFile << text << endl; file.close(); return true; } void SMS::setText(const QString & text) { d->s_text=text; } QString SMS::getText() const { return d->s_text; } QString SMS::getDate() const { return d->dt_datetime.toString(); } QDateTime SMS::getDateTime() const { return d->dt_datetime; } void SMS::setRawSlot(const QString &rawSlot){ d->s_rawSlot=rawSlot;} QString SMS::rawSlot() const { return d->s_rawSlot;} void SMS::setNumbers(const QStringList & numbers) { d->sl_numbers=numbers; } void SMS::setFolder( int newFolder ) { d->i_folder = newFolder; } int SMS::folder() const { return d->i_folder; } QList<int> *SMS::idList() { return &(d->v_id); } void SMS::setSlot( int newSlot ) { d->i_slot=newSlot; emit updated(); } SMS::SMSType SMS::type() const { return d->i_type; } void SMS::setType( SMSType newType ) { d->i_type = newType; emit updated(); } int SMS::slot() const { return d->i_slot; } bool SMS::unread() const { return d->b_unread; } void SMS::setUnread(bool unread) { d->b_unread=unread;} <|endoftext|>
<commit_before>/* * Created on: 19 Apr 2014 * Author: Vladimir Ivan * * Copyright (c) 2016, University Of Edinburgh * 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 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 <exotica/Problems/UnconstrainedTimeIndexedProblem.h> #include <exotica/Setup.h> REGISTER_PROBLEM_TYPE("UnconstrainedTimeIndexedProblem", exotica::UnconstrainedTimeIndexedProblem) namespace exotica { UnconstrainedTimeIndexedProblem::UnconstrainedTimeIndexedProblem() : T(0), tau(0), Q_rate(0), W_rate(0), H_rate(0) { Flags = KIN_FK | KIN_J; } UnconstrainedTimeIndexedProblem::~UnconstrainedTimeIndexedProblem() { } void UnconstrainedTimeIndexedProblem::Instantiate(UnconstrainedTimeIndexedProblemInitializer& init) { T = init.T; if (T <= 2) { throw_named("Invalid number of timesteps: " << T); } tau = init.Tau; Q_rate = init.Qrate; H_rate = init.Hrate; W_rate = init.Wrate; NumTasks = Tasks.size(); PhiN = 0; JN = 0; TaskSpaceVector yref; for (int i = 0; i < NumTasks; i++) { appendVector(yref.map, Tasks[i]->getLieGroupIndices()); PhiN += Tasks[i]->Length; JN += Tasks[i]->LengthJ; } N = scene_->getSolver().getNumControlledJoints(); W = Eigen::MatrixXd::Identity(N, N) * W_rate; if (init.W.rows() > 0) { if (init.W.rows() == N) { W.diagonal() = init.W * W_rate; } else { throw_named("W dimension mismatch! Expected " << N << ", got " << init.W.rows()); } } H = Eigen::MatrixXd::Identity(N, N) * Q_rate; Q = Eigen::MatrixXd::Identity(N, N) * H_rate; if (init.Rho.rows() == 0) { Rho.assign(T, Eigen::VectorXd::Ones(NumTasks)); } else if (init.Rho.rows() == NumTasks) { Rho.assign(T, init.Rho); } else if (init.Rho.rows() == NumTasks * T) { Rho.resize(T); for (int i = 0; i < T; i++) { Rho[i] = init.Rho.segment(i * NumTasks, NumTasks); } } else { throw_named("Invalid task weights rho! " << init.Rho.rows()); } yref.setZero(PhiN); y.assign(T, yref); Phi = y; ydiff.assign(T, Eigen::VectorXd::Zero(JN)); J.assign(T, Eigen::MatrixXd(JN, N)); // Set initial trajectory InitialTrajectory.resize(T, getStartState()); } void UnconstrainedTimeIndexedProblem::setInitialTrajectory( const std::vector<Eigen::VectorXd> q_init_in) { if (q_init_in.size() != T) throw_pretty("Expected initial trajectory of length " << T << " but got " << q_init_in.size()); if (q_init_in[0].rows() != N) throw_pretty("Expected states to have " << N << " rows but got " << q_init_in[0].rows()); InitialTrajectory = q_init_in; setStartState(q_init_in[0]); } std::vector<Eigen::VectorXd> UnconstrainedTimeIndexedProblem::getInitialTrajectory() { return InitialTrajectory; } double UnconstrainedTimeIndexedProblem::getDuration() { return tau * (double)T; } void UnconstrainedTimeIndexedProblem::Update(Eigen::VectorXdRefConst x, int t) { scene_->Update(x, static_cast<double>(t) * tau); for (int i = 0; i < NumTasks; i++) { Tasks[i]->update(x, Phi[t].data.segment(Tasks[i]->Start, Tasks[i]->Length), J[t].middleRows(Tasks[i]->StartJ, Tasks[i]->LengthJ)); } ydiff[t] = y[t] - Phi[t]; } void UnconstrainedTimeIndexedProblem::setGoal(const std::string& task_name, Eigen::VectorXdRefConst goal, int t) { try { if (t >= T || t < -1) { throw_pretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T); } else if (t == -1) { t = T - 1; } TaskMap_ptr task = TaskMaps.at(task_name); y[t].data.segment(task->Start, task->Length) = goal; } catch (std::out_of_range& e) { throw_pretty("Cannot set Goal. Task map '" << task_name << "' Does not exist."); } } void UnconstrainedTimeIndexedProblem::setRho(const std::string& task_name, const double rho, int t) { try { if (t >= T || t < -1) { throw_pretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T); } else if (t == -1) { t = T - 1; } TaskMap_ptr task = TaskMaps.at(task_name); Rho[t](task->Id) = rho; } catch (std::out_of_range& e) { throw_pretty("Cannot set Rho. Task map '" << task_name << "' Does not exist."); } } Eigen::VectorXd UnconstrainedTimeIndexedProblem::getGoal(const std::string& task_name, int t) { try { if (t >= T || t < -1) { throw_pretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T); } else if (t == -1) { t = T - 1; } TaskMap_ptr task = TaskMaps.at(task_name); return y[t].data.segment(task->Start, task->Length); } catch (std::out_of_range& e) { throw_pretty("Cannot get Goal. Task map '" << task_name << "' Does not exist."); } } double UnconstrainedTimeIndexedProblem::getRho(const std::string& task_name, int t) { try { if (t >= T || t < -1) { throw_pretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T); } else if (t == -1) { t = T - 1; } TaskMap_ptr task = TaskMaps.at(task_name); return Rho[t](task->Id); } catch (std::out_of_range& e) { throw_pretty("Cannot get Rho. Task map '" << task_name << "' Does not exist."); } } } <commit_msg>UnconstrainedTimeIndexedProblem: Allow -1 index for update()<commit_after>/* * Created on: 19 Apr 2014 * Author: Vladimir Ivan * * Copyright (c) 2016, University Of Edinburgh * 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 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 <exotica/Problems/UnconstrainedTimeIndexedProblem.h> #include <exotica/Setup.h> REGISTER_PROBLEM_TYPE("UnconstrainedTimeIndexedProblem", exotica::UnconstrainedTimeIndexedProblem) namespace exotica { UnconstrainedTimeIndexedProblem::UnconstrainedTimeIndexedProblem() : T(0), tau(0), Q_rate(0), W_rate(0), H_rate(0) { Flags = KIN_FK | KIN_J; } UnconstrainedTimeIndexedProblem::~UnconstrainedTimeIndexedProblem() { } void UnconstrainedTimeIndexedProblem::Instantiate(UnconstrainedTimeIndexedProblemInitializer& init) { T = init.T; if (T <= 2) { throw_named("Invalid number of timesteps: " << T); } tau = init.Tau; Q_rate = init.Qrate; H_rate = init.Hrate; W_rate = init.Wrate; NumTasks = Tasks.size(); PhiN = 0; JN = 0; TaskSpaceVector yref; for (int i = 0; i < NumTasks; i++) { appendVector(yref.map, Tasks[i]->getLieGroupIndices()); PhiN += Tasks[i]->Length; JN += Tasks[i]->LengthJ; } N = scene_->getSolver().getNumControlledJoints(); W = Eigen::MatrixXd::Identity(N, N) * W_rate; if (init.W.rows() > 0) { if (init.W.rows() == N) { W.diagonal() = init.W * W_rate; } else { throw_named("W dimension mismatch! Expected " << N << ", got " << init.W.rows()); } } H = Eigen::MatrixXd::Identity(N, N) * Q_rate; Q = Eigen::MatrixXd::Identity(N, N) * H_rate; if (init.Rho.rows() == 0) { Rho.assign(T, Eigen::VectorXd::Ones(NumTasks)); } else if (init.Rho.rows() == NumTasks) { Rho.assign(T, init.Rho); } else if (init.Rho.rows() == NumTasks * T) { Rho.resize(T); for (int i = 0; i < T; i++) { Rho[i] = init.Rho.segment(i * NumTasks, NumTasks); } } else { throw_named("Invalid task weights rho! " << init.Rho.rows()); } yref.setZero(PhiN); y.assign(T, yref); Phi = y; ydiff.assign(T, Eigen::VectorXd::Zero(JN)); J.assign(T, Eigen::MatrixXd(JN, N)); // Set initial trajectory InitialTrajectory.resize(T, getStartState()); } void UnconstrainedTimeIndexedProblem::setInitialTrajectory( const std::vector<Eigen::VectorXd> q_init_in) { if (q_init_in.size() != T) throw_pretty("Expected initial trajectory of length " << T << " but got " << q_init_in.size()); if (q_init_in[0].rows() != N) throw_pretty("Expected states to have " << N << " rows but got " << q_init_in[0].rows()); InitialTrajectory = q_init_in; setStartState(q_init_in[0]); } std::vector<Eigen::VectorXd> UnconstrainedTimeIndexedProblem::getInitialTrajectory() { return InitialTrajectory; } double UnconstrainedTimeIndexedProblem::getDuration() { return tau * (double)T; } void UnconstrainedTimeIndexedProblem::Update(Eigen::VectorXdRefConst x, int t) { if (t >= T || t < -1) { throw_pretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T); } else if (t == -1) { t = T - 1; } scene_->Update(x, static_cast<double>(t) * tau); for (int i = 0; i < NumTasks; i++) { Tasks[i]->update(x, Phi[t].data.segment(Tasks[i]->Start, Tasks[i]->Length), J[t].middleRows(Tasks[i]->StartJ, Tasks[i]->LengthJ)); } ydiff[t] = y[t] - Phi[t]; } void UnconstrainedTimeIndexedProblem::setGoal(const std::string& task_name, Eigen::VectorXdRefConst goal, int t) { try { if (t >= T || t < -1) { throw_pretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T); } else if (t == -1) { t = T - 1; } TaskMap_ptr task = TaskMaps.at(task_name); y[t].data.segment(task->Start, task->Length) = goal; } catch (std::out_of_range& e) { throw_pretty("Cannot set Goal. Task map '" << task_name << "' Does not exist."); } } void UnconstrainedTimeIndexedProblem::setRho(const std::string& task_name, const double rho, int t) { try { if (t >= T || t < -1) { throw_pretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T); } else if (t == -1) { t = T - 1; } TaskMap_ptr task = TaskMaps.at(task_name); Rho[t](task->Id) = rho; } catch (std::out_of_range& e) { throw_pretty("Cannot set Rho. Task map '" << task_name << "' Does not exist."); } } Eigen::VectorXd UnconstrainedTimeIndexedProblem::getGoal(const std::string& task_name, int t) { try { if (t >= T || t < -1) { throw_pretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T); } else if (t == -1) { t = T - 1; } TaskMap_ptr task = TaskMaps.at(task_name); return y[t].data.segment(task->Start, task->Length); } catch (std::out_of_range& e) { throw_pretty("Cannot get Goal. Task map '" << task_name << "' Does not exist."); } } double UnconstrainedTimeIndexedProblem::getRho(const std::string& task_name, int t) { try { if (t >= T || t < -1) { throw_pretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T); } else if (t == -1) { t = T - 1; } TaskMap_ptr task = TaskMaps.at(task_name); return Rho[t](task->Id); } catch (std::out_of_range& e) { throw_pretty("Cannot get Rho. Task map '" << task_name << "' Does not exist."); } } } <|endoftext|>
<commit_before>#include "firestore/src/ios/firestore_ios.h" #include <utility> #include "app/src/include/firebase/future.h" #include "app/src/reference_counted_future_impl.h" #include "auth/src/include/firebase/auth.h" #include "firestore/src/include/firebase/firestore.h" #include "firestore/src/ios/converter_ios.h" #include "firestore/src/ios/credentials_provider_ios.h" #include "firestore/src/ios/document_reference_ios.h" #include "firestore/src/ios/document_snapshot_ios.h" #include "firestore/src/ios/listener_ios.h" #include "absl/memory/memory.h" #include "absl/types/any.h" #include "Firestore/core/src/firebase/firestore/api/document_reference.h" #include "Firestore/core/src/firebase/firestore/api/query_core.h" #include "Firestore/core/src/firebase/firestore/model/database_id.h" #include "Firestore/core/src/firebase/firestore/model/resource_path.h" #include "Firestore/core/src/firebase/firestore/util/async_queue.h" #include "Firestore/core/src/firebase/firestore/util/executor.h" #include "Firestore/core/src/firebase/firestore/util/log.h" #include "Firestore/core/src/firebase/firestore/util/status.h" namespace firebase { namespace firestore { namespace { using auth::CredentialsProvider; using ::firebase::auth::Auth; using model::DatabaseId; using model::ResourcePath; using util::AsyncQueue; using util::Executor; using util::Status; std::unique_ptr<AsyncQueue> CreateWorkerQueue() { auto executor = Executor::CreateSerial("com.google.firebase.firestore"); return absl::make_unique<AsyncQueue>(std::move(executor)); } std::unique_ptr<CredentialsProvider> CreateCredentialsProvider(App* app) { return absl::make_unique<FirebaseCppCredentialsProvider>(Auth::GetAuth(app)); } } // namespace FirestoreInternal::FirestoreInternal(App* app) : FirestoreInternal{app, CreateCredentialsProvider(app)} {} FirestoreInternal::FirestoreInternal( App* app, std::unique_ptr<CredentialsProvider> credentials) : app_(NOT_NULL(app)), firestore_(CreateFirestore(app, std::move(credentials))) { ApplyDefaultSettings(); } FirestoreInternal::~FirestoreInternal() { ClearListeners(); } std::shared_ptr<api::Firestore> FirestoreInternal::CreateFirestore( App* app, std::unique_ptr<CredentialsProvider> credentials) { const AppOptions& opt = app->options(); return std::make_shared<api::Firestore>(DatabaseId{opt.project_id()}, app->name(), std::move(credentials), CreateWorkerQueue(), this); } CollectionReference FirestoreInternal::Collection( const char* collection_path) const { auto result = firestore_->GetCollection(collection_path); return MakePublic(std::move(result)); } DocumentReference FirestoreInternal::Document(const char* document_path) const { auto result = firestore_->GetDocument(document_path); return MakePublic(std::move(result)); } Query FirestoreInternal::CollectionGroup(const char* collection_id) const { core::Query core_query = firestore_->GetCollectionGroup(collection_id); api::Query api_query(std::move(core_query), firestore_); return MakePublic(std::move(api_query)); } Settings FirestoreInternal::settings() const { Settings result; const api::Settings& from = firestore_->settings(); result.set_host(from.host()); result.set_ssl_enabled(from.ssl_enabled()); result.set_persistence_enabled(from.persistence_enabled()); // TODO(varconst): implement `cache_size_bytes` in public `Settings` and // uncomment. // result.set_cache_size_bytes(from.cache_size_bytes()); return result; } void FirestoreInternal::set_settings(const Settings& from) { api::Settings settings; settings.set_host(from.host()); settings.set_ssl_enabled(from.is_ssl_enabled()); settings.set_persistence_enabled(from.is_persistence_enabled()); // TODO(varconst): implement `cache_size_bytes` in public `Settings` and // uncomment. // settings.set_cache_size_bytes(from.cache_size_bytes()); firestore_->set_settings(settings); std::unique_ptr<Executor> user_executor = from.CreateExecutor(); firestore_->set_user_executor(std::move(user_executor)); } WriteBatch FirestoreInternal::batch() const { return MakePublic(firestore_->GetBatch()); } Future<void> FirestoreInternal::RunTransaction(TransactionFunction* update) { return RunTransaction( [update](Transaction* transaction, std::string* error_message) { return update->Apply(transaction, error_message); }); } Future<void> FirestoreInternal::RunTransaction( std::function<Error(Transaction*, std::string*)> update) { auto executor = absl::ShareUniquePtr(Executor::CreateConcurrent( "com.google.firebase.firestore.transaction", /*threads=*/5)); auto promise = promise_factory_.CreatePromise<void>(AsyncApi::kRunTransaction); // TODO(c++14): move into lambda. auto update_callback = [this, update, executor]( std::shared_ptr<core::Transaction> core_transaction, core::TransactionResultCallback eventual_result_callback) { executor->Execute( [this, update, core_transaction, eventual_result_callback] { std::string error_message; // Note: there is no `MakePublic` overload for `Transaction` // because it is not copyable or movable and thus cannot be // returned from a function. auto* transaction_internal = new TransactionInternal(core_transaction, this); Transaction transaction{transaction_internal}; Error error_code = update(&transaction, &error_message); if (error_code == Error::Ok) { eventual_result_callback(Status::OK()); } else { // TODO(varconst): port this from iOS // If the error is a user error, set flag to not retry the // transaction. // if (is_user_error) { // transaction.MarkPermanentlyFailed(); // } eventual_result_callback(Status{error_code, error_message}); } }); }; auto final_result_callback = [promise](util::Status status) mutable { if (status.ok()) { // Note: the result is deliberately ignored here, because it is not // clear how to surface the `any` to the public API. promise.SetValue(); } else { promise.SetError(std::move(status)); } }; firestore_->RunTransaction(std::move(update_callback), std::move(final_result_callback)); return promise.future(); } Future<void> FirestoreInternal::RunTransactionLastResult() { return promise_factory_.LastResult<void>(AsyncApi::kRunTransaction); } Future<void> FirestoreInternal::DisableNetwork() { auto promise = promise_factory_.CreatePromise<void>(AsyncApi::kDisableNetwork); firestore_->DisableNetwork(StatusCallbackWithPromise(promise)); return promise.future(); } Future<void> FirestoreInternal::DisableNetworkLastResult() { return promise_factory_.LastResult<void>(AsyncApi::kDisableNetwork); } Future<void> FirestoreInternal::EnableNetwork() { auto promise = promise_factory_.CreatePromise<void>(AsyncApi::kEnableNetwork); firestore_->EnableNetwork(StatusCallbackWithPromise(promise)); return promise.future(); } Future<void> FirestoreInternal::EnableNetworkLastResult() { return promise_factory_.LastResult<void>(AsyncApi::kEnableNetwork); } Future<void> FirestoreInternal::Terminate() { auto promise = promise_factory_.CreatePromise<void>(AsyncApi::kTerminate); ClearListeners(); firestore_->Terminate(StatusCallbackWithPromise(promise)); return promise.future(); } Future<void> FirestoreInternal::TerminateLastResult() { return promise_factory_.LastResult<void>(AsyncApi::kTerminate); } Future<void> FirestoreInternal::WaitForPendingWrites() { auto promise = promise_factory_.CreatePromise<void>(AsyncApi::kWaitForPendingWrites); firestore_->WaitForPendingWrites(StatusCallbackWithPromise(promise)); return promise.future(); } Future<void> FirestoreInternal::WaitForPendingWritesLastResult() { return promise_factory_.LastResult<void>(AsyncApi::kWaitForPendingWrites); } Future<void> FirestoreInternal::ClearPersistence() { auto promise = promise_factory_.CreatePromise<void>(AsyncApi::kClearPersistence); firestore_->ClearPersistence(StatusCallbackWithPromise(promise)); return promise.future(); } Future<void> FirestoreInternal::ClearPersistenceLastResult() { return promise_factory_.LastResult<void>(AsyncApi::kClearPersistence); } void FirestoreInternal::ClearListeners() { std::lock_guard<std::mutex> lock(listeners_mutex_); for (auto* listener : listeners_) { listener->Remove(); } listeners_.clear(); } ListenerRegistration FirestoreInternal::AddSnapshotsInSyncListener( EventListener<void>* listener) { std::function<void()> listener_function = [listener] { listener->OnEvent(Error::Ok); }; auto result = firestore_->AddSnapshotsInSyncListener( ListenerWithCallback(std::move(listener_function))); return MakePublic(std::move(result), this); } ListenerRegistration FirestoreInternal::AddSnapshotsInSyncListener( std::function<void()> callback) { auto result = firestore_->AddSnapshotsInSyncListener( ListenerWithCallback(std::move(callback))); return MakePublic(std::move(result), this); } void FirestoreInternal::RegisterListenerRegistration( ListenerRegistrationInternal* registration) { std::lock_guard<std::mutex> lock(listeners_mutex_); listeners_.insert(registration); } void FirestoreInternal::UnregisterListenerRegistration( ListenerRegistrationInternal* registration) { std::lock_guard<std::mutex> lock(listeners_mutex_); auto iter = listeners_.find(registration); if (iter != listeners_.end()) { delete *iter; listeners_.erase(iter); } } void FirestoreInternal::ApplyDefaultSettings() { // Explicitly apply the default settings to the underlying `api::Firestore`, // because otherwise, its executor will stay null (unless the user happens to // call `set_settings`, which we cannot rely upon). set_settings(settings()); } void Firestore::set_logging_enabled(bool logging_enabled) { LogSetLevel(logging_enabled ? util::kLogLevelDebug : util::kLogLevelNotice); } } // namespace firestore } // namespace firebase <commit_msg>Import of the hotfix to Firestore release 1.10.0 from GitHub.<commit_after>#include "firestore/src/ios/firestore_ios.h" #include <utility> #include "app/src/include/firebase/future.h" #include "app/src/reference_counted_future_impl.h" #include "auth/src/include/firebase/auth.h" #include "firestore/src/include/firebase/firestore.h" #include "firestore/src/ios/converter_ios.h" #include "firestore/src/ios/credentials_provider_ios.h" #include "firestore/src/ios/document_reference_ios.h" #include "firestore/src/ios/document_snapshot_ios.h" #include "firestore/src/ios/listener_ios.h" #include "absl/memory/memory.h" #include "absl/types/any.h" #include "Firestore/core/src/firebase/firestore/api/document_reference.h" #include "Firestore/core/src/firebase/firestore/api/query_core.h" #include "Firestore/core/src/firebase/firestore/model/database_id.h" #include "Firestore/core/src/firebase/firestore/model/resource_path.h" #include "Firestore/core/src/firebase/firestore/util/async_queue.h" #include "Firestore/core/src/firebase/firestore/util/executor.h" #include "Firestore/core/src/firebase/firestore/util/log.h" #include "Firestore/core/src/firebase/firestore/util/status.h" namespace firebase { namespace firestore { namespace { using auth::CredentialsProvider; using ::firebase::auth::Auth; using model::DatabaseId; using model::ResourcePath; using util::AsyncQueue; using util::Executor; using util::Status; std::shared_ptr<AsyncQueue> CreateWorkerQueue() { auto executor = Executor::CreateSerial("com.google.firebase.firestore"); return AsyncQueue::Create(std::move(executor)); } std::unique_ptr<CredentialsProvider> CreateCredentialsProvider(App* app) { return absl::make_unique<FirebaseCppCredentialsProvider>(Auth::GetAuth(app)); } } // namespace FirestoreInternal::FirestoreInternal(App* app) : FirestoreInternal{app, CreateCredentialsProvider(app)} {} FirestoreInternal::FirestoreInternal( App* app, std::unique_ptr<CredentialsProvider> credentials) : app_(NOT_NULL(app)), firestore_(CreateFirestore(app, std::move(credentials))) { ApplyDefaultSettings(); } FirestoreInternal::~FirestoreInternal() { ClearListeners(); } std::shared_ptr<api::Firestore> FirestoreInternal::CreateFirestore( App* app, std::unique_ptr<CredentialsProvider> credentials) { const AppOptions& opt = app->options(); return std::make_shared<api::Firestore>(DatabaseId{opt.project_id()}, app->name(), std::move(credentials), CreateWorkerQueue(), this); } CollectionReference FirestoreInternal::Collection( const char* collection_path) const { auto result = firestore_->GetCollection(collection_path); return MakePublic(std::move(result)); } DocumentReference FirestoreInternal::Document(const char* document_path) const { auto result = firestore_->GetDocument(document_path); return MakePublic(std::move(result)); } Query FirestoreInternal::CollectionGroup(const char* collection_id) const { core::Query core_query = firestore_->GetCollectionGroup(collection_id); api::Query api_query(std::move(core_query), firestore_); return MakePublic(std::move(api_query)); } Settings FirestoreInternal::settings() const { Settings result; const api::Settings& from = firestore_->settings(); result.set_host(from.host()); result.set_ssl_enabled(from.ssl_enabled()); result.set_persistence_enabled(from.persistence_enabled()); // TODO(varconst): implement `cache_size_bytes` in public `Settings` and // uncomment. // result.set_cache_size_bytes(from.cache_size_bytes()); return result; } void FirestoreInternal::set_settings(const Settings& from) { api::Settings settings; settings.set_host(from.host()); settings.set_ssl_enabled(from.is_ssl_enabled()); settings.set_persistence_enabled(from.is_persistence_enabled()); // TODO(varconst): implement `cache_size_bytes` in public `Settings` and // uncomment. // settings.set_cache_size_bytes(from.cache_size_bytes()); firestore_->set_settings(settings); std::unique_ptr<Executor> user_executor = from.CreateExecutor(); firestore_->set_user_executor(std::move(user_executor)); } WriteBatch FirestoreInternal::batch() const { return MakePublic(firestore_->GetBatch()); } Future<void> FirestoreInternal::RunTransaction(TransactionFunction* update) { return RunTransaction( [update](Transaction* transaction, std::string* error_message) { return update->Apply(transaction, error_message); }); } Future<void> FirestoreInternal::RunTransaction( std::function<Error(Transaction*, std::string*)> update) { auto executor = absl::ShareUniquePtr(Executor::CreateConcurrent( "com.google.firebase.firestore.transaction", /*threads=*/5)); auto promise = promise_factory_.CreatePromise<void>(AsyncApi::kRunTransaction); // TODO(c++14): move into lambda. auto update_callback = [this, update, executor]( std::shared_ptr<core::Transaction> core_transaction, core::TransactionResultCallback eventual_result_callback) { executor->Execute( [this, update, core_transaction, eventual_result_callback] { std::string error_message; // Note: there is no `MakePublic` overload for `Transaction` // because it is not copyable or movable and thus cannot be // returned from a function. auto* transaction_internal = new TransactionInternal(core_transaction, this); Transaction transaction{transaction_internal}; Error error_code = update(&transaction, &error_message); if (error_code == Error::Ok) { eventual_result_callback(Status::OK()); } else { // TODO(varconst): port this from iOS // If the error is a user error, set flag to not retry the // transaction. // if (is_user_error) { // transaction.MarkPermanentlyFailed(); // } eventual_result_callback(Status{error_code, error_message}); } }); }; auto final_result_callback = [promise](util::Status status) mutable { if (status.ok()) { // Note: the result is deliberately ignored here, because it is not // clear how to surface the `any` to the public API. promise.SetValue(); } else { promise.SetError(std::move(status)); } }; firestore_->RunTransaction(std::move(update_callback), std::move(final_result_callback)); return promise.future(); } Future<void> FirestoreInternal::RunTransactionLastResult() { return promise_factory_.LastResult<void>(AsyncApi::kRunTransaction); } Future<void> FirestoreInternal::DisableNetwork() { auto promise = promise_factory_.CreatePromise<void>(AsyncApi::kDisableNetwork); firestore_->DisableNetwork(StatusCallbackWithPromise(promise)); return promise.future(); } Future<void> FirestoreInternal::DisableNetworkLastResult() { return promise_factory_.LastResult<void>(AsyncApi::kDisableNetwork); } Future<void> FirestoreInternal::EnableNetwork() { auto promise = promise_factory_.CreatePromise<void>(AsyncApi::kEnableNetwork); firestore_->EnableNetwork(StatusCallbackWithPromise(promise)); return promise.future(); } Future<void> FirestoreInternal::EnableNetworkLastResult() { return promise_factory_.LastResult<void>(AsyncApi::kEnableNetwork); } Future<void> FirestoreInternal::Terminate() { auto promise = promise_factory_.CreatePromise<void>(AsyncApi::kTerminate); ClearListeners(); firestore_->Terminate(StatusCallbackWithPromise(promise)); return promise.future(); } Future<void> FirestoreInternal::TerminateLastResult() { return promise_factory_.LastResult<void>(AsyncApi::kTerminate); } Future<void> FirestoreInternal::WaitForPendingWrites() { auto promise = promise_factory_.CreatePromise<void>(AsyncApi::kWaitForPendingWrites); firestore_->WaitForPendingWrites(StatusCallbackWithPromise(promise)); return promise.future(); } Future<void> FirestoreInternal::WaitForPendingWritesLastResult() { return promise_factory_.LastResult<void>(AsyncApi::kWaitForPendingWrites); } Future<void> FirestoreInternal::ClearPersistence() { auto promise = promise_factory_.CreatePromise<void>(AsyncApi::kClearPersistence); firestore_->ClearPersistence(StatusCallbackWithPromise(promise)); return promise.future(); } Future<void> FirestoreInternal::ClearPersistenceLastResult() { return promise_factory_.LastResult<void>(AsyncApi::kClearPersistence); } void FirestoreInternal::ClearListeners() { std::lock_guard<std::mutex> lock(listeners_mutex_); for (auto* listener : listeners_) { listener->Remove(); } listeners_.clear(); } ListenerRegistration FirestoreInternal::AddSnapshotsInSyncListener( EventListener<void>* listener) { std::function<void()> listener_function = [listener] { listener->OnEvent(Error::Ok); }; auto result = firestore_->AddSnapshotsInSyncListener( ListenerWithCallback(std::move(listener_function))); return MakePublic(std::move(result), this); } ListenerRegistration FirestoreInternal::AddSnapshotsInSyncListener( std::function<void()> callback) { auto result = firestore_->AddSnapshotsInSyncListener( ListenerWithCallback(std::move(callback))); return MakePublic(std::move(result), this); } void FirestoreInternal::RegisterListenerRegistration( ListenerRegistrationInternal* registration) { std::lock_guard<std::mutex> lock(listeners_mutex_); listeners_.insert(registration); } void FirestoreInternal::UnregisterListenerRegistration( ListenerRegistrationInternal* registration) { std::lock_guard<std::mutex> lock(listeners_mutex_); auto iter = listeners_.find(registration); if (iter != listeners_.end()) { delete *iter; listeners_.erase(iter); } } void FirestoreInternal::ApplyDefaultSettings() { // Explicitly apply the default settings to the underlying `api::Firestore`, // because otherwise, its executor will stay null (unless the user happens to // call `set_settings`, which we cannot rely upon). set_settings(settings()); } void Firestore::set_logging_enabled(bool logging_enabled) { LogSetLevel(logging_enabled ? util::kLogLevelDebug : util::kLogLevelNotice); } } // namespace firestore } // namespace firebase <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #ifndef JUBATUS_CORE_COMMON_ASSERT_HPP_ #define JUBATUS_CORE_COMMON_ASSERT_HPP_ #ifndef JUBATUS_DISABLE_ASSERTIONS #include <stdlib.h> #include <assert.h> #include <iostream> #define CHECK(expr, message) { \ if (!(expr)) { \ std::cerr << "ASSERTION FAILED: " << message << ": " \ << #expr << std::endl; \ abort(); \ }} // declares expr to be true // unlike glog CHECK, this macro cannot take trailing `<<'; // please use JUBATUS_ASSERT_MSG if you need extra messages. #define JUBATUS_ASSERT(expr) do { CHECK((expr), ""); } while (0) // declares expr to be true; if false, messages are shown #define JUBATUS_ASSERT_MSG(expr, messages) \ do { CHECK((expr), messages); } while (0) // declares control flow not to reach here #define JUBATUS_ASSERT_UNREACHABLE() \ do { CHECK(0, "control flow not to reach here"); } while (0) // helpers to compare values #define JUBATUS_ASSERT_EQ(a, b, messages) \ do { CHECK((a) == (b), messages); } while (0) #define JUBATUS_ASSERT_NE(a, b, messages) \ do { CHECK((a) != (b), messages); } while (0) #define JUBATUS_ASSERT_LE(a, b, messages) \ do { CHECK((a) <= (b), messages); } while (0) #define JUBATUS_ASSERT_LT(a, b, messages) \ do { CHECK((a) < (b), messages); } while (0) #define JUBATUS_ASSERT_GE(a, b, messages) \ do { CHECK((a) >= (b), messages); } while (0) #define JUBATUS_ASSERT_GT(a, b, messages) \ do { CHECK((a) > (b), messages); } while (0) #else // #ifndef JUBATUS_DISABLE_ASSERTIONS #define JUBATUS_ASSERT(expr) ((void)0) #define JUBATUS_ASSERT_MSG(expr, msg) ((void)0) #ifndef __has_builtin #define __has_builtin(x) 0 #endif #if __has_builtin(__builtin_unreachable) || \ __GNUC__ == 4 && __GNUC_MINOR__ >= 5 // TODO(gintenlabo): Add __GUNC__ >= 5 if GCC 5.x has __builtin_unreachable #define JUBATUS_ASSERT_UNREACHABLE() __builtin_unreachable() #else #include <exception> // NOLINT #define JUBATUS_ASSERT_UNREACHABLE() std::terminate() #endif #define JUBATUS_ASSERT_EQ(a, b, messages) ((void)0) #define JUBATUS_ASSERT_NE(a, b, messages) ((void)0) #define JUBATUS_ASSERT_LE(a, b, messages) ((void)0) #define JUBATUS_ASSERT_LT(a, b, messages) ((void)0) #define JUBATUS_ASSERT_GE(a, b, messages) ((void)0) #define JUBATUS_ASSERT_GT(a, b, messages) ((void)0) #endif // #ifndef JUBATUS_DISABLE_ASSERTIONS #endif // JUBATUS_CORE_COMMON_ASSERT_HPP_ <commit_msg>use std::terminate instead of abort<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #ifndef JUBATUS_CORE_COMMON_ASSERT_HPP_ #define JUBATUS_CORE_COMMON_ASSERT_HPP_ #ifndef JUBATUS_DISABLE_ASSERTIONS #include <stdlib.h> #include <assert.h> #include <iostream> #define CHECK(expr, message) { \ if (!(expr)) { \ std::cerr << "ASSERTION FAILED: " << message << ": " \ << #expr << std::endl; \ std::terminate(); \ }} // declares expr to be true // unlike glog CHECK, this macro cannot take trailing `<<'; // please use JUBATUS_ASSERT_MSG if you need extra messages. #define JUBATUS_ASSERT(expr) do { CHECK(expr, ""); } while (0) // declares expr to be true; if false, messages are shown #define JUBATUS_ASSERT_MSG(expr, messages) \ do { CHECK((expr), messages); } while (0) // declares control flow not to reach here #define JUBATUS_ASSERT_UNREACHABLE() \ do { CHECK(0, "control flow not to reach here"); } while (0) // helpers to compare values #define JUBATUS_ASSERT_EQ(a, b, messages) \ do { CHECK((a) == (b), messages); } while (0) #define JUBATUS_ASSERT_NE(a, b, messages) \ do { CHECK((a) != (b), messages); } while (0) #define JUBATUS_ASSERT_LE(a, b, messages) \ do { CHECK((a) <= (b), messages); } while (0) #define JUBATUS_ASSERT_LT(a, b, messages) \ do { CHECK((a) < (b), messages); } while (0) #define JUBATUS_ASSERT_GE(a, b, messages) \ do { CHECK((a) >= (b), messages); } while (0) #define JUBATUS_ASSERT_GT(a, b, messages) \ do { CHECK((a) > (b), messages); } while (0) #else // #ifndef JUBATUS_DISABLE_ASSERTIONS #define JUBATUS_ASSERT(expr) ((void)0) #define JUBATUS_ASSERT_MSG(expr, msg) ((void)0) #ifndef __has_builtin #define __has_builtin(x) 0 #endif #if __has_builtin(__builtin_unreachable) || \ __GNUC__ == 4 && __GNUC_MINOR__ >= 5 // TODO(gintenlabo): Add __GUNC__ >= 5 if GCC 5.x has __builtin_unreachable #define JUBATUS_ASSERT_UNREACHABLE() __builtin_unreachable() #else #include <exception> // NOLINT #define JUBATUS_ASSERT_UNREACHABLE() std::terminate() #endif #define JUBATUS_ASSERT_EQ(a, b, messages) ((void)0) #define JUBATUS_ASSERT_NE(a, b, messages) ((void)0) #define JUBATUS_ASSERT_LE(a, b, messages) ((void)0) #define JUBATUS_ASSERT_LT(a, b, messages) ((void)0) #define JUBATUS_ASSERT_GE(a, b, messages) ((void)0) #define JUBATUS_ASSERT_GT(a, b, messages) ((void)0) #endif // #ifndef JUBATUS_DISABLE_ASSERTIONS #endif // JUBATUS_CORE_COMMON_ASSERT_HPP_ <|endoftext|>
<commit_before>//----------------------------------- // Copyright Pierric Gimmig 2013-2017 //----------------------------------- #include "TextRenderer.h" #include "App.h" #include "Core.h" #include "GlCanvas.h" #include "GlUtils.h" #include "Params.h" #include "freetype-gl/vertex-buffer.h" #include "shader.h" //----------------------------------------------------------------------------- typedef struct { float x, y, z; // position float s, t; // texture float r, g, b, a; // color } vertex_t; //----------------------------------------------------------------------------- TextRenderer::TextRenderer() : m_Atlas(NULL), m_Buffer(NULL), m_Font(NULL), m_Canvas(NULL), m_Initialized(false), m_DrawOutline(false) {} //----------------------------------------------------------------------------- TextRenderer::~TextRenderer() { if (m_Font) { texture_font_delete(m_Font); } if (m_Buffer) { vertex_buffer_delete(m_Buffer); } } //----------------------------------------------------------------------------- void TextRenderer::Init() { if (m_Initialized) return; m_Font = NULL; int atlasSize = 2 * 1024; m_Atlas = texture_atlas_new(atlasSize, atlasSize, 1); const auto exePath = Path::GetExecutablePath(); const auto fontFileName = exePath + "fonts/Vera.ttf"; static float fsize = GParams.m_FontSize; m_Buffer = vertex_buffer_new("vertex:3f,tex_coord:2f,color:4f"); m_Font = texture_font_new_from_file(m_Atlas, fsize, fontFileName.c_str()); for (int i = 10; i <= 100; i += 10) { m_FontsBySize[i] = texture_font_new_from_file(m_Atlas, i, fontFileName.c_str()); } m_Pen.x = 0; m_Pen.y = 0; glGenTextures(1, &m_Atlas->id); const auto vertShaderFileName = exePath + "shaders/v3f-t2f-c4f.vert"; const auto fragShaderFileName = exePath + "shaders/v3f-t2f-c4f.frag"; m_Shader = shader_load(vertShaderFileName.c_str(), fragShaderFileName.c_str()); mat4_set_identity(&m_Proj); mat4_set_identity(&m_Model); mat4_set_identity(&m_View); m_Initialized = true; } //----------------------------------------------------------------------------- void TextRenderer::SetFontSize(int a_Size) { texture_font_t* font = m_FontsBySize[a_Size]; if (font) { m_Font = font; } } //----------------------------------------------------------------------------- void TextRenderer::Display() { if (m_DrawOutline) { DrawOutline(m_Buffer); } // Lazy init if (!m_Initialized) { Init(); } glBindTexture(GL_TEXTURE_2D, m_Atlas->id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<GLsizei>(m_Atlas->width), static_cast<GLsizei>(m_Atlas->height), 0, GL_RED, GL_UNSIGNED_BYTE, m_Atlas->data); // Get current projection matrix GLfloat matrix[16]; glGetFloatv(GL_PROJECTION_MATRIX, matrix); mat4* proj = reinterpret_cast<mat4*>(&matrix[0]); m_Proj = *proj; mat4_set_orthographic(&m_Proj, 0, m_Canvas->getWidth(), 0, m_Canvas->getHeight(), -1, 1); glUseProgram(m_Shader); { glUniform1i(glGetUniformLocation(m_Shader, "texture"), 0); glUniformMatrix4fv(glGetUniformLocation(m_Shader, "model"), 1, 0, m_Model.data); glUniformMatrix4fv(glGetUniformLocation(m_Shader, "view"), 1, 0, m_View.data); glUniformMatrix4fv(glGetUniformLocation(m_Shader, "projection"), 1, 0, m_Proj.data); vertex_buffer_render(m_Buffer, GL_TRIANGLES); /*PRINT_VAR(m_Model); PRINT_VAR(m_View); PRINT_VAR(m_Proj);*/ } glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); } //----------------------------------------------------------------------------- void TextRenderer::DrawOutline(vertex_buffer_t* a_Buffer) { glBegin(GL_LINES); for (size_t i = 0; i < a_Buffer->indices->size; i += 3) { GLuint i0 = *static_cast<const GLuint*>(vector_get(a_Buffer->indices, i + 0)); GLuint i1 = *static_cast<const GLuint*>(vector_get(a_Buffer->indices, i + 1)); GLuint i2 = *static_cast<const GLuint*>(vector_get(a_Buffer->indices, i + 2)); vertex_t v0 = *static_cast<const vertex_t*>(vector_get(a_Buffer->vertices, i0)); vertex_t v1 = *static_cast<const vertex_t*>(vector_get(a_Buffer->vertices, i1)); vertex_t v2 = *static_cast<const vertex_t*>(vector_get(a_Buffer->vertices, i2)); glVertex3f(v0.x, v0.y, v0.z); glVertex3f(v1.x, v1.y, v1.z); glVertex3f(v1.x, v1.y, v1.z); glVertex3f(v2.x, v2.y, v2.z); glVertex3f(v2.x, v2.y, v2.z); glVertex3f(v0.x, v0.y, v0.z); } glEnd(); } //----------------------------------------------------------------------------- void TextRenderer::AddTextInternal(texture_font_t* font, const char* text, const vec4& color, vec2* pen, float a_MaxSize, float a_Z, bool) { size_t i; float r = color.red, g = color.green, b = color.blue, a = color.alpha; float textZ = a_Z; float maxWidth = a_MaxSize == -1.f ? FLT_MAX : ToScreenSpace(a_MaxSize); float strWidth = 0.f; int minX = INT_MAX; int maxX = -INT_MAX; for (i = 0; i < strlen(text); ++i) { if (!texture_font_find_glyph(font, text + i)) { texture_font_load_glyph(font, text + i); } texture_glyph_t* glyph = texture_font_get_glyph(font, text + i); if (glyph != NULL) { float kerning = 0.0f; if (i > 0) { kerning = texture_glyph_get_kerning(glyph, text + i - 1); } pen->x += kerning; float x0 = static_cast<int>(pen->x + glyph->offset_x); float y0 = static_cast<int>(pen->y + glyph->offset_y); float x1 = static_cast<int>(x0 + glyph->width); float y1 = static_cast<int>(y0 - glyph->height); float s0 = glyph->s0; float t0 = glyph->t0; float s1 = glyph->s1; float t1 = glyph->t1; GLuint indices[6] = {0, 1, 2, 0, 2, 3}; vertex_t vertices[4] = {{x0, y0, textZ, s0, t0, r, g, b, a}, {x0, y1, textZ, s0, t1, r, g, b, a}, {x1, y1, textZ, s1, t1, r, g, b, a}, {x1, y0, textZ, s1, t0, r, g, b, a}}; minX = std::min(minX, static_cast<int>(x0)); maxX = std::max(maxX, static_cast<int>(x1)); strWidth = maxX - minX; if (strWidth > maxWidth) { break; } vertex_buffer_push_back(m_Buffer, vertices, 4, indices, 6); pen->x += glyph->advance_x; } } } //----------------------------------------------------------------------------- void TextRenderer::AddText(const char* a_Text, float a_X, float a_Y, float a_Z, const Color& a_Color, float a_MaxSize, bool a_RightJustified) { ToScreenSpace(a_X, a_Y, m_Pen.x, m_Pen.y); if (a_RightJustified) { a_MaxSize = FLT_MAX; int stringWidth, stringHeight; GetStringSize(a_Text, stringWidth, stringHeight); m_Pen.x -= stringWidth; } AddTextInternal(m_Font, a_Text, ColorToVec4(a_Color), &m_Pen, a_MaxSize, a_Z); } //----------------------------------------------------------------------------- void TextRenderer::AddTextTrailingCharsPrioritized( const char* a_Text, float a_X, float a_Y, float a_Z, const Color& a_Color, size_t a_TrailingCharsLength, float a_MaxSize) { float tempPenX = ToScreenSpace(a_X); float maxWidth = a_MaxSize == -1.f ? FLT_MAX : ToScreenSpace(a_MaxSize); float strWidth = 0.f; int minX = INT_MAX; int maxX = -INT_MAX; const size_t textLen = strlen(a_Text); size_t i; for (i = 0; i < textLen; ++i) { if (!texture_font_find_glyph(m_Font, a_Text + i)) { texture_font_load_glyph(m_Font, a_Text + i); } texture_glyph_t* glyph = texture_font_get_glyph(m_Font, a_Text + i); if (glyph != NULL) { float kerning = 0.0f; if (i > 0) { kerning = texture_glyph_get_kerning(glyph, a_Text + i - 1); } tempPenX += kerning; int x0 = static_cast<int>(tempPenX + glyph->offset_x); int x1 = static_cast<int>(x0 + glyph->width); minX = std::min(minX, x0); maxX = std::max(maxX, x1); strWidth = float(maxX - minX); if (strWidth > maxWidth) { break; } tempPenX += glyph->advance_x; } } // TODO: Technically, we'd want the size of "... <TIME>" + remaining // characters auto fittingCharsCount = i; static const char* ELLIPSIS_TEXT = "... "; static const size_t ELLIPSIS_TEXT_LEN = strlen(ELLIPSIS_TEXT); static const size_t LEADING_CHARS_COUNT = 1; static const size_t ELLIPSIS_BUFFER_SIZE = ELLIPSIS_TEXT_LEN + LEADING_CHARS_COUNT; bool useEllipsisText = (fittingCharsCount < textLen) && (fittingCharsCount > (a_TrailingCharsLength + ELLIPSIS_BUFFER_SIZE)); if (!useEllipsisText) { AddText(a_Text, a_X, a_Y, a_Z, a_Color, a_MaxSize); } else { auto leadingCharCount = fittingCharsCount - (a_TrailingCharsLength + ELLIPSIS_TEXT_LEN); std::string modifiedText(a_Text, leadingCharCount); modifiedText.append(ELLIPSIS_TEXT); auto timePosition = textLen - a_TrailingCharsLength; modifiedText.append(&a_Text[timePosition], a_TrailingCharsLength); AddText(modifiedText.c_str(), a_X, a_Y, a_Z, a_Color, a_MaxSize); } } //----------------------------------------------------------------------------- int TextRenderer::AddText2D(const char* a_Text, int a_X, int a_Y, float a_Z, const Color& a_Color, float a_MaxSize, bool a_RightJustified, bool a_InvertY) { if (a_RightJustified) { int stringWidth, stringHeight; GetStringSize(a_Text, stringWidth, stringHeight); a_X -= stringWidth; } m_Pen.x = a_X; m_Pen.y = a_InvertY ? m_Canvas->getHeight() - a_Y : a_Y; AddTextInternal(m_Font, a_Text, ColorToVec4(a_Color), &m_Pen, a_MaxSize, a_Z); return a_X; } //----------------------------------------------------------------------------- void TextRenderer::GetStringSize(const char* a_Text, int& a_Width, int& a_Height) { float stringWidth = 0; float stringHeight = 0; std::size_t len = strlen(a_Text); for (std::size_t i = 0; i < len; ++i) { texture_glyph_t* glyph = texture_font_get_glyph(m_Font, a_Text + i); if (glyph != NULL) { float kerning = 0.0f; if (i > 0) { kerning = texture_glyph_get_kerning(glyph, a_Text + i - 1); } stringWidth += kerning; stringWidth += glyph->advance_x; if (glyph->height > stringHeight) stringHeight = glyph->height; } } a_Width = static_cast<int>(stringWidth); a_Height = static_cast<int>(stringHeight); } //----------------------------------------------------------------------------- int TextRenderer::GetStringHeight(const char* a_Text) { int w, h; GetStringSize(a_Text, w, h); return h; } //----------------------------------------------------------------------------- void TextRenderer::ToScreenSpace(float a_X, float a_Y, float& o_X, float& o_Y) { float WorldWidth = m_Canvas->GetWorldWidth(); float WorldHeight = m_Canvas->GetWorldHeight(); float WorldTopLeftX = m_Canvas->GetWorldTopLeftX(); float WorldMinLeftY = m_Canvas->GetWorldTopLeftY() - WorldHeight; o_X = ((a_X - WorldTopLeftX) / WorldWidth) * m_Canvas->getWidth(); o_Y = ((a_Y - WorldMinLeftY) / WorldHeight) * m_Canvas->getHeight(); } //----------------------------------------------------------------------------- float TextRenderer::ToScreenSpace(float a_Size) { return (a_Size / m_Canvas->GetWorldWidth()) * m_Canvas->getWidth(); } //----------------------------------------------------------------------------- void TextRenderer::Clear() { m_Pen.x = 0.f; m_Pen.y = 0.f; if (m_Buffer) { vertex_buffer_clear(m_Buffer); } } //----------------------------------------------------------------------------- const TextBox& TextRenderer::GetSceneBox() const { return m_Canvas->GetSceneBox(); } //----------------------------------------------------------------------------- int TextRenderer::GetNumCharacters() const { return int(m_Buffer->vertices->size) / 4; } <commit_msg>Fix TextRenderer not initialized<commit_after>//----------------------------------- // Copyright Pierric Gimmig 2013-2017 //----------------------------------- #include "TextRenderer.h" #include "App.h" #include "Core.h" #include "GlCanvas.h" #include "GlUtils.h" #include "Params.h" #include "freetype-gl/vertex-buffer.h" #include "shader.h" //----------------------------------------------------------------------------- typedef struct { float x, y, z; // position float s, t; // texture float r, g, b, a; // color } vertex_t; //----------------------------------------------------------------------------- TextRenderer::TextRenderer() : m_Atlas(NULL), m_Buffer(NULL), m_Font(NULL), m_Canvas(NULL), m_Initialized(false), m_DrawOutline(false) {} //----------------------------------------------------------------------------- TextRenderer::~TextRenderer() { if (m_Font) { texture_font_delete(m_Font); } if (m_Buffer) { vertex_buffer_delete(m_Buffer); } } //----------------------------------------------------------------------------- void TextRenderer::Init() { if (m_Initialized) return; m_Font = NULL; int atlasSize = 2 * 1024; m_Atlas = texture_atlas_new(atlasSize, atlasSize, 1); const auto exePath = Path::GetExecutablePath(); const auto fontFileName = exePath + "fonts/Vera.ttf"; static float fsize = GParams.m_FontSize; m_Buffer = vertex_buffer_new("vertex:3f,tex_coord:2f,color:4f"); m_Font = texture_font_new_from_file(m_Atlas, fsize, fontFileName.c_str()); for (int i = 10; i <= 100; i += 10) { m_FontsBySize[i] = texture_font_new_from_file(m_Atlas, i, fontFileName.c_str()); } m_Pen.x = 0; m_Pen.y = 0; glGenTextures(1, &m_Atlas->id); const auto vertShaderFileName = exePath + "shaders/v3f-t2f-c4f.vert"; const auto fragShaderFileName = exePath + "shaders/v3f-t2f-c4f.frag"; m_Shader = shader_load(vertShaderFileName.c_str(), fragShaderFileName.c_str()); mat4_set_identity(&m_Proj); mat4_set_identity(&m_Model); mat4_set_identity(&m_View); m_Initialized = true; } //----------------------------------------------------------------------------- void TextRenderer::SetFontSize(int a_Size) { texture_font_t* font = m_FontsBySize[a_Size]; if (font) { m_Font = font; } } //----------------------------------------------------------------------------- void TextRenderer::Display() { if (m_DrawOutline) { DrawOutline(m_Buffer); } // Lazy init if (!m_Initialized) { Init(); } glBindTexture(GL_TEXTURE_2D, m_Atlas->id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<GLsizei>(m_Atlas->width), static_cast<GLsizei>(m_Atlas->height), 0, GL_RED, GL_UNSIGNED_BYTE, m_Atlas->data); // Get current projection matrix GLfloat matrix[16]; glGetFloatv(GL_PROJECTION_MATRIX, matrix); mat4* proj = reinterpret_cast<mat4*>(&matrix[0]); m_Proj = *proj; mat4_set_orthographic(&m_Proj, 0, m_Canvas->getWidth(), 0, m_Canvas->getHeight(), -1, 1); glUseProgram(m_Shader); { glUniform1i(glGetUniformLocation(m_Shader, "texture"), 0); glUniformMatrix4fv(glGetUniformLocation(m_Shader, "model"), 1, 0, m_Model.data); glUniformMatrix4fv(glGetUniformLocation(m_Shader, "view"), 1, 0, m_View.data); glUniformMatrix4fv(glGetUniformLocation(m_Shader, "projection"), 1, 0, m_Proj.data); vertex_buffer_render(m_Buffer, GL_TRIANGLES); /*PRINT_VAR(m_Model); PRINT_VAR(m_View); PRINT_VAR(m_Proj);*/ } glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); } //----------------------------------------------------------------------------- void TextRenderer::DrawOutline(vertex_buffer_t* a_Buffer) { glBegin(GL_LINES); for (size_t i = 0; i < a_Buffer->indices->size; i += 3) { GLuint i0 = *static_cast<const GLuint*>(vector_get(a_Buffer->indices, i + 0)); GLuint i1 = *static_cast<const GLuint*>(vector_get(a_Buffer->indices, i + 1)); GLuint i2 = *static_cast<const GLuint*>(vector_get(a_Buffer->indices, i + 2)); vertex_t v0 = *static_cast<const vertex_t*>(vector_get(a_Buffer->vertices, i0)); vertex_t v1 = *static_cast<const vertex_t*>(vector_get(a_Buffer->vertices, i1)); vertex_t v2 = *static_cast<const vertex_t*>(vector_get(a_Buffer->vertices, i2)); glVertex3f(v0.x, v0.y, v0.z); glVertex3f(v1.x, v1.y, v1.z); glVertex3f(v1.x, v1.y, v1.z); glVertex3f(v2.x, v2.y, v2.z); glVertex3f(v2.x, v2.y, v2.z); glVertex3f(v0.x, v0.y, v0.z); } glEnd(); } //----------------------------------------------------------------------------- void TextRenderer::AddTextInternal(texture_font_t* font, const char* text, const vec4& color, vec2* pen, float a_MaxSize, float a_Z, bool) { size_t i; float r = color.red, g = color.green, b = color.blue, a = color.alpha; float textZ = a_Z; float maxWidth = a_MaxSize == -1.f ? FLT_MAX : ToScreenSpace(a_MaxSize); float strWidth = 0.f; int minX = INT_MAX; int maxX = -INT_MAX; for (i = 0; i < strlen(text); ++i) { if (!texture_font_find_glyph(font, text + i)) { texture_font_load_glyph(font, text + i); } texture_glyph_t* glyph = texture_font_get_glyph(font, text + i); if (glyph != NULL) { float kerning = 0.0f; if (i > 0) { kerning = texture_glyph_get_kerning(glyph, text + i - 1); } pen->x += kerning; float x0 = static_cast<int>(pen->x + glyph->offset_x); float y0 = static_cast<int>(pen->y + glyph->offset_y); float x1 = static_cast<int>(x0 + glyph->width); float y1 = static_cast<int>(y0 - glyph->height); float s0 = glyph->s0; float t0 = glyph->t0; float s1 = glyph->s1; float t1 = glyph->t1; GLuint indices[6] = {0, 1, 2, 0, 2, 3}; vertex_t vertices[4] = {{x0, y0, textZ, s0, t0, r, g, b, a}, {x0, y1, textZ, s0, t1, r, g, b, a}, {x1, y1, textZ, s1, t1, r, g, b, a}, {x1, y0, textZ, s1, t0, r, g, b, a}}; minX = std::min(minX, static_cast<int>(x0)); maxX = std::max(maxX, static_cast<int>(x1)); strWidth = maxX - minX; if (strWidth > maxWidth) { break; } vertex_buffer_push_back(m_Buffer, vertices, 4, indices, 6); pen->x += glyph->advance_x; } } } //----------------------------------------------------------------------------- void TextRenderer::AddText(const char* a_Text, float a_X, float a_Y, float a_Z, const Color& a_Color, float a_MaxSize, bool a_RightJustified) { ToScreenSpace(a_X, a_Y, m_Pen.x, m_Pen.y); if (a_RightJustified) { a_MaxSize = FLT_MAX; int stringWidth, stringHeight; GetStringSize(a_Text, stringWidth, stringHeight); m_Pen.x -= stringWidth; } AddTextInternal(m_Font, a_Text, ColorToVec4(a_Color), &m_Pen, a_MaxSize, a_Z); } //----------------------------------------------------------------------------- void TextRenderer::AddTextTrailingCharsPrioritized( const char* a_Text, float a_X, float a_Y, float a_Z, const Color& a_Color, size_t a_TrailingCharsLength, float a_MaxSize) { if (!m_Initialized) { Init(); } float tempPenX = ToScreenSpace(a_X); float maxWidth = a_MaxSize == -1.f ? FLT_MAX : ToScreenSpace(a_MaxSize); float strWidth = 0.f; int minX = INT_MAX; int maxX = -INT_MAX; const size_t textLen = strlen(a_Text); size_t i; for (i = 0; i < textLen; ++i) { if (!texture_font_find_glyph(m_Font, a_Text + i)) { texture_font_load_glyph(m_Font, a_Text + i); } texture_glyph_t* glyph = texture_font_get_glyph(m_Font, a_Text + i); if (glyph != NULL) { float kerning = 0.0f; if (i > 0) { kerning = texture_glyph_get_kerning(glyph, a_Text + i - 1); } tempPenX += kerning; int x0 = static_cast<int>(tempPenX + glyph->offset_x); int x1 = static_cast<int>(x0 + glyph->width); minX = std::min(minX, x0); maxX = std::max(maxX, x1); strWidth = float(maxX - minX); if (strWidth > maxWidth) { break; } tempPenX += glyph->advance_x; } } // TODO: Technically, we'd want the size of "... <TIME>" + remaining // characters auto fittingCharsCount = i; static const char* ELLIPSIS_TEXT = "... "; static const size_t ELLIPSIS_TEXT_LEN = strlen(ELLIPSIS_TEXT); static const size_t LEADING_CHARS_COUNT = 1; static const size_t ELLIPSIS_BUFFER_SIZE = ELLIPSIS_TEXT_LEN + LEADING_CHARS_COUNT; bool useEllipsisText = (fittingCharsCount < textLen) && (fittingCharsCount > (a_TrailingCharsLength + ELLIPSIS_BUFFER_SIZE)); if (!useEllipsisText) { AddText(a_Text, a_X, a_Y, a_Z, a_Color, a_MaxSize); } else { auto leadingCharCount = fittingCharsCount - (a_TrailingCharsLength + ELLIPSIS_TEXT_LEN); std::string modifiedText(a_Text, leadingCharCount); modifiedText.append(ELLIPSIS_TEXT); auto timePosition = textLen - a_TrailingCharsLength; modifiedText.append(&a_Text[timePosition], a_TrailingCharsLength); AddText(modifiedText.c_str(), a_X, a_Y, a_Z, a_Color, a_MaxSize); } } //----------------------------------------------------------------------------- int TextRenderer::AddText2D(const char* a_Text, int a_X, int a_Y, float a_Z, const Color& a_Color, float a_MaxSize, bool a_RightJustified, bool a_InvertY) { if (a_RightJustified) { int stringWidth, stringHeight; GetStringSize(a_Text, stringWidth, stringHeight); a_X -= stringWidth; } m_Pen.x = a_X; m_Pen.y = a_InvertY ? m_Canvas->getHeight() - a_Y : a_Y; AddTextInternal(m_Font, a_Text, ColorToVec4(a_Color), &m_Pen, a_MaxSize, a_Z); return a_X; } //----------------------------------------------------------------------------- void TextRenderer::GetStringSize(const char* a_Text, int& a_Width, int& a_Height) { float stringWidth = 0; float stringHeight = 0; std::size_t len = strlen(a_Text); for (std::size_t i = 0; i < len; ++i) { texture_glyph_t* glyph = texture_font_get_glyph(m_Font, a_Text + i); if (glyph != NULL) { float kerning = 0.0f; if (i > 0) { kerning = texture_glyph_get_kerning(glyph, a_Text + i - 1); } stringWidth += kerning; stringWidth += glyph->advance_x; if (glyph->height > stringHeight) stringHeight = glyph->height; } } a_Width = static_cast<int>(stringWidth); a_Height = static_cast<int>(stringHeight); } //----------------------------------------------------------------------------- int TextRenderer::GetStringHeight(const char* a_Text) { int w, h; GetStringSize(a_Text, w, h); return h; } //----------------------------------------------------------------------------- void TextRenderer::ToScreenSpace(float a_X, float a_Y, float& o_X, float& o_Y) { float WorldWidth = m_Canvas->GetWorldWidth(); float WorldHeight = m_Canvas->GetWorldHeight(); float WorldTopLeftX = m_Canvas->GetWorldTopLeftX(); float WorldMinLeftY = m_Canvas->GetWorldTopLeftY() - WorldHeight; o_X = ((a_X - WorldTopLeftX) / WorldWidth) * m_Canvas->getWidth(); o_Y = ((a_Y - WorldMinLeftY) / WorldHeight) * m_Canvas->getHeight(); } //----------------------------------------------------------------------------- float TextRenderer::ToScreenSpace(float a_Size) { return (a_Size / m_Canvas->GetWorldWidth()) * m_Canvas->getWidth(); } //----------------------------------------------------------------------------- void TextRenderer::Clear() { m_Pen.x = 0.f; m_Pen.y = 0.f; if (m_Buffer) { vertex_buffer_clear(m_Buffer); } } //----------------------------------------------------------------------------- const TextBox& TextRenderer::GetSceneBox() const { return m_Canvas->GetSceneBox(); } //----------------------------------------------------------------------------- int TextRenderer::GetNumCharacters() const { return int(m_Buffer->vertices->size) / 4; } <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #ifndef JUBATUS_CORE_COMMON_ASSERT_HPP_ #define JUBATUS_CORE_COMMON_ASSERT_HPP_ #ifndef JUBATUS_DISABLE_ASSERTIONS #include <stdlib.h> #include <assert.h> #include <iostream> #include <string> #include "jubatus/util/lang/cast.h" #define JUBA_CHECK(a, op, b, message) { \ using jubatus::util::lang::lexical_cast; \ if (! ((a) op (b))) { \ std::cerr << "ASSERTION FAILED: " << message << ": " \ << #a << " " << #op << " " << #b \ << " (" << __FILE__ << ":" << __LINE__ << ")" << std::endl; \ std::cerr << "... where " << #a << " = " \ << lexical_cast<std::string>(a) << std::endl \ << " and " << #b << " = " \ << lexical_cast<std::string>(b) << std::endl; \ std::terminate(); \ }} // declares expr to be true // unlike glog CHECK, this macro cannot take trailing `<<'; // please use JUBATUS_ASSERT_MSG if you need extra messages. #define JUBATUS_ASSERT(expr) \ do { JUBATUS_ASSERT_MSG(expr, ""); } while (0) // declares expr to be true; if false, messages are shown #define JUBATUS_ASSERT_MSG(expr, messages) \ do { JUBA_CHECK(expr, ==, true, messages); } while (0) // declares control flow not to reach here #define JUBATUS_ASSERT_UNREACHABLE() \ do { JUBA_CHECK(0, !=, 0, "control flow not to reach here"); } while (0) // helpers to compare values #define JUBATUS_ASSERT_EQ(a, b, messages) \ do { JUBA_CHECK(a, ==, b, messages); } while (0) #define JUBATUS_ASSERT_NE(a, b, messages) \ do { JUBA_CHECK(a, !=, b, messages); } while (0) #define JUBATUS_ASSERT_LE(a, b, messages) \ do { JUBA_CHECK(a, <=, b, messages); } while (0) #define JUBATUS_ASSERT_LT(a, b, messages) \ do { JUBA_CHECK(a, <, b, messages); } while (0) #define JUBATUS_ASSERT_GE(a, b, messages) \ do { JUBA_CHECK(a, >=, b, messages); } while (0) #define JUBATUS_ASSERT_GT(a, b, messages) \ do { JUBA_CHECK(a, >, b, messages); } while (0) #else // #ifndef JUBATUS_DISABLE_ASSERTIONS #define JUBATUS_ASSERT(expr) ((void)0) #define JUBATUS_ASSERT_MSG(expr, msg) ((void)0) #ifndef __has_builtin #define __has_builtin(x) 0 #endif #if __has_builtin(__builtin_unreachable) || \ __GNUC__ == 4 && __GNUC_MINOR__ >= 5 // TODO(gintenlabo): Add __GUNC__ >= 5 if GCC 5.x has __builtin_unreachable #define JUBATUS_ASSERT_UNREACHABLE() __builtin_unreachable() #else #include <exception> // NOLINT #define JUBATUS_ASSERT_UNREACHABLE() std::terminate() #endif #define JUBATUS_ASSERT_EQ(a, b, messages) ((void)0) #define JUBATUS_ASSERT_NE(a, b, messages) ((void)0) #define JUBATUS_ASSERT_LE(a, b, messages) ((void)0) #define JUBATUS_ASSERT_LT(a, b, messages) ((void)0) #define JUBATUS_ASSERT_GE(a, b, messages) ((void)0) #define JUBATUS_ASSERT_GT(a, b, messages) ((void)0) #endif // #ifndef JUBATUS_DISABLE_ASSERTIONS #endif // JUBATUS_CORE_COMMON_ASSERT_HPP_ <commit_msg>separate assertion macros<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #ifndef JUBATUS_CORE_COMMON_ASSERT_HPP_ #define JUBATUS_CORE_COMMON_ASSERT_HPP_ #ifndef JUBATUS_DISABLE_ASSERTIONS #include <stdlib.h> #include <assert.h> #include <iostream> #include <string> #include "jubatus/util/lang/cast.h" #define JUBA_CHECK(a, op, b, message) { \ using jubatus::util::lang::lexical_cast; \ if (! ((a) op (b))) { \ std::cerr << "ASSERTION FAILED: " << message << ": " \ << #a << " " << #op << " " << #b \ << " (" << __FILE__ << ":" << __LINE__ << ")" << std::endl; \ std::cerr << "... where " << #a << " = " \ << lexical_cast<std::string>(a) << std::endl \ << " and " << #b << " = " \ << lexical_cast<std::string>(b) << std::endl; \ std::terminate(); \ }} // declares expr to be true; if false, messages are shown #define JUBATUS_ASSERT_MSG(expr, message) \ do { \ using jubatus::util::lang::lexical_cast; \ if (! (expr)) { \ std::cerr << "ASSERTION FAILED: " << message << ": " \ << #expr << " == " << lexical_cast<std::string>(expr) \ << " (" << __FILE__ << ":" << __LINE__ << ")" << std::endl; \ std::terminate(); \ } \ } while (0) // declares expr to be true // unlike glog CHECK, this macro cannot take trailing `<<'; // please use JUBATUS_ASSERT_MSG if you need extra messages. #define JUBATUS_ASSERT(expr) \ do { JUBATUS_ASSERT_MSG(expr, ""); } while (0) // declares control flow not to reach here #define JUBATUS_ASSERT_UNREACHABLE() \ do { JUBATUS_ASSERT_MSG(0, "control flow not to reach here"); } while (0) // helpers to compare values #define JUBATUS_ASSERT_EQ(a, b, messages) \ do { JUBA_CHECK(a, ==, b, messages); } while (0) #define JUBATUS_ASSERT_NE(a, b, messages) \ do { JUBA_CHECK(a, !=, b, messages); } while (0) #define JUBATUS_ASSERT_LE(a, b, messages) \ do { JUBA_CHECK(a, <=, b, messages); } while (0) #define JUBATUS_ASSERT_LT(a, b, messages) \ do { JUBA_CHECK(a, <, b, messages); } while (0) #define JUBATUS_ASSERT_GE(a, b, messages) \ do { JUBA_CHECK(a, >=, b, messages); } while (0) #define JUBATUS_ASSERT_GT(a, b, messages) \ do { JUBA_CHECK(a, >, b, messages); } while (0) #else // #ifndef JUBATUS_DISABLE_ASSERTIONS #define JUBATUS_ASSERT(expr) ((void)0) #define JUBATUS_ASSERT_MSG(expr, msg) ((void)0) #ifndef __has_builtin #define __has_builtin(x) 0 #endif #if __has_builtin(__builtin_unreachable) || \ __GNUC__ == 4 && __GNUC_MINOR__ >= 5 // TODO(gintenlabo): Add __GUNC__ >= 5 if GCC 5.x has __builtin_unreachable #define JUBATUS_ASSERT_UNREACHABLE() __builtin_unreachable() #else #include <exception> // NOLINT #define JUBATUS_ASSERT_UNREACHABLE() std::terminate() #endif #define JUBATUS_ASSERT_EQ(a, b, messages) ((void)0) #define JUBATUS_ASSERT_NE(a, b, messages) ((void)0) #define JUBATUS_ASSERT_LE(a, b, messages) ((void)0) #define JUBATUS_ASSERT_LT(a, b, messages) ((void)0) #define JUBATUS_ASSERT_GE(a, b, messages) ((void)0) #define JUBATUS_ASSERT_GT(a, b, messages) ((void)0) #endif // #ifndef JUBATUS_DISABLE_ASSERTIONS #endif // JUBATUS_CORE_COMMON_ASSERT_HPP_ <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "util.hpp" #include <arpa/inet.h> #ifdef __APPLE__ #include <libproc.h> #endif #include <net/if.h> #include <netinet/in.h> #include <pwd.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/stat.h> #include <unistd.h> #include <cerrno> #include <climits> #include <cstdio> #include <cstdlib> #include <cstring> #include <csignal> #include <fstream> #include <sstream> #include <string> #include <utility> #include <vector> #include <glog/logging.h> #include <pficommon/lang/exception.h> #include <pficommon/text/json.h> #include "jubatus/core/common/exception.hpp" using std::string; using pfi::lang::lexical_cast; using pfi::lang::parse_error; namespace jubatus { namespace server { namespace common { namespace util { // TODO(kashihara): AF_INET does not specify IPv6 void get_ip(const char* nic, string& out) { int fd; struct ifreq ifr; fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd == -1) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( "Failed to create socket(AF_INET, SOCK_DGRAM)") << jubatus::core::common::exception::error_errno(errno)); } ifr.ifr_addr.sa_family = AF_INET; strncpy(ifr.ifr_name, nic, IFNAMSIZ - 1); if (ioctl(fd, SIOCGIFADDR, &ifr) == -1) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( "Failed to get IP address from interface") << jubatus::core::common::exception::error_errno(errno)); } close(fd); struct sockaddr_in* sin = (struct sockaddr_in*) (&(ifr.ifr_addr)); out = inet_ntoa((struct in_addr) (sin->sin_addr)); } string get_ip(const char* nic) { string ret; get_ip(nic, ret); return ret; } string base_name(const string& path) { size_t found = path.rfind('/'); return found != string::npos ? path.substr(found + 1) : path; } std::string get_program_name() { // WARNING: this code will only work on linux or OS X #ifdef __APPLE__ char path[PROC_PIDPATHINFO_MAXSIZE]; int ret = proc_pidpath(getpid(), path, PROC_PIDPATHINFO_MAXSIZE); #else const char* exe_sym_path = "/proc/self/exe"; // when BSD: /proc/curproc/file // when Solaris: /proc/self/path/a.out // Unix: getexecname(3) char path[PATH_MAX]; ssize_t ret = readlink(exe_sym_path, path, PATH_MAX); if (ret != -1) { if (ret == PATH_MAX) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( "Failed to get program name. Path size overed PATH_MAX.") << jubatus::core::common::exception::error_errno(errno)); } path[ret] = '\0'; } #endif if (ret < 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("Failed to get program name") << core::common::exception::error_errno(errno)); } // get basename const string program_base_name = base_name(path); if (program_base_name == path) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( string("Failed to get program name from path: ") + path) << jubatus::core::common::exception::error_file_name(path)); } return program_base_name; } std::string get_user_name() { uid_t uid = getuid(); int64_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX); std::vector<char> buf(buflen); struct passwd pwd; struct passwd* result; int ret = getpwuid_r(uid, &pwd, &buf[0], buflen, &result); if (ret == 0) { if (result != NULL) { return result->pw_name; } throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("User not found") << core::common::exception::error_api_func("getpwuid_r")); } throw JUBATUS_EXCEPTION( jubatus::core::common::exception::runtime_error("Failed to get user name") << jubatus::core::common::exception::error_api_func("getpwuid_r") << jubatus::core::common::exception::error_errno(ret)); } bool is_writable(const char* dir_path) { struct stat st_buf; if (stat(dir_path, &st_buf) < 0) { return false; } if (!S_ISDIR(st_buf.st_mode)) { errno = ENOTDIR; return false; } if (access(dir_path, W_OK) < 0) { return false; } return true; } int daemonize() { return daemon(0, 0); } void append_env_path(const string& e, const string& argv0) { const char* env = getenv(e.c_str()); string new_path = string(env) + ":" + argv0; setenv(e.c_str(), new_path.c_str(), new_path.size()); } void append_server_path(const string& argv0) { const char* env = getenv("PATH"); char cwd[PATH_MAX]; if (!getcwd(cwd, PATH_MAX)) { throw JUBATUS_EXCEPTION( jubatus::core::common::exception::runtime_error("Failed to getcwd")) << jubatus::core::common::exception::error_errno(errno); } string p = argv0.substr(0, argv0.find_last_of('/')); string new_path = string(env) + ":" + cwd + "/" + p + "/../server"; setenv("PATH", new_path.c_str(), new_path.size()); } namespace { string get_statm_path() { // /proc/[pid]/statm shows using page size char path[64]; int pid = getpid(); // convert pid_t to int (for "%d") snprintf(path, sizeof(path), "/proc/%d/statm", pid); return path; } } // namespace void get_machine_status(machine_status_t& status) { // WARNING: this code will only work on linux uint64_t vm_virt = 0, vm_rss = 0, vm_shr = 0; { string path = get_statm_path(); std::ifstream statm(path.c_str()); if (statm) { const int64_t page_size = sysconf(_SC_PAGESIZE); statm >> vm_virt >> vm_rss >> vm_shr; vm_virt = vm_virt * page_size / 1024; vm_rss = vm_rss * page_size / 1024; vm_shr = vm_shr * page_size / 1024; } } // in KB status.vm_size = vm_virt; // total program size(virtual memory) status.vm_resident = vm_rss; // resident set size status.vm_share = vm_shr; // shared } namespace { void exit_on_term(int /* signum */) { LOG(INFO) << "stopping RPC server"; exit(0); } } // namespace void set_exit_on_term() { struct sigaction sigact; sigact.sa_handler = exit_on_term; sigact.sa_flags = SA_RESTART; if (sigaction(SIGTERM, &sigact, NULL) != 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("can't set SIGTERM handler") << core::common::exception::error_api_func("sigaction") << core::common::exception::error_errno(errno)); } if (sigaction(SIGINT, &sigact, NULL) != 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("can't set SIGINT handler") << core::common::exception::error_api_func("sigaction") << core::common::exception::error_errno(errno)); } } void ignore_sigpipe() { // portable code for socket write(2) MSG_NOSIGNAL if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { throw JUBATUS_EXCEPTION( jubatus::core::common::exception::runtime_error("can't ignore SIGPIPE") << jubatus::core::common::exception::error_api_func("signal") << jubatus::core::common::exception::error_errno(errno)); } } } // namespace util } // namespace common } // namespace server } // namespace jubatus <commit_msg>Modify set_exit_on_term<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "util.hpp" #include <arpa/inet.h> #ifdef __APPLE__ #include <libproc.h> #endif #include <net/if.h> #include <netinet/in.h> #include <pwd.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/stat.h> #include <unistd.h> #include <cerrno> #include <climits> #include <cstdio> #include <cstdlib> #include <cstring> #include <csignal> #include <fstream> #include <sstream> #include <string> #include <utility> #include <vector> #include <glog/logging.h> #include <pficommon/lang/exception.h> #include <pficommon/text/json.h> #include <pficommon/concurrent/thread.h> #include "jubatus/core/common/exception.hpp" using std::string; using pfi::lang::lexical_cast; using pfi::lang::parse_error; namespace jubatus { namespace server { namespace common { namespace util { // TODO(kashihara): AF_INET does not specify IPv6 void get_ip(const char* nic, string& out) { int fd; struct ifreq ifr; fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd == -1) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( "Failed to create socket(AF_INET, SOCK_DGRAM)") << jubatus::core::common::exception::error_errno(errno)); } ifr.ifr_addr.sa_family = AF_INET; strncpy(ifr.ifr_name, nic, IFNAMSIZ - 1); if (ioctl(fd, SIOCGIFADDR, &ifr) == -1) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( "Failed to get IP address from interface") << jubatus::core::common::exception::error_errno(errno)); } close(fd); struct sockaddr_in* sin = (struct sockaddr_in*) (&(ifr.ifr_addr)); out = inet_ntoa((struct in_addr) (sin->sin_addr)); } string get_ip(const char* nic) { string ret; get_ip(nic, ret); return ret; } string base_name(const string& path) { size_t found = path.rfind('/'); return found != string::npos ? path.substr(found + 1) : path; } std::string get_program_name() { // WARNING: this code will only work on linux or OS X #ifdef __APPLE__ char path[PROC_PIDPATHINFO_MAXSIZE]; int ret = proc_pidpath(getpid(), path, PROC_PIDPATHINFO_MAXSIZE); #else const char* exe_sym_path = "/proc/self/exe"; // when BSD: /proc/curproc/file // when Solaris: /proc/self/path/a.out // Unix: getexecname(3) char path[PATH_MAX]; ssize_t ret = readlink(exe_sym_path, path, PATH_MAX); if (ret != -1) { if (ret == PATH_MAX) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( "Failed to get program name. Path size overed PATH_MAX.") << jubatus::core::common::exception::error_errno(errno)); } path[ret] = '\0'; } #endif if (ret < 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("Failed to get program name") << core::common::exception::error_errno(errno)); } // get basename const string program_base_name = base_name(path); if (program_base_name == path) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( string("Failed to get program name from path: ") + path) << jubatus::core::common::exception::error_file_name(path)); } return program_base_name; } std::string get_user_name() { uid_t uid = getuid(); int64_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX); std::vector<char> buf(buflen); struct passwd pwd; struct passwd* result; int ret = getpwuid_r(uid, &pwd, &buf[0], buflen, &result); if (ret == 0) { if (result != NULL) { return result->pw_name; } throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("User not found") << core::common::exception::error_api_func("getpwuid_r")); } throw JUBATUS_EXCEPTION( jubatus::core::common::exception::runtime_error("Failed to get user name") << jubatus::core::common::exception::error_api_func("getpwuid_r") << jubatus::core::common::exception::error_errno(ret)); } bool is_writable(const char* dir_path) { struct stat st_buf; if (stat(dir_path, &st_buf) < 0) { return false; } if (!S_ISDIR(st_buf.st_mode)) { errno = ENOTDIR; return false; } if (access(dir_path, W_OK) < 0) { return false; } return true; } int daemonize() { return daemon(0, 0); } void append_env_path(const string& e, const string& argv0) { const char* env = getenv(e.c_str()); string new_path = string(env) + ":" + argv0; setenv(e.c_str(), new_path.c_str(), new_path.size()); } void append_server_path(const string& argv0) { const char* env = getenv("PATH"); char cwd[PATH_MAX]; if (!getcwd(cwd, PATH_MAX)) { throw JUBATUS_EXCEPTION( jubatus::core::common::exception::runtime_error("Failed to getcwd")) << jubatus::core::common::exception::error_errno(errno); } string p = argv0.substr(0, argv0.find_last_of('/')); string new_path = string(env) + ":" + cwd + "/" + p + "/../server"; setenv("PATH", new_path.c_str(), new_path.size()); } namespace { string get_statm_path() { // /proc/[pid]/statm shows using page size char path[64]; int pid = getpid(); // convert pid_t to int (for "%d") snprintf(path, sizeof(path), "/proc/%d/statm", pid); return path; } } // namespace void get_machine_status(machine_status_t& status) { // WARNING: this code will only work on linux uint64_t vm_virt = 0, vm_rss = 0, vm_shr = 0; { string path = get_statm_path(); std::ifstream statm(path.c_str()); if (statm) { const int64_t page_size = sysconf(_SC_PAGESIZE); statm >> vm_virt >> vm_rss >> vm_shr; vm_virt = vm_virt * page_size / 1024; vm_rss = vm_rss * page_size / 1024; vm_shr = vm_shr * page_size / 1024; } } // in KB status.vm_size = vm_virt; // total program size(virtual memory) status.vm_resident = vm_rss; // resident set size status.vm_share = vm_shr; // shared } namespace { // helper functions to handle sigset void clear_sigset(sigset_t* ss) { if (sigemptyset(ss) != 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("failed to call sigemptyset") << core::common::exception::error_api_func("clear_sigset") << core::common::exception::error_errno(errno)); } } void add_signal(sigset_t* ss, int signum) { if (sigaddset(ss, signum) != 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("failed to call sigaddset") << core::common::exception::error_api_func("add_signal") << core::common::exception::error_errno(errno)); } } void setup_sigset(sigset_t* ss) { clear_sigset(ss); add_signal(ss, SIGTERM); add_signal(ss, SIGINT); } void block_signals(const sigset_t* ss) { if (sigprocmask(SIG_BLOCK, ss, NULL) != 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("failed to call sigprocmask") << core::common::exception::error_api_func("block_signals") << core::common::exception::error_errno(errno)); } } void exit_on_term() { // internal function; do not call this function outside of set_exit_on_term try { sigset_t ss; setup_sigset(&ss); block_signals(&ss); int signo; if (sigwait(&ss, &signo) != 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("failed to call sigwait") << core::common::exception::error_api_func("exit_on_term") << core::common::exception::error_errno(errno)); } switch (signo) { case SIGINT: case SIGTERM: // intended signal; continue break; default: // unintended signal; raise error throw JUBATUS_EXCEPTION( core::common::exception::runtime_error( "unknown signal caught by sigwait (possibily logic error)") << core::common::exception::error_api_func("set_exit_on_term") << core::common::exception::error_errno(errno)); } LOG(INFO) << "stopping RPC server"; // TODO(SubaruG): PUT CODES TO STOP OTHER THREADS HERE; // or move sigwait to main thread // and use pthread_cancel exit(0); // never returns } catch (const jubatus::core::common::exception::jubatus_exception& e) { LOG(FATAL) << e.diagnostic_information(true); } catch (const std::exception& e) { LOG(FATAL) << e.what(); } abort(); } } // namespace void set_exit_on_term() { sigset_t ss; setup_sigset(&ss); block_signals(&ss); pfi::concurrent::thread(&exit_on_term).start(); } void ignore_sigpipe() { // portable code for socket write(2) MSG_NOSIGNAL if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { throw JUBATUS_EXCEPTION( jubatus::core::common::exception::runtime_error("can't ignore SIGPIPE") << jubatus::core::common::exception::error_api_func("signal") << jubatus::core::common::exception::error_errno(errno)); } } } // namespace util } // namespace common } // namespace server } // namespace jubatus <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file ContractionState.cxx ** Manages visibility of lines for folding and wrapping. **/ // Copyright 1998-2007 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <string.h> #include "Platform.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "ContractionState.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif ContractionState::ContractionState() : visible(0), expanded(0), heights(0), displayLines(0), linesInDocument(1) { //InsertLine(0); } ContractionState::~ContractionState() { Clear(); } void ContractionState::EnsureData() { if (OneToOne()) { visible = new RunStyles(); expanded = new RunStyles(); heights = new RunStyles(); displayLines = new Partitioning(4); InsertLines(0, linesInDocument); } } void ContractionState::Clear() { delete visible; visible = 0; delete expanded; expanded = 0; delete heights; heights = 0; delete displayLines; displayLines = 0; linesInDocument = 1; } int ContractionState::LinesInDoc() const { if (OneToOne()) { return linesInDocument; } else { return displayLines->Partitions() - 1; } } int ContractionState::LinesDisplayed() const { if (OneToOne()) { return linesInDocument; } else { return displayLines->PositionFromPartition(LinesInDoc()); } } int ContractionState::DisplayFromDoc(int lineDoc) const { if (OneToOne()) { return lineDoc; } else { if (lineDoc > displayLines->Partitions()) lineDoc = displayLines->Partitions(); return displayLines->PositionFromPartition(lineDoc); } } int ContractionState::DocFromDisplay(int lineDisplay) const { if (OneToOne()) { return lineDisplay; } else { if (lineDisplay <= 0) { return 0; } if (lineDisplay > LinesDisplayed()) { return displayLines->PartitionFromPosition(LinesDisplayed()); } int lineDoc = displayLines->PartitionFromPosition(lineDisplay); PLATFORM_ASSERT(GetVisible(lineDoc)); return lineDoc; } } void ContractionState::InsertLine(int lineDoc) { if (OneToOne()) { linesInDocument++; } else { visible->InsertSpace(lineDoc, 1); visible->SetValueAt(lineDoc, 1); expanded->InsertSpace(lineDoc, 1); expanded->SetValueAt(lineDoc, 1); heights->InsertSpace(lineDoc, 1); heights->SetValueAt(lineDoc, 1); int lineDisplay = DisplayFromDoc(lineDoc); displayLines->InsertPartition(lineDoc, lineDisplay); displayLines->InsertText(lineDoc, 1); } } void ContractionState::InsertLines(int lineDoc, int lineCount) { for (int l = 0; l < lineCount; l++) { InsertLine(lineDoc + l); } Check(); } void ContractionState::DeleteLine(int lineDoc) { if (OneToOne()) { linesInDocument--; } else { if (GetVisible(lineDoc)) { displayLines->InsertText(lineDoc, -heights->ValueAt(lineDoc)); } displayLines->RemovePartition(lineDoc); visible->DeleteRange(lineDoc, 1); expanded->DeleteRange(lineDoc, 1); heights->DeleteRange(lineDoc, 1); } } void ContractionState::DeleteLines(int lineDoc, int lineCount) { for (int l = 0; l < lineCount; l++) { DeleteLine(lineDoc); } Check(); } bool ContractionState::GetVisible(int lineDoc) const { if (OneToOne()) { return true; } else { if (lineDoc >= visible->Length()) return true; return visible->ValueAt(lineDoc) == 1; } } bool ContractionState::SetVisible(int lineDocStart, int lineDocEnd, bool visible_) { if (OneToOne() && visible_) { return false; } else { EnsureData(); int delta = 0; Check(); if ((lineDocStart <= lineDocEnd) && (lineDocStart >= 0) && (lineDocEnd < LinesInDoc())) { for (int line = lineDocStart; line <= lineDocEnd; line++) { if (GetVisible(line) != visible_) { int difference = visible_ ? heights->ValueAt(line) : -heights->ValueAt(line); visible->SetValueAt(line, visible_ ? 1 : 0); displayLines->InsertText(line, difference); delta += difference; } } } else { return false; } Check(); return delta != 0; } } bool ContractionState::HiddenLines() const { if (OneToOne()) { return false; } else { return !visible->AllSameAs(1); } } bool ContractionState::GetExpanded(int lineDoc) const { if (OneToOne()) { return true; } else { Check(); return expanded->ValueAt(lineDoc) == 1; } } bool ContractionState::SetExpanded(int lineDoc, bool expanded_) { if (OneToOne() && expanded_) { return false; } else { EnsureData(); if (expanded_ != (expanded->ValueAt(lineDoc) == 1)) { expanded->SetValueAt(lineDoc, expanded_ ? 1 : 0); Check(); return true; } else { Check(); return false; } } } int ContractionState::ContractedNext(int lineDocStart) const { if (OneToOne()) { return -1; } else { Check(); if (!expanded->ValueAt(lineDocStart)) { return lineDocStart; } else { int lineDocNextChange = expanded->EndRun(lineDocStart); if (lineDocNextChange < LinesInDoc()) return lineDocNextChange; else return -1; } } } int ContractionState::GetHeight(int lineDoc) const { if (OneToOne()) { return 1; } else { return heights->ValueAt(lineDoc); } } // Set the number of display lines needed for this line. // Return true if this is a change. bool ContractionState::SetHeight(int lineDoc, int height) { if (OneToOne() && (height == 1)) { return false; } else { EnsureData(); if (GetHeight(lineDoc) != height) { if (GetVisible(lineDoc)) { displayLines->InsertText(lineDoc, height - GetHeight(lineDoc)); } heights->SetValueAt(lineDoc, height); Check(); return true; } else { Check(); return false; } } } void ContractionState::ShowAll() { int lines = LinesInDoc(); Clear(); linesInDocument = lines; } // Debugging checks void ContractionState::Check() const { #ifdef CHECK_CORRECTNESS for (int vline = 0; vline < LinesDisplayed(); vline++) { const int lineDoc = DocFromDisplay(vline); PLATFORM_ASSERT(GetVisible(lineDoc)); } for (int lineDoc = 0; lineDoc < LinesInDoc(); lineDoc++) { const int displayThis = DisplayFromDoc(lineDoc); const int displayNext = DisplayFromDoc(lineDoc + 1); const int height = displayNext - displayThis; PLATFORM_ASSERT(height >= 0); if (GetVisible(lineDoc)) { PLATFORM_ASSERT(GetHeight(lineDoc) == height); } else { PLATFORM_ASSERT(0 == height); } } #endif } <commit_msg>Fix for assertion failure with annotation. Bug #3347268. Protect against setting height of line beyond end of document.<commit_after>// Scintilla source code edit control /** @file ContractionState.cxx ** Manages visibility of lines for folding and wrapping. **/ // Copyright 1998-2007 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <string.h> #include "Platform.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "ContractionState.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif ContractionState::ContractionState() : visible(0), expanded(0), heights(0), displayLines(0), linesInDocument(1) { //InsertLine(0); } ContractionState::~ContractionState() { Clear(); } void ContractionState::EnsureData() { if (OneToOne()) { visible = new RunStyles(); expanded = new RunStyles(); heights = new RunStyles(); displayLines = new Partitioning(4); InsertLines(0, linesInDocument); } } void ContractionState::Clear() { delete visible; visible = 0; delete expanded; expanded = 0; delete heights; heights = 0; delete displayLines; displayLines = 0; linesInDocument = 1; } int ContractionState::LinesInDoc() const { if (OneToOne()) { return linesInDocument; } else { return displayLines->Partitions() - 1; } } int ContractionState::LinesDisplayed() const { if (OneToOne()) { return linesInDocument; } else { return displayLines->PositionFromPartition(LinesInDoc()); } } int ContractionState::DisplayFromDoc(int lineDoc) const { if (OneToOne()) { return lineDoc; } else { if (lineDoc > displayLines->Partitions()) lineDoc = displayLines->Partitions(); return displayLines->PositionFromPartition(lineDoc); } } int ContractionState::DocFromDisplay(int lineDisplay) const { if (OneToOne()) { return lineDisplay; } else { if (lineDisplay <= 0) { return 0; } if (lineDisplay > LinesDisplayed()) { return displayLines->PartitionFromPosition(LinesDisplayed()); } int lineDoc = displayLines->PartitionFromPosition(lineDisplay); PLATFORM_ASSERT(GetVisible(lineDoc)); return lineDoc; } } void ContractionState::InsertLine(int lineDoc) { if (OneToOne()) { linesInDocument++; } else { visible->InsertSpace(lineDoc, 1); visible->SetValueAt(lineDoc, 1); expanded->InsertSpace(lineDoc, 1); expanded->SetValueAt(lineDoc, 1); heights->InsertSpace(lineDoc, 1); heights->SetValueAt(lineDoc, 1); int lineDisplay = DisplayFromDoc(lineDoc); displayLines->InsertPartition(lineDoc, lineDisplay); displayLines->InsertText(lineDoc, 1); } } void ContractionState::InsertLines(int lineDoc, int lineCount) { for (int l = 0; l < lineCount; l++) { InsertLine(lineDoc + l); } Check(); } void ContractionState::DeleteLine(int lineDoc) { if (OneToOne()) { linesInDocument--; } else { if (GetVisible(lineDoc)) { displayLines->InsertText(lineDoc, -heights->ValueAt(lineDoc)); } displayLines->RemovePartition(lineDoc); visible->DeleteRange(lineDoc, 1); expanded->DeleteRange(lineDoc, 1); heights->DeleteRange(lineDoc, 1); } } void ContractionState::DeleteLines(int lineDoc, int lineCount) { for (int l = 0; l < lineCount; l++) { DeleteLine(lineDoc); } Check(); } bool ContractionState::GetVisible(int lineDoc) const { if (OneToOne()) { return true; } else { if (lineDoc >= visible->Length()) return true; return visible->ValueAt(lineDoc) == 1; } } bool ContractionState::SetVisible(int lineDocStart, int lineDocEnd, bool visible_) { if (OneToOne() && visible_) { return false; } else { EnsureData(); int delta = 0; Check(); if ((lineDocStart <= lineDocEnd) && (lineDocStart >= 0) && (lineDocEnd < LinesInDoc())) { for (int line = lineDocStart; line <= lineDocEnd; line++) { if (GetVisible(line) != visible_) { int difference = visible_ ? heights->ValueAt(line) : -heights->ValueAt(line); visible->SetValueAt(line, visible_ ? 1 : 0); displayLines->InsertText(line, difference); delta += difference; } } } else { return false; } Check(); return delta != 0; } } bool ContractionState::HiddenLines() const { if (OneToOne()) { return false; } else { return !visible->AllSameAs(1); } } bool ContractionState::GetExpanded(int lineDoc) const { if (OneToOne()) { return true; } else { Check(); return expanded->ValueAt(lineDoc) == 1; } } bool ContractionState::SetExpanded(int lineDoc, bool expanded_) { if (OneToOne() && expanded_) { return false; } else { EnsureData(); if (expanded_ != (expanded->ValueAt(lineDoc) == 1)) { expanded->SetValueAt(lineDoc, expanded_ ? 1 : 0); Check(); return true; } else { Check(); return false; } } } int ContractionState::ContractedNext(int lineDocStart) const { if (OneToOne()) { return -1; } else { Check(); if (!expanded->ValueAt(lineDocStart)) { return lineDocStart; } else { int lineDocNextChange = expanded->EndRun(lineDocStart); if (lineDocNextChange < LinesInDoc()) return lineDocNextChange; else return -1; } } } int ContractionState::GetHeight(int lineDoc) const { if (OneToOne()) { return 1; } else { return heights->ValueAt(lineDoc); } } // Set the number of display lines needed for this line. // Return true if this is a change. bool ContractionState::SetHeight(int lineDoc, int height) { if (OneToOne() && (height == 1)) { return false; } else if (lineDoc < LinesInDoc()) { EnsureData(); if (GetHeight(lineDoc) != height) { if (GetVisible(lineDoc)) { displayLines->InsertText(lineDoc, height - GetHeight(lineDoc)); } heights->SetValueAt(lineDoc, height); Check(); return true; } else { Check(); return false; } } } void ContractionState::ShowAll() { int lines = LinesInDoc(); Clear(); linesInDocument = lines; } // Debugging checks void ContractionState::Check() const { #ifdef CHECK_CORRECTNESS for (int vline = 0; vline < LinesDisplayed(); vline++) { const int lineDoc = DocFromDisplay(vline); PLATFORM_ASSERT(GetVisible(lineDoc)); } for (int lineDoc = 0; lineDoc < LinesInDoc(); lineDoc++) { const int displayThis = DisplayFromDoc(lineDoc); const int displayNext = DisplayFromDoc(lineDoc + 1); const int height = displayNext - displayThis; PLATFORM_ASSERT(height >= 0); if (GetVisible(lineDoc)) { PLATFORM_ASSERT(GetHeight(lineDoc) == height); } else { PLATFORM_ASSERT(0 == height); } } #endif } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: bootstrap.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: fs $ $Date: 2000-12-01 14:08:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONFIGMGR_BOOTSTRAP_HXX_ #define CONFIGMGR_BOOTSTRAP_HXX_ #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif namespace osl { class Profile; } namespace configmgr { class IConfigSession; // =================================================================================== #define PORTAL_SESSION_IDENTIFIER "portal" #define REMOTE_SESSION_IDENTIFIER "remote" #define LOCAL_SESSION_IDENTIFIER "local" #define SETUP_SESSION_IDENTIFIER "setup" #define PLUGIN_SESSION_IDENTIFIER "plugin" // =================================================================================== // = ConnectionSettings // =================================================================================== class ConnectionSettings { public: enum SETTING_ORIGIN { SO_SREGISTRY, SO_OVERRIDE, SO_FALLBACK, SO_UNKNOWN }; protected: // ine single setting struct Setting { ::com::sun::star::uno::Any aValue; SETTING_ORIGIN eOrigin; Setting() : eOrigin(SO_UNKNOWN) { } Setting(const ::rtl::OUString& _rValue, SETTING_ORIGIN _eOrigin) : aValue(::com::sun::star::uno::makeAny(_rValue)), eOrigin(_eOrigin) { } Setting(const sal_Int32 _nValue, SETTING_ORIGIN _eOrigin) : aValue(::com::sun::star::uno::makeAny(_nValue)), eOrigin(_eOrigin) { } Setting(const ::com::sun::star::uno::Any& _rValue, SETTING_ORIGIN _eOrigin) : aValue(_rValue), eOrigin(_eOrigin) { } }; DECLARE_STL_USTRINGACCESS_MAP( Setting, SettingsImpl ); SettingsImpl m_aImpl; ::osl::Profile* m_pSRegistry; public: /// default ctor ConnectionSettings(); /// dtor ~ConnectionSettings(); /// copy ctor ConnectionSettings(const ConnectionSettings& _rSource); /** construct a settings object. <p>The runtime overrides given will be merged with the settings found in a sversion.ini (sversionrc), if any. The former overrule the latter</p> */ ConnectionSettings(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rRuntimeOverrides ); /// merge the given overrides into a new ConnectionSettings object const ConnectionSettings& merge(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides); /// merge the given overrides into the object itself ConnectionSettings merge(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides) const { return ConnectionSettings(*this).merge(_rOverrides); } // check setting existence sal_Bool hasUser() const; sal_Bool hasPassword() const; sal_Bool hasServer() const; sal_Bool hasPort() const; sal_Bool hasTimeout() const; sal_Bool isValidSourcePath() const; sal_Bool isValidUpdatePath() const; // get a special setting ::rtl::OUString getSessionType() const; ::rtl::OUString getUser() const; ::rtl::OUString getPassword() const; ::rtl::OUString getSourcePath() const; ::rtl::OUString getUpdatePath() const; ::rtl::OUString getServer() const; sal_Int32 getPort() const; sal_Int32 getTimeout() const; // set a new session type. Must be one of the *_SESSION_IDENTIFIER defines void setSessionType(const ::rtl::OUString& _rSessionIdentifier); IConfigSession* ConnectionSettings::createConnection( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > const& _rxServiceMgr) const; protected: void construct(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides); // transfer runtime overwrites into m_aImpl. Existent settings will be overwritten. void implTranslate(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides) throw (::com::sun::star::lang::IllegalArgumentException); /** normalize a path setting, delete it if the value could not be normalized @return <TRUE/> if the setting exists and is a valid path */ sal_Bool implNormalizePathSetting(const sal_Char* _pSetting); // translate old settings, which exist for compatiblity only, into new ones void implTranslateCompatibilitySettings(); // if we do not already have the given config path setting, ensure that it exists (calculated relative to a given path) void ensureConfigPath(const sal_Char* _pSetting, const ::rtl::OUString& _rBasePath, const sal_Char* _pRelative); sal_Bool haveSetting(const sal_Char* _pName) const; void putSetting(const sal_Char* _pName, const Setting& _rSetting); void clearSetting(const sal_Char* _pName); ::rtl::OUString getStringSetting(const sal_Char* _pName) const; sal_Int32 getIntSetting(const sal_Char* _pName) const; Setting getSetting(const sal_Char* _pName) const; Setting getMaybeSetting(const sal_Char* _pName) const; ::rtl::OUString getProfileStringItem(const sal_Char* _pSection, const sal_Char* _pKey); sal_Int32 getProfileIntItem(const sal_Char* _pSection, const sal_Char* _pKey); private: // ensures that m_aImpl contains a session type // to be called from within construct only void implDetermineSessionType(); // collect settings from the sregistry, put them into m_aImpl, if not overruled by runtime settings void implCollectSRegistrySetting(); // clear items which are not relevant because of the session type origin void clearIrrelevantItems(); }; } #endif // CONFIGMGR_BOOTSTRAP_HXX_ <commit_msg>#81469#<commit_after>/************************************************************************* * * $RCSfile: bootstrap.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: tlx $ $Date: 2000-12-07 12:14:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONFIGMGR_BOOTSTRAP_HXX_ #define CONFIGMGR_BOOTSTRAP_HXX_ #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif namespace osl { class Profile; } namespace configmgr { class IConfigSession; // =================================================================================== #define PORTAL_SESSION_IDENTIFIER "portal" #define REMOTE_SESSION_IDENTIFIER "remote" #define LOCAL_SESSION_IDENTIFIER "local" #define SETUP_SESSION_IDENTIFIER "setup" #define PLUGIN_SESSION_IDENTIFIER "plugin" // =================================================================================== // = ConnectionSettings // =================================================================================== class ConnectionSettings { public: enum SETTING_ORIGIN { SO_SREGISTRY, SO_OVERRIDE, SO_FALLBACK, SO_UNKNOWN }; protected: // ine single setting struct Setting { ::com::sun::star::uno::Any aValue; SETTING_ORIGIN eOrigin; Setting() : eOrigin(SO_UNKNOWN) { } Setting(const ::rtl::OUString& _rValue, SETTING_ORIGIN _eOrigin) : aValue(::com::sun::star::uno::makeAny(_rValue)), eOrigin(_eOrigin) { } Setting(const sal_Int32 _nValue, SETTING_ORIGIN _eOrigin) : aValue(::com::sun::star::uno::makeAny(_nValue)), eOrigin(_eOrigin) { } Setting(const ::com::sun::star::uno::Any& _rValue, SETTING_ORIGIN _eOrigin) : aValue(_rValue), eOrigin(_eOrigin) { } }; DECLARE_STL_USTRINGACCESS_MAP( Setting, SettingsImpl ); SettingsImpl m_aImpl; ::osl::Profile* m_pSRegistry; public: /// default ctor ConnectionSettings(); /// dtor ~ConnectionSettings(); /// copy ctor ConnectionSettings(const ConnectionSettings& _rSource); /** construct a settings object. <p>The runtime overrides given will be merged with the settings found in a sversion.ini (sversionrc), if any. The former overrule the latter</p> */ ConnectionSettings(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rRuntimeOverrides ); /// merge the given overrides into a new ConnectionSettings object const ConnectionSettings& merge(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides); /// merge the given overrides into the object itself ConnectionSettings merge(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides) const { return ConnectionSettings(*this).merge(_rOverrides); } // check setting existence sal_Bool hasRegistryRC() const { return m_pSRegistry != 0; } sal_Bool hasUser() const; sal_Bool hasPassword() const; sal_Bool hasServer() const; sal_Bool hasPort() const; sal_Bool hasTimeout() const; sal_Bool isValidSourcePath() const; sal_Bool isValidUpdatePath() const; // get a special setting ::rtl::OUString getSessionType() const; ::rtl::OUString getUser() const; ::rtl::OUString getPassword() const; ::rtl::OUString getSourcePath() const; ::rtl::OUString getUpdatePath() const; ::rtl::OUString getServer() const; sal_Int32 getPort() const; sal_Int32 getTimeout() const; // set a new session type. Must be one of the *_SESSION_IDENTIFIER defines void setSessionType(const ::rtl::OUString& _rSessionIdentifier); IConfigSession* ConnectionSettings::createConnection( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > const& _rxServiceMgr) const; protected: void construct(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides); // transfer runtime overwrites into m_aImpl. Existent settings will be overwritten. void implTranslate(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides) throw (::com::sun::star::lang::IllegalArgumentException); /** normalize a path setting, delete it if the value could not be normalized @return <TRUE/> if the setting exists and is a valid path */ sal_Bool implNormalizePathSetting(const sal_Char* _pSetting); // translate old settings, which exist for compatiblity only, into new ones void implTranslateCompatibilitySettings(); // if we do not already have the given config path setting, ensure that it exists (calculated relative to a given path) void ensureConfigPath(const sal_Char* _pSetting, const ::rtl::OUString& _rBasePath, const sal_Char* _pRelative); sal_Bool haveSetting(const sal_Char* _pName) const; void putSetting(const sal_Char* _pName, const Setting& _rSetting); void clearSetting(const sal_Char* _pName); ::rtl::OUString getStringSetting(const sal_Char* _pName) const; sal_Int32 getIntSetting(const sal_Char* _pName) const; Setting getSetting(const sal_Char* _pName) const; Setting getMaybeSetting(const sal_Char* _pName) const; ::rtl::OUString getProfileStringItem(const sal_Char* _pSection, const sal_Char* _pKey); sal_Int32 getProfileIntItem(const sal_Char* _pSection, const sal_Char* _pKey); private: // ensures that m_aImpl contains a session type // to be called from within construct only void implDetermineSessionType(); // collect settings from the sregistry, put them into m_aImpl, if not overruled by runtime settings void implCollectSRegistrySetting(); // clear items which are not relevant because of the session type origin void clearIrrelevantItems(); }; } #endif // CONFIGMGR_BOOTSTRAP_HXX_ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: writersvc.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2005-09-08 04:43:30 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "writersvc.hxx" #ifndef CONFIGMGR_API_FACTORY_HXX_ #include "confapifactory.hxx" #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERHANDLER_HPP_ #include <com/sun/star/configuration/backend/XLayerHandler.hpp> #endif #ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_ #include <com/sun/star/lang/WrappedTargetException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETRUNTIMEEXCEPTION_HPP_ #include <com/sun/star/lang/WrappedTargetRuntimeException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif // ----------------------------------------------------------------------------- namespace configmgr { // ----------------------------------------------------------------------------- namespace xml { // ----------------------------------------------------------------------------- namespace uno = ::com::sun::star::uno; namespace lang = ::com::sun::star::lang; namespace io = ::com::sun::star::io; namespace sax = ::com::sun::star::xml::sax; namespace backenduno = ::com::sun::star::configuration::backend; // ----------------------------------------------------------------------------- template <class BackendInterface> struct WriterServiceTraits; // ----------------------------------------------------------------------------- static inline void clear(OUString & _rs) { _rs = OUString(); } // ----------------------------------------------------------------------------- template <class BackendInterface> WriterService<BackendInterface>::WriterService(CreationArg _xContext) : m_xServiceFactory(_xContext->getServiceManager(), uno::UNO_QUERY) , m_xWriter() { if (!m_xServiceFactory.is()) { OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration XML Writer: Context has no service manager")); throw uno::RuntimeException(sMessage,NULL); } } // ----------------------------------------------------------------------------- // XInitialization template <class BackendInterface> void SAL_CALL WriterService<BackendInterface>::initialize( const uno::Sequence< uno::Any >& aArguments ) throw (uno::Exception, uno::RuntimeException) { switch(aArguments.getLength()) { case 0: { break; } case 1: { if (aArguments[0] >>= m_xWriter) break; uno::Reference< io::XOutputStream > xStream; if (aArguments[0] >>= xStream) { this->setOutputStream(xStream); break; } OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Cannot use argument to initialize a Configuration XML Writer" "- SAX XDocumentHandler or XOutputStream expected")); throw lang::IllegalArgumentException(sMessage,*this,1); } default: { OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Too many arguments to initialize a Configuration Parser")); throw lang::IllegalArgumentException(sMessage,*this,0); } } } // ----------------------------------------------------------------------------- template <class BackendInterface> inline ServiceInfoHelper WriterService<BackendInterface>::getServiceInfo() { return WriterServiceTraits<BackendInterface>::getServiceInfo(); } // ----------------------------------------------------------------------------- // XServiceInfo template <class BackendInterface> ::rtl::OUString SAL_CALL WriterService<BackendInterface>::getImplementationName( ) throw (uno::RuntimeException) { return getServiceInfo().getImplementationName( ); } // ----------------------------------------------------------------------------- template <class BackendInterface> sal_Bool SAL_CALL WriterService<BackendInterface>::supportsService( const ::rtl::OUString& ServiceName ) throw (uno::RuntimeException) { return getServiceInfo().supportsService( ServiceName ); } // ----------------------------------------------------------------------------- template <class BackendInterface> uno::Sequence< ::rtl::OUString > SAL_CALL WriterService<BackendInterface>::getSupportedServiceNames( ) throw (uno::RuntimeException) { return getServiceInfo().getSupportedServiceNames( ); } // ----------------------------------------------------------------------------- template <class BackendInterface> void SAL_CALL WriterService<BackendInterface>::setOutputStream( const uno::Reference< io::XOutputStream >& aStream ) throw (uno::RuntimeException) { uno::Reference< io::XActiveDataSource > xDS( m_xWriter, uno::UNO_QUERY ); if (xDS.is()) { xDS->setOutputStream(aStream); } else { SaxHandler xNewHandler = this->createHandler(); xDS.set( xNewHandler, uno::UNO_QUERY ); if (!xDS.is()) { OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration XML Writer: Cannot set output stream to sax.Writer - missing interface XActiveDataSource.")); throw uno::RuntimeException(sMessage,*this); } xDS->setOutputStream(aStream); m_xWriter = xNewHandler; } } // ----------------------------------------------------------------------------- template <class BackendInterface> uno::Reference< io::XOutputStream > SAL_CALL WriterService<BackendInterface>::getOutputStream( ) throw (uno::RuntimeException) { uno::Reference< io::XActiveDataSource > xDS( m_xWriter, uno::UNO_QUERY ); return xDS.is()? xDS->getOutputStream() : uno::Reference< io::XOutputStream >(); } // ----------------------------------------------------------------------------- template <class BackendInterface> uno::Reference< sax::XDocumentHandler > WriterService<BackendInterface>::getWriteHandler() throw (uno::RuntimeException) { if (!m_xWriter.is()) m_xWriter = this->createHandler(); return m_xWriter; } // ----------------------------------------------------------------------------- template <class BackendInterface> uno::Reference< sax::XDocumentHandler > WriterService<BackendInterface>::createHandler() const throw (uno::RuntimeException) { try { static rtl::OUString const k_sSaxWriterSvc( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Writer") ); return SaxHandler::query( getServiceFactory()->createInstance(k_sSaxWriterSvc) ); } catch (uno::RuntimeException& ) { throw; } catch (uno::Exception& e) { lang::XInitialization * const pThis = const_cast<WriterService *>(this); throw lang::WrappedTargetRuntimeException(e.Message, pThis, uno::makeAny(e)); } } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- AsciiServiceName const aLayerWriterServices[] = { "com.sun.star.configuration.backend.xml.LayerWriter", 0 }; extern // needed by SunCC 5.2, if used from template const ServiceImplementationInfo aLayerWriterSI = { "com.sun.star.comp.configuration.backend.xml.LayerWriter", aLayerWriterServices, 0 }; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- template <> struct WriterServiceTraits< backenduno::XLayerHandler > { typedef backenduno::XLayerHandler Handler; static ServiceImplementationInfo const * getServiceInfo() { return & aLayerWriterSI; } }; // ----------------------------------------------------------------------------- const ServiceRegistrationInfo* getLayerWriterServiceInfo() { return getRegistrationInfo(& aLayerWriterSI); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // instantiate here ! template class WriterService< backenduno::XLayerHandler >; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- } // namespace // ----------------------------------------------------------------------------- } // namespace <commit_msg>INTEGRATION: CWS pchfix02 (1.9.60); FILE MERGED 2006/09/01 17:20:54 kaib 1.9.60.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: writersvc.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: obo $ $Date: 2006-09-16 15:36:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_configmgr.hxx" #include "writersvc.hxx" #ifndef CONFIGMGR_API_FACTORY_HXX_ #include "confapifactory.hxx" #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERHANDLER_HPP_ #include <com/sun/star/configuration/backend/XLayerHandler.hpp> #endif #ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_ #include <com/sun/star/lang/WrappedTargetException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETRUNTIMEEXCEPTION_HPP_ #include <com/sun/star/lang/WrappedTargetRuntimeException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif // ----------------------------------------------------------------------------- namespace configmgr { // ----------------------------------------------------------------------------- namespace xml { // ----------------------------------------------------------------------------- namespace uno = ::com::sun::star::uno; namespace lang = ::com::sun::star::lang; namespace io = ::com::sun::star::io; namespace sax = ::com::sun::star::xml::sax; namespace backenduno = ::com::sun::star::configuration::backend; // ----------------------------------------------------------------------------- template <class BackendInterface> struct WriterServiceTraits; // ----------------------------------------------------------------------------- static inline void clear(OUString & _rs) { _rs = OUString(); } // ----------------------------------------------------------------------------- template <class BackendInterface> WriterService<BackendInterface>::WriterService(CreationArg _xContext) : m_xServiceFactory(_xContext->getServiceManager(), uno::UNO_QUERY) , m_xWriter() { if (!m_xServiceFactory.is()) { OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration XML Writer: Context has no service manager")); throw uno::RuntimeException(sMessage,NULL); } } // ----------------------------------------------------------------------------- // XInitialization template <class BackendInterface> void SAL_CALL WriterService<BackendInterface>::initialize( const uno::Sequence< uno::Any >& aArguments ) throw (uno::Exception, uno::RuntimeException) { switch(aArguments.getLength()) { case 0: { break; } case 1: { if (aArguments[0] >>= m_xWriter) break; uno::Reference< io::XOutputStream > xStream; if (aArguments[0] >>= xStream) { this->setOutputStream(xStream); break; } OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Cannot use argument to initialize a Configuration XML Writer" "- SAX XDocumentHandler or XOutputStream expected")); throw lang::IllegalArgumentException(sMessage,*this,1); } default: { OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Too many arguments to initialize a Configuration Parser")); throw lang::IllegalArgumentException(sMessage,*this,0); } } } // ----------------------------------------------------------------------------- template <class BackendInterface> inline ServiceInfoHelper WriterService<BackendInterface>::getServiceInfo() { return WriterServiceTraits<BackendInterface>::getServiceInfo(); } // ----------------------------------------------------------------------------- // XServiceInfo template <class BackendInterface> ::rtl::OUString SAL_CALL WriterService<BackendInterface>::getImplementationName( ) throw (uno::RuntimeException) { return getServiceInfo().getImplementationName( ); } // ----------------------------------------------------------------------------- template <class BackendInterface> sal_Bool SAL_CALL WriterService<BackendInterface>::supportsService( const ::rtl::OUString& ServiceName ) throw (uno::RuntimeException) { return getServiceInfo().supportsService( ServiceName ); } // ----------------------------------------------------------------------------- template <class BackendInterface> uno::Sequence< ::rtl::OUString > SAL_CALL WriterService<BackendInterface>::getSupportedServiceNames( ) throw (uno::RuntimeException) { return getServiceInfo().getSupportedServiceNames( ); } // ----------------------------------------------------------------------------- template <class BackendInterface> void SAL_CALL WriterService<BackendInterface>::setOutputStream( const uno::Reference< io::XOutputStream >& aStream ) throw (uno::RuntimeException) { uno::Reference< io::XActiveDataSource > xDS( m_xWriter, uno::UNO_QUERY ); if (xDS.is()) { xDS->setOutputStream(aStream); } else { SaxHandler xNewHandler = this->createHandler(); xDS.set( xNewHandler, uno::UNO_QUERY ); if (!xDS.is()) { OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration XML Writer: Cannot set output stream to sax.Writer - missing interface XActiveDataSource.")); throw uno::RuntimeException(sMessage,*this); } xDS->setOutputStream(aStream); m_xWriter = xNewHandler; } } // ----------------------------------------------------------------------------- template <class BackendInterface> uno::Reference< io::XOutputStream > SAL_CALL WriterService<BackendInterface>::getOutputStream( ) throw (uno::RuntimeException) { uno::Reference< io::XActiveDataSource > xDS( m_xWriter, uno::UNO_QUERY ); return xDS.is()? xDS->getOutputStream() : uno::Reference< io::XOutputStream >(); } // ----------------------------------------------------------------------------- template <class BackendInterface> uno::Reference< sax::XDocumentHandler > WriterService<BackendInterface>::getWriteHandler() throw (uno::RuntimeException) { if (!m_xWriter.is()) m_xWriter = this->createHandler(); return m_xWriter; } // ----------------------------------------------------------------------------- template <class BackendInterface> uno::Reference< sax::XDocumentHandler > WriterService<BackendInterface>::createHandler() const throw (uno::RuntimeException) { try { static rtl::OUString const k_sSaxWriterSvc( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Writer") ); return SaxHandler::query( getServiceFactory()->createInstance(k_sSaxWriterSvc) ); } catch (uno::RuntimeException& ) { throw; } catch (uno::Exception& e) { lang::XInitialization * const pThis = const_cast<WriterService *>(this); throw lang::WrappedTargetRuntimeException(e.Message, pThis, uno::makeAny(e)); } } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- AsciiServiceName const aLayerWriterServices[] = { "com.sun.star.configuration.backend.xml.LayerWriter", 0 }; extern // needed by SunCC 5.2, if used from template const ServiceImplementationInfo aLayerWriterSI = { "com.sun.star.comp.configuration.backend.xml.LayerWriter", aLayerWriterServices, 0 }; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- template <> struct WriterServiceTraits< backenduno::XLayerHandler > { typedef backenduno::XLayerHandler Handler; static ServiceImplementationInfo const * getServiceInfo() { return & aLayerWriterSI; } }; // ----------------------------------------------------------------------------- const ServiceRegistrationInfo* getLayerWriterServiceInfo() { return getRegistrationInfo(& aLayerWriterSI); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // instantiate here ! template class WriterService< backenduno::XLayerHandler >; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- } // namespace // ----------------------------------------------------------------------------- } // namespace <|endoftext|>
<commit_before>#include "cpluginproxy.h" #include "assert/advanced_assert.h" CPluginProxy::CPluginProxy() : _currentPanel(PluginUnknownPanel) { } void CPluginProxy::setToolMenuEntryCreatorImplementation(CPluginProxy::CreateToolMenuEntryImplementationType implementation) { _createToolMenuEntryImplementation = implementation; } void CPluginProxy::createToolMenuEntries(std::vector<MenuTree> menuEntries) { if (_createToolMenuEntryImplementation) _createToolMenuEntryImplementation(menuEntries); } void CPluginProxy::panelContentsChanged(PanelPosition panel, const QString &folder, const std::map<qulonglong, CFileSystemObject>& contents) { PanelState& state = _panelState[panel]; state.panelContents = contents; state.currentFolder = folder; } void CPluginProxy::selectionChanged(PanelPosition panel, std::vector<qulonglong> selectedItemsHashes) { PanelState& state = _panelState[panel]; state.selectedItemsHashes = selectedItemsHashes; } void CPluginProxy::currentItemChanged(PanelPosition panel, qulonglong currentItemHash) { PanelState& state = _panelState[panel]; state.currentItemHash = currentItemHash; } void CPluginProxy::currentPanelChanged(PanelPosition panel) { _currentPanel = panel; } PanelState& CPluginProxy::currentPanelState() { static PanelState empty; if (_currentPanel == PluginUnknownPanel) { empty = PanelState(); return empty; } const auto state = _panelState.find(_currentPanel); if (state == _panelState.end()) { empty = PanelState(); return empty; } else return state->second; } const PanelState& CPluginProxy::currentPanelState() const { static const PanelState empty; if (_currentPanel == PluginUnknownPanel) return empty; const auto state = _panelState.find(_currentPanel); if (state == _panelState.end()) return empty; else return state->second; } QString CPluginProxy::currentFolderPath() const { if (_currentPanel == PluginUnknownPanel) return QString(); const auto state = _panelState.find(_currentPanel); if (state == _panelState.end()) return QString(); else return state->second.currentFolder; } QString CPluginProxy::currentItemPath() const { return currentItem().fullAbsolutePath(); } const CFileSystemObject &CPluginProxy::currentItem() const { const PanelState& panelState = currentPanelState(); if (panelState.currentItemHash != 0) { auto fileSystemObject = panelState.panelContents.find(panelState.currentItemHash); assert_r(fileSystemObject != panelState.panelContents.end()); return fileSystemObject->second; } else { static const CFileSystemObject dummy; return dummy; } } bool CPluginProxy::currentItemIsFile() const { return currentItem().isFile(); } bool CPluginProxy::currentItemIsDir() const { return currentItem().isDir(); } <commit_msg>Crash fixed<commit_after>#include "cpluginproxy.h" #include "assert/advanced_assert.h" CPluginProxy::CPluginProxy() : _currentPanel(PluginUnknownPanel) { } void CPluginProxy::setToolMenuEntryCreatorImplementation(CPluginProxy::CreateToolMenuEntryImplementationType implementation) { _createToolMenuEntryImplementation = implementation; } void CPluginProxy::createToolMenuEntries(std::vector<MenuTree> menuEntries) { if (_createToolMenuEntryImplementation) _createToolMenuEntryImplementation(menuEntries); } void CPluginProxy::panelContentsChanged(PanelPosition panel, const QString &folder, const std::map<qulonglong, CFileSystemObject>& contents) { PanelState& state = _panelState[panel]; state.panelContents = contents; state.currentFolder = folder; } void CPluginProxy::selectionChanged(PanelPosition panel, std::vector<qulonglong> selectedItemsHashes) { PanelState& state = _panelState[panel]; state.selectedItemsHashes = selectedItemsHashes; } void CPluginProxy::currentItemChanged(PanelPosition panel, qulonglong currentItemHash) { PanelState& state = _panelState[panel]; state.currentItemHash = currentItemHash; } void CPluginProxy::currentPanelChanged(PanelPosition panel) { _currentPanel = panel; } PanelState& CPluginProxy::currentPanelState() { static PanelState empty; if (_currentPanel == PluginUnknownPanel) { empty = PanelState(); return empty; } const auto state = _panelState.find(_currentPanel); if (state == _panelState.end()) { empty = PanelState(); return empty; } else return state->second; } const PanelState& CPluginProxy::currentPanelState() const { static const PanelState empty; if (_currentPanel == PluginUnknownPanel) return empty; const auto state = _panelState.find(_currentPanel); if (state == _panelState.end()) return empty; else return state->second; } QString CPluginProxy::currentFolderPath() const { if (_currentPanel == PluginUnknownPanel) return QString(); const auto state = _panelState.find(_currentPanel); if (state == _panelState.end()) return QString(); else return state->second.currentFolder; } QString CPluginProxy::currentItemPath() const { return currentItem().fullAbsolutePath(); } const CFileSystemObject &CPluginProxy::currentItem() const { static const CFileSystemObject dummy; const PanelState& panelState = currentPanelState(); if (panelState.currentItemHash != 0) { auto fileSystemObject = panelState.panelContents.find(panelState.currentItemHash); assert_and_return_r(fileSystemObject != panelState.panelContents.end(), dummy); return fileSystemObject->second; } else return dummy; } bool CPluginProxy::currentItemIsFile() const { return currentItem().isFile(); } bool CPluginProxy::currentItemIsDir() const { return currentItem().isDir(); } <|endoftext|>
<commit_before>#include "curler.h" using namespace AhoViewer::Booru; #include "imagefetcher.h" // Used for looking closer at what libcurl is doing // set it to 1 with CXXFLAGS and prepare to be spammed #ifndef VERBOSE_LIBCURL #define VERBOSE_LIBCURL 0 #endif const char* Curler::UserAgent{ "Mozilla/5.0" }; size_t Curler::write_cb(const unsigned char* ptr, size_t size, size_t nmemb, void* userp) { Curler* self{ static_cast<Curler*>(userp) }; if (self->is_cancelled()) return 0; if (self->m_DownloadTotal == 0) { curl_off_t s; curl_easy_getinfo(self->m_EasyHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &s); self->m_DownloadTotal = s; } if (self->m_Pause) return CURL_WRITEFUNC_PAUSE; size_t len{ size * nmemb }; self->m_Buffer.insert(self->m_Buffer.end(), ptr, ptr + len); self->m_SignalWrite(ptr, len); self->m_DownloadCurrent = self->m_Buffer.size(); if (!self->is_cancelled()) self->m_SignalProgress(); return len; } int Curler::progress_cb(void* userp, curl_off_t, curl_off_t, curl_off_t, curl_off_t) { Curler* self{ static_cast<Curler*>(userp) }; return self->is_cancelled(); } Curler::Curler(const std::string& url, CURLSH* share) : m_EasyHandle(curl_easy_init()), m_Cancel(Gio::Cancellable::create()) { curl_easy_setopt(m_EasyHandle, CURLOPT_USERAGENT, UserAgent); curl_easy_setopt(m_EasyHandle, CURLOPT_WRITEFUNCTION, &Curler::write_cb); curl_easy_setopt(m_EasyHandle, CURLOPT_WRITEDATA, this); curl_easy_setopt(m_EasyHandle, CURLOPT_XFERINFOFUNCTION, &Curler::progress_cb); curl_easy_setopt(m_EasyHandle, CURLOPT_XFERINFODATA, this); curl_easy_setopt(m_EasyHandle, CURLOPT_NOPROGRESS, 0); curl_easy_setopt(m_EasyHandle, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(m_EasyHandle, CURLOPT_MAXREDIRS, 5); curl_easy_setopt(m_EasyHandle, CURLOPT_VERBOSE, VERBOSE_LIBCURL); curl_easy_setopt(m_EasyHandle, CURLOPT_CONNECTTIMEOUT, 60); curl_easy_setopt(m_EasyHandle, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(m_EasyHandle, CURLOPT_PRIVATE, this); #ifdef _WIN32 gchar* g{ g_win32_get_package_installation_directory_of_module(NULL) }; if (g) { std::string cert_path{ Glib::build_filename(g, "curl-ca-bundle.crt") }; curl_easy_setopt(m_EasyHandle, CURLOPT_CAINFO, cert_path.c_str()); g_free(g); } #endif // _WIN32 if (!url.empty()) set_url(url); if (share) set_share_handle(share); } Curler::~Curler() { curl_easy_cleanup(m_EasyHandle); } void Curler::set_url(std::string url) { m_Url = std::move(url); curl_easy_setopt(m_EasyHandle, CURLOPT_URL, m_Url.c_str()); } void Curler::set_follow_location(const bool n) const { curl_easy_setopt(m_EasyHandle, CURLOPT_FOLLOWLOCATION, n); } void Curler::set_referer(const std::string& url) const { curl_easy_setopt(m_EasyHandle, CURLOPT_REFERER, url.c_str()); } void Curler::set_http_auth(const std::string& u, const std::string& p) const { if (!u.empty()) { curl_easy_setopt(m_EasyHandle, CURLOPT_USERNAME, u.c_str()); curl_easy_setopt(m_EasyHandle, CURLOPT_PASSWORD, p.c_str()); } } void Curler::set_cookie_jar(const std::string& path) const { curl_easy_setopt(m_EasyHandle, CURLOPT_COOKIEJAR, path.c_str()); } void Curler::set_cookie_file(const std::string& path) const { curl_easy_setopt(m_EasyHandle, CURLOPT_COOKIEFILE, path.c_str()); } void Curler::set_post_fields(const std::string& fields) const { curl_easy_setopt(m_EasyHandle, CURLOPT_POSTFIELDSIZE, fields.length()); curl_easy_setopt(m_EasyHandle, CURLOPT_POSTFIELDS, fields.c_str()); } void Curler::set_share_handle(CURLSH* s) const { curl_easy_setopt(m_EasyHandle, CURLOPT_SHARE, s); } std::string Curler::escape(const std::string& str) const { std::string r; char* s{ curl_easy_escape(m_EasyHandle, str.c_str(), str.length()) }; if (s) { r = s; curl_free(s); } return r; } bool Curler::perform() { m_Cancel->reset(); clear(); return curl_easy_perform(m_EasyHandle) == CURLE_OK; } void Curler::get_progress(curl_off_t& current, curl_off_t& total) { current = m_DownloadCurrent; total = m_DownloadTotal; } long Curler::get_response_code() const { long c; curl_easy_getinfo(m_EasyHandle, CURLINFO_RESPONSE_CODE, &c); return c; } void Curler::pause() { m_Pause = true; } void Curler::unpause() { if (m_ImageFetcher) { m_ImageFetcher->unpause_handle(this); } else { m_Pause = false; curl_easy_pause(m_EasyHandle, CURLPAUSE_CONT); } } void Curler::save_file(const std::string& path) const { std::string etag; Glib::RefPtr<Gio::File> f{ Gio::File::create_for_path(path) }; f->replace_contents(reinterpret_cast<const char*>(m_Buffer.data()), m_Buffer.size(), "", etag); } void Curler::save_file_async(const std::string& path, const Gio::SlotAsyncReady& cb) { Glib::RefPtr<Gio::File> f{ Gio::File::create_for_path(path) }; f->replace_contents_async( cb, m_Cancel, reinterpret_cast<const char*>(m_Buffer.data()), m_Buffer.size(), ""); } void Curler::save_file_finish(const Glib::RefPtr<Gio::AsyncResult>& r) { Glib::RefPtr<Gio::File> f{ Glib::RefPtr<Gio::File>::cast_dynamic(r->get_source_object_base()) }; clear(); if (f) f->replace_contents_finish(r); } <commit_msg>booru/curler: Set a more accurate user agent string<commit_after>#include "curler.h" using namespace AhoViewer::Booru; #include "imagefetcher.h" // Used for looking closer at what libcurl is doing // set it to 1 with CXXFLAGS and prepare to be spammed #ifndef VERBOSE_LIBCURL #define VERBOSE_LIBCURL 0 #endif const char* Curler::UserAgent { #if defined(__linux__) "Mozilla/5.0 (Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0" #elif defined(__APPLE__) "Mozilla/5.0 (Macintosh; Intel Mac OS X 11.4; rv:89.0) Gecko/20100101 Firefox/89.0" #elif defined(_WIN32) "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0" #else "Mozilla/5.0" #endif }; size_t Curler::write_cb(const unsigned char* ptr, size_t size, size_t nmemb, void* userp) { Curler* self{ static_cast<Curler*>(userp) }; if (self->is_cancelled()) return 0; if (self->m_DownloadTotal == 0) { curl_off_t s; curl_easy_getinfo(self->m_EasyHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &s); self->m_DownloadTotal = s; } if (self->m_Pause) return CURL_WRITEFUNC_PAUSE; size_t len{ size * nmemb }; self->m_Buffer.insert(self->m_Buffer.end(), ptr, ptr + len); self->m_SignalWrite(ptr, len); self->m_DownloadCurrent = self->m_Buffer.size(); if (!self->is_cancelled()) self->m_SignalProgress(); return len; } int Curler::progress_cb(void* userp, curl_off_t, curl_off_t, curl_off_t, curl_off_t) { Curler* self{ static_cast<Curler*>(userp) }; return self->is_cancelled(); } Curler::Curler(const std::string& url, CURLSH* share) : m_EasyHandle(curl_easy_init()), m_Cancel(Gio::Cancellable::create()) { curl_easy_setopt(m_EasyHandle, CURLOPT_USERAGENT, UserAgent); curl_easy_setopt(m_EasyHandle, CURLOPT_WRITEFUNCTION, &Curler::write_cb); curl_easy_setopt(m_EasyHandle, CURLOPT_WRITEDATA, this); curl_easy_setopt(m_EasyHandle, CURLOPT_XFERINFOFUNCTION, &Curler::progress_cb); curl_easy_setopt(m_EasyHandle, CURLOPT_XFERINFODATA, this); curl_easy_setopt(m_EasyHandle, CURLOPT_NOPROGRESS, 0); curl_easy_setopt(m_EasyHandle, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(m_EasyHandle, CURLOPT_MAXREDIRS, 5); curl_easy_setopt(m_EasyHandle, CURLOPT_VERBOSE, VERBOSE_LIBCURL); curl_easy_setopt(m_EasyHandle, CURLOPT_CONNECTTIMEOUT, 60); curl_easy_setopt(m_EasyHandle, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(m_EasyHandle, CURLOPT_PRIVATE, this); #ifdef _WIN32 gchar* g{ g_win32_get_package_installation_directory_of_module(NULL) }; if (g) { std::string cert_path{ Glib::build_filename(g, "curl-ca-bundle.crt") }; curl_easy_setopt(m_EasyHandle, CURLOPT_CAINFO, cert_path.c_str()); g_free(g); } #endif // _WIN32 if (!url.empty()) set_url(url); if (share) set_share_handle(share); } Curler::~Curler() { curl_easy_cleanup(m_EasyHandle); } void Curler::set_url(std::string url) { m_Url = std::move(url); curl_easy_setopt(m_EasyHandle, CURLOPT_URL, m_Url.c_str()); } void Curler::set_follow_location(const bool n) const { curl_easy_setopt(m_EasyHandle, CURLOPT_FOLLOWLOCATION, n); } void Curler::set_referer(const std::string& url) const { curl_easy_setopt(m_EasyHandle, CURLOPT_REFERER, url.c_str()); } void Curler::set_http_auth(const std::string& u, const std::string& p) const { if (!u.empty()) { curl_easy_setopt(m_EasyHandle, CURLOPT_USERNAME, u.c_str()); curl_easy_setopt(m_EasyHandle, CURLOPT_PASSWORD, p.c_str()); } } void Curler::set_cookie_jar(const std::string& path) const { curl_easy_setopt(m_EasyHandle, CURLOPT_COOKIEJAR, path.c_str()); } void Curler::set_cookie_file(const std::string& path) const { curl_easy_setopt(m_EasyHandle, CURLOPT_COOKIEFILE, path.c_str()); } void Curler::set_post_fields(const std::string& fields) const { curl_easy_setopt(m_EasyHandle, CURLOPT_POSTFIELDSIZE, fields.length()); curl_easy_setopt(m_EasyHandle, CURLOPT_POSTFIELDS, fields.c_str()); } void Curler::set_share_handle(CURLSH* s) const { curl_easy_setopt(m_EasyHandle, CURLOPT_SHARE, s); } std::string Curler::escape(const std::string& str) const { std::string r; char* s{ curl_easy_escape(m_EasyHandle, str.c_str(), str.length()) }; if (s) { r = s; curl_free(s); } return r; } bool Curler::perform() { m_Cancel->reset(); clear(); return curl_easy_perform(m_EasyHandle) == CURLE_OK; } void Curler::get_progress(curl_off_t& current, curl_off_t& total) { current = m_DownloadCurrent; total = m_DownloadTotal; } long Curler::get_response_code() const { long c; curl_easy_getinfo(m_EasyHandle, CURLINFO_RESPONSE_CODE, &c); return c; } void Curler::pause() { m_Pause = true; } void Curler::unpause() { if (m_ImageFetcher) { m_ImageFetcher->unpause_handle(this); } else { m_Pause = false; curl_easy_pause(m_EasyHandle, CURLPAUSE_CONT); } } void Curler::save_file(const std::string& path) const { std::string etag; Glib::RefPtr<Gio::File> f{ Gio::File::create_for_path(path) }; f->replace_contents(reinterpret_cast<const char*>(m_Buffer.data()), m_Buffer.size(), "", etag); } void Curler::save_file_async(const std::string& path, const Gio::SlotAsyncReady& cb) { Glib::RefPtr<Gio::File> f{ Gio::File::create_for_path(path) }; f->replace_contents_async( cb, m_Cancel, reinterpret_cast<const char*>(m_Buffer.data()), m_Buffer.size(), ""); } void Curler::save_file_finish(const Glib::RefPtr<Gio::AsyncResult>& r) { Glib::RefPtr<Gio::File> f{ Glib::RefPtr<Gio::File>::cast_dynamic(r->get_source_object_base()) }; clear(); if (f) f->replace_contents_finish(r); } <|endoftext|>
<commit_before>/* systemtray.cpp - Kopete Tray Dock Icon Copyright (c) 2002 by Nick Betcher <nbetcher@kde.org> Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org> Copyright (c) 2003-2004 by Olivier Goffart <ogoffart@kde.org> Kopete (c) 2002-2007 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "systemtray.h" #include <qtimer.h> #include <qregexp.h> #include <QMouseEvent> #include <QPixmap> #include <QEvent> #include <kaboutdata.h> #include <kactioncollection.h> #include <kaction.h> #include <kmenu.h> #include <klocale.h> #include <kdebug.h> #include <kiconloader.h> #include "kopeteuiglobal.h" #include "kopetechatsessionmanager.h" #include "kopetebehaviorsettings.h" #include "kopetemetacontact.h" #include "kopeteaccount.h" #include "kopeteaccountmanager.h" #include "kopetecontact.h" #include "kopetewindow.h" KopeteSystemTray* KopeteSystemTray::s_systemTray = 0; KopeteSystemTray* KopeteSystemTray::systemTray( QWidget *parent ) { if( !s_systemTray ) s_systemTray = new KopeteSystemTray( parent ); return s_systemTray; } KopeteSystemTray::KopeteSystemTray(QWidget* parent) : KAnimatedSystemTrayIcon(parent) , mMovie(0) { kDebug(14010) ; setToolTip(KGlobal::mainComponent().aboutData()->shortDescription()); mIsBlinkIcon = false; mIsBlinking = false; mBlinkTimer = new QTimer(this); mBlinkTimer->setObjectName("mBlinkTimer"); mKopeteIcon = loadIcon("kopete"); // Hack which allow us to disable window restoring or hiding when we should process event (BUG:157663) disconnect( this, SIGNAL(activated( QSystemTrayIcon::ActivationReason )), 0 ,0 ); connect(contextMenu(), SIGNAL(aboutToShow()), this, SLOT(slotAboutToShowMenu())); connect(mBlinkTimer, SIGNAL(timeout()), this, SLOT(slotBlink())); connect(Kopete::ChatSessionManager::self() , SIGNAL(newEvent(Kopete::MessageEvent*)), this, SLOT(slotNewEvent(Kopete::MessageEvent*))); connect(Kopete::BehaviorSettings::self(), SIGNAL(configChanged()), this, SLOT(slotConfigChanged())); connect(Kopete::AccountManager::self(), SIGNAL(accountOnlineStatusChanged(Kopete::Account *, const Kopete::OnlineStatus &, const Kopete::OnlineStatus &)), this, SLOT(slotReevaluateAccountStates())); // the slot called by default by the quit action, KSystemTray::maybeQuit(), // just closes the parent window, which is hard to distinguish in that window's closeEvent() // from a click on the window's close widget // in the quit case, we want to quit the application // in the close widget click case, we only want to hide the parent window // so instead, we make it call our general purpose quit slot on the window, which causes a window close and everything else we need // KDE4 - app will have to listen for quitSelected instead QAction *quit = actionCollection()->action( "file_quit" ); quit->disconnect(); KopeteWindow *myParent = static_cast<KopeteWindow *>( parent ); connect( quit, SIGNAL( activated() ), myParent, SLOT( slotQuit() ) ); connect( this, SIGNAL( activated( QSystemTrayIcon::ActivationReason ) ), SLOT( slotActivated( QSystemTrayIcon::ActivationReason ) ) ); setIcon(mKopeteIcon); slotReevaluateAccountStates(); slotConfigChanged(); } KopeteSystemTray::~KopeteSystemTray() { kDebug(14010) ; // delete mBlinkTimer; } void KopeteSystemTray::slotAboutToShowMenu() { emit aboutToShowMenu(qobject_cast<KMenu *>(contextMenu())); } void KopeteSystemTray::slotActivated( QSystemTrayIcon::ActivationReason reason ) { bool shouldProcessEvent( reason == QSystemTrayIcon::MiddleClick || reason == QSystemTrayIcon::DoubleClick || ( reason == QSystemTrayIcon::Trigger && Kopete::BehaviorSettings::self()->trayflashNotifyLeftClickOpensMessage())); if ( isBlinking() && shouldProcessEvent ) { if ( !mEventList.isEmpty() ) mEventList.first()->apply(); } else if ( reason == QSystemTrayIcon::Trigger ) { toggleActive(); } } // void KopeteSystemTray::contextMenuAboutToShow( KMenu *me ) // { // //kDebug(14010) << "Called."; // emit aboutToShowMenu( me ); // } void KopeteSystemTray::startBlink( const QString &icon ) { startBlink( loadIcon( icon ) ); } void KopeteSystemTray::startBlink( const QIcon &icon ) { mBlinkIcon = icon; if ( mBlinkTimer->isActive() == false ) { mIsBlinkIcon = true; mIsBlinking = true; mBlinkTimer->setSingleShot( false ); mBlinkTimer->start( 1000 ); } else { mBlinkTimer->stop(); mIsBlinkIcon = true; mIsBlinking = true; mBlinkTimer->setSingleShot( false ); mBlinkTimer->start( 1000 ); } } void KopeteSystemTray::startBlink() { if ( !mMovie ) mMovie = KIconLoader::global()->loadMovie( QLatin1String( "newmessage" ), KIconLoader::Panel ); // KIconLoader already checked isValid() if ( !mMovie) return; if (!movie()) setMovie( mMovie ); startMovie(); } void KopeteSystemTray::stopBlink() { if ( mMovie ) kDebug( 14010 ) << "stopping movie."; else if ( mBlinkTimer->isActive() ) mBlinkTimer->stop(); if ( mMovie ) mMovie->setPaused(true); mIsBlinkIcon = false; mIsBlinking = false; //setPixmap( mKopeteIcon ); slotReevaluateAccountStates(); } void KopeteSystemTray::slotBlink() { setIcon( mIsBlinkIcon ? mKopeteIcon : mBlinkIcon ); mIsBlinkIcon = !mIsBlinkIcon; } void KopeteSystemTray::slotNewEvent( Kopete::MessageEvent *event ) { if( Kopete::BehaviorSettings::self()->useMessageStack() ) mEventList.prepend( event ); else mEventList.append( event ); connect(event, SIGNAL(done(Kopete::MessageEvent*)), this, SLOT(slotEventDone(Kopete::MessageEvent*))); // tray animation if ( Kopete::BehaviorSettings::self()->trayflashNotify() ) startBlink(); } void KopeteSystemTray::slotEventDone(Kopete::MessageEvent *event) { mEventList.removeAll(event); if(mEventList.isEmpty()) stopBlink(); } void KopeteSystemTray::slotConfigChanged() { // kDebug(14010) << "called."; if ( Kopete::BehaviorSettings::self()->showSystemTray() ) show(); else hide(); // for users without kicker or a similar docking app } void KopeteSystemTray::slotReevaluateAccountStates() { // If there is a pending message, we don't need to refresh the system tray now. // This function will even be called when the animation will stop. if ( mIsBlinking ) return; //kDebug(14010) ; bool bOnline = false; bool bAway = false; bool bOffline = false; Kopete::Contact *c = 0; QListIterator<Kopete::Account *> it(Kopete::AccountManager::self()->accounts()); while ( it.hasNext() ) { c = it.next()->myself(); if (!c) continue; if (c->onlineStatus().status() == Kopete::OnlineStatus::Online) { bOnline = true; // at least one contact is online } else if (c->onlineStatus().status() == Kopete::OnlineStatus::Away || c->onlineStatus().status() == Kopete::OnlineStatus::Invisible) { bAway = true; // at least one contact is away or invisible } else // this account must be offline (or unknown, which I don't know how to handle) { bOffline = true; } } if (!bOnline && !bAway && !bOffline) // special case, no accounts defined (yet) bOffline = true; if (bAway) { if (!bOnline && !bOffline) // none online and none offline -> all away setIcon(loadIcon("kopete_all_away")); else setIcon(loadIcon("kopete_some_away")); } else if(bOnline) { /*if(bOffline) // at least one offline and at least one online -> some accounts online setIcon(loadIcon("kopete_some_online")); else*/ // none offline and none away -> all online setIcon(mKopeteIcon); } else // none away and none online -> all offline { //kDebug(14010) << "All Accounts offline!"; setIcon(loadIcon("kopete_offline")); } } QString KopeteSystemTray::squashMessage( const Kopete::Message& msg ) { QString msgText = msg.parsedBody(); QRegExp rx( "(<a.*>((http://)?(.+))</a>)" ); rx.setMinimal( true ); if ( rx.indexIn( msgText ) == -1 ) { // no URLs in text, just pick the first 30 chars of // the parsed text if necessary. We used parsed text // so that things like "<knuff>" show correctly // Escape it after snipping it to not snip entities msgText =msg.plainBody() ; if( msgText.length() > 30 ) msgText = msgText.left( 30 ) + QLatin1String( " ..." ); msgText=Kopete::Message::escape(msgText); } else { QString plainText = msg.plainBody(); if ( plainText.length() > 30 ) { QString fullUrl = rx.cap( 2 ); QString shorterUrl; if ( fullUrl.length() > 30 ) { QString urlWithoutProtocol = rx.cap( 4 ); shorterUrl = urlWithoutProtocol.left( 27 ) + QLatin1String( "... " ); } else { shorterUrl = fullUrl.left( 27 ) + QLatin1String( "... " ); } // remove message text msgText = QLatin1String( "... " ) + rx.cap( 1 ) + QLatin1String( " ..." ); // find last occurrence of URL (the one inside the <a> tag) int revUrlOffset = msgText.lastIndexOf( fullUrl ); msgText.replace( revUrlOffset, fullUrl.length(), shorterUrl ); } } return msgText; } #include "systemtray.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>Autogenerate systray icon from the kopete icon in the theme instead of using the now outdated icons from KDE 3.5. Grayed for offline, overlays in the bottom right corner for invisible and away. BUG: 163793<commit_after>/* systemtray.cpp - Kopete Tray Dock Icon Copyright (c) 2002 by Nick Betcher <nbetcher@kde.org> Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org> Copyright (c) 2003-2004 by Olivier Goffart <ogoffart@kde.org> Kopete (c) 2002-2007 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "systemtray.h" #include <qtimer.h> #include <qregexp.h> #include <QMouseEvent> #include <QPixmap> #include <QEvent> #include <QPainter> #include <kaboutdata.h> #include <kactioncollection.h> #include <kaction.h> #include <kmenu.h> #include <klocale.h> #include <kdebug.h> #include <kiconloader.h> #include "kopeteuiglobal.h" #include "kopetechatsessionmanager.h" #include "kopetebehaviorsettings.h" #include "kopetemetacontact.h" #include "kopeteaccount.h" #include "kopeteaccountmanager.h" #include "kopetecontact.h" #include "kopetewindow.h" #include <kiconeffect.h> KopeteSystemTray* KopeteSystemTray::s_systemTray = 0; KopeteSystemTray* KopeteSystemTray::systemTray( QWidget *parent ) { if( !s_systemTray ) s_systemTray = new KopeteSystemTray( parent ); return s_systemTray; } KopeteSystemTray::KopeteSystemTray(QWidget* parent) : KAnimatedSystemTrayIcon(parent) , mMovie(0) { kDebug(14010) ; setToolTip(KGlobal::mainComponent().aboutData()->shortDescription()); mIsBlinkIcon = false; mIsBlinking = false; mBlinkTimer = new QTimer(this); mBlinkTimer->setObjectName("mBlinkTimer"); mKopeteIcon = loadIcon("kopete"); // Hack which allow us to disable window restoring or hiding when we should process event (BUG:157663) disconnect( this, SIGNAL(activated( QSystemTrayIcon::ActivationReason )), 0 ,0 ); connect(contextMenu(), SIGNAL(aboutToShow()), this, SLOT(slotAboutToShowMenu())); connect(mBlinkTimer, SIGNAL(timeout()), this, SLOT(slotBlink())); connect(Kopete::ChatSessionManager::self() , SIGNAL(newEvent(Kopete::MessageEvent*)), this, SLOT(slotNewEvent(Kopete::MessageEvent*))); connect(Kopete::BehaviorSettings::self(), SIGNAL(configChanged()), this, SLOT(slotConfigChanged())); connect(Kopete::AccountManager::self(), SIGNAL(accountOnlineStatusChanged(Kopete::Account *, const Kopete::OnlineStatus &, const Kopete::OnlineStatus &)), this, SLOT(slotReevaluateAccountStates())); // the slot called by default by the quit action, KSystemTray::maybeQuit(), // just closes the parent window, which is hard to distinguish in that window's closeEvent() // from a click on the window's close widget // in the quit case, we want to quit the application // in the close widget click case, we only want to hide the parent window // so instead, we make it call our general purpose quit slot on the window, which causes a window close and everything else we need // KDE4 - app will have to listen for quitSelected instead QAction *quit = actionCollection()->action( "file_quit" ); quit->disconnect(); KopeteWindow *myParent = static_cast<KopeteWindow *>( parent ); connect( quit, SIGNAL( activated() ), myParent, SLOT( slotQuit() ) ); connect( this, SIGNAL( activated( QSystemTrayIcon::ActivationReason ) ), SLOT( slotActivated( QSystemTrayIcon::ActivationReason ) ) ); setIcon(mKopeteIcon); slotReevaluateAccountStates(); slotConfigChanged(); } KopeteSystemTray::~KopeteSystemTray() { kDebug(14010) ; // delete mBlinkTimer; } void KopeteSystemTray::slotAboutToShowMenu() { emit aboutToShowMenu(qobject_cast<KMenu *>(contextMenu())); } void KopeteSystemTray::slotActivated( QSystemTrayIcon::ActivationReason reason ) { bool shouldProcessEvent( reason == QSystemTrayIcon::MiddleClick || reason == QSystemTrayIcon::DoubleClick || ( reason == QSystemTrayIcon::Trigger && Kopete::BehaviorSettings::self()->trayflashNotifyLeftClickOpensMessage())); if ( isBlinking() && shouldProcessEvent ) { if ( !mEventList.isEmpty() ) mEventList.first()->apply(); } else if ( reason == QSystemTrayIcon::Trigger ) { toggleActive(); } } // void KopeteSystemTray::contextMenuAboutToShow( KMenu *me ) // { // //kDebug(14010) << "Called."; // emit aboutToShowMenu( me ); // } void KopeteSystemTray::startBlink( const QString &icon ) { startBlink( loadIcon( icon ) ); } void KopeteSystemTray::startBlink( const QIcon &icon ) { mBlinkIcon = icon; if ( mBlinkTimer->isActive() == false ) { mIsBlinkIcon = true; mIsBlinking = true; mBlinkTimer->setSingleShot( false ); mBlinkTimer->start( 1000 ); } else { mBlinkTimer->stop(); mIsBlinkIcon = true; mIsBlinking = true; mBlinkTimer->setSingleShot( false ); mBlinkTimer->start( 1000 ); } } void KopeteSystemTray::startBlink() { if ( !mMovie ) mMovie = KIconLoader::global()->loadMovie( QLatin1String( "newmessage" ), KIconLoader::Panel ); // KIconLoader already checked isValid() if ( !mMovie) return; if (!movie()) setMovie( mMovie ); startMovie(); } void KopeteSystemTray::stopBlink() { if ( mMovie ) kDebug( 14010 ) << "stopping movie."; else if ( mBlinkTimer->isActive() ) mBlinkTimer->stop(); if ( mMovie ) mMovie->setPaused(true); mIsBlinkIcon = false; mIsBlinking = false; //setPixmap( mKopeteIcon ); slotReevaluateAccountStates(); } void KopeteSystemTray::slotBlink() { setIcon( mIsBlinkIcon ? mKopeteIcon : mBlinkIcon ); mIsBlinkIcon = !mIsBlinkIcon; } void KopeteSystemTray::slotNewEvent( Kopete::MessageEvent *event ) { if( Kopete::BehaviorSettings::self()->useMessageStack() ) mEventList.prepend( event ); else mEventList.append( event ); connect(event, SIGNAL(done(Kopete::MessageEvent*)), this, SLOT(slotEventDone(Kopete::MessageEvent*))); // tray animation if ( Kopete::BehaviorSettings::self()->trayflashNotify() ) startBlink(); } void KopeteSystemTray::slotEventDone(Kopete::MessageEvent *event) { mEventList.removeAll(event); if(mEventList.isEmpty()) stopBlink(); } void KopeteSystemTray::slotConfigChanged() { // kDebug(14010) << "called."; if ( Kopete::BehaviorSettings::self()->showSystemTray() ) show(); else hide(); // for users without kicker or a similar docking app } void KopeteSystemTray::slotReevaluateAccountStates() { // If there is a pending message, we don't need to refresh the system tray now. // This function will even be called when the animation will stop. if ( mIsBlinking ) return; Kopete::OnlineStatus highestStatus; foreach ( Kopete::Account *account, Kopete::AccountManager::self()->accounts()) { if ( account->myself() && account->myself()->onlineStatus() > highestStatus ) { highestStatus = account->myself()->onlineStatus(); } } switch ( highestStatus.status() ) { case Kopete::OnlineStatus::Unknown: case Kopete::OnlineStatus::Offline: case Kopete::OnlineStatus::Connecting: { QImage offlineIcon = mKopeteIcon.pixmap(22,22).toImage(); KIconEffect::toGray( offlineIcon, 0.85 ); setIcon( QPixmap::fromImage( offlineIcon ) ); break; } case Kopete::OnlineStatus::Invisible: { QPixmap statusOverlay = loadIcon("user-invisible").pixmap(11,11); QPixmap statusIcon = mKopeteIcon.pixmap(22,22); if (!statusIcon.isNull() && !statusOverlay.isNull()) { QPainter painter(&statusIcon); painter.drawPixmap(QPoint(11,11), statusOverlay); } setIcon( statusIcon ); break; } case Kopete::OnlineStatus::Away: { QPixmap statusOverlay = loadIcon("user-away").pixmap(11,11); QPixmap statusIcon = mKopeteIcon.pixmap(22,22); if (!statusIcon.isNull() && !statusOverlay.isNull()) { QPainter painter(&statusIcon); painter.drawPixmap(QPoint(11,11), statusOverlay); } setIcon( statusIcon ); break; } case Kopete::OnlineStatus::Online: setIcon( mKopeteIcon ); break; } } QString KopeteSystemTray::squashMessage( const Kopete::Message& msg ) { QString msgText = msg.parsedBody(); QRegExp rx( "(<a.*>((http://)?(.+))</a>)" ); rx.setMinimal( true ); if ( rx.indexIn( msgText ) == -1 ) { // no URLs in text, just pick the first 30 chars of // the parsed text if necessary. We used parsed text // so that things like "<knuff>" show correctly // Escape it after snipping it to not snip entities msgText =msg.plainBody() ; if( msgText.length() > 30 ) msgText = msgText.left( 30 ) + QLatin1String( " ..." ); msgText=Kopete::Message::escape(msgText); } else { QString plainText = msg.plainBody(); if ( plainText.length() > 30 ) { QString fullUrl = rx.cap( 2 ); QString shorterUrl; if ( fullUrl.length() > 30 ) { QString urlWithoutProtocol = rx.cap( 4 ); shorterUrl = urlWithoutProtocol.left( 27 ) + QLatin1String( "... " ); } else { shorterUrl = fullUrl.left( 27 ) + QLatin1String( "... " ); } // remove message text msgText = QLatin1String( "... " ) + rx.cap( 1 ) + QLatin1String( " ..." ); // find last occurrence of URL (the one inside the <a> tag) int revUrlOffset = msgText.lastIndexOf( fullUrl ); msgText.replace( revUrlOffset, fullUrl.length(), shorterUrl ); } } return msgText; } #include "systemtray.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>/**************************************************************************** * * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include <QElapsedTimer> #include <cmath> #include "MultiVehicleManager.h" #include "FirmwarePlugin.h" #include "MAVLinkProtocol.h" #include "FollowMe.h" #include "Vehicle.h" #include "PositionManager.h" #include "SettingsManager.h" #include "AppSettings.h" QGC_LOGGING_CATEGORY(FollowMeLog, "FollowMeLog") FollowMe::FollowMe(QGCApplication* app, QGCToolbox* toolbox) : QGCTool(app, toolbox) { _gcsMotionReportTimer.setSingleShot(false); } void FollowMe::setToolbox(QGCToolbox* toolbox) { QGCTool::setToolbox(toolbox); connect(&_gcsMotionReportTimer, &QTimer::timeout, this, &FollowMe::_sendGCSMotionReport); connect(toolbox->settingsManager()->appSettings()->followTarget(), &Fact::rawValueChanged, this, &FollowMe::_settingsChanged); _settingsChanged(); } void FollowMe::_settingsChanged() { _currentMode = _toolbox->settingsManager()->appSettings()->followTarget()->rawValue().toUInt(); switch (_currentMode) { case MODE_NEVER: disconnect(_toolbox->multiVehicleManager(), &MultiVehicleManager::vehicleAdded, this, &FollowMe::_vehicleAdded); disconnect(_toolbox->multiVehicleManager(), &MultiVehicleManager::vehicleRemoved, this, &FollowMe::_vehicleRemoved); _disableFollowSend(); break; case MODE_ALWAYS: connect(_toolbox->multiVehicleManager(), &MultiVehicleManager::vehicleAdded, this, &FollowMe::_vehicleAdded); connect(_toolbox->multiVehicleManager(), &MultiVehicleManager::vehicleRemoved, this, &FollowMe::_vehicleRemoved); _enableFollowSend(); break; case MODE_FOLLOWME: connect(_toolbox->multiVehicleManager(), &MultiVehicleManager::vehicleAdded, this, &FollowMe::_vehicleAdded); connect(_toolbox->multiVehicleManager(), &MultiVehicleManager::vehicleRemoved, this, &FollowMe::_vehicleRemoved); _enableIfVehicleInFollow(); break; } } void FollowMe::_enableFollowSend() { if (!_gcsMotionReportTimer.isActive()) { _gcsMotionReportTimer.setInterval(qMin(_toolbox->qgcPositionManager()->updateInterval(), 250)); _gcsMotionReportTimer.start(); } } void FollowMe::_disableFollowSend() { if (_gcsMotionReportTimer.isActive()) { _gcsMotionReportTimer.stop(); } } void FollowMe::_sendGCSMotionReport() { QGeoPositionInfo geoPositionInfo = _toolbox->qgcPositionManager()->geoPositionInfo(); QGeoCoordinate gcsCoordinate = geoPositionInfo.coordinate(); if (!geoPositionInfo.isValid()) { return; } // First check to see if any vehicles need follow me updates bool needFollowMe = false; if (_currentMode == MODE_ALWAYS) { needFollowMe = true; } else if (_currentMode == MODE_FOLLOWME) { QmlObjectListModel* vehicles = _toolbox->multiVehicleManager()->vehicles(); for (int i=0; i<vehicles->count(); i++) { Vehicle* vehicle = vehicles->value<Vehicle*>(i); if (_isFollowFlightMode(vehicle, vehicle->flightMode())) { needFollowMe = true; } } } if (!needFollowMe) { return; } GCSMotionReport motionReport = {}; uint8_t estimatation_capabilities = 0; // get the current location coordinates motionReport.lat_int = static_cast<int>(gcsCoordinate.latitude() * 1e7); motionReport.lon_int = static_cast<int>(gcsCoordinate.longitude() * 1e7); motionReport.altMetersAMSL = gcsCoordinate.altitude(); estimatation_capabilities |= (1 << POS); if (geoPositionInfo.hasAttribute(QGeoPositionInfo::Direction) == true) { estimatation_capabilities |= (1 << HEADING); motionReport.headingDegrees = geoPositionInfo.attribute(QGeoPositionInfo::Direction); } // get the current eph and epv if (geoPositionInfo.hasAttribute(QGeoPositionInfo::HorizontalAccuracy)) { motionReport.pos_std_dev[0] = motionReport.pos_std_dev[1] = geoPositionInfo.attribute(QGeoPositionInfo::HorizontalAccuracy); } if (geoPositionInfo.hasAttribute(QGeoPositionInfo::VerticalAccuracy)) { motionReport.pos_std_dev[2] = geoPositionInfo.attribute(QGeoPositionInfo::VerticalAccuracy); } // calculate z velocity if it's available if (geoPositionInfo.hasAttribute(QGeoPositionInfo::VerticalSpeed)) { motionReport.vzMetersPerSec = geoPositionInfo.attribute(QGeoPositionInfo::VerticalSpeed); } // calculate x,y velocity if it's available if (geoPositionInfo.hasAttribute(QGeoPositionInfo::Direction) && geoPositionInfo.hasAttribute(QGeoPositionInfo::GroundSpeed) == true) { estimatation_capabilities |= (1 << VEL); qreal direction = _degreesToRadian(geoPositionInfo.attribute(QGeoPositionInfo::Direction)); qreal velocity = geoPositionInfo.attribute(QGeoPositionInfo::GroundSpeed); motionReport.vxMetersPerSec = cos(direction)*velocity; motionReport.vyMetersPerSec = sin(direction)*velocity; } else { motionReport.vxMetersPerSec = 0; motionReport.vyMetersPerSec = 0; } QmlObjectListModel* vehicles = _toolbox->multiVehicleManager()->vehicles(); for (int i=0; i<vehicles->count(); i++) { Vehicle* vehicle = vehicles->value<Vehicle*>(i); if (_isFollowFlightMode(vehicle, vehicle->flightMode())) { qCDebug(FollowMeLog) << "sendGCSMotionReport latInt:lonInt:altMetersAMSL" << motionReport.lat_int << motionReport.lon_int << motionReport.altMetersAMSL; vehicle->firmwarePlugin()->sendGCSMotionReport(vehicle, motionReport, estimatation_capabilities); } } } double FollowMe::_degreesToRadian(double deg) { return deg * M_PI / 180.0; } void FollowMe::_vehicleAdded(Vehicle* vehicle) { connect(vehicle, &Vehicle::flightModeChanged, this, &FollowMe::_enableIfVehicleInFollow); _enableIfVehicleInFollow(); } void FollowMe::_vehicleRemoved(Vehicle* vehicle) { disconnect(vehicle, &Vehicle::flightModeChanged, this, &FollowMe::_enableIfVehicleInFollow); _enableIfVehicleInFollow(); } void FollowMe::_enableIfVehicleInFollow(void) { if (_currentMode == MODE_ALWAYS) { // System always enabled return; } // Any vehicle in follow mode will enable the system QmlObjectListModel* vehicles = _toolbox->multiVehicleManager()->vehicles(); for (int i=0; i< vehicles->count(); i++) { Vehicle* vehicle = vehicles->value<Vehicle*>(i); if (_isFollowFlightMode(vehicle, vehicle->flightMode())) { _enableFollowSend(); return; } } _disableFollowSend(); } bool FollowMe::_isFollowFlightMode (Vehicle* vehicle, const QString& flightMode) { return flightMode.compare(vehicle->followFlightMode()) == 0; } <commit_msg>FollowMe: Fix bug preventing sending GCS motion report when setting is always.<commit_after>/**************************************************************************** * * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include <QElapsedTimer> #include <cmath> #include "MultiVehicleManager.h" #include "FirmwarePlugin.h" #include "MAVLinkProtocol.h" #include "FollowMe.h" #include "Vehicle.h" #include "PositionManager.h" #include "SettingsManager.h" #include "AppSettings.h" QGC_LOGGING_CATEGORY(FollowMeLog, "FollowMeLog") FollowMe::FollowMe(QGCApplication* app, QGCToolbox* toolbox) : QGCTool(app, toolbox) { _gcsMotionReportTimer.setSingleShot(false); } void FollowMe::setToolbox(QGCToolbox* toolbox) { QGCTool::setToolbox(toolbox); connect(&_gcsMotionReportTimer, &QTimer::timeout, this, &FollowMe::_sendGCSMotionReport); connect(toolbox->settingsManager()->appSettings()->followTarget(), &Fact::rawValueChanged, this, &FollowMe::_settingsChanged); _settingsChanged(); } void FollowMe::_settingsChanged() { _currentMode = _toolbox->settingsManager()->appSettings()->followTarget()->rawValue().toUInt(); switch (_currentMode) { case MODE_NEVER: disconnect(_toolbox->multiVehicleManager(), &MultiVehicleManager::vehicleAdded, this, &FollowMe::_vehicleAdded); disconnect(_toolbox->multiVehicleManager(), &MultiVehicleManager::vehicleRemoved, this, &FollowMe::_vehicleRemoved); _disableFollowSend(); break; case MODE_ALWAYS: connect(_toolbox->multiVehicleManager(), &MultiVehicleManager::vehicleAdded, this, &FollowMe::_vehicleAdded); connect(_toolbox->multiVehicleManager(), &MultiVehicleManager::vehicleRemoved, this, &FollowMe::_vehicleRemoved); _enableFollowSend(); break; case MODE_FOLLOWME: connect(_toolbox->multiVehicleManager(), &MultiVehicleManager::vehicleAdded, this, &FollowMe::_vehicleAdded); connect(_toolbox->multiVehicleManager(), &MultiVehicleManager::vehicleRemoved, this, &FollowMe::_vehicleRemoved); _enableIfVehicleInFollow(); break; } } void FollowMe::_enableFollowSend() { if (!_gcsMotionReportTimer.isActive()) { _gcsMotionReportTimer.setInterval(qMin(_toolbox->qgcPositionManager()->updateInterval(), 250)); _gcsMotionReportTimer.start(); } } void FollowMe::_disableFollowSend() { if (_gcsMotionReportTimer.isActive()) { _gcsMotionReportTimer.stop(); } } void FollowMe::_sendGCSMotionReport() { QGeoPositionInfo geoPositionInfo = _toolbox->qgcPositionManager()->geoPositionInfo(); QGeoCoordinate gcsCoordinate = geoPositionInfo.coordinate(); if (!geoPositionInfo.isValid()) { return; } // First check to see if any vehicles need follow me updates bool needFollowMe = false; if (_currentMode == MODE_ALWAYS) { needFollowMe = true; } else if (_currentMode == MODE_FOLLOWME) { QmlObjectListModel* vehicles = _toolbox->multiVehicleManager()->vehicles(); for (int i=0; i<vehicles->count(); i++) { Vehicle* vehicle = vehicles->value<Vehicle*>(i); if (_isFollowFlightMode(vehicle, vehicle->flightMode())) { needFollowMe = true; } } } if (!needFollowMe) { return; } GCSMotionReport motionReport = {}; uint8_t estimatation_capabilities = 0; // get the current location coordinates motionReport.lat_int = static_cast<int>(gcsCoordinate.latitude() * 1e7); motionReport.lon_int = static_cast<int>(gcsCoordinate.longitude() * 1e7); motionReport.altMetersAMSL = gcsCoordinate.altitude(); estimatation_capabilities |= (1 << POS); if (geoPositionInfo.hasAttribute(QGeoPositionInfo::Direction) == true) { estimatation_capabilities |= (1 << HEADING); motionReport.headingDegrees = geoPositionInfo.attribute(QGeoPositionInfo::Direction); } // get the current eph and epv if (geoPositionInfo.hasAttribute(QGeoPositionInfo::HorizontalAccuracy)) { motionReport.pos_std_dev[0] = motionReport.pos_std_dev[1] = geoPositionInfo.attribute(QGeoPositionInfo::HorizontalAccuracy); } if (geoPositionInfo.hasAttribute(QGeoPositionInfo::VerticalAccuracy)) { motionReport.pos_std_dev[2] = geoPositionInfo.attribute(QGeoPositionInfo::VerticalAccuracy); } // calculate z velocity if it's available if (geoPositionInfo.hasAttribute(QGeoPositionInfo::VerticalSpeed)) { motionReport.vzMetersPerSec = geoPositionInfo.attribute(QGeoPositionInfo::VerticalSpeed); } // calculate x,y velocity if it's available if (geoPositionInfo.hasAttribute(QGeoPositionInfo::Direction) && geoPositionInfo.hasAttribute(QGeoPositionInfo::GroundSpeed) == true) { estimatation_capabilities |= (1 << VEL); qreal direction = _degreesToRadian(geoPositionInfo.attribute(QGeoPositionInfo::Direction)); qreal velocity = geoPositionInfo.attribute(QGeoPositionInfo::GroundSpeed); motionReport.vxMetersPerSec = cos(direction)*velocity; motionReport.vyMetersPerSec = sin(direction)*velocity; } else { motionReport.vxMetersPerSec = 0; motionReport.vyMetersPerSec = 0; } QmlObjectListModel* vehicles = _toolbox->multiVehicleManager()->vehicles(); for (int i=0; i<vehicles->count(); i++) { Vehicle* vehicle = vehicles->value<Vehicle*>(i); if (_currentMode == MODE_ALWAYS || _isFollowFlightMode(vehicle, vehicle->flightMode())) { qCDebug(FollowMeLog) << "sendGCSMotionReport latInt:lonInt:altMetersAMSL" << motionReport.lat_int << motionReport.lon_int << motionReport.altMetersAMSL; vehicle->firmwarePlugin()->sendGCSMotionReport(vehicle, motionReport, estimatation_capabilities); } } } double FollowMe::_degreesToRadian(double deg) { return deg * M_PI / 180.0; } void FollowMe::_vehicleAdded(Vehicle* vehicle) { connect(vehicle, &Vehicle::flightModeChanged, this, &FollowMe::_enableIfVehicleInFollow); _enableIfVehicleInFollow(); } void FollowMe::_vehicleRemoved(Vehicle* vehicle) { disconnect(vehicle, &Vehicle::flightModeChanged, this, &FollowMe::_enableIfVehicleInFollow); _enableIfVehicleInFollow(); } void FollowMe::_enableIfVehicleInFollow(void) { if (_currentMode == MODE_ALWAYS) { // System always enabled return; } // Any vehicle in follow mode will enable the system QmlObjectListModel* vehicles = _toolbox->multiVehicleManager()->vehicles(); for (int i=0; i< vehicles->count(); i++) { Vehicle* vehicle = vehicles->value<Vehicle*>(i); if (_isFollowFlightMode(vehicle, vehicle->flightMode())) { _enableFollowSend(); return; } } _disableFollowSend(); } bool FollowMe::_isFollowFlightMode (Vehicle* vehicle, const QString& flightMode) { return flightMode.compare(vehicle->followFlightMode()) == 0; } <|endoftext|>
<commit_before> #include "net.h" #include "masternodeconfig.h" #include "util.h" #include "ui_interface.h" #include <base58.h> CMasternodeConfig masternodeConfig; void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) { CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex); entries.push_back(cme); } bool CMasternodeConfig::read(std::string& strErr) { int linenumber = 1; boost::filesystem::ifstream streamConfig(GetMasternodeConfigFile()); if (!streamConfig.good()) { return true; // No masternode.conf file is OK } for(std::string line; std::getline(streamConfig, line); linenumber++) { if(line.empty()) { continue; } std::istringstream iss(line); std::string alias, ip, privKey, txHash, outputIndex; if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { iss.str(line); iss.clear(); if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { strErr = _("Could not parse masternode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\""; streamConfig.close(); return false; } } if(Params().NetworkID() == CBaseChainParams::MAIN) { if(CService(ip).GetPort() != 9999) { strErr = _("Invalid port detected in masternode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + _("(must be 9999 for mainnet)"); streamConfig.close(); return false; } } else if(CService(ip).GetPort() == 9999) { strErr = _("Invalid port detected in masternode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + _("(9999 could be used only on mainnet)"); streamConfig.close(); return false; } add(alias, ip, privKey, txHash, outputIndex); } streamConfig.close(); return true; } <commit_msg>recognize comments in masternode.conf / write initial file<commit_after> #include "net.h" #include "masternodeconfig.h" #include "util.h" #include "ui_interface.h" #include <base58.h> CMasternodeConfig masternodeConfig; void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) { CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex); entries.push_back(cme); } bool CMasternodeConfig::read(std::string& strErr) { int linenumber = 1; boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile(); boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile); if (!streamConfig.good()) { FILE* configFile = fopen(pathMasternodeConfigFile.string().c_str(), "a"); if (configFile != NULL) { std::string strHeader = "# Masternode config file\n" "# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n" "# Example: mn1 127.0.0.2:19999 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n"; fwrite(strHeader.c_str(), std::strlen(strHeader.c_str()), 1, configFile); fclose(configFile); } return true; // Nothing to read, so just return } for(std::string line; std::getline(streamConfig, line); linenumber++) { if(line.empty()) continue; std::istringstream iss(line); std::string comment, alias, ip, privKey, txHash, outputIndex; if (iss >> comment) { if(comment.at(0) == '#') continue; iss.str(line); iss.clear(); } if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { iss.str(line); iss.clear(); if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { strErr = _("Could not parse masternode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\""; streamConfig.close(); return false; } } if(Params().NetworkID() == CBaseChainParams::MAIN) { if(CService(ip).GetPort() != 9999) { strErr = _("Invalid port detected in masternode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + _("(must be 9999 for mainnet)"); streamConfig.close(); return false; } } else if(CService(ip).GetPort() == 9999) { strErr = _("Invalid port detected in masternode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + _("(9999 could be used only on mainnet)"); streamConfig.close(); return false; } add(alias, ip, privKey, txHash, outputIndex); } streamConfig.close(); return true; } <|endoftext|>
<commit_before>#include "medButton.h" #include <QtGui> class medButtonPrivate { public: QLabel * icon; }; medButton::medButton( QWidget *parent, QString resourceLocation, QString toolTip ): QWidget(parent), d(new medButtonPrivate) { d->icon = new QLabel(this); d->icon->setPixmap(QPixmap(resourceLocation)); QHBoxLayout * layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(d->icon); setToolTip(toolTip); } medButton::medButton( QWidget *parent, QPixmap pixmap, QString toolTip ): QWidget(parent),d(new medButtonPrivate) { d->icon = new QLabel(this); d->icon->setPixmap(pixmap); QHBoxLayout *layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(d->icon); setToolTip(toolTip); } medButton::~medButton( void ) { } QSize medButton::sizeHint( void ) const { return d->icon->size(); } void medButton::setIcon(QPixmap icon) { d->icon->setPixmap(icon); } void medButton::mousePressEvent( QMouseEvent *event ) { emit triggered(); } <commit_msg>Fix memory leak in medButton.<commit_after>#include "medButton.h" #include <QtGui> class medButtonPrivate { public: QLabel * icon; }; medButton::medButton( QWidget *parent, QString resourceLocation, QString toolTip ): QWidget(parent), d(new medButtonPrivate) { d->icon = new QLabel(this); d->icon->setPixmap(QPixmap(resourceLocation)); QHBoxLayout * layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(d->icon); setToolTip(toolTip); } medButton::medButton( QWidget *parent, QPixmap pixmap, QString toolTip ): QWidget(parent),d(new medButtonPrivate) { d->icon = new QLabel(this); d->icon->setPixmap(pixmap); QHBoxLayout *layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(d->icon); setToolTip(toolTip); } medButton::~medButton( void ) { delete d; } QSize medButton::sizeHint( void ) const { return d->icon->size(); } void medButton::setIcon(QPixmap icon) { d->icon->setPixmap(icon); } void medButton::mousePressEvent( QMouseEvent *event ) { emit triggered(); } <|endoftext|>
<commit_before>//================================================================================================= // Copyright (C) 2017 Olivier Mallet - All Rights Reserved //================================================================================================= #ifndef GENETICALGORITHM_HPP #define GENETICALGORITHM_HPP namespace galgo { //================================================================================================= template <typename T, int...N> class GeneticAlgorithm { static_assert(std::is_same<float,T>::value || std::is_same<double,T>::value, "variable type can only be float or double, please amend."); template <typename K, int...S> friend class Population; template <typename K, int...S> friend class Chromosome; template <typename K> using Functor = std::vector<K> (*)(const std::vector<K>&); private: Population<T,N...> pop; // population of chromosomes std::tuple<typename std::remove_reference<Parameter<T,N>>::type...> tp; // tuple of parameters std::vector<T> lowerBound; // parameter(s) lower bound std::vector<T> upperBound; // parameter(s) upper bound std::vector<T> initialSet; // initial set of parameter(s) public: // objective function functor Functor<T> Objective; // selection method functor initialized to roulette wheel selection void (*Selection)(Population<T,N...>&) = RWS; // cross-over method functor initialized to 1-point cross-over void (*CrossOver)(const Population<T,N...>&, CHR<T,N...>&, CHR<T,N...>&) = P1XO; // mutation method functor initialized to single-point mutation void (*Mutation)(CHR<T,N...>&) = SPM; // adaptation to constraint(s) method functor void (*Adaptation)(Population<T,N...>&) = nullptr; // constraint(s) functor std::vector<T> (*Constraint)(const std::vector<T>&) = nullptr; T covrate = .50; // cross-over rate T mutrate = .05; // mutation rate T SP = 1.5; // selective pressure for RSP selection method T tolerance = 0.0; // terminal condition (inactive if equal to zero) int elitpop = 1; // elit population size int matsize; // mating pool size, set to popsize by default int tntsize = 10; // tournament size int genstep = 10; // generation step for outputting results int precision = 5; // precision for outputting results // constructor GeneticAlgorithm(Functor<T> objective, int popsize, const Parameter<T,N>&...args, int nbgen, bool output = false); // run genetic algorithm void run(); // return best chromosome const CHR<T,N...>& result() const; private: int nbbit; // total number of bits per chromosome int nbgen; // number of generations int nogen = 0; // numero of generation int nbparam; // number of parameters to be estimated int popsize; // population size bool output; // control if results must be outputted // end recursion on parameters template <int I = 0> typename std::enable_if<I == sizeof...(N), void>::type init(); // recursion on parameters template <int I = 0> typename std::enable_if<I < sizeof...(N), void>::type init(); // check inputs validity bool check() const ; // print results for each new generation void print() const; }; /*-------------------------------------------------------------------------------------------------*/ // constructor template <typename T, int...N> GeneticAlgorithm<T,N...>::GeneticAlgorithm(Functor<T> objective, int popsize, const Parameter<T,N>&...args, int nbgen, bool output) { this->Objective = objective; this->popsize = popsize; this->matsize = popsize; this->tp = std::make_tuple(args...); this->nbbit = sum(N...); this->nbgen = nbgen; this->nbparam = sizeof...(N); this->output = output; } /*-------------------------------------------------------------------------------------------------*/ // end of recursion on parameters template <typename T, int...N> template <int I> inline typename std::enable_if<I == sizeof...(N), void>::type GeneticAlgorithm<T,N...>::init() {} // recursion on parameters template <typename T, int...N> template <int I> inline typename std::enable_if<I < sizeof...(N), void>::type GeneticAlgorithm<T,N...>::init() { const auto& par = std::get<I>(tp); lowerBound.push_back(par.data[0]); upperBound.push_back(par.data[1]); if (par.data.size() > 2) { initialSet.push_back(par.data[2]); } init<I + 1>(); } /*-------------------------------------------------------------------------------------------------*/ // check inputs validity template <typename T, int...N> bool GeneticAlgorithm<T,N...>::check() const { if (!initialSet.empty()) { for (int i = 0; i < nbparam; ++i) { if (initialSet[i] < lowerBound[i] || initialSet[i] > upperBound[i]) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, initial set of parameters (initialSet) cannot be outside [lowerBound,upperBound], please choose a set within these boundaries.\n"; return false; } } if (initialSet.size() != (unsigned)nbparam) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, initial set of parameters (initialSet) does not have the same dimension as the number of parameters, please adjust.\n"; return false; } } if (lowerBound.size() != upperBound.size()) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, lower bound (lowerBound) and upper bound (upperBound) must be of same dimension, please adjust.\n"; return false; } for (int i = 0; i < nbparam; ++i) { if (lowerBound[i] >= upperBound[i]) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, lower bound (lowerBound) cannot be equal or greater than upper bound (upperBound), please amend.\n"; return false; } } if (SP < 1.0 || SP > 2.0) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, selective pressure (SP) cannot be outside [1.0,2.0], please choose a real value within this interval.\n"; return false; } if (elitpop > popsize || elitpop < 0) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, elit population (elitpop) cannot outside [0,popsize], please choose an integral value within this interval.\n"; return false; } if (covrate < 0.0 || covrate > 1.0) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, cross-over rate (covrate) cannot outside [0.0,1.0], please choose a real value within this interval.\n"; return false; } if (genstep <= 0) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, generation step (genstep) cannot be <= 0, please choose an integral value > 0.\n"; return false; } return true; } /*-------------------------------------------------------------------------------------------------*/ // run genetic algorithm template <typename T, int...N> void GeneticAlgorithm<T,N...>::run() { // initialize parameters data lowerBound.clear(); upperBound.clear(); initialSet.clear(); init(); // checking inputs validity if (!check()) { return; } // setting adaptation method to default if needed if (Constraint != nullptr && Adaptation == nullptr) { Adaptation = DAC; } // initializing population pop = Population<T,N...>(*this); if (output) { std::cout << "\n Running Genetic Algorithm...\n"; std::cout << " ----------------------------\n"; } // creating population pop.creation(); // initializing best result and previous best result T bestResult = pop(0)->getTotal(); T prevBestResult = bestResult; // outputting results if (output) print(); // starting population evolution for (nogen = 1; nogen <= nbgen; ++nogen) { // evolving population pop.evolution(); // getting best current result bestResult = pop(0)->getTotal(); // outputting results if (output) print(); // checking convergence if (tolerance != 0.0) { if (fabs(bestResult - prevBestResult) < fabs(tolerance)) { break; } prevBestResult = bestResult; } } // outputting contraint value if (Constraint != nullptr) { // getting best parameter(s) constraint value(s) std::vector<T> cst = pop(0)->getConstraint(); if (output) { std::cout << "\n Constraint(s)\n"; std::cout << " -------------\n"; for (unsigned i = 0; i < cst.size(); ++i) { std::cout << " C"; if (nbparam > 1) { std::cout << std::to_string(i + 1); } std::cout << "(x) = " << std::setw(6) << std::fixed << std::setprecision(precision) << cst[i] << "\n"; } std::cout << "\n"; } } } /*-------------------------------------------------------------------------------------------------*/ // return best chromosome template <typename T, int...N> inline const CHR<T,N...>& GeneticAlgorithm<T,N...>::result() const { return pop(0); } /*-------------------------------------------------------------------------------------------------*/ // print results for each new generation template <typename T, int...N> void GeneticAlgorithm<T,N...>::print() const { // getting best parameter(s) from best chromosome std::vector<T> bestParam = pop(0)->getParam(); std::vector<T> bestResult = pop(0)->getResult(); if (nogen % genstep == 0) { std::cout << " Generation = " << std::setw(std::to_string(nbgen).size()) << nogen << " |"; for (int i = 0; i < nbparam; ++i) { std::cout << " X"; if (nbparam > 1) { std::cout << std::to_string(i + 1); } std::cout << " = " << std::setw(9) << std::fixed << std::setprecision(precision) << bestParam[i] << " |"; } for (unsigned i = 0; i < bestResult.size(); ++i) { std::cout << " F"; if (bestResult.size() > 1) { std::cout << std::to_string(i + 1); } std::cout << "(x) = " << std::setw(12) << std::fixed << std::setprecision(precision) << bestResult[i]; if (i < bestResult.size() - 1) { std::cout << " |"; } else { std::cout << "\n"; } } } } //================================================================================================= } #endif <commit_msg>Delete GeneticAlgorithm.hpp<commit_after><|endoftext|>
<commit_before>//================================================================================================= // Copyright (C) 2017 Olivier Mallet - All Rights Reserved //================================================================================================= #ifndef GENETICALGORITHM_HPP #define GENETICALGORITHM_HPP namespace galgo { //================================================================================================= template <typename T, int...N> class GeneticAlgorithm { static_assert(std::is_same<float,T>::value || std::is_same<double,T>::value, "variable type can only be float or double, please amend."); template <typename K, int...S> friend class Population; template <typename K, int...S> friend class Chromosome; template <typename K> using Functor = std::vector<K> (*)(const std::vector<K>&); private: Population<T,N...> pop; // population of chromosomes std::tuple<typename std::remove_reference<Parameter<T,N>>::type...> tp; // tuple of parameters std::vector<T> lowerBound; // parameter(s) lower bound std::vector<T> upperBound; // parameter(s) upper bound std::vector<T> initialSet; // initial set of parameter(s) public: // objective function functor Functor<T> Objective; // selection method functor initialized to roulette wheel selection void (*Selection)(Population<T,N...>&) = RWS; // cross-over method functor initialized to 1-point cross-over void (*CrossOver)(const Population<T,N...>&, CHR<T,N...>&, CHR<T,N...>&) = P1XO; // mutation method functor initialized to single-point mutation void (*Mutation)(CHR<T,N...>&) = SPM; // adaptation to constraint(s) method functor void (*Adaptation)(Population<T,N...>&) = nullptr; // constraint(s) functor std::vector<T> (*Constraint)(const std::vector<T>&) = nullptr; T covrate = .50; // cross-over rate T mutrate = .05; // mutation rate T SP = 1.5; // selective pressure for RSP selection method T tolerance = 0.0; // terminal condition (inactive if equal to zero) int elitpop = 1; // elit population size int matsize; // mating pool size, set to popsize by default int tntsize = 10; // tournament size int genstep = 10; // generation step for outputting results int precision = 5; // precision for outputting results // constructor GeneticAlgorithm(Functor<T> objective, int popsize, const Parameter<T,N>&...args, int nbgen, bool output = false); // run genetic algorithm void run(); // return best chromosome const CHR<T,N...>& result() const; private: int nbbit; // total number of bits per chromosome int nbgen; // number of generations int nogen = 0; // numero of generation int nbparam; // number of parameters to be estimated int popsize; // population size bool output; // control if results must be outputted // end of recursion for initializing parameter(s) data template <int I = 0> typename std::enable_if<I == sizeof...(N), void>::type init(); // recursion for initializing parameter(s) data template <int I = 0> typename std::enable_if<I < sizeof...(N), void>::type init(); // check inputs validity void check() const ; // print results for each new generation void print() const; }; /*-------------------------------------------------------------------------------------------------*/ // constructor template <typename T, int...N> GeneticAlgorithm<T,N...>::GeneticAlgorithm(Functor<T> objective, int popsize, const Parameter<T,N>&...args, int nbgen, bool output) { this->Objective = objective; this->popsize = popsize; this->matsize = popsize; this->tp = std::make_tuple(args...); this->nbbit = sum(N...); this->nbgen = nbgen; this->nbparam = sizeof...(N); this->output = output; } /*-------------------------------------------------------------------------------------------------*/ // end of recursion for initializing parameter(s) data template <typename T, int...N> template <int I> inline typename std::enable_if<I == sizeof...(N), void>::type GeneticAlgorithm<T,N...>::init() {} // recursion for initializing parameter(s) data template <typename T, int...N> template <int I> inline typename std::enable_if<I < sizeof...(N), void>::type GeneticAlgorithm<T,N...>::init() { const auto& par = std::get<I>(tp); lowerBound.push_back(par.data[0]); upperBound.push_back(par.data[1]); if (par.data.size() > 2) { initialSet.push_back(par.data[2]); } init<I + 1>(); } /*-------------------------------------------------------------------------------------------------*/ // check inputs validity template <typename T, int...N> void GeneticAlgorithm<T,N...>::check() const { if (!initialSet.empty()) { for (int i = 0; i < nbparam; ++i) { if (initialSet[i] < lowerBound[i] || initialSet[i] > upperBound[i]) { throw std::invalid_argument(" Error: in class galgo::Parameter<T,N>, initial parameter value cannot be outside the parameter boundaries, please choose a value between its lower and upper bounds."); } } if (initialSet.size() != (unsigned)nbparam) { throw std::invalid_argument(" Error: in class galgo::GeneticAlgorithm<T>, initial set of parameters does not have the same dimension than the number of parameters, please adjust."); } } if (SP < 1.0 || SP > 2.0) { throw std::invalid_argument(" Error: in class galgo::GeneticAlgorithm<T>, selective pressure (SP) cannot be outside [1.0,2.0], please choose a real value within this interval."); } if (elitpop > popsize || elitpop < 0) { throw std::invalid_argument(" Error: in class galgo::GeneticAlgorithm<T>, elit population (elitpop) cannot outside [0,popsize], please choose an integral value within this interval."); } if (covrate < 0.0 || covrate > 1.0) { throw std::invalid_argument(" Error: in class galgo::GeneticAlgorithm<T>, cross-over rate (covrate) cannot outside [0.0,1.0], please choose a real value within this interval."); } if (genstep <= 0) { throw std::invalid_argument(" Error: in class galgo::GeneticAlgorithm<T>, generation step (genstep) cannot be <= 0, please choose an integral value > 0."); } } /*-------------------------------------------------------------------------------------------------*/ // run genetic algorithm template <typename T, int...N> void GeneticAlgorithm<T,N...>::run() { lowerBound.clear(); upperBound.clear(); initialSet.clear(); // initializing parameter(s) data init(); // checking inputs validity check(); // setting adaptation method to default if needed if (Constraint != nullptr && Adaptation == nullptr) { Adaptation = DAC; } // initializing population pop = Population<T,N...>(*this); if (output) { std::cout << "\n Running Genetic Algorithm...\n"; std::cout << " ----------------------------\n"; } // creating population pop.creation(); // initializing best result and previous best result T bestResult = pop(0)->getTotal(); T prevBestResult = bestResult; // outputting results if (output) print(); // starting population evolution for (nogen = 1; nogen <= nbgen; ++nogen) { // evolving population pop.evolution(); // getting best current result bestResult = pop(0)->getTotal(); // outputting results if (output) print(); // checking convergence if (tolerance != 0.0) { if (fabs(bestResult - prevBestResult) < fabs(tolerance)) { break; } prevBestResult = bestResult; } } // outputting contraint value if (Constraint != nullptr) { // getting best parameter(s) constraint value(s) std::vector<T> cst = pop(0)->getConstraint(); if (output) { std::cout << "\n Constraint(s)\n"; std::cout << " -------------\n"; for (unsigned i = 0; i < cst.size(); ++i) { std::cout << " C"; if (nbparam > 1) { std::cout << std::to_string(i + 1); } std::cout << "(x) = " << std::setw(6) << std::fixed << std::setprecision(precision) << cst[i] << "\n"; } std::cout << "\n"; } } } /*-------------------------------------------------------------------------------------------------*/ // return best chromosome template <typename T, int...N> inline const CHR<T,N...>& GeneticAlgorithm<T,N...>::result() const { return pop(0); } /*-------------------------------------------------------------------------------------------------*/ // print results for each new generation template <typename T, int...N> void GeneticAlgorithm<T,N...>::print() const { // getting best parameter(s) from best chromosome std::vector<T> bestParam = pop(0)->getParam(); std::vector<T> bestResult = pop(0)->getResult(); if (nogen % genstep == 0) { std::cout << " Generation = " << std::setw(std::to_string(nbgen).size()) << nogen << " |"; for (int i = 0; i < nbparam; ++i) { std::cout << " X"; if (nbparam > 1) { std::cout << std::to_string(i + 1); } std::cout << " = " << std::setw(9) << std::fixed << std::setprecision(precision) << bestParam[i] << " |"; } for (unsigned i = 0; i < bestResult.size(); ++i) { std::cout << " F"; if (bestResult.size() > 1) { std::cout << std::to_string(i + 1); } std::cout << "(x) = " << std::setw(12) << std::fixed << std::setprecision(precision) << bestResult[i]; if (i < bestResult.size() - 1) { std::cout << " |"; } else { std::cout << "\n"; } } } } //================================================================================================= } #endif <commit_msg>Update GeneticAlgorithm.hpp<commit_after>//================================================================================================= // Copyright (C) 2017 Olivier Mallet - All Rights Reserved //================================================================================================= #ifndef GENETICALGORITHM_HPP #define GENETICALGORITHM_HPP namespace galgo { //================================================================================================= template <typename T, int...N> class GeneticAlgorithm { static_assert(std::is_same<float,T>::value || std::is_same<double,T>::value, "variable type can only be float or double, please amend."); template <typename K, int...S> friend class Population; template <typename K, int...S> friend class Chromosome; template <typename K> using Functor = std::vector<K> (*)(const std::vector<K>&); private: Population<T,N...> pop; // population of chromosomes std::tuple<typename std::remove_reference<Parameter<T,N>>::type...> tp; // tuple of parameters std::vector<T> lowerBound; // parameter(s) lower bound std::vector<T> upperBound; // parameter(s) upper bound std::vector<T> initialSet; // initial set of parameter(s) public: // objective function functor Functor<T> Objective; // selection method functor initialized to roulette wheel selection void (*Selection)(Population<T,N...>&) = RWS; // cross-over method functor initialized to 1-point cross-over void (*CrossOver)(const Population<T,N...>&, CHR<T,N...>&, CHR<T,N...>&) = P1XO; // mutation method functor initialized to single-point mutation void (*Mutation)(CHR<T,N...>&) = SPM; // adaptation to constraint(s) method functor void (*Adaptation)(Population<T,N...>&) = nullptr; // constraint(s) functor std::vector<T> (*Constraint)(const std::vector<T>&) = nullptr; T covrate = .50; // cross-over rate T mutrate = .05; // mutation rate T SP = 1.5; // selective pressure for RSP selection method T tolerance = 0.0; // terminal condition (inactive if equal to zero) int elitpop = 1; // elit population size int matsize; // mating pool size, set to popsize by default int tntsize = 10; // tournament size int genstep = 10; // generation step for outputting results int precision = 5; // precision for outputting results // constructor GeneticAlgorithm(Functor<T> objective, int popsize, const Parameter<T,N>&...args, int nbgen, bool output = false); // run genetic algorithm void run(); // return best chromosome const CHR<T,N...>& result() const; private: int nbbit; // total number of bits per chromosome int nbgen; // number of generations int nogen = 0; // numero of generation int nbparam; // number of parameters to be estimated int popsize; // population size bool output; // control if results must be outputted // end of recursion for initializing parameter(s) data template <int I = 0> typename std::enable_if<I == sizeof...(N), void>::type init(); // recursion for initializing parameter(s) data template <int I = 0> typename std::enable_if<I < sizeof...(N), void>::type init(); // check inputs validity void check() const ; // print results for each new generation void print() const; }; /*-------------------------------------------------------------------------------------------------*/ // constructor template <typename T, int...N> GeneticAlgorithm<T,N...>::GeneticAlgorithm(Functor<T> objective, int popsize, const Parameter<T,N>&...args, int nbgen, bool output) { this->Objective = objective; this->popsize = popsize; this->matsize = popsize; this->tp = std::make_tuple(args...); this->nbbit = sum(N...); this->nbgen = nbgen; this->nbparam = sizeof...(N); this->output = output; } /*-------------------------------------------------------------------------------------------------*/ // end of recursion for initializing parameter(s) data template <typename T, int...N> template <int I> inline typename std::enable_if<I == sizeof...(N), void>::type GeneticAlgorithm<T,N...>::init() {} // recursion for initializing parameter(s) data template <typename T, int...N> template <int I> inline typename std::enable_if<I < sizeof...(N), void>::type GeneticAlgorithm<T,N...>::init() { const auto& par = std::get<I>(tp); lowerBound.push_back(par.data[0]); upperBound.push_back(par.data[1]); if (par.data.size() > 2) { initialSet.push_back(par.data[2]); } init<I + 1>(); } /*-------------------------------------------------------------------------------------------------*/ // check inputs validity template <typename T, int...N> void GeneticAlgorithm<T,N...>::check() const { if (!initialSet.empty()) { for (int i = 0; i < nbparam; ++i) { if (initialSet[i] < lowerBound[i] || initialSet[i] > upperBound[i]) { throw std::invalid_argument("Error: in class galgo::Parameter<T,N>, initial parameter value cannot be outside the parameter boundaries, please choose a value between its lower and upper bounds."); } } if (initialSet.size() != (unsigned)nbparam) { throw std::invalid_argument("Error: in class galgo::GeneticAlgorithm<T>, initial set of parameters does not have the same dimension than the number of parameters, please adjust."); } } if (SP < 1.0 || SP > 2.0) { throw std::invalid_argument("Error: in class galgo::GeneticAlgorithm<T>, selective pressure (SP) cannot be outside [1.0,2.0], please choose a real value within this interval."); } if (elitpop > popsize || elitpop < 0) { throw std::invalid_argument("Error: in class galgo::GeneticAlgorithm<T>, elit population (elitpop) cannot outside [0,popsize], please choose an integral value within this interval."); } if (covrate < 0.0 || covrate > 1.0) { throw std::invalid_argument("Error: in class galgo::GeneticAlgorithm<T>, cross-over rate (covrate) cannot outside [0.0,1.0], please choose a real value within this interval."); } if (genstep <= 0) { throw std::invalid_argument("Error: in class galgo::GeneticAlgorithm<T>, generation step (genstep) cannot be <= 0, please choose an integral value > 0."); } } /*-------------------------------------------------------------------------------------------------*/ // run genetic algorithm template <typename T, int...N> void GeneticAlgorithm<T,N...>::run() { lowerBound.clear(); upperBound.clear(); initialSet.clear(); // initializing parameter(s) data init(); // checking inputs validity check(); // setting adaptation method to default if needed if (Constraint != nullptr && Adaptation == nullptr) { Adaptation = DAC; } // initializing population pop = Population<T,N...>(*this); if (output) { std::cout << "\n Running Genetic Algorithm...\n"; std::cout << " ----------------------------\n"; } // creating population pop.creation(); // initializing best result and previous best result T bestResult = pop(0)->getTotal(); T prevBestResult = bestResult; // outputting results if (output) print(); // starting population evolution for (nogen = 1; nogen <= nbgen; ++nogen) { // evolving population pop.evolution(); // getting best current result bestResult = pop(0)->getTotal(); // outputting results if (output) print(); // checking convergence if (tolerance != 0.0) { if (fabs(bestResult - prevBestResult) < fabs(tolerance)) { break; } prevBestResult = bestResult; } } // outputting contraint value if (Constraint != nullptr) { // getting best parameter(s) constraint value(s) std::vector<T> cst = pop(0)->getConstraint(); if (output) { std::cout << "\n Constraint(s)\n"; std::cout << " -------------\n"; for (unsigned i = 0; i < cst.size(); ++i) { std::cout << " C"; if (nbparam > 1) { std::cout << std::to_string(i + 1); } std::cout << "(x) = " << std::setw(6) << std::fixed << std::setprecision(precision) << cst[i] << "\n"; } std::cout << "\n"; } } } /*-------------------------------------------------------------------------------------------------*/ // return best chromosome template <typename T, int...N> inline const CHR<T,N...>& GeneticAlgorithm<T,N...>::result() const { return pop(0); } /*-------------------------------------------------------------------------------------------------*/ // print results for each new generation template <typename T, int...N> void GeneticAlgorithm<T,N...>::print() const { // getting best parameter(s) from best chromosome std::vector<T> bestParam = pop(0)->getParam(); std::vector<T> bestResult = pop(0)->getResult(); if (nogen % genstep == 0) { std::cout << " Generation = " << std::setw(std::to_string(nbgen).size()) << nogen << " |"; for (int i = 0; i < nbparam; ++i) { std::cout << " X"; if (nbparam > 1) { std::cout << std::to_string(i + 1); } std::cout << " = " << std::setw(9) << std::fixed << std::setprecision(precision) << bestParam[i] << " |"; } for (unsigned i = 0; i < bestResult.size(); ++i) { std::cout << " F"; if (bestResult.size() > 1) { std::cout << std::to_string(i + 1); } std::cout << "(x) = " << std::setw(12) << std::fixed << std::setprecision(precision) << bestResult[i]; if (i < bestResult.size() - 1) { std::cout << " |"; } else { std::cout << "\n"; } } } } //================================================================================================= } #endif <|endoftext|>
<commit_before>// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "boundary_info.h" #include "elem.h" #include "libmesh_logging.h" #include "parallel_mesh.h" #include "parallel.h" // ------------------------------------------------------------ // ParallelMesh class member functions ParallelMesh::ParallelMesh (unsigned int d) : UnstructuredMesh (d) { } ParallelMesh::~ParallelMesh () { this->clear(); // Free nodes and elements } // This might be specialized later, but right now it's just here to // make sure the compiler doesn't give us a default (non-deep) copy // constructor instead. ParallelMesh::ParallelMesh (const ParallelMesh &other_mesh) : UnstructuredMesh (other_mesh) { this->copy_nodes_and_elements(other_mesh); } ParallelMesh::ParallelMesh (const UnstructuredMesh &other_mesh) : UnstructuredMesh (other_mesh) { this->copy_nodes_and_elements(other_mesh); } const Point& ParallelMesh::point (const unsigned int i) const { assert (i < this->max_node_id()); assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return (*_nodes[i]); } const Node& ParallelMesh::node (const unsigned int i) const { assert (i < this->max_node_id()); assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return (*_nodes[i]); } Node& ParallelMesh::node (const unsigned int i) { assert (i < this->max_node_id()); assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return (*_nodes[i]); } const Node* ParallelMesh::node_ptr (const unsigned int i) const { assert (i < this->max_node_id()); assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return _nodes[i]; } Node* & ParallelMesh::node_ptr (const unsigned int i) { assert (i < this->max_node_id()); return _nodes[i]; } Elem* ParallelMesh::elem (const unsigned int i) const { assert (i < this->max_elem_id()); assert (_elements[i] != NULL); return _elements[i]; } Elem* ParallelMesh::add_elem (Elem* e) { if (e != NULL) e->set_id (this->max_elem_id()); _elements[this->max_elem_id()] = e; return e; } Elem* ParallelMesh::insert_elem (Elem* e) { if (_elements[e->id()]) this->delete_elem(_elements[e->id()]); _elements[e->id()] = e; return e; } void ParallelMesh::delete_elem(Elem* e) { assert (e != NULL); // Delete the element from the BoundaryInfo object this->boundary_info->remove(e); // But not yet from the container; we might invalidate // an iterator that way! //_elements.erase(e->id()); // Instead, we set it to NULL for now _elements[e->id()] = NULL; // delete the element delete e; } Node* ParallelMesh::add_point (const Point& p) { Node* n = Node::build(p, this->max_node_id()).release(); _nodes[this->max_node_id()] = n; return n; } Node* ParallelMesh::insert_node (Node* n) { // If we already have this node we cannot // simply delete it, because we may have elements // which are attached to its address. // // Instead, call the Node copy constructor to // overwrite the current node (but keep its address), // delete the provided node, and return the address of // the one we already had. if (_nodes.count(n->id())) { Node *my_n = _nodes[n->id()]; *my_n = *n; delete n; n = my_n; } else _nodes[n->id()] = n; return n; } void ParallelMesh::delete_node(Node* n) { assert (n != NULL); assert (n->id() < this->max_node_id()); // Delete the node from the BoundaryInfo object this->boundary_info->remove(n); // And from the container _nodes.erase(n->id()); // delete the node delete n; } void ParallelMesh::clear () { // Call parent clear function MeshBase::clear(); // Clear our elements and nodes { elem_iterator_imp it = _elements.begin(); const elem_iterator_imp end = _elements.end(); // There is no need to remove the elements from // the BoundaryInfo data structure since we // already cleared it. for (; it != end; ++it) delete *it; _elements.clear(); } // clear the nodes data structure { node_iterator_imp it = _nodes.begin(); node_iterator_imp end = _nodes.end(); // There is no need to remove the nodes from // the BoundaryInfo data structure since we // already cleared it. for (; it != end; ++it) delete *it; _nodes.clear(); } } template <typename T> void ParallelMesh::renumber_dof_objects (mapvector<T*> &objects) { typedef typename mapvector<T*>::veclike_iterator object_iterator; // In parallel we may not know what objects other processors have. // Start by figuring out how many unsigned int objects_on_me = 0; unsigned int unpartitioned_objects = 0; std::vector<unsigned int> ghost_objects_from_proc(libMesh::n_processors(), 0); object_iterator it = objects.begin(); object_iterator end = objects.end(); for (; it != end;) { T *obj = *it; // Remove any NULL container entries while we're here, // being careful not to invalidate our iterator if (!*it) objects.erase(it++); else { unsigned int obj_procid = obj->processor_id(); ghost_objects_from_proc[obj_procid]++; if (obj_procid == libMesh::processor_id()) objects_on_me++; else if (obj_procid == DofObject::invalid_processor_id) unpartitioned_objects++; ++it; } } std::vector<unsigned int> objects_on_proc(libMesh::n_processors(), 0); Parallel::allgather(objects_on_me, objects_on_proc); #ifndef NDEBUG unsigned int global_unpartitioned_objects = unpartitioned_objects; Parallel::max(global_unpartitioned_objects); assert(global_unpartitioned_objects == unpartitioned_objects); for (unsigned int p=0; p != libMesh::n_processors(); ++p) assert(ghost_objects_from_proc[p] <= objects_on_proc[p]); #endif // We'll renumber objects in blocks by processor id std::vector<unsigned int> first_object_on_proc(libMesh::n_processors()); for (unsigned int i=1; i != libMesh::n_processors(); ++i) first_object_on_proc[i] = first_object_on_proc[i-1] + objects_on_proc[i-1]; unsigned int next_id = first_object_on_proc[libMesh::processor_id()]; // First set new local object ids and build request sets // for non-local object ids // Request sets to send to each processor std::vector<std::vector<unsigned int> > requested_ids(libMesh::n_processors()); // We know how many objects live on each processor, so reseve() space for // each. for (unsigned int p=0; p != libMesh::n_processors(); ++p) if (p != libMesh::processor_id()) requested_ids[p].reserve(ghost_objects_from_proc[p]); end = objects.end(); for (it = objects.begin(); it != end; ++it) { T *obj = *it; if (obj->processor_id() == libMesh::processor_id()) obj->set_id(next_id++); else if (obj->processor_id() != DofObject::invalid_processor_id) requested_ids[obj->processor_id()].push_back(obj->id()); } // Next set ghost object ids from other processors if (libMesh::n_processors() > 1) { for (unsigned int p=1; p != libMesh::n_processors(); ++p) { // Trade my requests with processor procup and procdown unsigned int procup = (libMesh::processor_id() + p) % libMesh::n_processors(); unsigned int procdown = (libMesh::n_processors() + libMesh::processor_id() - p) % libMesh::n_processors(); std::vector<unsigned int> request_to_fill; Parallel::send_receive(procup, requested_ids[procup], procdown, request_to_fill); // Fill those requests std::vector<unsigned int> new_ids(request_to_fill.size()); for (unsigned int i=0; i != request_to_fill.size(); ++i) { assert(objects[request_to_fill[i]]); assert(objects[request_to_fill[i]]->processor_id() == libMesh::processor_id()); new_ids[i] = objects[request_to_fill[i]]->id(); assert(new_ids[i] >= first_object_on_proc[libMesh::processor_id()]); assert(new_ids[i] < first_object_on_proc[libMesh::processor_id()] + objects_on_proc[libMesh::processor_id()]); } // Trade back the results std::vector<unsigned int> filled_request; Parallel::send_receive(procdown, new_ids, procup, filled_request); // And copy the id changes we've now been informed of for (unsigned int i=0; i != filled_request.size(); ++i) { assert (objects[requested_ids[procup][i]]->processor_id() == procup); assert(filled_request[i] >= first_object_on_proc[procup]); assert(filled_request[i] < first_object_on_proc[procup] + objects_on_proc[procup]); objects[requested_ids[procup][i]]->set_id(filled_request[i]); } } } // Next set unpartitioned object ids next_id = 0; for (unsigned int i=0; i != libMesh::n_processors(); ++i) next_id += objects_on_proc[i]; for (it = objects.begin(); it != end; ++it) { T *obj = *it; if (obj->processor_id() == DofObject::invalid_processor_id) obj->set_id(next_id++); } // Finally shuffle around objects so that container indices // match ids end = objects.end(); for (it = objects.begin(); it != end;) { T *obj = *it; if (obj) // don't try shuffling already-NULL entries { T *next = objects[obj->id()]; // If we have to move this object if (next != obj) { // NULL out its original position for now // (our shuffling may put another object there shortly) *it = NULL; // There may already be another object with this id that // needs to be moved itself while (next) { // We shouldn't be trying to give two objects the // same id assert (next->id() != obj->id()); objects[obj->id()] = obj; obj = next; next = objects[obj->id()]; } objects[obj->id()] = obj; } } // Remove any container entries that were left as NULL, // being careful not to invalidate our iterator if (!*it) objects.erase(it++); else ++it; } } void ParallelMesh::renumber_nodes_and_elements () { START_LOG("renumber_nodes_and_elem()", "ParallelMesh"); std::set<unsigned int> used_nodes; // flag the nodes we need { element_iterator it = elements_begin(); element_iterator end = elements_end(); for (; it != end; ++it) { Elem *elem = *it; for (unsigned int n=0; n != elem->n_nodes(); ++n) used_nodes.insert(elem->node(n)); } } // Nodes not connected to any local elements are deleted { node_iterator_imp it = _nodes.begin(); node_iterator_imp end = _nodes.end(); for (; it != end;) { Node *node = *it; if (!used_nodes.count(node->id())) { // remove any boundary information associated with // this node this->boundary_info->remove (node); // delete the node delete node; _nodes.erase(it++); } else ++it; } } // Finally renumber all the elements this->renumber_dof_objects (_elements); // and all the remaining nodes this->renumber_dof_objects (_nodes); STOP_LOG("renumber_nodes_and_elem()", "ParallelMesh"); } void ParallelMesh::delete_nonlocal_elements() { START_LOG("delete_nonlocal_elements()", "ParallelMesh"); std::vector<bool> local_nodes(this->max_node_id(), false); std::vector<bool> semilocal_elems(this->max_elem_id(), false); const_element_iterator l_elem_it = this->local_elements_begin(), l_end = this->local_elements_end(); for (; l_elem_it != l_end; ++l_elem_it) { const Elem *elem = *l_elem_it; for (unsigned int n=0; n != elem->n_nodes(); ++n) local_nodes[elem->node(n)] = true; } element_iterator nl_elem_it = this->not_local_elements_begin(), nl_end = this->not_local_elements_end(); for (; nl_elem_it != nl_end; ++nl_elem_it) { Elem *elem = *nl_elem_it; for (unsigned int n=0; n != elem->n_nodes(); ++n) if (local_nodes[elem->node(n)]) { semilocal_elems[elem->id()] = true; break; } if (!semilocal_elems[elem->id()]) { // delete_elem doesn't currently invalidate element // iterators... that had better not change this->delete_elem(elem); } } // We eventually want to compact the _nodes and _elems vectors // But not do a repartition or anything // do not this->prepare_for_use(); STOP_LOG("delete_nonlocal_elements()", "ParallelMesh"); } void ParallelMesh::restore_nonlocal_elements() { // Someday... error(); } <commit_msg>bugfix, remove redundant variable<commit_after>// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "boundary_info.h" #include "elem.h" #include "libmesh_logging.h" #include "parallel_mesh.h" #include "parallel.h" // ------------------------------------------------------------ // ParallelMesh class member functions ParallelMesh::ParallelMesh (unsigned int d) : UnstructuredMesh (d) { } ParallelMesh::~ParallelMesh () { this->clear(); // Free nodes and elements } // This might be specialized later, but right now it's just here to // make sure the compiler doesn't give us a default (non-deep) copy // constructor instead. ParallelMesh::ParallelMesh (const ParallelMesh &other_mesh) : UnstructuredMesh (other_mesh) { this->copy_nodes_and_elements(other_mesh); } ParallelMesh::ParallelMesh (const UnstructuredMesh &other_mesh) : UnstructuredMesh (other_mesh) { this->copy_nodes_and_elements(other_mesh); } const Point& ParallelMesh::point (const unsigned int i) const { assert (i < this->max_node_id()); assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return (*_nodes[i]); } const Node& ParallelMesh::node (const unsigned int i) const { assert (i < this->max_node_id()); assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return (*_nodes[i]); } Node& ParallelMesh::node (const unsigned int i) { assert (i < this->max_node_id()); assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return (*_nodes[i]); } const Node* ParallelMesh::node_ptr (const unsigned int i) const { assert (i < this->max_node_id()); assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return _nodes[i]; } Node* & ParallelMesh::node_ptr (const unsigned int i) { assert (i < this->max_node_id()); return _nodes[i]; } Elem* ParallelMesh::elem (const unsigned int i) const { assert (i < this->max_elem_id()); assert (_elements[i] != NULL); return _elements[i]; } Elem* ParallelMesh::add_elem (Elem* e) { if (e != NULL) e->set_id (this->max_elem_id()); _elements[this->max_elem_id()] = e; return e; } Elem* ParallelMesh::insert_elem (Elem* e) { if (_elements[e->id()]) this->delete_elem(_elements[e->id()]); _elements[e->id()] = e; return e; } void ParallelMesh::delete_elem(Elem* e) { assert (e != NULL); // Delete the element from the BoundaryInfo object this->boundary_info->remove(e); // But not yet from the container; we might invalidate // an iterator that way! //_elements.erase(e->id()); // Instead, we set it to NULL for now _elements[e->id()] = NULL; // delete the element delete e; } Node* ParallelMesh::add_point (const Point& p) { Node* n = Node::build(p, this->max_node_id()).release(); _nodes[this->max_node_id()] = n; return n; } Node* ParallelMesh::insert_node (Node* n) { // If we already have this node we cannot // simply delete it, because we may have elements // which are attached to its address. // // Instead, call the Node copy constructor to // overwrite the current node (but keep its address), // delete the provided node, and return the address of // the one we already had. if (_nodes.count(n->id())) { Node *my_n = _nodes[n->id()]; *my_n = *n; delete n; n = my_n; } else _nodes[n->id()] = n; return n; } void ParallelMesh::delete_node(Node* n) { assert (n != NULL); assert (n->id() < this->max_node_id()); // Delete the node from the BoundaryInfo object this->boundary_info->remove(n); // And from the container _nodes.erase(n->id()); // delete the node delete n; } void ParallelMesh::clear () { // Call parent clear function MeshBase::clear(); // Clear our elements and nodes { elem_iterator_imp it = _elements.begin(); const elem_iterator_imp end = _elements.end(); // There is no need to remove the elements from // the BoundaryInfo data structure since we // already cleared it. for (; it != end; ++it) delete *it; _elements.clear(); } // clear the nodes data structure { node_iterator_imp it = _nodes.begin(); node_iterator_imp end = _nodes.end(); // There is no need to remove the nodes from // the BoundaryInfo data structure since we // already cleared it. for (; it != end; ++it) delete *it; _nodes.clear(); } } template <typename T> void ParallelMesh::renumber_dof_objects (mapvector<T*> &objects) { typedef typename mapvector<T*>::veclike_iterator object_iterator; // In parallel we may not know what objects other processors have. // Start by figuring out how many unsigned int unpartitioned_objects = 0; std::vector<unsigned int> ghost_objects_from_proc(libMesh::n_processors(), 0); object_iterator it = objects.begin(); object_iterator end = objects.end(); for (; it != end;) { T *obj = *it; // Remove any NULL container entries while we're here, // being careful not to invalidate our iterator if (!*it) objects.erase(it++); else { unsigned int obj_procid = obj->processor_id(); if (obj_procid == DofObject::invalid_processor_id) unpartitioned_objects++; else ghost_objects_from_proc[obj_procid]++; ++it; } } std::vector<unsigned int> objects_on_proc(libMesh::n_processors(), 0); Parallel::allgather(ghost_objects_from_proc[libMesh::processor_id()], objects_on_proc); #ifndef NDEBUG unsigned int global_unpartitioned_objects = unpartitioned_objects; Parallel::max(global_unpartitioned_objects); assert(global_unpartitioned_objects == unpartitioned_objects); for (unsigned int p=0; p != libMesh::n_processors(); ++p) assert(ghost_objects_from_proc[p] <= objects_on_proc[p]); #endif // We'll renumber objects in blocks by processor id std::vector<unsigned int> first_object_on_proc(libMesh::n_processors()); for (unsigned int i=1; i != libMesh::n_processors(); ++i) first_object_on_proc[i] = first_object_on_proc[i-1] + objects_on_proc[i-1]; unsigned int next_id = first_object_on_proc[libMesh::processor_id()]; // First set new local object ids and build request sets // for non-local object ids // Request sets to send to each processor std::vector<std::vector<unsigned int> > requested_ids(libMesh::n_processors()); // We know how many objects live on each processor, so reseve() space for // each. for (unsigned int p=0; p != libMesh::n_processors(); ++p) if (p != libMesh::processor_id()) requested_ids[p].reserve(ghost_objects_from_proc[p]); end = objects.end(); for (it = objects.begin(); it != end; ++it) { T *obj = *it; if (obj->processor_id() == libMesh::processor_id()) obj->set_id(next_id++); else if (obj->processor_id() != DofObject::invalid_processor_id) requested_ids[obj->processor_id()].push_back(obj->id()); } // Next set ghost object ids from other processors if (libMesh::n_processors() > 1) { for (unsigned int p=1; p != libMesh::n_processors(); ++p) { // Trade my requests with processor procup and procdown unsigned int procup = (libMesh::processor_id() + p) % libMesh::n_processors(); unsigned int procdown = (libMesh::n_processors() + libMesh::processor_id() - p) % libMesh::n_processors(); std::vector<unsigned int> request_to_fill; Parallel::send_receive(procup, requested_ids[procup], procdown, request_to_fill); // Fill those requests std::vector<unsigned int> new_ids(request_to_fill.size()); for (unsigned int i=0; i != request_to_fill.size(); ++i) { assert(objects[request_to_fill[i]]); assert(objects[request_to_fill[i]]->processor_id() == libMesh::processor_id()); new_ids[i] = objects[request_to_fill[i]]->id(); assert(new_ids[i] >= first_object_on_proc[libMesh::processor_id()]); assert(new_ids[i] < first_object_on_proc[libMesh::processor_id()] + objects_on_proc[libMesh::processor_id()]); } // Trade back the results std::vector<unsigned int> filled_request; Parallel::send_receive(procdown, new_ids, procup, filled_request); // And copy the id changes we've now been informed of for (unsigned int i=0; i != filled_request.size(); ++i) { assert (objects[requested_ids[procup][i]]->processor_id() == procup); assert(filled_request[i] >= first_object_on_proc[procup]); assert(filled_request[i] < first_object_on_proc[procup] + objects_on_proc[procup]); objects[requested_ids[procup][i]]->set_id(filled_request[i]); } } } // Next set unpartitioned object ids next_id = 0; for (unsigned int i=0; i != libMesh::n_processors(); ++i) next_id += objects_on_proc[i]; for (it = objects.begin(); it != end; ++it) { T *obj = *it; if (obj->processor_id() == DofObject::invalid_processor_id) obj->set_id(next_id++); } // Finally shuffle around objects so that container indices // match ids end = objects.end(); for (it = objects.begin(); it != end;) { T *obj = *it; if (obj) // don't try shuffling already-NULL entries { T *next = objects[obj->id()]; // If we have to move this object if (next != obj) { // NULL out its original position for now // (our shuffling may put another object there shortly) *it = NULL; // There may already be another object with this id that // needs to be moved itself while (next) { // We shouldn't be trying to give two objects the // same id assert (next->id() != obj->id()); objects[obj->id()] = obj; obj = next; next = objects[obj->id()]; } objects[obj->id()] = obj; } } // Remove any container entries that were left as NULL, // being careful not to invalidate our iterator if (!*it) objects.erase(it++); else ++it; } } void ParallelMesh::renumber_nodes_and_elements () { START_LOG("renumber_nodes_and_elem()", "ParallelMesh"); std::set<unsigned int> used_nodes; // flag the nodes we need { element_iterator it = elements_begin(); element_iterator end = elements_end(); for (; it != end; ++it) { Elem *elem = *it; for (unsigned int n=0; n != elem->n_nodes(); ++n) used_nodes.insert(elem->node(n)); } } // Nodes not connected to any local elements are deleted { node_iterator_imp it = _nodes.begin(); node_iterator_imp end = _nodes.end(); for (; it != end;) { Node *node = *it; if (!used_nodes.count(node->id())) { // remove any boundary information associated with // this node this->boundary_info->remove (node); // delete the node delete node; _nodes.erase(it++); } else ++it; } } // Finally renumber all the elements this->renumber_dof_objects (_elements); // and all the remaining nodes this->renumber_dof_objects (_nodes); STOP_LOG("renumber_nodes_and_elem()", "ParallelMesh"); } void ParallelMesh::delete_nonlocal_elements() { START_LOG("delete_nonlocal_elements()", "ParallelMesh"); std::vector<bool> local_nodes(this->max_node_id(), false); std::vector<bool> semilocal_elems(this->max_elem_id(), false); const_element_iterator l_elem_it = this->local_elements_begin(), l_end = this->local_elements_end(); for (; l_elem_it != l_end; ++l_elem_it) { const Elem *elem = *l_elem_it; for (unsigned int n=0; n != elem->n_nodes(); ++n) local_nodes[elem->node(n)] = true; } element_iterator nl_elem_it = this->not_local_elements_begin(), nl_end = this->not_local_elements_end(); for (; nl_elem_it != nl_end; ++nl_elem_it) { Elem *elem = *nl_elem_it; for (unsigned int n=0; n != elem->n_nodes(); ++n) if (local_nodes[elem->node(n)]) { semilocal_elems[elem->id()] = true; break; } if (!semilocal_elems[elem->id()]) { // delete_elem doesn't currently invalidate element // iterators... that had better not change this->delete_elem(elem); } } // We eventually want to compact the _nodes and _elems vectors // But not do a repartition or anything // do not this->prepare_for_use(); STOP_LOG("delete_nonlocal_elements()", "ParallelMesh"); } void ParallelMesh::restore_nonlocal_elements() { // Someday... error(); } <|endoftext|>
<commit_before>#ifdef CAN_EMULATOR #include "usbutil.h" #include "canread.h" #include "serialutil.h" #include "log.h" #include <stdlib.h> #define NUMERICAL_SIGNAL_COUNT 11 #define BOOLEAN_SIGNAL_COUNT 5 #define STATE_SIGNAL_COUNT 2 #define EVENT_SIGNAL_COUNT 1 extern SerialDevice SERIAL_DEVICE; extern UsbDevice USB_DEVICE; extern Listener listener; const char* NUMERICAL_SIGNALS[NUMERICAL_SIGNAL_COUNT] = { "steering_wheel_angle", "torque_at_transmission", "engine_speed", "vehicle_speed", "accelerator_pedal_position", "odometer", "fine_odometer_since_restart", "latitude", "longitude", "fuel_level", "fuel_consumed_since_restart", }; const char* BOOLEAN_SIGNALS[BOOLEAN_SIGNAL_COUNT] = { "parking_brake_status", "brake_pedal_status", "headlamp_status", "high_beam_status", "windshield_wiper_status", }; const char* STATE_SIGNALS[STATE_SIGNAL_COUNT] = { "transmission_gear_position", "ignition_status", }; const char* SIGNAL_STATES[STATE_SIGNAL_COUNT][3] = { { "neutral", "first", "second" }, { "off", "run", "accessory" }, }; const char* EVENT_SIGNALS[EVENT_SIGNAL_COUNT] = { "door_status", }; struct Event { const char* value; bool event; }; Event EVENT_SIGNAL_STATES[EVENT_SIGNAL_COUNT][3] = { { {"driver", false}, {"passenger", true}, {"rear_right", true}}, }; void setup() { srand(42); initializeLogging(); initializeSerial(&SERIAL_DEVICE); initializeUsb(&USB_DEVICE); } bool usbWriteStub(uint8_t* buffer) { debug("Ignoring write request -- running an emulator\r\n"); return true; } void loop() { while(1) { sendNumericalMessage( NUMERICAL_SIGNALS[rand() % NUMERICAL_SIGNAL_COUNT], rand() % 50 + rand() % 100 * .1, &listener); sendBooleanMessage(BOOLEAN_SIGNALS[rand() % BOOLEAN_SIGNAL_COUNT], rand() % 2 == 1 ? true : false, &listener); int stateSignalIndex = rand() % STATE_SIGNAL_COUNT; sendStringMessage(STATE_SIGNALS[stateSignalIndex], SIGNAL_STATES[stateSignalIndex][rand() % 3], &listener); int eventSignalIndex = rand() % EVENT_SIGNAL_COUNT; Event randomEvent = EVENT_SIGNAL_STATES[eventSignalIndex][rand() % 3]; sendEventedBooleanMessage(EVENT_SIGNALS[eventSignalIndex], randomEvent.value, randomEvent.event, &listener); processListenerQueues(&listener); readFromHost(&USB_DEVICE, usbWriteStub); readFromSerial(&SERIAL_DEVICE, usbWriteStub); } } void reset() { } const char* getMessageSet() { return "emulator"; } #endif // CAN_EMULATOR <commit_msg>Slow down the CAN emualtor rate a bit so we don't overflow every buffer.<commit_after>#ifdef CAN_EMULATOR #include "usbutil.h" #include "canread.h" #include "serialutil.h" #include "log.h" #include <stdlib.h> #define NUMERICAL_SIGNAL_COUNT 11 #define BOOLEAN_SIGNAL_COUNT 5 #define STATE_SIGNAL_COUNT 2 #define EVENT_SIGNAL_COUNT 1 extern SerialDevice SERIAL_DEVICE; extern UsbDevice USB_DEVICE; extern Listener listener; const char* NUMERICAL_SIGNALS[NUMERICAL_SIGNAL_COUNT] = { "steering_wheel_angle", "torque_at_transmission", "engine_speed", "vehicle_speed", "accelerator_pedal_position", "odometer", "fine_odometer_since_restart", "latitude", "longitude", "fuel_level", "fuel_consumed_since_restart", }; const char* BOOLEAN_SIGNALS[BOOLEAN_SIGNAL_COUNT] = { "parking_brake_status", "brake_pedal_status", "headlamp_status", "high_beam_status", "windshield_wiper_status", }; const char* STATE_SIGNALS[STATE_SIGNAL_COUNT] = { "transmission_gear_position", "ignition_status", }; const char* SIGNAL_STATES[STATE_SIGNAL_COUNT][3] = { { "neutral", "first", "second" }, { "off", "run", "accessory" }, }; const char* EVENT_SIGNALS[EVENT_SIGNAL_COUNT] = { "door_status", }; struct Event { const char* value; bool event; }; Event EVENT_SIGNAL_STATES[EVENT_SIGNAL_COUNT][3] = { { {"driver", false}, {"passenger", true}, {"rear_right", true}}, }; void setup() { srand(42); initializeLogging(); initializeSerial(&SERIAL_DEVICE); initializeUsb(&USB_DEVICE); } bool usbWriteStub(uint8_t* buffer) { debug("Ignoring write request -- running an emulator\r\n"); return true; } void loop() { while(1) { sendNumericalMessage( NUMERICAL_SIGNALS[rand() % NUMERICAL_SIGNAL_COUNT], rand() % 50 + rand() % 100 * .1, &listener); sendBooleanMessage(BOOLEAN_SIGNALS[rand() % BOOLEAN_SIGNAL_COUNT], rand() % 2 == 1 ? true : false, &listener); int stateSignalIndex = rand() % STATE_SIGNAL_COUNT; sendStringMessage(STATE_SIGNALS[stateSignalIndex], SIGNAL_STATES[stateSignalIndex][rand() % 3], &listener); int eventSignalIndex = rand() % EVENT_SIGNAL_COUNT; Event randomEvent = EVENT_SIGNAL_STATES[eventSignalIndex][rand() % 3]; sendEventedBooleanMessage(EVENT_SIGNALS[eventSignalIndex], randomEvent.value, randomEvent.event, &listener); Delay_MS(25); processListenerQueues(&listener); readFromHost(&USB_DEVICE, usbWriteStub); readFromSerial(&SERIAL_DEVICE, usbWriteStub); } } void reset() { } const char* getMessageSet() { return "emulator"; } #endif // CAN_EMULATOR <|endoftext|>
<commit_before>class CfgServerInfoMenu { addAction = 0; // Enable/disable action menu item | use 0 to disable | default: 1 (enabled) // antiHACK = "infiSTAR + BattlEye"; antiHACK = "BattlEye"; hostedBy = "Mgthost1"; ipPort = "189.1.169.221:2342"; openKey = "User7"; // https://community.bistudio.com/wiki/inputAction/actions openAtLogin = no; restart = 4; // Amount of hours before server automatically restarts serverName = "HC Corp A3Wasteland Altis"; class menuItems { // title AND content accept formatted text ( since update Oct5.2016 ) class first { menuName = "Rules"; title = "Regras do servidor|Server rules"; content[] = { "<t size='1.70'>Regras do servidor A3Wasteland Altis <t color='#b8870a'>HC Corp</t>|<t color='#b8870a'>HC Corp</t> A3Wasteland Altis server rules</t><br />", "1. É proibido o uso de cheats, exploits e/ou hacks. Penalidade: <t color='#ff0000'>banimento</t><br />", "1. Using cheats, exploits and/or hacks is forbidden. Penalty: <t color='#ff0000'>ban</t><br />", "2. Seja educado. Respeite o servidor, os administradores, os membros da HC Corp e todos os outros jogadores. Penalidades: primeira ofensa; aviso; ofensas seguintes; <t color='#ff0000'>banimento</t><br />", "2. Be polite. Respect the server, the administrators, the HC Corp members and all the other players. Penalties: first offense; warning; following offenses; <t color='#ff0000'>ban</t><br />" }; }; class second { menuName = "Missions"; title = "<t color='#b8870a'>Missões do servidor|Server missions</t>"; content[] = { "<br/>• Small Money Shipment: $50,000<br />• Medium Money Shipment: $75,000<br />• Large Money Shipment: $100,000<br />• Heavy Money Shipment: $150,000<br />• Sunken Treasure: $150,000<br /></p>" }; }; class third { menuName = "Events"; title = "<t color='#b8870a'>Eventos todo fim de semana|Events every weekend</t>"; content[] = {"<t size='1.75'>Próximo evento|Next event</t><br />• NÃO DISPONÍVEL|NOT AVAILABLE<br />"}; }; class fourth { menuName = "Admins"; title = "<t color='#b8870a'>Administradores|Administrators</t>"; content[] = {"<t size='1.75'>Admin</t><br /><t color='#b8870a'>• leonbarba<br />• rover047</t><br />"}; // content[] = {"<t size='1.75'>Admin</t><br /><t color='#b8870a'>• NICK 1<br />• NICK 2 <br />• NICK 3</t><br />", // "<t size='1.75'>Editor</t><br /><t color='#b8870a'>• NICK 1<br />• NICK 2</t><br />"}; }; // class fifth // { // menuName = "Rank"; // title = "<t color='#b8870a'>Top 10</t>"; // content[] = {"<t size='1.75'>Rank</t><br />• EM BREVE|SOON<br />"}; // }; // class sixth class fifth { menuName = "Communication"; title = "<t color='#b8870a'>Servidor de voz|Voice server</t>"; content[] = { "<t size='1.75'>TeamSpeak:</t><br /><t color='#b8870a'><a href='http://www.teamspeak.com/invite/186.228.98.5/?port=9991'>186.228.98.5:9991</a></t><br />" }; }; // class seventh // { // menuName = "Updates"; // title = "<t color='#b8870a'>Atualiza&ccedil;&otilde;es|Updates</t>"; // content[] = { // "<t size='1.75'>Atualiza&ccedil;&otilde;es|Updates</t><br /><t color='#b8870a'><a href='http://www.hccorp.com.br'>www.hccorp.com.br</a></t><br />" // }; // }; }; }; <commit_msg>Atualização Scarcode<commit_after>class CfgServerInfoMenu { addAction = 0; // Enable/disable action menu item | use 0 to disable | default: 1 (enabled) // antiHACK = "infiSTAR + BattlEye"; antiHACK = "BattlEye"; hostedBy = "Mgthost1"; ipPort = "189.1.169.221:2342"; openKey = "User7"; // https://community.bistudio.com/wiki/inputAction/actions openAtLogin = no; restart = 4; // Amount of hours before server automatically restarts serverName = "HC Corp A3Wasteland Altis"; class menuItems { // title AND content accept formatted text ( since update Oct5.2016 ) class first { menuName = "Rules"; title = "Regras do servidor|Server rules"; content[] = { "<t size='1.70'>Regras do servidor A3Wasteland Altis <t color='#b8870a'>HC Corp</t>|<t color='#b8870a'>HC Corp</t> A3Wasteland Altis server rules</t><br />", "1. É proibido o uso de cheats, exploits e/ou hacks. Penalidade: <t color='#ff0000'>banimento</t><br />", "1. Using cheats, exploits and/or hacks is forbidden. Penalty: <t color='#ff0000'>ban</t><br />", "2. Seja educado. Respeite o servidor, os administradores, os membros da HC Corp e todos os outros jogadores. Penalidades: primeira ofensa; aviso; ofensas seguintes; <t color='#ff0000'>banimento</t><br />", "2. Be polite. Respect the server, the administrators, the HC Corp members and all the other players. Penalties: first offense; warning; following offenses; <t color='#ff0000'>ban</t><br />" }; }; class second { menuName = "Missions"; title = "<t color='#b8870a'>Missões do servidor|Server missions</t>"; content[] = { "<br/>• Small Money Shipment: $50,000<br />• Medium Money Shipment: $100,000<br />• Large Money Shipment: $150,000<br />• Heavy Money Shipment: $200,000<br />• Sunken Treasure: $85,000<br /></p>" }; }; class third { menuName = "Events"; title = "<t color='#b8870a'>Eventos todo fim de semana|Events every weekend</t>"; content[] = {"<t size='1.75'>Próximo evento|Next event</t><br />• NÃO DISPONÍVEL|NOT AVAILABLE<br />"}; }; class fourth { menuName = "Admins"; title = "<t color='#b8870a'>Administradores|Administrators</t>"; content[] = {"<t size='1.75'>Admin</t><br /><t color='#b8870a'>• leonbarba<br />• rover047</t><br />"}; // content[] = {"<t size='1.75'>Admin</t><br /><t color='#b8870a'>• NICK 1<br />• NICK 2 <br />• NICK 3</t><br />", // "<t size='1.75'>Editor</t><br /><t color='#b8870a'>• NICK 1<br />• NICK 2</t><br />"}; }; // class fifth // { // menuName = "Rank"; // title = "<t color='#b8870a'>Top 10</t>"; // content[] = {"<t size='1.75'>Rank</t><br />• EM BREVE|SOON<br />"}; // }; // class sixth class fifth { menuName = "Communication"; title = "<t color='#b8870a'>Servidor de voz|Voice server</t>"; content[] = { "<t size='1.75'>TeamSpeak:</t><br /><t color='#b8870a'><a href='http://www.teamspeak.com/invite/186.228.98.5/?port=9991'>186.228.98.5:9991</a></t><br />" }; }; // class seventh // { // menuName = "Updates"; // title = "<t color='#b8870a'>Atualiza&ccedil;&otilde;es|Updates</t>"; // content[] = { // "<t size='1.75'>Atualiza&ccedil;&otilde;es|Updates</t><br /><t color='#b8870a'><a href='http://www.hccorp.com.br'>www.hccorp.com.br</a></t><br />" // }; // }; }; }; <|endoftext|>
<commit_before>#include <StdAfx.h> #include <UI/ViewPane/ViewPane.h> #include <UI/UIFunctions.h> #include <core/utility/strings.h> #include <core/utility/output.h> namespace viewpane { // Draw our header, if needed. HDWP ViewPane::DeferWindowPos( _In_ HDWP hWinPosInfo, const _In_ int x, const _In_ int y, const _In_ int width, const _In_ int height) { output::DebugPrint( output::dbgLevel::Draw, L"ViewPane::DeferWindowPos x:%d y:%d width:%d height:%d v:%d\n", x, y, width, height, m_Header.IsWindowVisible()); WC_B_S(m_Header.ShowWindow(SW_SHOW)); hWinPosInfo = ui::DeferWindowPos( hWinPosInfo, m_Header.GetSafeHwnd(), x, y, width, m_Header.GetFixedHeight(), L"ViewPane::DeferWindowPos::header2"); m_Header.OnSize(NULL, width, m_Header.GetFixedHeight()); output::DebugPrint(output::dbgLevel::Draw, L"ViewPane::DeferWindowPos end\n"); return hWinPosInfo; } void ViewPane::Initialize(_In_ CWnd* pParent, _In_opt_ HDC hdc) { if (pParent) m_hWndParent = pParent->m_hWnd; // We compute nID for our view and the header from the pane's base ID. const UINT nidHeader = IDC_PROP_CONTROL_ID_BASE + 2 * m_paneID; m_nID = IDC_PROP_CONTROL_ID_BASE + 2 * m_paneID + 1; m_Header.Initialize(pParent->GetSafeHwnd(), hdc, nidHeader); } ULONG ViewPane::HandleChange(UINT nID) { if (m_Header.HandleChange(nID)) { return m_paneID; } return static_cast<ULONG>(-1); } void ViewPane::SetMargins( int iMargin, int iSideMargin, int iLabelHeight, // Height of the label int iSmallHeightMargin, int iLargeHeightMargin, int iButtonHeight, // Height of buttons below the control int iEditHeight) // height of an edit control { m_iMargin = iMargin; m_iSideMargin = iSideMargin; m_iSmallHeightMargin = iSmallHeightMargin; m_iLargeHeightMargin = iLargeHeightMargin; m_iButtonHeight = iButtonHeight; m_iEditHeight = iEditHeight; m_Header.SetMargins(iMargin, iSideMargin, iLabelHeight, iButtonHeight); } void ViewPane::UpdateButtons() {} } // namespace viewpane<commit_msg>cleanup<commit_after>#include <StdAfx.h> #include <UI/ViewPane/ViewPane.h> #include <UI/UIFunctions.h> #include <core/utility/strings.h> #include <core/utility/output.h> namespace viewpane { // Draw our header, if needed. HDWP ViewPane::DeferWindowPos( _In_ HDWP hWinPosInfo, const _In_ int x, const _In_ int y, const _In_ int width, const _In_ int height) { output::DebugPrint( output::dbgLevel::Draw, L"ViewPane::DeferWindowPos x:%d y:%d width:%d height:%d v:%d\n", x, y, width, height, m_Header.IsWindowVisible()); hWinPosInfo = ui::DeferWindowPos( hWinPosInfo, m_Header.GetSafeHwnd(), x, y, width, m_Header.GetFixedHeight(), L"ViewPane::DeferWindowPos::header2"); output::DebugPrint(output::dbgLevel::Draw, L"ViewPane::DeferWindowPos end\n"); return hWinPosInfo; } void ViewPane::Initialize(_In_ CWnd* pParent, _In_opt_ HDC hdc) { if (pParent) m_hWndParent = pParent->m_hWnd; // We compute nID for our view and the header from the pane's base ID. const UINT nidHeader = IDC_PROP_CONTROL_ID_BASE + 2 * m_paneID; m_nID = IDC_PROP_CONTROL_ID_BASE + 2 * m_paneID + 1; m_Header.Initialize(pParent->GetSafeHwnd(), hdc, nidHeader); } ULONG ViewPane::HandleChange(UINT nID) { if (m_Header.HandleChange(nID)) { return m_paneID; } return static_cast<ULONG>(-1); } void ViewPane::SetMargins( int iMargin, int iSideMargin, int iLabelHeight, // Height of the label int iSmallHeightMargin, int iLargeHeightMargin, int iButtonHeight, // Height of buttons below the control int iEditHeight) // height of an edit control { m_iMargin = iMargin; m_iSideMargin = iSideMargin; m_iSmallHeightMargin = iSmallHeightMargin; m_iLargeHeightMargin = iLargeHeightMargin; m_iButtonHeight = iButtonHeight; m_iEditHeight = iEditHeight; m_Header.SetMargins(iMargin, iSideMargin, iLabelHeight, iButtonHeight); } void ViewPane::UpdateButtons() {} } // namespace viewpane<|endoftext|>
<commit_before>/* * Copyright (C) 2015-2016 Nagisa Sekiguchi * * 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 YDSH_MISC_LOGGER_BASE_HPP #define YDSH_MISC_LOGGER_BASE_HPP #include <unistd.h> #include <iostream> #include <fstream> #include <type_traits> #include <string> #include <cstring> #include <ctime> #include "flag_util.hpp" namespace ydsh { namespace __detail_log { inline unsigned int mask(unsigned int index) { return 1 << (index + 1); } template <typename P, typename E> class LoggerBase { private: static_assert(std::is_enum<E>::value, "must be enum type"); static constexpr unsigned int CLOSE_APPENDER = 1 << 0; std::ostream *appender; /** * if least significant bit is set, close appender */ unsigned int whiteList; LoggerBase(); public: ~LoggerBase() { if(hasFlag(this->whiteList, CLOSE_APPENDER)) { delete this->appender; this->appender = nullptr; } } static LoggerBase<P, E> &instance() { static LoggerBase<P, E> logger; return logger; } static bool checkPolicy(E e) { return hasFlag(instance().whiteList, mask(e)); } static std::ostream &format2digit(std::ostream &stream, int num) { return stream << (num < 10 ? "0" : "") << num; } static std::ostream &header(const char *funcName); }; template <typename P, typename E> LoggerBase<P, E>::LoggerBase() : appender(&std::cerr), whiteList(P::init()) { const char *path = getenv(P::appenderPath()); if(path != nullptr) { std::ostream *os = new std::ofstream(path); if(!(*os)) { delete os; os = nullptr; } if(os != nullptr) { this->appender = os; setFlag(this->whiteList, CLOSE_APPENDER); } } } template <typename P, typename E> std::ostream &LoggerBase<P, E>::header(const char *funcName) { std::ostream &stream = *instance().appender; time_t timer = time(nullptr); struct tm *local = localtime(&timer); stream << (local->tm_year + 1900) << "-"; format2digit(stream, local->tm_mon + 1) << "-"; format2digit(stream, local->tm_mday) << " "; format2digit(stream, local->tm_hour) << ":"; format2digit(stream, local->tm_min) << ":"; format2digit(stream, local->tm_sec); return stream << " [" << getpid() << "] " << funcName << "(): "; } template <unsigned int N> unsigned int initPolicy(const char *prefix, const char *arg) { static_assert(N < 32, "not allow more than 31 policy"); unsigned int policySet = 0; // parse arg const unsigned int prefixSize = strlen(prefix); unsigned int indexCount = 0; std::string buf(prefix); for(unsigned int i = 0; arg[i] != '\0'; i++) { char ch = arg[i]; switch(ch) { case ' ': case '\t': case '\r': case '\n': continue; case ',': { if(getenv(buf.c_str()) != nullptr) { ydsh::setFlag(policySet, mask(indexCount)); } indexCount++; buf = prefix; break; } default: buf += ch; break; } } if(buf.size() > prefixSize) { if(getenv(buf.c_str()) != nullptr) { setFlag(policySet, mask(indexCount)); } } return policySet; } template <typename T> inline void invoke(std::ostream &stream, T t) { t(stream); stream << std::endl; } } // namespace __detail_log } // namespace ydsh #ifdef USE_LOGGING #define LOG_L(E, B) \ do {\ using namespace ydsh;\ if(__detail_log::Logger::checkPolicy(__detail_log::LoggingPolicy::E)) {\ __detail_log::invoke(__detail_log::Logger::header(__func__), B);\ }\ } while(false) #define LOG(E, V) LOG_L(E, [&](std::ostream &__stream) { __stream << V; }) #define DEFINE_LOGGING_POLICY(PREFIX, APPENDER, ...) \ namespace ydsh { namespace __detail_log {\ struct LoggingPolicy {\ enum Policy { __VA_ARGS__ };\ static unsigned int init() { \ return initPolicy<sizeof((Policy[]){ __VA_ARGS__ }) / sizeof(Policy)>(PREFIX, #__VA_ARGS__);\ }\ static const char *appenderPath() { return PREFIX APPENDER; }\ };\ using Logger = LoggerBase<LoggingPolicy, LoggingPolicy::Policy>;\ }} #else #define LOG(E, B) #define LOG_L(E, B) #define DEFINE_LOGGING_POLICY(PREFIX, APPENDER, ...) #endif #endif //YDSH_MISC_LOGGER_BASE_HPP <commit_msg>cleanup<commit_after>/* * Copyright (C) 2015-2016 Nagisa Sekiguchi * * 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 YDSH_MISC_LOGGER_BASE_HPP #define YDSH_MISC_LOGGER_BASE_HPP #include <unistd.h> #include <iostream> #include <fstream> #include <type_traits> #include <string> #include <cstring> #include <ctime> #include "flag_util.hpp" namespace ydsh { namespace __detail_log { inline unsigned int mask(unsigned int index) { return 1 << (index + 1); } template <typename P, typename E> class LoggerBase { private: static_assert(std::is_enum<E>::value, "must be enum type"); static constexpr unsigned int CLOSE_APPENDER = 1 << 0; std::ostream *appender; /** * if least significant bit is set, close appender */ unsigned int whiteList; LoggerBase(); public: ~LoggerBase() { if(hasFlag(this->whiteList, CLOSE_APPENDER)) { delete this->appender; this->appender = nullptr; } } static LoggerBase<P, E> &instance() { static LoggerBase<P, E> logger; return logger; } static bool checkPolicy(E e) { return hasFlag(instance().whiteList, mask(e)); } static std::ostream &header(const char *funcName); }; template <typename P, typename E> LoggerBase<P, E>::LoggerBase() : appender(&std::cerr), whiteList(P::init()) { const char *path = getenv(P::appenderPath()); if(path != nullptr) { std::ostream *os = new std::ofstream(path); if(!(*os)) { delete os; os = nullptr; } if(os != nullptr) { this->appender = os; setFlag(this->whiteList, CLOSE_APPENDER); } } } template <typename P, typename E> std::ostream &LoggerBase<P, E>::header(const char *funcName) { std::ostream &stream = *instance().appender; time_t timer = time(nullptr); struct tm *local = localtime(&timer); char buf[32]; strftime(buf, 32, "%F %T", local); return stream << buf << " [" << getpid() << "] " << funcName << "(): "; } template <unsigned int N> unsigned int initPolicy(const char *prefix, const char *arg) { static_assert(N < 32, "not allow more than 31 policy"); unsigned int policySet = 0; // parse arg const unsigned int prefixSize = strlen(prefix); unsigned int indexCount = 0; std::string buf(prefix); for(unsigned int i = 0; arg[i] != '\0'; i++) { char ch = arg[i]; switch(ch) { case ' ': case '\t': case '\r': case '\n': continue; case ',': { if(getenv(buf.c_str()) != nullptr) { ydsh::setFlag(policySet, mask(indexCount)); } indexCount++; buf = prefix; break; } default: buf += ch; break; } } if(buf.size() > prefixSize) { if(getenv(buf.c_str()) != nullptr) { setFlag(policySet, mask(indexCount)); } } return policySet; } template <typename T> inline void invoke(std::ostream &stream, T t) { t(stream); stream << std::endl; } } // namespace __detail_log } // namespace ydsh #ifdef USE_LOGGING #define LOG_L(E, B) \ do {\ using namespace ydsh;\ if(__detail_log::Logger::checkPolicy(__detail_log::LoggingPolicy::E)) {\ __detail_log::invoke(__detail_log::Logger::header(__func__), B);\ }\ } while(false) #define LOG(E, V) LOG_L(E, [&](std::ostream &__stream) { __stream << V; }) #define DEFINE_LOGGING_POLICY(PREFIX, APPENDER, ...) \ namespace ydsh { namespace __detail_log {\ struct LoggingPolicy {\ enum Policy { __VA_ARGS__ };\ static unsigned int init() { \ return initPolicy<sizeof((Policy[]){ __VA_ARGS__ }) / sizeof(Policy)>(PREFIX, #__VA_ARGS__);\ }\ static const char *appenderPath() { return PREFIX APPENDER; }\ };\ using Logger = LoggerBase<LoggingPolicy, LoggingPolicy::Policy>;\ }} #else #define LOG(E, B) #define LOG_L(E, B) #define DEFINE_LOGGING_POLICY(PREFIX, APPENDER, ...) #endif #endif //YDSH_MISC_LOGGER_BASE_HPP <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/crash_reporter/crash_reporter_win.h" #include <string> #include "base/files/file_util.h" #include "base/logging.h" #include "base/memory/singleton.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/common/result_codes.h" #include "gin/public/debug.h" #include "sandbox/win/src/nt_internals.h" #pragma intrinsic(_AddressOfReturnAddress) #pragma intrinsic(_ReturnAddress) #ifdef _WIN64 // See http://msdn.microsoft.com/en-us/library/ddssxxy8.aspx typedef struct _UNWIND_INFO { unsigned char Version : 3; unsigned char Flags : 5; unsigned char SizeOfProlog; unsigned char CountOfCodes; unsigned char FrameRegister : 4; unsigned char FrameOffset : 4; ULONG ExceptionHandler; } UNWIND_INFO, *PUNWIND_INFO; #endif namespace crash_reporter { namespace { // Minidump with stacks, PEB, TEB, and unloaded module list. const MINIDUMP_TYPE kSmallDumpType = static_cast<MINIDUMP_TYPE>( MiniDumpWithProcessThreadData | // Get PEB and TEB. MiniDumpWithUnloadedModules); // Get unloaded modules when available. const wchar_t kWaitEventFormat[] = L"$1CrashServiceWaitEvent"; const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\$1 Crash Service"; // Matches breakpad/src/client/windows/common/ipc_protocol.h. const int kNameMaxLength = 64; const int kValueMaxLength = 64; typedef NTSTATUS(WINAPI* NtTerminateProcessPtr)(HANDLE ProcessHandle, NTSTATUS ExitStatus); char* g_real_terminate_process_stub = NULL; void TerminateProcessWithoutDump() { // Patched stub exists based on conditions (See InitCrashReporter). // As a side note this function also gets called from // WindowProcExceptionFilter. if (g_real_terminate_process_stub == NULL) { ::TerminateProcess(::GetCurrentProcess(), content::RESULT_CODE_KILLED); } else { NtTerminateProcessPtr real_terminate_proc = reinterpret_cast<NtTerminateProcessPtr>( static_cast<char*>(g_real_terminate_process_stub)); real_terminate_proc(::GetCurrentProcess(), content::RESULT_CODE_KILLED); } } #ifdef _WIN64 int CrashForExceptionInNonABICompliantCodeRange( PEXCEPTION_RECORD ExceptionRecord, ULONG64 EstablisherFrame, PCONTEXT ContextRecord, PDISPATCHER_CONTEXT DispatcherContext) { EXCEPTION_POINTERS info = {ExceptionRecord, ContextRecord}; if (!CrashReporter::GetInstance()) return EXCEPTION_CONTINUE_SEARCH; return static_cast<CrashReporterWin*>(CrashReporter::GetInstance()) ->CrashForException(&info); } struct ExceptionHandlerRecord { RUNTIME_FUNCTION runtime_function; UNWIND_INFO unwind_info; unsigned char thunk[12]; }; bool RegisterNonABICompliantCodeRange(void* start, size_t size_in_bytes) { ExceptionHandlerRecord* record = reinterpret_cast<ExceptionHandlerRecord*>(start); // We assume that the first page of the code range is executable and // committed and reserved for breakpad. What could possibly go wrong? // All addresses are 32bit relative offsets to start. record->runtime_function.BeginAddress = 0; record->runtime_function.EndAddress = base::checked_cast<DWORD>(size_in_bytes); record->runtime_function.UnwindData = offsetof(ExceptionHandlerRecord, unwind_info); // Create unwind info that only specifies an exception handler. record->unwind_info.Version = 1; record->unwind_info.Flags = UNW_FLAG_EHANDLER; record->unwind_info.SizeOfProlog = 0; record->unwind_info.CountOfCodes = 0; record->unwind_info.FrameRegister = 0; record->unwind_info.FrameOffset = 0; record->unwind_info.ExceptionHandler = offsetof(ExceptionHandlerRecord, thunk); // Hardcoded thunk. // mov imm64, rax record->thunk[0] = 0x48; record->thunk[1] = 0xb8; void* handler = reinterpret_cast<void*>(&CrashForExceptionInNonABICompliantCodeRange); memcpy(&record->thunk[2], &handler, 8); // jmp rax record->thunk[10] = 0xff; record->thunk[11] = 0xe0; // Protect reserved page against modifications. DWORD old_protect; return VirtualProtect(start, sizeof(ExceptionHandlerRecord), PAGE_EXECUTE_READ, &old_protect) && RtlAddFunctionTable(&record->runtime_function, 1, reinterpret_cast<DWORD64>(start)); } void UnregisterNonABICompliantCodeRange(void* start) { ExceptionHandlerRecord* record = reinterpret_cast<ExceptionHandlerRecord*>(start); RtlDeleteFunctionTable(&record->runtime_function); } #endif // _WIN64 } // namespace CrashReporterWin::CrashReporterWin() {} CrashReporterWin::~CrashReporterWin() {} void CrashReporterWin::InitBreakpad(const std::string& product_name, const std::string& version, const std::string& company_name, const std::string& submit_url, const base::FilePath& crashes_dir, bool upload_to_server, bool skip_system_crash_handler) { skip_system_crash_handler_ = skip_system_crash_handler; base::string16 pipe_name = base::ReplaceStringPlaceholders( kPipeNameFormat, base::UTF8ToUTF16(product_name), NULL); base::string16 wait_name = base::ReplaceStringPlaceholders( kWaitEventFormat, base::UTF8ToUTF16(product_name), NULL); // Wait until the crash service is started. HANDLE wait_event = ::CreateEventW(NULL, TRUE, FALSE, wait_name.c_str()); if (wait_event != NULL) { WaitForSingleObject(wait_event, 1000); CloseHandle(wait_event); } // ExceptionHandler() attaches our handler and ~ExceptionHandler() detaches // it, so we must explicitly reset *before* we instantiate our new handler // to allow any previous handler to detach in the correct order. breakpad_.reset(); breakpad_.reset(new google_breakpad::ExceptionHandler( crashes_dir.DirName().value(), FilterCallback, MinidumpCallback, this, google_breakpad::ExceptionHandler::HANDLER_ALL, kSmallDumpType, pipe_name.c_str(), GetCustomInfo(product_name, version, company_name, upload_to_server))); if (!breakpad_->IsOutOfProcess()) LOG(ERROR) << "Cannot initialize out-of-process crash handler"; #ifdef _WIN64 // Hook up V8 to breakpad. if (!code_range_registered_) { code_range_registered_ = true; // gin::Debug::SetCodeRangeCreatedCallback only runs the callback when // Isolate is just created, so we have to manually run following code here. void* code_range = nullptr; size_t size = 0; v8::Isolate::GetCurrent()->GetCodeRange(&code_range, &size); if (code_range && size && RegisterNonABICompliantCodeRange(code_range, size)) { gin::Debug::SetCodeRangeDeletedCallback( UnregisterNonABICompliantCodeRange); } } #endif } void CrashReporterWin::SetUploadParameters() { upload_parameters_["platform"] = "win32"; } int CrashReporterWin::CrashForException(EXCEPTION_POINTERS* info) { if (breakpad_) { breakpad_->WriteMinidumpForException(info); if (skip_system_crash_handler_) TerminateProcessWithoutDump(); else RaiseFailFastException(info->ExceptionRecord, info->ContextRecord, 0); } return EXCEPTION_CONTINUE_SEARCH; } // static bool CrashReporterWin::FilterCallback(void* context, EXCEPTION_POINTERS* exinfo, MDRawAssertionInfo* assertion) { return true; } // static bool CrashReporterWin::MinidumpCallback(const wchar_t* dump_path, const wchar_t* minidump_id, void* context, EXCEPTION_POINTERS* exinfo, MDRawAssertionInfo* assertion, bool succeeded) { CrashReporterWin* self = static_cast<CrashReporterWin*>(context); if (succeeded && self->skip_system_crash_handler_) return true; else return false; } google_breakpad::CustomClientInfo* CrashReporterWin::GetCustomInfo( const std::string& product_name, const std::string& version, const std::string& company_name, bool upload_to_server) { custom_info_entries_.clear(); custom_info_entries_.reserve(3 + upload_parameters_.size()); custom_info_entries_.push_back( google_breakpad::CustomInfoEntry(L"prod", L"Electron")); custom_info_entries_.push_back(google_breakpad::CustomInfoEntry( L"ver", base::UTF8ToWide(version).c_str())); if (!upload_to_server) { custom_info_entries_.push_back( google_breakpad::CustomInfoEntry(L"skip_upload", L"1")); } for (StringMap::const_iterator iter = upload_parameters_.begin(); iter != upload_parameters_.end(); ++iter) { // breakpad has hardcoded the length of name/value, and doesn't truncate // the values itself, so we have to truncate them here otherwise weird // things may happen. std::wstring name = base::UTF8ToWide(iter->first); std::wstring value = base::UTF8ToWide(iter->second); if (name.length() > kNameMaxLength - 1) name.resize(kNameMaxLength - 1); if (value.length() > kValueMaxLength - 1) value.resize(kValueMaxLength - 1); custom_info_entries_.push_back( google_breakpad::CustomInfoEntry(name.c_str(), value.c_str())); } custom_info_.entries = &custom_info_entries_.front(); custom_info_.count = custom_info_entries_.size(); return &custom_info_; } // static CrashReporterWin* CrashReporterWin::GetInstance() { return base::Singleton<CrashReporterWin>::get(); } // static CrashReporter* CrashReporter::GetInstance() { return CrashReporterWin::GetInstance(); } } // namespace crash_reporter <commit_msg>fix: correct crash reporter for Windows on Arm (#17533)<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/crash_reporter/crash_reporter_win.h" #include <string> #include "base/files/file_util.h" #include "base/logging.h" #include "base/memory/singleton.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/common/result_codes.h" #include "gin/public/debug.h" #include "sandbox/win/src/nt_internals.h" #pragma intrinsic(_AddressOfReturnAddress) #pragma intrinsic(_ReturnAddress) #ifdef _WIN64 // See http://msdn.microsoft.com/en-us/library/ddssxxy8.aspx typedef struct _UNWIND_INFO { unsigned char Version : 3; unsigned char Flags : 5; unsigned char SizeOfProlog; unsigned char CountOfCodes; unsigned char FrameRegister : 4; unsigned char FrameOffset : 4; ULONG ExceptionHandler; } UNWIND_INFO, *PUNWIND_INFO; #endif namespace crash_reporter { namespace { // Minidump with stacks, PEB, TEB, and unloaded module list. const MINIDUMP_TYPE kSmallDumpType = static_cast<MINIDUMP_TYPE>( MiniDumpWithProcessThreadData | // Get PEB and TEB. MiniDumpWithUnloadedModules); // Get unloaded modules when available. const wchar_t kWaitEventFormat[] = L"$1CrashServiceWaitEvent"; const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\$1 Crash Service"; // Matches breakpad/src/client/windows/common/ipc_protocol.h. const int kNameMaxLength = 64; const int kValueMaxLength = 64; typedef NTSTATUS(WINAPI* NtTerminateProcessPtr)(HANDLE ProcessHandle, NTSTATUS ExitStatus); char* g_real_terminate_process_stub = NULL; void TerminateProcessWithoutDump() { // Patched stub exists based on conditions (See InitCrashReporter). // As a side note this function also gets called from // WindowProcExceptionFilter. if (g_real_terminate_process_stub == NULL) { ::TerminateProcess(::GetCurrentProcess(), content::RESULT_CODE_KILLED); } else { NtTerminateProcessPtr real_terminate_proc = reinterpret_cast<NtTerminateProcessPtr>( static_cast<char*>(g_real_terminate_process_stub)); real_terminate_proc(::GetCurrentProcess(), content::RESULT_CODE_KILLED); } } #ifdef _WIN64 int CrashForExceptionInNonABICompliantCodeRange( PEXCEPTION_RECORD ExceptionRecord, ULONG64 EstablisherFrame, PCONTEXT ContextRecord, PDISPATCHER_CONTEXT DispatcherContext) { EXCEPTION_POINTERS info = {ExceptionRecord, ContextRecord}; if (!CrashReporter::GetInstance()) return EXCEPTION_CONTINUE_SEARCH; return static_cast<CrashReporterWin*>(CrashReporter::GetInstance()) ->CrashForException(&info); } struct ExceptionHandlerRecord { RUNTIME_FUNCTION runtime_function; UNWIND_INFO unwind_info; unsigned char thunk[12]; }; bool RegisterNonABICompliantCodeRange(void* start, size_t size_in_bytes) { ExceptionHandlerRecord* record = reinterpret_cast<ExceptionHandlerRecord*>(start); // We assume that the first page of the code range is executable and // committed and reserved for breakpad. What could possibly go wrong? // All addresses are 32bit relative offsets to start. record->runtime_function.BeginAddress = 0; #if defined(_M_ARM64) record->runtime_function.FunctionLength = base::checked_cast<DWORD>(size_in_bytes); #else record->runtime_function.EndAddress = base::checked_cast<DWORD>(size_in_bytes); #endif record->runtime_function.UnwindData = offsetof(ExceptionHandlerRecord, unwind_info); // Create unwind info that only specifies an exception handler. record->unwind_info.Version = 1; record->unwind_info.Flags = UNW_FLAG_EHANDLER; record->unwind_info.SizeOfProlog = 0; record->unwind_info.CountOfCodes = 0; record->unwind_info.FrameRegister = 0; record->unwind_info.FrameOffset = 0; record->unwind_info.ExceptionHandler = offsetof(ExceptionHandlerRecord, thunk); // Hardcoded thunk. // mov imm64, rax record->thunk[0] = 0x48; record->thunk[1] = 0xb8; void* handler = reinterpret_cast<void*>(&CrashForExceptionInNonABICompliantCodeRange); memcpy(&record->thunk[2], &handler, 8); // jmp rax record->thunk[10] = 0xff; record->thunk[11] = 0xe0; // Protect reserved page against modifications. DWORD old_protect; return VirtualProtect(start, sizeof(ExceptionHandlerRecord), PAGE_EXECUTE_READ, &old_protect) && RtlAddFunctionTable(&record->runtime_function, 1, reinterpret_cast<DWORD64>(start)); } void UnregisterNonABICompliantCodeRange(void* start) { ExceptionHandlerRecord* record = reinterpret_cast<ExceptionHandlerRecord*>(start); RtlDeleteFunctionTable(&record->runtime_function); } #endif // _WIN64 } // namespace CrashReporterWin::CrashReporterWin() {} CrashReporterWin::~CrashReporterWin() {} void CrashReporterWin::InitBreakpad(const std::string& product_name, const std::string& version, const std::string& company_name, const std::string& submit_url, const base::FilePath& crashes_dir, bool upload_to_server, bool skip_system_crash_handler) { skip_system_crash_handler_ = skip_system_crash_handler; base::string16 pipe_name = base::ReplaceStringPlaceholders( kPipeNameFormat, base::UTF8ToUTF16(product_name), NULL); base::string16 wait_name = base::ReplaceStringPlaceholders( kWaitEventFormat, base::UTF8ToUTF16(product_name), NULL); // Wait until the crash service is started. HANDLE wait_event = ::CreateEventW(NULL, TRUE, FALSE, wait_name.c_str()); if (wait_event != NULL) { WaitForSingleObject(wait_event, 1000); CloseHandle(wait_event); } // ExceptionHandler() attaches our handler and ~ExceptionHandler() detaches // it, so we must explicitly reset *before* we instantiate our new handler // to allow any previous handler to detach in the correct order. breakpad_.reset(); breakpad_.reset(new google_breakpad::ExceptionHandler( crashes_dir.DirName().value(), FilterCallback, MinidumpCallback, this, google_breakpad::ExceptionHandler::HANDLER_ALL, kSmallDumpType, pipe_name.c_str(), GetCustomInfo(product_name, version, company_name, upload_to_server))); if (!breakpad_->IsOutOfProcess()) LOG(ERROR) << "Cannot initialize out-of-process crash handler"; #ifdef _WIN64 // Hook up V8 to breakpad. if (!code_range_registered_) { code_range_registered_ = true; // gin::Debug::SetCodeRangeCreatedCallback only runs the callback when // Isolate is just created, so we have to manually run following code here. void* code_range = nullptr; size_t size = 0; v8::Isolate::GetCurrent()->GetCodeRange(&code_range, &size); if (code_range && size && RegisterNonABICompliantCodeRange(code_range, size)) { gin::Debug::SetCodeRangeDeletedCallback( UnregisterNonABICompliantCodeRange); } } #endif } void CrashReporterWin::SetUploadParameters() { upload_parameters_["platform"] = "win32"; } int CrashReporterWin::CrashForException(EXCEPTION_POINTERS* info) { if (breakpad_) { breakpad_->WriteMinidumpForException(info); if (skip_system_crash_handler_) TerminateProcessWithoutDump(); else RaiseFailFastException(info->ExceptionRecord, info->ContextRecord, 0); } return EXCEPTION_CONTINUE_SEARCH; } // static bool CrashReporterWin::FilterCallback(void* context, EXCEPTION_POINTERS* exinfo, MDRawAssertionInfo* assertion) { return true; } // static bool CrashReporterWin::MinidumpCallback(const wchar_t* dump_path, const wchar_t* minidump_id, void* context, EXCEPTION_POINTERS* exinfo, MDRawAssertionInfo* assertion, bool succeeded) { CrashReporterWin* self = static_cast<CrashReporterWin*>(context); if (succeeded && self->skip_system_crash_handler_) return true; else return false; } google_breakpad::CustomClientInfo* CrashReporterWin::GetCustomInfo( const std::string& product_name, const std::string& version, const std::string& company_name, bool upload_to_server) { custom_info_entries_.clear(); custom_info_entries_.reserve(3 + upload_parameters_.size()); custom_info_entries_.push_back( google_breakpad::CustomInfoEntry(L"prod", L"Electron")); custom_info_entries_.push_back(google_breakpad::CustomInfoEntry( L"ver", base::UTF8ToWide(version).c_str())); if (!upload_to_server) { custom_info_entries_.push_back( google_breakpad::CustomInfoEntry(L"skip_upload", L"1")); } for (StringMap::const_iterator iter = upload_parameters_.begin(); iter != upload_parameters_.end(); ++iter) { // breakpad has hardcoded the length of name/value, and doesn't truncate // the values itself, so we have to truncate them here otherwise weird // things may happen. std::wstring name = base::UTF8ToWide(iter->first); std::wstring value = base::UTF8ToWide(iter->second); if (name.length() > kNameMaxLength - 1) name.resize(kNameMaxLength - 1); if (value.length() > kValueMaxLength - 1) value.resize(kValueMaxLength - 1); custom_info_entries_.push_back( google_breakpad::CustomInfoEntry(name.c_str(), value.c_str())); } custom_info_.entries = &custom_info_entries_.front(); custom_info_.count = custom_info_entries_.size(); return &custom_info_; } // static CrashReporterWin* CrashReporterWin::GetInstance() { return base::Singleton<CrashReporterWin>::get(); } // static CrashReporter* CrashReporter::GetInstance() { return CrashReporterWin::GetInstance(); } } // namespace crash_reporter <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "core.h" #include "protocol.h" #include "util.h" // // Main network // unsigned int pnSeed[] = { 0x12346678 }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xb5; pchMessageStart[2] = 0xdf; pchMessageStart[3] = 0xdb; vAlertPubKey = ParseHex("043a314ee36a4796baeb6a488e38f62c45f2dc69331cfc49b2a867fa95467f4e3aac21a03bebe8f977d7f29fb4487a5947a98cc38d3c48dd04c261899f4384fd6c"); nDefaultPort = 15660; nRPCPort = 15661; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); nSubsidyHalvingInterval = 172800; // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. const char* pszTimestamp = "9/05/2013 @ 5:10PM: Virgin Galactic's SpaceShipTwo Succeeds In Second Rocket-Powered Flight."; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 128 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678aaaa0fe55482f1967f1a67130b7105cd6a000e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1378495795; genesis.nBits = 0x1e0fffff; genesis.nNonce = 285333548; //// debug print hashGenesisBlock = genesis.GetHash(); /* while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()) { if (++genesis.nNonce==0) break; hashGenesisBlock = genesis.GetHash(); } */ printf("hashGenesisBlock = %s\n", hashGenesisBlock.ToString().c_str()); printf("hashMerkleRoot = %s\n", genesis.hashMerkleRoot.ToString().c_str()); printf("%x\n", bnProofOfWorkLimit.GetCompact()); genesis.print(); assert(hashGenesisBlock == uint256("0x000000e02a1a674989cc114a50fea6d46e9fd18620129418589364b75f3292ac")); assert(genesis.hashMerkleRoot == uint256("0xaee5ee4074090a7564fd6a51e16a9e0ef4656d14fe4798be3e13d085cbbf7577")); vSeeds.push_back(CDNSSeedData("bitcoin.sipa.be", "seed.bitcoin.sipa.be")); vSeeds.push_back(CDNSSeedData("bluematt.me", "dnsseed.bluematt.me")); vSeeds.push_back(CDNSSeedData("xf2.org", "bitseed.xf2.org")); vSeeds.push_back(CDNSSeedData("dashjr.org", "dnsseed.bitcoin.dashjr.org")); base58Prefixes[PUBKEY_ADDRESS] = 127; base58Prefixes[SCRIPT_ADDRESS] = 9; base58Prefixes[SECRET_KEY] = 224; // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' const int64 nTwoDays = 2 * 24 * 60 * 60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0x05; pchMessageStart[1] = 0xfe; pchMessageStart[2] = 0xa9; pchMessageStart[3] = 0x01; vAlertPubKey = ParseHex("043a314ee36a4796baeb6a488e38f62c45f2dc69331cfc49b2a867fa95467f4e3aac21a03bebe8f977d7f29fb4487a5947a98cc38d3c48dd04c261899f4384fd6c"); nDefaultPort = 28077; nRPCPort = 28078; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1439972967; genesis.nNonce = 4224972; //// debug print hashGenesisBlock = genesis.GetHash(); //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){ // if (++genesis.nNonce==0) break; // hashGenesisBlock = genesis.GetHash(); //} printf("hashGenesisBlock-testnet = %s\n", hashGenesisBlock.ToString().c_str()); printf("hashMerkleRoot-testnet = %s\n", genesis.hashMerkleRoot.ToString().c_str()); genesis.print(); assert(hashGenesisBlock == uint256("0xa6e7e253dd963065e18841baf1f2b3617ff4ee144132e51f86d16096f55f0040")); vFixedSeeds.clear(); vSeeds.clear(); // vSeeds.push_back(CDNSSeedData("tigercoin.test", "test.tigercoin.org")); base58Prefixes[PUBKEY_ADDRESS] = 77; base58Prefixes[SCRIPT_ADDRESS] = 177; base58Prefixes[SECRET_KEY] = 239; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0x0f; pchMessageStart[2] = 0xa5; pchMessageStart[3] = 0x5a; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1396688602; genesis.nBits = 0x207fffff; genesis.nNonce = 3; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 28444; strDataDir = "regtest"; //// debug print hashGenesisBlock = genesis.GetHash(); //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){ // if (++genesis.nNonce==0) break; // hashGenesisBlock = genesis.GetHash(); //} printf("%s\n", hashGenesisBlock.ToString().c_str()); printf("%s\n", genesis.hashMerkleRoot.ToString().c_str()); genesis.print(); // assert(hashGenesisBlock == uint256("0x13d8d31dde96874006da503dd2b63fa68c698dc823334359e417aa3a92f80433")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. base58Prefixes[PUBKEY_ADDRESS] = 0; base58Prefixes[SCRIPT_ADDRESS] = 5; base58Prefixes[SECRET_KEY] = 128; } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>New test chain genesis block hash<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "core.h" #include "protocol.h" #include "util.h" // // Main network // unsigned int pnSeed[] = { 0x12346678 }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xb5; pchMessageStart[2] = 0xdf; pchMessageStart[3] = 0xdb; vAlertPubKey = ParseHex("043a314ee36a4796baeb6a488e38f62c45f2dc69331cfc49b2a867fa95467f4e3aac21a03bebe8f977d7f29fb4487a5947a98cc38d3c48dd04c261899f4384fd6c"); nDefaultPort = 15660; nRPCPort = 15661; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); nSubsidyHalvingInterval = 172800; // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. const char* pszTimestamp = "9/05/2013 @ 5:10PM: Virgin Galactic's SpaceShipTwo Succeeds In Second Rocket-Powered Flight."; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 128 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678aaaa0fe55482f1967f1a67130b7105cd6a000e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1378495795; genesis.nBits = 0x1e0fffff; genesis.nNonce = 285333548; //// debug print hashGenesisBlock = genesis.GetHash(); /* while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()) { if (++genesis.nNonce==0) break; hashGenesisBlock = genesis.GetHash(); } */ printf("hashGenesisBlock = %s\n", hashGenesisBlock.ToString().c_str()); printf("hashMerkleRoot = %s\n", genesis.hashMerkleRoot.ToString().c_str()); printf("%x\n", bnProofOfWorkLimit.GetCompact()); genesis.print(); assert(hashGenesisBlock == uint256("0x000000e02a1a674989cc114a50fea6d46e9fd18620129418589364b75f3292ac")); assert(genesis.hashMerkleRoot == uint256("0xaee5ee4074090a7564fd6a51e16a9e0ef4656d14fe4798be3e13d085cbbf7577")); vSeeds.push_back(CDNSSeedData("bitcoin.sipa.be", "seed.bitcoin.sipa.be")); vSeeds.push_back(CDNSSeedData("bluematt.me", "dnsseed.bluematt.me")); vSeeds.push_back(CDNSSeedData("xf2.org", "bitseed.xf2.org")); vSeeds.push_back(CDNSSeedData("dashjr.org", "dnsseed.bitcoin.dashjr.org")); base58Prefixes[PUBKEY_ADDRESS] = 127; base58Prefixes[SCRIPT_ADDRESS] = 9; base58Prefixes[SECRET_KEY] = 224; // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' const int64 nTwoDays = 2 * 24 * 60 * 60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0x05; pchMessageStart[1] = 0xfe; pchMessageStart[2] = 0xa9; pchMessageStart[3] = 0x01; vAlertPubKey = ParseHex("043a314ee36a4796baeb6a488e38f62c45f2dc69331cfc49b2a867fa95467f4e3aac21a03bebe8f977d7f29fb4487a5947a98cc38d3c48dd04c261899f4384fd6c"); nDefaultPort = 28077; nRPCPort = 28078; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1439972967; genesis.nNonce = 4224972; //// debug print hashGenesisBlock = genesis.GetHash(); //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){ // if (++genesis.nNonce==0) break; // hashGenesisBlock = genesis.GetHash(); //} printf("hashGenesisBlock-testnet = %s\n", hashGenesisBlock.ToString().c_str()); printf("hashMerkleRoot-testnet = %s\n", genesis.hashMerkleRoot.ToString().c_str()); genesis.print(); assert(hashGenesisBlock == uint256("0x000000d1641a6b5ec882202ebfd57c7b3fd92ecdc974320d4c7ef2e07ae019cf")); vFixedSeeds.clear(); vSeeds.clear(); // vSeeds.push_back(CDNSSeedData("tigercoin.test", "test.tigercoin.org")); base58Prefixes[PUBKEY_ADDRESS] = 77; base58Prefixes[SCRIPT_ADDRESS] = 177; base58Prefixes[SECRET_KEY] = 239; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0x0f; pchMessageStart[2] = 0xa5; pchMessageStart[3] = 0x5a; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1396688602; genesis.nBits = 0x207fffff; genesis.nNonce = 3; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 28444; strDataDir = "regtest"; //// debug print hashGenesisBlock = genesis.GetHash(); //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){ // if (++genesis.nNonce==0) break; // hashGenesisBlock = genesis.GetHash(); //} printf("%s\n", hashGenesisBlock.ToString().c_str()); printf("%s\n", genesis.hashMerkleRoot.ToString().c_str()); genesis.print(); // assert(hashGenesisBlock == uint256("0x13d8d31dde96874006da503dd2b63fa68c698dc823334359e417aa3a92f80433")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. base58Prefixes[PUBKEY_ADDRESS] = 0; base58Prefixes[SCRIPT_ADDRESS] = 5; base58Prefixes[SECRET_KEY] = 128; } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010 Belledonne Communications SARL. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTIC<ULAR 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 "module.hh" #include "agent.hh" #include <sofia-sip/msg_addr.h> using namespace ::std; class NatHelper : public Module, protected ModuleToolbox{ public: NatHelper(Agent *ag) : Module(ag){ } ~NatHelper(){ } virtual void onRequest(shared_ptr<RequestSipEvent> &ev) { const shared_ptr<MsgSip> &ms = ev->getMsgSip(); sip_t *sip=ms->getSip(); sip_request_t *rq = sip->sip_request; /* if we receive a request whose first via is wrong (received or rport parameters are present), fix any possible Contact headers with the same wrong ip address and ports */ fixContactFromVia(ms->getHome(), sip, sip->sip_via); if (rq->rq_method==sip_method_invite || rq->rq_method==sip_method_subscribe){ //be in the record route for all requests that can estabish a dialog addRecordRouteIncoming (ms->getHome(),getAgent(), ev); } if (rq->rq_method==sip_method_register && sip->sip_path && sip->sip_path->r_url && url_has_param(sip->sip_path->r_url, "uniq")) { // add remote to path const sip_via_t *via=sip->sip_via; const char *received=via->v_received; const char *rport=via->v_rport; const char *transport=sip_via_transport(via); url_t *path=sip->sip_path->r_url; if (empty(received)) received=via->v_host; if (!rport) rport=via->v_port; if (!transport) transport="udp"; path->url_host=received; path->url_port=rport; url_strip_transport(path); if (0 != strcasecmp(transport, "UDP")) url_param_add(ms->getHome(), path, transport); /* sip_path_t *path=rport ? sip_path_format(ms->getHome(),"sip:%s:%s;transport=%s;lr", received, rport, transport) : sip_path_format(ms->getHome(),"sip:%s;transport=%s;lr", received, transport); if (!prependNewRoutable(ms->getMsg(), sip, sip->sip_path, path)) { SLOGD << "Identical path already existing: " << url_as_string(ms->getHome(), path->r_url); } else { SLOGD << "Path added to: " << url_as_string(ms->getHome(), path->r_url); } */ } } virtual void onResponse(shared_ptr<ResponseSipEvent> &ev){ const shared_ptr<MsgSip> &ms = ev->getMsgSip(); sip_status_t *st = ms->getSip()->sip_status; sip_cseq_t *cseq = ms->getSip()->sip_cseq; /*in responses that establish a dialog, masquerade Contact so that further requests (including the ACK) are routed in the same way*/ if (cseq && (cseq->cs_method==sip_method_invite || cseq->cs_method==sip_method_subscribe)){ if (st->st_status>=200 && st->st_status<=299){ sip_contact_t *ct = ms->getSip()->sip_contact; if (ct && ct->m_url) { if (!url_has_param(ct->m_url, mContactVerifiedParam.c_str())) { fixContactInResponse(ms->getHome(),ms->getMsg(),ms->getSip()); url_param_add(ms->getHome(), ct->m_url, mContactVerifiedParam.c_str()); } else if (ms->getSip()->sip_via && ms->getSip()->sip_via->v_next && !ms->getSip()->sip_via->v_next->v_next) { // Via contains client and first proxy LOGD("Removing verified param from response contact"); ct->m_url->url_params = url_strip_param_string(su_strdup(ms->getHome(),ct->m_url->url_params),mContactVerifiedParam.c_str()); } } } } } protected: virtual void onDeclare(GenericStruct * module_config){ ConfigItemDescriptor items[]={ { String , "contact-verified-param" , "Internal URI parameter added to response contact by first proxy and cleaned by last one.", "verified" }, config_item_end }; module_config->addChildrenValues(items); } virtual void onLoad(const GenericStruct *root){ mContactVerifiedParam=root->get<ConfigString>("contact-verified-param")->read(); } private: string mContactVerifiedParam; bool empty(const char *value){ return value==NULL || value[0]=='\0'; } void fixContactInResponse(su_home_t *home, msg_t *msg, sip_t *sip){ const su_addrinfo_t *ai=msg_addrinfo(msg); const sip_via_t *via=sip->sip_via; const char *via_transport=sip_via_transport(via); char ct_transport[20]={0}; if (ai!=NULL){ char ip[NI_MAXHOST]; char port[NI_MAXSERV]; int err=getnameinfo(ai->ai_addr,ai->ai_addrlen,ip,sizeof(ip),port,sizeof(port),NI_NUMERICHOST|NI_NUMERICSERV); if (err!=0){ LOGE("getnameinfo() error: %s",gai_strerror(err)); }else{ sip_contact_t *ctt=sip->sip_contact; if (ctt && ctt->m_url && ctt->m_url->url_host){ if (strcmp(ip,ctt->m_url->url_host)!=0 || !sipPortEquals(ctt->m_url->url_port,port)){ LOGD("Response is coming from %s:%s, fixing contact",ip,port); ctt->m_url->url_host=su_strdup(home,ip); ctt->m_url->url_port=su_strdup(home,port); }else LOGD("Contact in response is correct."); url_param(ctt->m_url->url_params,"transport",ct_transport,sizeof(ct_transport)-1); if (strcasecmp(via_transport,"UDP")==0){ if (ct_transport[0]!='\0'){ LOGD("Contact in response has incorrect transport parameter, removing it"); ctt->m_url->url_params=url_strip_param_string(su_strdup(home,ctt->m_url->url_params),"transport"); } }else if (strcasecmp(via_transport,ct_transport)!=0) { char param[64]; snprintf(param,sizeof(param)-1,"transport=%s",via_transport); LOGD("Contact in response has incorrect transport parameter, replacing by %s",via_transport); ctt->m_url->url_params=url_strip_param_string(su_strdup(home,ctt->m_url->url_params),"transport"); url_param_add(home,ctt->m_url,param); } } } } } void fixContactFromVia(su_home_t *home, sip_t *msg, const sip_via_t *via){ sip_contact_t *ctt=msg->sip_contact; const char *received=via->v_received; const char *rport=via->v_rport; const char *via_transport=sip_via_transport(via); bool is_frontend=(via->v_next==NULL); /*true if we are the first proxy the request is walking through*/ bool single_contact=(ctt!=NULL && ctt->m_next==NULL); if (empty(received) && empty(rport)) return; /*nothing to do*/ if (empty(received)){ /*case where the rport is not empty but received is empty (because the host was correct)*/ received=via->v_host; } if (rport==NULL) rport=via->v_port; //if no rport is given, then trust the via port. for (;ctt!=NULL;ctt=ctt->m_next){ if (ctt->m_url && ctt->m_url->url_host){ const char *host=ctt->m_url->url_host; char ct_transport[20]={0}; url_param(ctt->m_url->url_params,"transport",ct_transport,sizeof(ct_transport)-1); /*If we have a single contact and we are the front-end proxy, or if we found a ip:port in a contact that seems incorrect because the same appeared fixed in the via, then fix it*/ if ( (is_frontend && single_contact) || (strcmp(host,via->v_host)==0 && sipPortEquals(ctt->m_url->url_port,via->v_port) && transportEquals(via_transport,ct_transport))){ if (strcmp(host,received)!=0 || !sipPortEquals(ctt->m_url->url_port,rport)){ LOGD("Fixing contact header with %s:%s to %s:%s", ctt->m_url->url_host, ctt->m_url->url_port ? ctt->m_url->url_port :"" , received, rport ? rport : ""); ctt->m_url->url_host=received; ctt->m_url->url_port=rport; } if (!transportEquals(via_transport,ct_transport)) { char param[64]; snprintf(param,sizeof(param)-1,"transport=%s",via_transport); LOGD("Contact in request has incorrect transport parameter, replacing by %s",via_transport); ctt->m_url->url_params=url_strip_param_string(su_strdup(home,ctt->m_url->url_params),"transport"); url_param_add(home,ctt->m_url,param); } } } } } static ModuleInfo<NatHelper> sInfo; }; ModuleInfo<NatHelper> NatHelper::sInfo("NatHelper", "The NatHelper module executes small tasks to make SIP work smoothly despite firewalls." "It corrects the Contact headers that contain obviously inconsistent addresses, and adds " "a Record-Route to ensure subsequent requests are routed also by the proxy, through the UDP or TCP " "channel each client opened to the proxy.", ModuleInfoBase::ModuleOid::NatHelper); <commit_msg>Don't use url_strip_transport in path nat helper<commit_after>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010 Belledonne Communications SARL. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTIC<ULAR 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 "module.hh" #include "agent.hh" #include <sofia-sip/msg_addr.h> using namespace ::std; class NatHelper : public Module, protected ModuleToolbox{ public: NatHelper(Agent *ag) : Module(ag){ } ~NatHelper(){ } virtual void onRequest(shared_ptr<RequestSipEvent> &ev) { const shared_ptr<MsgSip> &ms = ev->getMsgSip(); sip_t *sip=ms->getSip(); sip_request_t *rq = sip->sip_request; /* if we receive a request whose first via is wrong (received or rport parameters are present), fix any possible Contact headers with the same wrong ip address and ports */ fixContactFromVia(ms->getHome(), sip, sip->sip_via); if (rq->rq_method==sip_method_invite || rq->rq_method==sip_method_subscribe){ //be in the record route for all requests that can estabish a dialog addRecordRouteIncoming (ms->getHome(),getAgent(), ev); } if (rq->rq_method==sip_method_register && sip->sip_path && sip->sip_path->r_url && url_has_param(sip->sip_path->r_url, "uniq")) { // add remote to path const sip_via_t *via=sip->sip_via; const char *received=via->v_received; const char *rport=via->v_rport; const char *transport=sip_via_transport(via); url_t *path=sip->sip_path->r_url; if (empty(received)) received=via->v_host; if (!rport) rport=via->v_port; if (!transport) transport="udp"; path->url_host=received; path->url_port=rport; // url_strip_transport is not what we want // note that params will never be null url_strip_param_string((char*) path->url_params, "transport"); if (0 != strcasecmp(transport, "UDP")) url_param_add(ms->getHome(), path, transport); /* sip_path_t *path=rport ? sip_path_format(ms->getHome(),"sip:%s:%s;transport=%s;lr", received, rport, transport) : sip_path_format(ms->getHome(),"sip:%s;transport=%s;lr", received, transport); if (!prependNewRoutable(ms->getMsg(), sip, sip->sip_path, path)) { SLOGD << "Identical path already existing: " << url_as_string(ms->getHome(), path->r_url); } else { SLOGD << "Path added to: " << url_as_string(ms->getHome(), path->r_url); } */ } } virtual void onResponse(shared_ptr<ResponseSipEvent> &ev){ const shared_ptr<MsgSip> &ms = ev->getMsgSip(); sip_status_t *st = ms->getSip()->sip_status; sip_cseq_t *cseq = ms->getSip()->sip_cseq; /*in responses that establish a dialog, masquerade Contact so that further requests (including the ACK) are routed in the same way*/ if (cseq && (cseq->cs_method==sip_method_invite || cseq->cs_method==sip_method_subscribe)){ if (st->st_status>=200 && st->st_status<=299){ sip_contact_t *ct = ms->getSip()->sip_contact; if (ct && ct->m_url) { if (!url_has_param(ct->m_url, mContactVerifiedParam.c_str())) { fixContactInResponse(ms->getHome(),ms->getMsg(),ms->getSip()); url_param_add(ms->getHome(), ct->m_url, mContactVerifiedParam.c_str()); } else if (ms->getSip()->sip_via && ms->getSip()->sip_via->v_next && !ms->getSip()->sip_via->v_next->v_next) { // Via contains client and first proxy LOGD("Removing verified param from response contact"); ct->m_url->url_params = url_strip_param_string(su_strdup(ms->getHome(),ct->m_url->url_params),mContactVerifiedParam.c_str()); } } } } } protected: virtual void onDeclare(GenericStruct * module_config){ ConfigItemDescriptor items[]={ { String , "contact-verified-param" , "Internal URI parameter added to response contact by first proxy and cleaned by last one.", "verified" }, config_item_end }; module_config->addChildrenValues(items); } virtual void onLoad(const GenericStruct *root){ mContactVerifiedParam=root->get<ConfigString>("contact-verified-param")->read(); } private: string mContactVerifiedParam; bool empty(const char *value){ return value==NULL || value[0]=='\0'; } void fixContactInResponse(su_home_t *home, msg_t *msg, sip_t *sip){ const su_addrinfo_t *ai=msg_addrinfo(msg); const sip_via_t *via=sip->sip_via; const char *via_transport=sip_via_transport(via); char ct_transport[20]={0}; if (ai!=NULL){ char ip[NI_MAXHOST]; char port[NI_MAXSERV]; int err=getnameinfo(ai->ai_addr,ai->ai_addrlen,ip,sizeof(ip),port,sizeof(port),NI_NUMERICHOST|NI_NUMERICSERV); if (err!=0){ LOGE("getnameinfo() error: %s",gai_strerror(err)); }else{ sip_contact_t *ctt=sip->sip_contact; if (ctt && ctt->m_url && ctt->m_url->url_host){ if (strcmp(ip,ctt->m_url->url_host)!=0 || !sipPortEquals(ctt->m_url->url_port,port)){ LOGD("Response is coming from %s:%s, fixing contact",ip,port); ctt->m_url->url_host=su_strdup(home,ip); ctt->m_url->url_port=su_strdup(home,port); }else LOGD("Contact in response is correct."); url_param(ctt->m_url->url_params,"transport",ct_transport,sizeof(ct_transport)-1); if (strcasecmp(via_transport,"UDP")==0){ if (ct_transport[0]!='\0'){ LOGD("Contact in response has incorrect transport parameter, removing it"); ctt->m_url->url_params=url_strip_param_string(su_strdup(home,ctt->m_url->url_params),"transport"); } }else if (strcasecmp(via_transport,ct_transport)!=0) { char param[64]; snprintf(param,sizeof(param)-1,"transport=%s",via_transport); LOGD("Contact in response has incorrect transport parameter, replacing by %s",via_transport); ctt->m_url->url_params=url_strip_param_string(su_strdup(home,ctt->m_url->url_params),"transport"); url_param_add(home,ctt->m_url,param); } } } } } void fixContactFromVia(su_home_t *home, sip_t *msg, const sip_via_t *via){ sip_contact_t *ctt=msg->sip_contact; const char *received=via->v_received; const char *rport=via->v_rport; const char *via_transport=sip_via_transport(via); bool is_frontend=(via->v_next==NULL); /*true if we are the first proxy the request is walking through*/ bool single_contact=(ctt!=NULL && ctt->m_next==NULL); if (empty(received) && empty(rport)) return; /*nothing to do*/ if (empty(received)){ /*case where the rport is not empty but received is empty (because the host was correct)*/ received=via->v_host; } if (rport==NULL) rport=via->v_port; //if no rport is given, then trust the via port. for (;ctt!=NULL;ctt=ctt->m_next){ if (ctt->m_url && ctt->m_url->url_host){ const char *host=ctt->m_url->url_host; char ct_transport[20]={0}; url_param(ctt->m_url->url_params,"transport",ct_transport,sizeof(ct_transport)-1); /*If we have a single contact and we are the front-end proxy, or if we found a ip:port in a contact that seems incorrect because the same appeared fixed in the via, then fix it*/ if ( (is_frontend && single_contact) || (strcmp(host,via->v_host)==0 && sipPortEquals(ctt->m_url->url_port,via->v_port) && transportEquals(via_transport,ct_transport))){ if (strcmp(host,received)!=0 || !sipPortEquals(ctt->m_url->url_port,rport)){ LOGD("Fixing contact header with %s:%s to %s:%s", ctt->m_url->url_host, ctt->m_url->url_port ? ctt->m_url->url_port :"" , received, rport ? rport : ""); ctt->m_url->url_host=received; ctt->m_url->url_port=rport; } if (!transportEquals(via_transport,ct_transport)) { char param[64]; snprintf(param,sizeof(param)-1,"transport=%s",via_transport); LOGD("Contact in request has incorrect transport parameter, replacing by %s",via_transport); ctt->m_url->url_params=url_strip_param_string(su_strdup(home,ctt->m_url->url_params),"transport"); url_param_add(home,ctt->m_url,param); } } } } } static ModuleInfo<NatHelper> sInfo; }; ModuleInfo<NatHelper> NatHelper::sInfo("NatHelper", "The NatHelper module executes small tasks to make SIP work smoothly despite firewalls." "It corrects the Contact headers that contain obviously inconsistent addresses, and adds " "a Record-Route to ensure subsequent requests are routed also by the proxy, through the UDP or TCP " "channel each client opened to the proxy.", ModuleInfoBase::ModuleOid::NatHelper); <|endoftext|>
<commit_before>// Copyright (c) 2011-2013, Zeex // 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 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 <iomanip> #include <iostream> #include "duration.h" #include "function.h" #include "function_statistics.h" #include "statistics_writer_html.h" #include "performance_counter.h" #include "statistics.h" #include "time_utils.h" namespace amxprof { void StatisticsWriterHtml::Write(const Statistics *stats) { *stream() << "<!DOCTYPE html>\n" "<html>\n" "<head>\n" " <title>" << "Profile of '" << script_name() << "'</title>\n" " <script type=\"text/javascript\"\n" " src=\"http://code.jquery.com/jquery-latest.min.js\">\n" " </script>\n" " <script type=\"text/javascript\"\n" " src=\"http://tablesorter.com/__jquery.tablesorter.min.js\">\n" " </script>\n" " <script type=\"text/javascript\">\n" " $(document).ready(function() {\n" " $('#data').tablesorter();\n" " });\n" " </script>\n" "</head>\n" "<body>\n" ; *stream() << " <style type=\"text/css\">\n" " table {\n" " border-spacing: 0;\n" " border-collapse: collapse;\n" " }\n" " table#data {\n" " width: 100%;\n" " }\n" " table, th, td {\n" " border-width: thin;\n" " border-style: solid;\n" " border-color: #aaaaaa;\n" " }\n" " th {\n" " text-align: left;\n" " background-color: #cccccc;\n" " }\n" " th.group {\n" " text-align: center;\n" " }\n" " td {\n" " text-align: left;\n" " font-family: Consolas, \"DejaVu Sans Mono\", \"Courier New\", Monospace;\n" " }\n" " tbody tr:nth-child(odd) {\n" " background-color: #eeeeee;\n" " }\n" " tbody tr:hover {\n" " background-color: #c0e3eb;\n" " }\n" " </style>\n" " <table id=\"meta\">\n" " <thead>\n" " <tr>\n" " <th>Name</th>\n" " <th>Value</th>\n" " </tr>\n" " </thead>\n" " <tbody>\n" ; if (print_date()) { *stream() << " <tr>\n" " <td>Date</td>\n" " <td>" << CTime() << "</td>\n" " </tr>\n" ; } if (print_run_time()) { *stream() << " <tr>\n" " <td>Duration</td>\n" " <td>" << TimeSpan(stats->GetTotalRunTime()) << "</td>\n" " </tr>\n" ; } *stream() << " </tbody>\n" " </table>\n" " <br/>\n" " <table id=\"data\" class=\"tablesorter\">\n" " <thead>\n" " <tr>\n" " <th rowspan=\"2\">Type</th>\n" " <th rowspan=\"2\">Name</th>\n" " <th rowspan=\"2\">Calls</th>\n" " <th colspan=\"4\" class=\"group\">Self Time</th>\n" " <th colspan=\"4\" class=\"group\">Total Time</th>\n" " </tr>\n" " <tr>\n" " <th>%</th>\n" " <th>whole</th>\n" " <th>average</th>\n" " <th>worst</th>\n" " <th>%</th>\n" " <th>whole</th>\n" " <th>average</th>\n" " <th>worst</th>\n" " </tr>\n" " </thead>\n" " <tbody>\n" ; std::vector<FunctionStatistics*> all_fn_stats; stats->GetStatistics(all_fn_stats); Nanoseconds self_time_all; for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin(); iterator != all_fn_stats.end(); ++iterator) { const FunctionStatistics *fn_stats = *iterator; self_time_all += fn_stats->self_time(); }; Nanoseconds total_time_all; for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin(); iterator != all_fn_stats.end(); ++iterator) { const FunctionStatistics *fn_stats = *iterator; total_time_all += fn_stats->total_time(); }; std::ostream::fmtflags flags = stream()->flags(); stream()->flags(flags | std::ostream::fixed); for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin(); iterator != all_fn_stats.end(); ++iterator) { const FunctionStatistics *fn_stats = *iterator; double self_time_percent = fn_stats->self_time().count() * 100 / self_time_all.count(); double total_time_percent = fn_stats->total_time().count() * 100 / total_time_all.count(); double self_time = Seconds(fn_stats->self_time()).count(); double total_time = Seconds(fn_stats->total_time()).count(); double avg_self_time = Milliseconds(fn_stats->self_time()).count() / fn_stats->num_calls(); double avg_total_time = Milliseconds(fn_stats->total_time()).count() / fn_stats->num_calls(); double worst_self_time = Milliseconds(fn_stats->worst_self_time()).count(); double worst_total_time = Milliseconds(fn_stats->worst_total_time()).count(); *stream() << " <tr>\n" << " <td>" << fn_stats->function()->GetTypeString() << "</td>\n" << " <td>" << fn_stats->function()->name() << "</td>\n" << " <td>" << fn_stats->num_calls() << "</td>\n" << " <td>" << std::setprecision(2) << self_time_percent << "%</td>\n" << " <td>" << std::setprecision(1) << self_time << "</td>\n" << " <td>" << std::setprecision(1) << avg_self_time << "</td>\n" << " <td>" << std::setprecision(1) << worst_self_time << "</td>\n" << " <td>" << std::setprecision(2) << total_time_percent << "%</td>\n" << " <td>" << std::setprecision(1) << total_time << "</td>\n" << " <td>" << std::setprecision(1) << avg_total_time << "</td>\n" << " <td>" << std::setprecision(1) << worst_total_time << "</td>\n" << " </tr>\n"; }; stream()->flags(flags); *stream() << " </tbody>\n" " </table>\n" "</body>\n" "</html>\n" ; } } // namespace amxprof <commit_msg>Whole time -> Overall time<commit_after>// Copyright (c) 2011-2013, Zeex // 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 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 <iomanip> #include <iostream> #include "duration.h" #include "function.h" #include "function_statistics.h" #include "statistics_writer_html.h" #include "performance_counter.h" #include "statistics.h" #include "time_utils.h" namespace amxprof { void StatisticsWriterHtml::Write(const Statistics *stats) { *stream() << "<!DOCTYPE html>\n" "<html>\n" "<head>\n" " <title>" << "Profile of '" << script_name() << "'</title>\n" " <script type=\"text/javascript\"\n" " src=\"http://code.jquery.com/jquery-latest.min.js\">\n" " </script>\n" " <script type=\"text/javascript\"\n" " src=\"http://tablesorter.com/__jquery.tablesorter.min.js\">\n" " </script>\n" " <script type=\"text/javascript\">\n" " $(document).ready(function() {\n" " $('#data').tablesorter();\n" " });\n" " </script>\n" "</head>\n" "<body>\n" ; *stream() << " <style type=\"text/css\">\n" " table {\n" " border-spacing: 0;\n" " border-collapse: collapse;\n" " }\n" " table#data {\n" " width: 100%;\n" " }\n" " table, th, td {\n" " border-width: thin;\n" " border-style: solid;\n" " border-color: #aaaaaa;\n" " }\n" " th {\n" " text-align: left;\n" " background-color: #cccccc;\n" " }\n" " th.group {\n" " text-align: center;\n" " }\n" " td {\n" " text-align: left;\n" " font-family: Consolas, \"DejaVu Sans Mono\", \"Courier New\", Monospace;\n" " }\n" " tbody tr:nth-child(odd) {\n" " background-color: #eeeeee;\n" " }\n" " tbody tr:hover {\n" " background-color: #c0e3eb;\n" " }\n" " </style>\n" " <table id=\"meta\">\n" " <thead>\n" " <tr>\n" " <th>Name</th>\n" " <th>Value</th>\n" " </tr>\n" " </thead>\n" " <tbody>\n" ; if (print_date()) { *stream() << " <tr>\n" " <td>Date</td>\n" " <td>" << CTime() << "</td>\n" " </tr>\n" ; } if (print_run_time()) { *stream() << " <tr>\n" " <td>Duration</td>\n" " <td>" << TimeSpan(stats->GetTotalRunTime()) << "</td>\n" " </tr>\n" ; } *stream() << " </tbody>\n" " </table>\n" " <br/>\n" " <table id=\"data\" class=\"tablesorter\">\n" " <thead>\n" " <tr>\n" " <th rowspan=\"2\">Type</th>\n" " <th rowspan=\"2\">Name</th>\n" " <th rowspan=\"2\">Calls</th>\n" " <th colspan=\"4\" class=\"group\">Self Time</th>\n" " <th colspan=\"4\" class=\"group\">Total Time</th>\n" " </tr>\n" " <tr>\n" " <th>%</th>\n" " <th>overall</th>\n" " <th>average</th>\n" " <th>worst</th>\n" " <th>%</th>\n" " <th>overall</th>\n" " <th>average</th>\n" " <th>worst</th>\n" " </tr>\n" " </thead>\n" " <tbody>\n" ; std::vector<FunctionStatistics*> all_fn_stats; stats->GetStatistics(all_fn_stats); Nanoseconds self_time_all; for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin(); iterator != all_fn_stats.end(); ++iterator) { const FunctionStatistics *fn_stats = *iterator; self_time_all += fn_stats->self_time(); }; Nanoseconds total_time_all; for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin(); iterator != all_fn_stats.end(); ++iterator) { const FunctionStatistics *fn_stats = *iterator; total_time_all += fn_stats->total_time(); }; std::ostream::fmtflags flags = stream()->flags(); stream()->flags(flags | std::ostream::fixed); for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin(); iterator != all_fn_stats.end(); ++iterator) { const FunctionStatistics *fn_stats = *iterator; double self_time_percent = fn_stats->self_time().count() * 100 / self_time_all.count(); double total_time_percent = fn_stats->total_time().count() * 100 / total_time_all.count(); double self_time = Seconds(fn_stats->self_time()).count(); double total_time = Seconds(fn_stats->total_time()).count(); double avg_self_time = Milliseconds(fn_stats->self_time()).count() / fn_stats->num_calls(); double avg_total_time = Milliseconds(fn_stats->total_time()).count() / fn_stats->num_calls(); double worst_self_time = Milliseconds(fn_stats->worst_self_time()).count(); double worst_total_time = Milliseconds(fn_stats->worst_total_time()).count(); *stream() << " <tr>\n" << " <td>" << fn_stats->function()->GetTypeString() << "</td>\n" << " <td>" << fn_stats->function()->name() << "</td>\n" << " <td>" << fn_stats->num_calls() << "</td>\n" << " <td>" << std::setprecision(2) << self_time_percent << "%</td>\n" << " <td>" << std::setprecision(1) << self_time << "</td>\n" << " <td>" << std::setprecision(1) << avg_self_time << "</td>\n" << " <td>" << std::setprecision(1) << worst_self_time << "</td>\n" << " <td>" << std::setprecision(2) << total_time_percent << "%</td>\n" << " <td>" << std::setprecision(1) << total_time << "</td>\n" << " <td>" << std::setprecision(1) << avg_total_time << "</td>\n" << " <td>" << std::setprecision(1) << worst_total_time << "</td>\n" << " </tr>\n"; }; stream()->flags(flags); *stream() << " </tbody>\n" " </table>\n" "</body>\n" "</html>\n" ; } } // namespace amxprof <|endoftext|>
<commit_before>/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <jni.h> #include <aws/testing/android/AndroidTesting.h> #ifdef __cplusplus extern "C" { #endif // __cplusplus JNIEXPORT jint JNICALL Java_aws_coretests_TestActivity_linkTest( JNIEnv* env, jobject classRef, jobject context ) { return Java_aws_coretests_TestActivity_runTests(env, classRef, context); } #ifdef __cplusplus } #endif // __cplusplus <commit_msg>Bad path in android testing project<commit_after>/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <jni.h> #include <aws/testing/platform/android/AndroidTesting.h> #ifdef __cplusplus extern "C" { #endif // __cplusplus JNIEXPORT jint JNICALL Java_aws_coretests_TestActivity_linkTest( JNIEnv* env, jobject classRef, jobject context ) { return Java_aws_coretests_TestActivity_runTests(env, classRef, context); } #ifdef __cplusplus } #endif // __cplusplus <|endoftext|>
<commit_before>//===-- FunctionLoweringInfo.cpp ------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This implements routines for translating functions from LLVM IR into // Machine IR. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "function-lowering-info" #include "FunctionLoweringInfo.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/IntrinsicInst.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/CodeGen/Analysis.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetFrameInfo.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetIntrinsicInfo.h" #include "llvm/Target/TargetLowering.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MathExtras.h" #include <algorithm> using namespace llvm; /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by /// PHI nodes or outside of the basic block that defines it, or used by a /// switch or atomic instruction, which may expand to multiple basic blocks. static bool isUsedOutsideOfDefiningBlock(const Instruction *I) { if (I->use_empty()) return false; if (isa<PHINode>(I)) return true; const BasicBlock *BB = I->getParent(); for (Value::const_use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI) if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI)) return true; return false; } /// isOnlyUsedInEntryBlock - If the specified argument is only used in the /// entry block, return true. This includes arguments used by switches, since /// the switch may expand into multiple basic blocks. static bool isOnlyUsedInEntryBlock(const Argument *A, bool EnableFastISel) { // With FastISel active, we may be splitting blocks, so force creation // of virtual registers for all non-dead arguments. if (EnableFastISel) return A->use_empty(); const BasicBlock *Entry = A->getParent()->begin(); for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI) if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI)) return false; // Use not in entry block. return true; } FunctionLoweringInfo::FunctionLoweringInfo(const TargetLowering &tli) : TLI(tli) { } void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf) { Fn = &fn; MF = &mf; RegInfo = &MF->getRegInfo(); // Create a vreg for each argument register that is not dead and is used // outside of the entry block for the function. for (Function::const_arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end(); AI != E; ++AI) if (!isOnlyUsedInEntryBlock(AI, EnableFastISel)) InitializeRegForValue(AI); // Initialize the mapping of values to registers. This is only set up for // instruction values that are used outside of the block that defines // them. Function::const_iterator BB = Fn->begin(), EB = Fn->end(); for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) { const Type *Ty = AI->getAllocatedType(); uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty); unsigned Align = std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), AI->getAlignment()); TySize *= CUI->getZExtValue(); // Get total allocated size. if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects. StaticAllocaMap[AI] = MF->getFrameInfo()->CreateStackObject(TySize, Align, false); } for (; BB != EB; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) if (isUsedOutsideOfDefiningBlock(I)) if (!isa<AllocaInst>(I) || !StaticAllocaMap.count(cast<AllocaInst>(I))) InitializeRegForValue(I); // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This // also creates the initial PHI MachineInstrs, though none of the input // operands are populated. for (BB = Fn->begin(); BB != EB; ++BB) { MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB); MBBMap[BB] = MBB; MF->push_back(MBB); // Transfer the address-taken flag. This is necessary because there could // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only // the first one should be marked. if (BB->hasAddressTaken()) MBB->setHasAddressTaken(); // Create Machine PHI nodes for LLVM PHI nodes, lowering them as // appropriate. for (BasicBlock::const_iterator I = BB->begin(); const PHINode *PN = dyn_cast<PHINode>(I); ++I) { if (PN->use_empty()) continue; DebugLoc DL = PN->getDebugLoc(); unsigned PHIReg = ValueMap[PN]; assert(PHIReg && "PHI node does not have an assigned virtual register!"); SmallVector<EVT, 4> ValueVTs; ComputeValueVTs(TLI, PN->getType(), ValueVTs); for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { EVT VT = ValueVTs[vti]; unsigned NumRegisters = TLI.getNumRegisters(Fn->getContext(), VT); const TargetInstrInfo *TII = MF->getTarget().getInstrInfo(); for (unsigned i = 0; i != NumRegisters; ++i) BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i); PHIReg += NumRegisters; } } } // Mark landing pad blocks. for (BB = Fn->begin(); BB != EB; ++BB) if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator())) MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad(); } /// clear - Clear out all the function-specific state. This returns this /// FunctionLoweringInfo to an empty state, ready to be used for a /// different function. void FunctionLoweringInfo::clear() { assert(CatchInfoFound.size() == CatchInfoLost.size() && "Not all catch info was assigned to a landing pad!"); MBBMap.clear(); ValueMap.clear(); StaticAllocaMap.clear(); #ifndef NDEBUG CatchInfoLost.clear(); CatchInfoFound.clear(); #endif LiveOutRegInfo.clear(); ArgDbgValues.clear(); } unsigned FunctionLoweringInfo::MakeReg(EVT VT) { return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT)); } /// CreateRegForValue - Allocate the appropriate number of virtual registers of /// the correctly promoted or expanded types. Assign these registers /// consecutive vreg numbers and return the first assigned number. /// /// In the case that the given value has struct or array type, this function /// will assign registers for each member or element. /// unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) { SmallVector<EVT, 4> ValueVTs; ComputeValueVTs(TLI, V->getType(), ValueVTs); unsigned FirstReg = 0; for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { EVT ValueVT = ValueVTs[Value]; EVT RegisterVT = TLI.getRegisterType(V->getContext(), ValueVT); unsigned NumRegs = TLI.getNumRegisters(V->getContext(), ValueVT); for (unsigned i = 0; i != NumRegs; ++i) { unsigned R = MakeReg(RegisterVT); if (!FirstReg) FirstReg = R; } } return FirstReg; } /// AddCatchInfo - Extract the personality and type infos from an eh.selector /// call, and add them to the specified machine basic block. void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI, MachineBasicBlock *MBB) { // Inform the MachineModuleInfo of the personality for this landing pad. const ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2)); assert(CE->getOpcode() == Instruction::BitCast && isa<Function>(CE->getOperand(0)) && "Personality should be a function"); MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0))); // Gather all the type infos for this landing pad and pass them along to // MachineModuleInfo. std::vector<const GlobalVariable *> TyInfo; unsigned N = I.getNumOperands(); for (unsigned i = N - 1; i > 2; --i) { if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) { unsigned FilterLength = CI->getZExtValue(); unsigned FirstCatch = i + FilterLength + !FilterLength; assert (FirstCatch <= N && "Invalid filter length"); if (FirstCatch < N) { TyInfo.reserve(N - FirstCatch); for (unsigned j = FirstCatch; j < N; ++j) TyInfo.push_back(ExtractTypeInfo(I.getOperand(j))); MMI->addCatchTypeInfo(MBB, TyInfo); TyInfo.clear(); } if (!FilterLength) { // Cleanup. MMI->addCleanup(MBB); } else { // Filter. TyInfo.reserve(FilterLength - 1); for (unsigned j = i + 1; j < FirstCatch; ++j) TyInfo.push_back(ExtractTypeInfo(I.getOperand(j))); MMI->addFilterTypeInfo(MBB, TyInfo); TyInfo.clear(); } N = i; } } if (N > 3) { TyInfo.reserve(N - 3); for (unsigned j = 3; j < N; ++j) TyInfo.push_back(ExtractTypeInfo(I.getOperand(j))); MMI->addCatchTypeInfo(MBB, TyInfo); } } void llvm::CopyCatchInfo(const BasicBlock *SrcBB, const BasicBlock *DestBB, MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) { for (BasicBlock::const_iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I) if (const EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) { // Apply the catch info to DestBB. AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]); #ifndef NDEBUG if (!FLI.MBBMap[SrcBB]->isLandingPad()) FLI.CatchInfoFound.insert(EHSel); #endif } } <commit_msg>prune an include<commit_after>//===-- FunctionLoweringInfo.cpp ------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This implements routines for translating functions from LLVM IR into // Machine IR. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "function-lowering-info" #include "FunctionLoweringInfo.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/IntrinsicInst.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/CodeGen/Analysis.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetFrameInfo.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetLowering.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MathExtras.h" #include <algorithm> using namespace llvm; /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by /// PHI nodes or outside of the basic block that defines it, or used by a /// switch or atomic instruction, which may expand to multiple basic blocks. static bool isUsedOutsideOfDefiningBlock(const Instruction *I) { if (I->use_empty()) return false; if (isa<PHINode>(I)) return true; const BasicBlock *BB = I->getParent(); for (Value::const_use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI) if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI)) return true; return false; } /// isOnlyUsedInEntryBlock - If the specified argument is only used in the /// entry block, return true. This includes arguments used by switches, since /// the switch may expand into multiple basic blocks. static bool isOnlyUsedInEntryBlock(const Argument *A, bool EnableFastISel) { // With FastISel active, we may be splitting blocks, so force creation // of virtual registers for all non-dead arguments. if (EnableFastISel) return A->use_empty(); const BasicBlock *Entry = A->getParent()->begin(); for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI) if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI)) return false; // Use not in entry block. return true; } FunctionLoweringInfo::FunctionLoweringInfo(const TargetLowering &tli) : TLI(tli) { } void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf) { Fn = &fn; MF = &mf; RegInfo = &MF->getRegInfo(); // Create a vreg for each argument register that is not dead and is used // outside of the entry block for the function. for (Function::const_arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end(); AI != E; ++AI) if (!isOnlyUsedInEntryBlock(AI, EnableFastISel)) InitializeRegForValue(AI); // Initialize the mapping of values to registers. This is only set up for // instruction values that are used outside of the block that defines // them. Function::const_iterator BB = Fn->begin(), EB = Fn->end(); for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) { const Type *Ty = AI->getAllocatedType(); uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty); unsigned Align = std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), AI->getAlignment()); TySize *= CUI->getZExtValue(); // Get total allocated size. if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects. StaticAllocaMap[AI] = MF->getFrameInfo()->CreateStackObject(TySize, Align, false); } for (; BB != EB; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) if (isUsedOutsideOfDefiningBlock(I)) if (!isa<AllocaInst>(I) || !StaticAllocaMap.count(cast<AllocaInst>(I))) InitializeRegForValue(I); // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This // also creates the initial PHI MachineInstrs, though none of the input // operands are populated. for (BB = Fn->begin(); BB != EB; ++BB) { MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB); MBBMap[BB] = MBB; MF->push_back(MBB); // Transfer the address-taken flag. This is necessary because there could // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only // the first one should be marked. if (BB->hasAddressTaken()) MBB->setHasAddressTaken(); // Create Machine PHI nodes for LLVM PHI nodes, lowering them as // appropriate. for (BasicBlock::const_iterator I = BB->begin(); const PHINode *PN = dyn_cast<PHINode>(I); ++I) { if (PN->use_empty()) continue; DebugLoc DL = PN->getDebugLoc(); unsigned PHIReg = ValueMap[PN]; assert(PHIReg && "PHI node does not have an assigned virtual register!"); SmallVector<EVT, 4> ValueVTs; ComputeValueVTs(TLI, PN->getType(), ValueVTs); for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { EVT VT = ValueVTs[vti]; unsigned NumRegisters = TLI.getNumRegisters(Fn->getContext(), VT); const TargetInstrInfo *TII = MF->getTarget().getInstrInfo(); for (unsigned i = 0; i != NumRegisters; ++i) BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i); PHIReg += NumRegisters; } } } // Mark landing pad blocks. for (BB = Fn->begin(); BB != EB; ++BB) if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator())) MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad(); } /// clear - Clear out all the function-specific state. This returns this /// FunctionLoweringInfo to an empty state, ready to be used for a /// different function. void FunctionLoweringInfo::clear() { assert(CatchInfoFound.size() == CatchInfoLost.size() && "Not all catch info was assigned to a landing pad!"); MBBMap.clear(); ValueMap.clear(); StaticAllocaMap.clear(); #ifndef NDEBUG CatchInfoLost.clear(); CatchInfoFound.clear(); #endif LiveOutRegInfo.clear(); ArgDbgValues.clear(); } unsigned FunctionLoweringInfo::MakeReg(EVT VT) { return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT)); } /// CreateRegForValue - Allocate the appropriate number of virtual registers of /// the correctly promoted or expanded types. Assign these registers /// consecutive vreg numbers and return the first assigned number. /// /// In the case that the given value has struct or array type, this function /// will assign registers for each member or element. /// unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) { SmallVector<EVT, 4> ValueVTs; ComputeValueVTs(TLI, V->getType(), ValueVTs); unsigned FirstReg = 0; for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { EVT ValueVT = ValueVTs[Value]; EVT RegisterVT = TLI.getRegisterType(V->getContext(), ValueVT); unsigned NumRegs = TLI.getNumRegisters(V->getContext(), ValueVT); for (unsigned i = 0; i != NumRegs; ++i) { unsigned R = MakeReg(RegisterVT); if (!FirstReg) FirstReg = R; } } return FirstReg; } /// AddCatchInfo - Extract the personality and type infos from an eh.selector /// call, and add them to the specified machine basic block. void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI, MachineBasicBlock *MBB) { // Inform the MachineModuleInfo of the personality for this landing pad. const ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2)); assert(CE->getOpcode() == Instruction::BitCast && isa<Function>(CE->getOperand(0)) && "Personality should be a function"); MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0))); // Gather all the type infos for this landing pad and pass them along to // MachineModuleInfo. std::vector<const GlobalVariable *> TyInfo; unsigned N = I.getNumOperands(); for (unsigned i = N - 1; i > 2; --i) { if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) { unsigned FilterLength = CI->getZExtValue(); unsigned FirstCatch = i + FilterLength + !FilterLength; assert (FirstCatch <= N && "Invalid filter length"); if (FirstCatch < N) { TyInfo.reserve(N - FirstCatch); for (unsigned j = FirstCatch; j < N; ++j) TyInfo.push_back(ExtractTypeInfo(I.getOperand(j))); MMI->addCatchTypeInfo(MBB, TyInfo); TyInfo.clear(); } if (!FilterLength) { // Cleanup. MMI->addCleanup(MBB); } else { // Filter. TyInfo.reserve(FilterLength - 1); for (unsigned j = i + 1; j < FirstCatch; ++j) TyInfo.push_back(ExtractTypeInfo(I.getOperand(j))); MMI->addFilterTypeInfo(MBB, TyInfo); TyInfo.clear(); } N = i; } } if (N > 3) { TyInfo.reserve(N - 3); for (unsigned j = 3; j < N; ++j) TyInfo.push_back(ExtractTypeInfo(I.getOperand(j))); MMI->addCatchTypeInfo(MBB, TyInfo); } } void llvm::CopyCatchInfo(const BasicBlock *SrcBB, const BasicBlock *DestBB, MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) { for (BasicBlock::const_iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I) if (const EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) { // Apply the catch info to DestBB. AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]); #ifndef NDEBUG if (!FLI.MBBMap[SrcBB]->isLandingPad()) FLI.CatchInfoFound.insert(EHSel); #endif } } <|endoftext|>
<commit_before>#include <iostream> #include "Jitter_Statement.h" using namespace Jitter; std::string Jitter::ConditionToString(CONDITION condition) { switch(condition) { case CONDITION_LT: return "LT"; break; case CONDITION_LE: return "LE"; break; case CONDITION_GT: return "GT"; break; case CONDITION_EQ: return "EQ"; break; case CONDITION_NE: return "NE"; break; case CONDITION_BL: return "BL"; break; case CONDITION_AB: return "AB"; break; default: return "??"; break; } } void Jitter::DumpStatementList(const StatementList& statements) { for(const auto& statement : statements) { if(statement.dst) { std::cout << statement.dst->ToString(); std::cout << " := "; } if(statement.src1) { std::cout << statement.src1->ToString(); } switch(statement.op) { case OP_ADD: case OP_ADD64: case OP_ADDREF: case OP_FP_ADD: std::cout << " + "; break; case OP_SUB: case OP_SUB64: case OP_FP_SUB: std::cout << " - "; break; case OP_CMP: case OP_CMP64: case OP_FP_CMP: std::cout << " CMP(" << ConditionToString(statement.jmpCondition) << ") "; break; case OP_MUL: case OP_MULS: case OP_FP_MUL: std::cout << " * "; break; case OP_MULSHL: std::cout << " *(HL) "; break; case OP_MULSHH: std::cout << " *(HH) "; break; case OP_DIV: case OP_DIVS: case OP_FP_DIV: std::cout << " / "; break; case OP_AND: case OP_AND64: case OP_MD_AND: std::cout << " & "; break; case OP_LZC: std::cout << " LZC"; break; case OP_OR: case OP_MD_OR: std::cout << " | "; break; case OP_XOR: case OP_MD_XOR: std::cout << " ^ "; break; case OP_NOT: case OP_MD_NOT: std::cout << " ! "; break; case OP_SRL: case OP_SRL64: std::cout << " >> "; break; case OP_SRA: case OP_SRA64: std::cout << " >>A "; break; case OP_SLL: case OP_SLL64: std::cout << " << "; break; case OP_NOP: std::cout << " NOP "; break; case OP_MOV: break; case OP_STOREATREF: std::cout << " <- "; break; case OP_LOADFROMREF: std::cout << " LOADFROM "; break; case OP_RELTOREF: std::cout << " TOREF "; break; case OP_PARAM: case OP_PARAM_RET: std::cout << " PARAM "; break; case OP_CALL: std::cout << " CALL "; break; case OP_RETVAL: std::cout << " RETURNVALUE "; break; case OP_JMP: std::cout << " JMP{" << statement.jmpBlock << "} "; break; case OP_CONDJMP: std::cout << " JMP{" << statement.jmpBlock << "}(" << ConditionToString(statement.jmpCondition) << ") "; break; case OP_LABEL: std::cout << "LABEL_" << statement.jmpBlock << ":"; break; case OP_EXTLOW64: std::cout << " EXTLOW64"; break; case OP_EXTHIGH64: std::cout << " EXTHIGH64"; break; case OP_MERGETO64: std::cout << " MERGETO64 "; break; case OP_MERGETO256: std::cout << " MERGETO256 "; break; case OP_FP_ABS: std::cout << " ABS"; break; case OP_FP_NEG: std::cout << " NEG"; break; case OP_FP_MIN: std::cout << " MIN "; break; case OP_FP_MAX: std::cout << " MAX "; break; case OP_FP_SQRT: std::cout << " SQRT"; break; case OP_FP_RSQRT: std::cout << " RSQRT"; break; case OP_FP_RCPL: std::cout << " RCPL"; break; case OP_FP_TOINT_TRUNC: std::cout << " INT(TRUNC)"; break; case OP_FP_LDCST: std::cout << " LOAD "; break; case OP_MD_MOV_MASKED: std::cout << " MOVMSK "; break; case OP_MD_PACK_HB: std::cout << " PACK_HB "; break; case OP_MD_PACK_WH: std::cout << " PACK_WH "; break; case OP_MD_UNPACK_LOWER_BH: std::cout << " UNPACK_LOWER_BH "; break; case OP_MD_UNPACK_LOWER_HW: std::cout << " UNPACK_LOWER_HW "; break; case OP_MD_UNPACK_LOWER_WD: std::cout << " UNPACK_LOWER_WD "; break; case OP_MD_UNPACK_UPPER_BH: std::cout << " UNPACK_UPPER_BH "; break; case OP_MD_UNPACK_UPPER_WD: std::cout << " UNPACK_UPPER_WD "; break; case OP_MD_ADD_B: std::cout << " +(B) "; break; case OP_MD_ADD_H: std::cout << " +(H) "; break; case OP_MD_ADD_W: std::cout << " +(W) "; break; case OP_MD_ADDUS_B: std::cout << " +(USB) "; break; case OP_MD_ADDUS_W: std::cout << " +(USW) "; break; case OP_MD_ADDSS_H: std::cout << " +(SSH) "; break; case OP_MD_ADDSS_W: std::cout << " +(SSW) "; break; case OP_MD_SUB_B: std::cout << " -(B) "; break; case OP_MD_SUB_W: std::cout << " -(W) "; break; case OP_MD_SUBSS_H: std::cout << " -(SSH) "; break; case OP_MD_SLLW: std::cout << " <<(W) "; break; case OP_MD_SLLH: std::cout << " <<(H) "; break; case OP_MD_SRLH: std::cout << " >>(H) "; break; case OP_MD_SRLW: std::cout << " >>(W) "; break; case OP_MD_SRAH: std::cout << " >>A(H) "; break; case OP_MD_SRAW: std::cout << " >>A(W) "; break; case OP_MD_SRL256: std::cout << " >>(256) "; break; case OP_MD_CMPEQ_W: std::cout << " CMP(EQ,W) "; break; case OP_MD_CMPGT_H: std::cout << " CMP(GT,H) "; break; case OP_MD_ADD_S: std::cout << " +(S) "; break; case OP_MD_SUB_S: std::cout << " -(S) "; break; case OP_MD_MUL_S: std::cout << " *(S) "; break; case OP_MD_DIV_S: std::cout << " /(S) "; break; case OP_MD_MIN_H: std::cout << " MIN(H) "; break; case OP_MD_MIN_W: std::cout << " MIN(W) "; break; case OP_MD_MIN_S: std::cout << " MIN(S) "; break; case OP_MD_MAX_H: std::cout << " MAX(H) "; break; case OP_MD_MAX_W: std::cout << " MAX(W) "; break; case OP_MD_MAX_S: std::cout << " MAX(S) "; break; case OP_MD_ISNEGATIVE: std::cout << " ISNEGATIVE"; break; case OP_MD_ISZERO: std::cout << " ISZERO"; break; case OP_MD_EXPAND: std::cout << " EXPAND"; break; case OP_MD_TOWORD_TRUNCATE: std::cout << " TOWORD_TRUNCATE"; break; default: std::cout << " ?? "; break; } if(statement.src2) { std::cout << statement.src2->ToString(); } std::cout << std::endl; } } <commit_msg>Added some missing operations in statement dump.<commit_after>#include <iostream> #include "Jitter_Statement.h" using namespace Jitter; std::string Jitter::ConditionToString(CONDITION condition) { switch(condition) { case CONDITION_LT: return "LT"; break; case CONDITION_LE: return "LE"; break; case CONDITION_GT: return "GT"; break; case CONDITION_EQ: return "EQ"; break; case CONDITION_NE: return "NE"; break; case CONDITION_BL: return "BL"; break; case CONDITION_AB: return "AB"; break; default: return "??"; break; } } void Jitter::DumpStatementList(const StatementList& statements) { for(const auto& statement : statements) { if(statement.dst) { std::cout << statement.dst->ToString(); std::cout << " := "; } if(statement.src1) { std::cout << statement.src1->ToString(); } switch(statement.op) { case OP_ADD: case OP_ADD64: case OP_ADDREF: case OP_FP_ADD: std::cout << " + "; break; case OP_SUB: case OP_SUB64: case OP_FP_SUB: std::cout << " - "; break; case OP_CMP: case OP_CMP64: case OP_FP_CMP: std::cout << " CMP(" << ConditionToString(statement.jmpCondition) << ") "; break; case OP_MUL: case OP_MULS: case OP_FP_MUL: std::cout << " * "; break; case OP_MULSHL: std::cout << " *(HL) "; break; case OP_MULSHH: std::cout << " *(HH) "; break; case OP_DIV: case OP_DIVS: case OP_FP_DIV: std::cout << " / "; break; case OP_AND: case OP_AND64: case OP_MD_AND: std::cout << " & "; break; case OP_LZC: std::cout << " LZC"; break; case OP_OR: case OP_MD_OR: std::cout << " | "; break; case OP_XOR: case OP_MD_XOR: std::cout << " ^ "; break; case OP_NOT: case OP_MD_NOT: std::cout << " ! "; break; case OP_SRL: case OP_SRL64: std::cout << " >> "; break; case OP_SRA: case OP_SRA64: std::cout << " >>A "; break; case OP_SLL: case OP_SLL64: std::cout << " << "; break; case OP_NOP: std::cout << " NOP "; break; case OP_MOV: break; case OP_STOREATREF: std::cout << " <- "; break; case OP_LOADFROMREF: std::cout << " LOADFROM "; break; case OP_RELTOREF: std::cout << " TOREF "; break; case OP_PARAM: case OP_PARAM_RET: std::cout << " PARAM "; break; case OP_CALL: std::cout << " CALL "; break; case OP_RETVAL: std::cout << " RETURNVALUE "; break; case OP_JMP: std::cout << " JMP{" << statement.jmpBlock << "} "; break; case OP_CONDJMP: std::cout << " JMP{" << statement.jmpBlock << "}(" << ConditionToString(statement.jmpCondition) << ") "; break; case OP_LABEL: std::cout << "LABEL_" << statement.jmpBlock << ":"; break; case OP_EXTLOW64: std::cout << " EXTLOW64"; break; case OP_EXTHIGH64: std::cout << " EXTHIGH64"; break; case OP_MERGETO64: std::cout << " MERGETO64 "; break; case OP_MERGETO256: std::cout << " MERGETO256 "; break; case OP_FP_ABS: std::cout << " ABS"; break; case OP_FP_NEG: std::cout << " NEG"; break; case OP_FP_MIN: std::cout << " MIN "; break; case OP_FP_MAX: std::cout << " MAX "; break; case OP_FP_SQRT: std::cout << " SQRT"; break; case OP_FP_RSQRT: std::cout << " RSQRT"; break; case OP_FP_RCPL: std::cout << " RCPL"; break; case OP_FP_TOINT_TRUNC: std::cout << " INT(TRUNC)"; break; case OP_FP_LDCST: std::cout << " LOAD "; break; case OP_MD_MOV_MASKED: std::cout << " MOVMSK "; break; case OP_MD_PACK_HB: std::cout << " PACK_HB "; break; case OP_MD_PACK_WH: std::cout << " PACK_WH "; break; case OP_MD_UNPACK_LOWER_BH: std::cout << " UNPACK_LOWER_BH "; break; case OP_MD_UNPACK_LOWER_HW: std::cout << " UNPACK_LOWER_HW "; break; case OP_MD_UNPACK_LOWER_WD: std::cout << " UNPACK_LOWER_WD "; break; case OP_MD_UNPACK_UPPER_BH: std::cout << " UNPACK_UPPER_BH "; break; case OP_MD_UNPACK_UPPER_WD: std::cout << " UNPACK_UPPER_WD "; break; case OP_MD_ADD_B: std::cout << " +(B) "; break; case OP_MD_ADD_H: std::cout << " +(H) "; break; case OP_MD_ADD_W: std::cout << " +(W) "; break; case OP_MD_ADDUS_B: std::cout << " +(USB) "; break; case OP_MD_ADDUS_W: std::cout << " +(USW) "; break; case OP_MD_ADDSS_H: std::cout << " +(SSH) "; break; case OP_MD_ADDSS_W: std::cout << " +(SSW) "; break; case OP_MD_SUB_B: std::cout << " -(B) "; break; case OP_MD_SUB_W: std::cout << " -(W) "; break; case OP_MD_SUBSS_H: std::cout << " -(SSH) "; break; case OP_MD_SLLW: std::cout << " <<(W) "; break; case OP_MD_SLLH: std::cout << " <<(H) "; break; case OP_MD_SRLH: std::cout << " >>(H) "; break; case OP_MD_SRLW: std::cout << " >>(W) "; break; case OP_MD_SRAH: std::cout << " >>A(H) "; break; case OP_MD_SRAW: std::cout << " >>A(W) "; break; case OP_MD_SRL256: std::cout << " >>(256) "; break; case OP_MD_CMPEQ_W: std::cout << " CMP(EQ,W) "; break; case OP_MD_CMPGT_H: std::cout << " CMP(GT,H) "; break; case OP_MD_ADD_S: std::cout << " +(S) "; break; case OP_MD_SUB_S: std::cout << " -(S) "; break; case OP_MD_MUL_S: std::cout << " *(S) "; break; case OP_MD_DIV_S: std::cout << " /(S) "; break; case OP_MD_MIN_H: std::cout << " MIN(H) "; break; case OP_MD_MIN_W: std::cout << " MIN(W) "; break; case OP_MD_MIN_S: std::cout << " MIN(S) "; break; case OP_MD_MAX_H: std::cout << " MAX(H) "; break; case OP_MD_MAX_W: std::cout << " MAX(W) "; break; case OP_MD_MAX_S: std::cout << " MAX(S) "; break; case OP_MD_ABS_S: std::cout << " ABS(S)"; break; case OP_MD_ISNEGATIVE: std::cout << " ISNEGATIVE"; break; case OP_MD_ISZERO: std::cout << " ISZERO"; break; case OP_MD_EXPAND: std::cout << " EXPAND"; break; case OP_MD_TOSINGLE: std::cout << " TOSINGLE"; break; case OP_MD_TOWORD_TRUNCATE: std::cout << " TOWORD_TRUNCATE"; break; default: std::cout << " ?? "; break; } if(statement.src2) { std::cout << statement.src2->ToString(); } std::cout << std::endl; } } <|endoftext|>
<commit_before>//===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass lowers instrprof_increment intrinsics emitted by a frontend for // profiling. It also builds the data structures and initialization code needed // for updating execution counts and emitting the profile at runtime. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Instrumentation.h" #include "llvm/ADT/Triple.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Module.h" #include "llvm/Transforms/Utils/ModuleUtils.h" using namespace llvm; #define DEBUG_TYPE "instrprof" namespace { class InstrProfiling : public ModulePass { public: static char ID; InstrProfiling() : ModulePass(ID) {} InstrProfiling(const InstrProfOptions &Options) : ModulePass(ID), Options(Options) {} const char *getPassName() const override { return "Frontend instrumentation-based coverage lowering"; } bool runOnModule(Module &M) override; void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); } private: InstrProfOptions Options; Module *M; DenseMap<GlobalVariable *, GlobalVariable *> RegionCounters; std::vector<Value *> UsedVars; bool isMachO() const { return Triple(M->getTargetTriple()).isOSBinFormatMachO(); } /// Get the section name for the counter variables. StringRef getCountersSection() const { return isMachO() ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts"; } /// Get the section name for the name variables. StringRef getNameSection() const { return isMachO() ? "__DATA,__llvm_prf_names" : "__llvm_prf_names"; } /// Get the section name for the profile data variables. StringRef getDataSection() const { return isMachO() ? "__DATA,__llvm_prf_data" : "__llvm_prf_data"; } /// Get the section name for the coverage mapping data. StringRef getCoverageSection() const { return isMachO() ? "__DATA,__llvm_covmap" : "__llvm_covmap"; } /// Replace instrprof_increment with an increment of the appropriate value. void lowerIncrement(InstrProfIncrementInst *Inc); /// Set up the section and uses for coverage data and its references. void lowerCoverageData(GlobalVariable *CoverageData); /// Get the region counters for an increment, creating them if necessary. /// /// If the counter array doesn't yet exist, the profile data variables /// referring to them will also be created. GlobalVariable *getOrCreateRegionCounters(InstrProfIncrementInst *Inc); /// Emit runtime registration functions for each profile data variable. void emitRegistration(); /// Emit the necessary plumbing to pull in the runtime initialization. void emitRuntimeHook(); /// Add uses of our data variables and runtime hook. void emitUses(); /// Create a static initializer for our data, on platforms that need it, /// and for any profile output file that was specified. void emitInitialization(); }; } // anonymous namespace char InstrProfiling::ID = 0; INITIALIZE_PASS(InstrProfiling, "instrprof", "Frontend instrumentation-based coverage lowering.", false, false) ModulePass *llvm::createInstrProfilingPass(const InstrProfOptions &Options) { return new InstrProfiling(Options); } bool InstrProfiling::runOnModule(Module &M) { bool MadeChange = false; this->M = &M; RegionCounters.clear(); UsedVars.clear(); for (Function &F : M) for (BasicBlock &BB : F) for (auto I = BB.begin(), E = BB.end(); I != E;) if (auto *Inc = dyn_cast<InstrProfIncrementInst>(I++)) { lowerIncrement(Inc); MadeChange = true; } if (GlobalVariable *Coverage = M.getNamedGlobal("__llvm_coverage_mapping")) { lowerCoverageData(Coverage); MadeChange = true; } if (!MadeChange) return false; emitRegistration(); emitRuntimeHook(); emitUses(); emitInitialization(); return true; } void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) { GlobalVariable *Counters = getOrCreateRegionCounters(Inc); IRBuilder<> Builder(Inc->getParent(), *Inc); uint64_t Index = Inc->getIndex()->getZExtValue(); llvm::Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index); llvm::Value *Count = Builder.CreateLoad(Addr, "pgocount"); Count = Builder.CreateAdd(Count, Builder.getInt64(1)); Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr)); Inc->eraseFromParent(); } void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageData) { CoverageData->setSection(getCoverageSection()); CoverageData->setAlignment(8); Constant *Init = CoverageData->getInitializer(); // We're expecting { i32, i32, i32, i32, [n x { i8*, i32, i32 }], [m x i8] } // for some C. If not, the frontend's given us something broken. assert(Init->getNumOperands() == 6 && "bad number of fields in coverage map"); assert(isa<ConstantArray>(Init->getAggregateElement(4)) && "invalid function list in coverage map"); ConstantArray *Records = cast<ConstantArray>(Init->getAggregateElement(4)); for (unsigned I = 0, E = Records->getNumOperands(); I < E; ++I) { Constant *Record = Records->getOperand(I); Value *V = const_cast<Value *>(Record->getOperand(0))->stripPointerCasts(); assert(isa<GlobalVariable>(V) && "Missing reference to function name"); GlobalVariable *Name = cast<GlobalVariable>(V); // If we have region counters for this name, we've already handled it. auto It = RegionCounters.find(Name); if (It != RegionCounters.end()) continue; // Move the name variable to the right section. Name->setSection(getNameSection()); Name->setAlignment(1); } } /// Get the name of a profiling variable for a particular function. static std::string getVarName(InstrProfIncrementInst *Inc, StringRef VarName) { auto *Arr = cast<ConstantDataArray>(Inc->getName()->getInitializer()); StringRef Name = Arr->isCString() ? Arr->getAsCString() : Arr->getAsString(); return ("__llvm_profile_" + VarName + "_" + Name).str(); } GlobalVariable * InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) { GlobalVariable *Name = Inc->getName(); auto It = RegionCounters.find(Name); if (It != RegionCounters.end()) return It->second; // Move the name variable to the right section. Name->setSection(getNameSection()); Name->setAlignment(1); uint64_t NumCounters = Inc->getNumCounters()->getZExtValue(); LLVMContext &Ctx = M->getContext(); ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters); // Create the counters variable. auto *Counters = new GlobalVariable(*M, CounterTy, false, Name->getLinkage(), Constant::getNullValue(CounterTy), getVarName(Inc, "counters")); Counters->setVisibility(Name->getVisibility()); Counters->setSection(getCountersSection()); Counters->setAlignment(8); RegionCounters[Inc->getName()] = Counters; // Create data variable. auto *NameArrayTy = Name->getType()->getPointerElementType(); auto *Int32Ty = Type::getInt32Ty(Ctx); auto *Int64Ty = Type::getInt64Ty(Ctx); auto *Int8PtrTy = Type::getInt8PtrTy(Ctx); auto *Int64PtrTy = Type::getInt64PtrTy(Ctx); Type *DataTypes[] = {Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int64PtrTy}; auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes)); Constant *DataVals[] = { ConstantInt::get(Int32Ty, NameArrayTy->getArrayNumElements()), ConstantInt::get(Int32Ty, NumCounters), ConstantInt::get(Int64Ty, Inc->getHash()->getZExtValue()), ConstantExpr::getBitCast(Name, Int8PtrTy), ConstantExpr::getBitCast(Counters, Int64PtrTy)}; auto *Data = new GlobalVariable(*M, DataTy, true, Name->getLinkage(), ConstantStruct::get(DataTy, DataVals), getVarName(Inc, "data")); Data->setVisibility(Name->getVisibility()); Data->setSection(getDataSection()); Data->setAlignment(8); // Mark the data variable as used so that it isn't stripped out. UsedVars.push_back(Data); return Counters; } void InstrProfiling::emitRegistration() { // Don't do this for Darwin. compiler-rt uses linker magic. if (Triple(M->getTargetTriple()).isOSDarwin()) return; // Construct the function. auto *VoidTy = Type::getVoidTy(M->getContext()); auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext()); auto *RegisterFTy = FunctionType::get(VoidTy, false); auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage, "__llvm_profile_register_functions", M); RegisterF->setUnnamedAddr(true); if (Options.NoRedZone) RegisterF->addFnAttr(Attribute::NoRedZone); auto *RuntimeRegisterTy = llvm::FunctionType::get(VoidTy, VoidPtrTy, false); auto *RuntimeRegisterF = Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage, "__llvm_profile_register_function", M); IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF)); for (Value *Data : UsedVars) IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy)); IRB.CreateRetVoid(); } void InstrProfiling::emitRuntimeHook() { const char *const RuntimeVarName = "__llvm_profile_runtime"; const char *const RuntimeUserName = "__llvm_profile_runtime_user"; // If the module's provided its own runtime, we don't need to do anything. if (M->getGlobalVariable(RuntimeVarName)) return; // Declare an external variable that will pull in the runtime initialization. auto *Int32Ty = Type::getInt32Ty(M->getContext()); auto *Var = new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage, nullptr, RuntimeVarName); // Make a function that uses it. auto *User = Function::Create(FunctionType::get(Int32Ty, false), GlobalValue::LinkOnceODRLinkage, RuntimeUserName, M); User->addFnAttr(Attribute::NoInline); if (Options.NoRedZone) User->addFnAttr(Attribute::NoRedZone); User->setVisibility(GlobalValue::HiddenVisibility); IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User)); auto *Load = IRB.CreateLoad(Var); IRB.CreateRet(Load); // Mark the user variable as used so that it isn't stripped out. UsedVars.push_back(User); } void InstrProfiling::emitUses() { if (UsedVars.empty()) return; GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used"); std::vector<Constant*> MergedVars; if (LLVMUsed) { // Collect the existing members of llvm.used. ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer()); for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I) MergedVars.push_back(Inits->getOperand(I)); LLVMUsed->eraseFromParent(); } Type *i8PTy = Type::getInt8PtrTy(M->getContext()); // Add uses for our data. for (auto *Value : UsedVars) MergedVars.push_back( ConstantExpr::getBitCast(cast<llvm::Constant>(Value), i8PTy)); // Recreate llvm.used. ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size()); LLVMUsed = new llvm::GlobalVariable( *M, ATy, false, llvm::GlobalValue::AppendingLinkage, llvm::ConstantArray::get(ATy, MergedVars), "llvm.used"); LLVMUsed->setSection("llvm.metadata"); } void InstrProfiling::emitInitialization() { std::string InstrProfileOutput = Options.InstrProfileOutput; Constant *RegisterF = M->getFunction("__llvm_profile_register_functions"); if (!RegisterF && InstrProfileOutput.empty()) return; // Create the initialization function. auto *VoidTy = Type::getVoidTy(M->getContext()); auto *F = Function::Create(FunctionType::get(VoidTy, false), GlobalValue::InternalLinkage, "__llvm_profile_init", M); F->setUnnamedAddr(true); F->addFnAttr(Attribute::NoInline); if (Options.NoRedZone) F->addFnAttr(Attribute::NoRedZone); // Add the basic block and the necessary calls. IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F)); if (RegisterF) IRB.CreateCall(RegisterF); if (!InstrProfileOutput.empty()) { auto *Int8PtrTy = Type::getInt8PtrTy(M->getContext()); auto *SetNameTy = FunctionType::get(VoidTy, Int8PtrTy, false); auto *SetNameF = Function::Create(SetNameTy, GlobalValue::ExternalLinkage, "__llvm_profile_set_filename_env_override", M); // Create variable for profile name Constant *ProfileNameConst = ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true); GlobalVariable *ProfileName = new GlobalVariable(*M, ProfileNameConst->getType(), true, GlobalValue::PrivateLinkage, ProfileNameConst); IRB.CreateCall(SetNameF, IRB.CreatePointerCast(ProfileName, Int8PtrTy)); } IRB.CreateRetVoid(); appendToGlobalCtors(*M, F, 0); } <commit_msg>InstrProf: Update name of compiler-rt routine for setting filename<commit_after>//===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass lowers instrprof_increment intrinsics emitted by a frontend for // profiling. It also builds the data structures and initialization code needed // for updating execution counts and emitting the profile at runtime. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Instrumentation.h" #include "llvm/ADT/Triple.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Module.h" #include "llvm/Transforms/Utils/ModuleUtils.h" using namespace llvm; #define DEBUG_TYPE "instrprof" namespace { class InstrProfiling : public ModulePass { public: static char ID; InstrProfiling() : ModulePass(ID) {} InstrProfiling(const InstrProfOptions &Options) : ModulePass(ID), Options(Options) {} const char *getPassName() const override { return "Frontend instrumentation-based coverage lowering"; } bool runOnModule(Module &M) override; void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); } private: InstrProfOptions Options; Module *M; DenseMap<GlobalVariable *, GlobalVariable *> RegionCounters; std::vector<Value *> UsedVars; bool isMachO() const { return Triple(M->getTargetTriple()).isOSBinFormatMachO(); } /// Get the section name for the counter variables. StringRef getCountersSection() const { return isMachO() ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts"; } /// Get the section name for the name variables. StringRef getNameSection() const { return isMachO() ? "__DATA,__llvm_prf_names" : "__llvm_prf_names"; } /// Get the section name for the profile data variables. StringRef getDataSection() const { return isMachO() ? "__DATA,__llvm_prf_data" : "__llvm_prf_data"; } /// Get the section name for the coverage mapping data. StringRef getCoverageSection() const { return isMachO() ? "__DATA,__llvm_covmap" : "__llvm_covmap"; } /// Replace instrprof_increment with an increment of the appropriate value. void lowerIncrement(InstrProfIncrementInst *Inc); /// Set up the section and uses for coverage data and its references. void lowerCoverageData(GlobalVariable *CoverageData); /// Get the region counters for an increment, creating them if necessary. /// /// If the counter array doesn't yet exist, the profile data variables /// referring to them will also be created. GlobalVariable *getOrCreateRegionCounters(InstrProfIncrementInst *Inc); /// Emit runtime registration functions for each profile data variable. void emitRegistration(); /// Emit the necessary plumbing to pull in the runtime initialization. void emitRuntimeHook(); /// Add uses of our data variables and runtime hook. void emitUses(); /// Create a static initializer for our data, on platforms that need it, /// and for any profile output file that was specified. void emitInitialization(); }; } // anonymous namespace char InstrProfiling::ID = 0; INITIALIZE_PASS(InstrProfiling, "instrprof", "Frontend instrumentation-based coverage lowering.", false, false) ModulePass *llvm::createInstrProfilingPass(const InstrProfOptions &Options) { return new InstrProfiling(Options); } bool InstrProfiling::runOnModule(Module &M) { bool MadeChange = false; this->M = &M; RegionCounters.clear(); UsedVars.clear(); for (Function &F : M) for (BasicBlock &BB : F) for (auto I = BB.begin(), E = BB.end(); I != E;) if (auto *Inc = dyn_cast<InstrProfIncrementInst>(I++)) { lowerIncrement(Inc); MadeChange = true; } if (GlobalVariable *Coverage = M.getNamedGlobal("__llvm_coverage_mapping")) { lowerCoverageData(Coverage); MadeChange = true; } if (!MadeChange) return false; emitRegistration(); emitRuntimeHook(); emitUses(); emitInitialization(); return true; } void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) { GlobalVariable *Counters = getOrCreateRegionCounters(Inc); IRBuilder<> Builder(Inc->getParent(), *Inc); uint64_t Index = Inc->getIndex()->getZExtValue(); llvm::Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index); llvm::Value *Count = Builder.CreateLoad(Addr, "pgocount"); Count = Builder.CreateAdd(Count, Builder.getInt64(1)); Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr)); Inc->eraseFromParent(); } void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageData) { CoverageData->setSection(getCoverageSection()); CoverageData->setAlignment(8); Constant *Init = CoverageData->getInitializer(); // We're expecting { i32, i32, i32, i32, [n x { i8*, i32, i32 }], [m x i8] } // for some C. If not, the frontend's given us something broken. assert(Init->getNumOperands() == 6 && "bad number of fields in coverage map"); assert(isa<ConstantArray>(Init->getAggregateElement(4)) && "invalid function list in coverage map"); ConstantArray *Records = cast<ConstantArray>(Init->getAggregateElement(4)); for (unsigned I = 0, E = Records->getNumOperands(); I < E; ++I) { Constant *Record = Records->getOperand(I); Value *V = const_cast<Value *>(Record->getOperand(0))->stripPointerCasts(); assert(isa<GlobalVariable>(V) && "Missing reference to function name"); GlobalVariable *Name = cast<GlobalVariable>(V); // If we have region counters for this name, we've already handled it. auto It = RegionCounters.find(Name); if (It != RegionCounters.end()) continue; // Move the name variable to the right section. Name->setSection(getNameSection()); Name->setAlignment(1); } } /// Get the name of a profiling variable for a particular function. static std::string getVarName(InstrProfIncrementInst *Inc, StringRef VarName) { auto *Arr = cast<ConstantDataArray>(Inc->getName()->getInitializer()); StringRef Name = Arr->isCString() ? Arr->getAsCString() : Arr->getAsString(); return ("__llvm_profile_" + VarName + "_" + Name).str(); } GlobalVariable * InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) { GlobalVariable *Name = Inc->getName(); auto It = RegionCounters.find(Name); if (It != RegionCounters.end()) return It->second; // Move the name variable to the right section. Name->setSection(getNameSection()); Name->setAlignment(1); uint64_t NumCounters = Inc->getNumCounters()->getZExtValue(); LLVMContext &Ctx = M->getContext(); ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters); // Create the counters variable. auto *Counters = new GlobalVariable(*M, CounterTy, false, Name->getLinkage(), Constant::getNullValue(CounterTy), getVarName(Inc, "counters")); Counters->setVisibility(Name->getVisibility()); Counters->setSection(getCountersSection()); Counters->setAlignment(8); RegionCounters[Inc->getName()] = Counters; // Create data variable. auto *NameArrayTy = Name->getType()->getPointerElementType(); auto *Int32Ty = Type::getInt32Ty(Ctx); auto *Int64Ty = Type::getInt64Ty(Ctx); auto *Int8PtrTy = Type::getInt8PtrTy(Ctx); auto *Int64PtrTy = Type::getInt64PtrTy(Ctx); Type *DataTypes[] = {Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int64PtrTy}; auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes)); Constant *DataVals[] = { ConstantInt::get(Int32Ty, NameArrayTy->getArrayNumElements()), ConstantInt::get(Int32Ty, NumCounters), ConstantInt::get(Int64Ty, Inc->getHash()->getZExtValue()), ConstantExpr::getBitCast(Name, Int8PtrTy), ConstantExpr::getBitCast(Counters, Int64PtrTy)}; auto *Data = new GlobalVariable(*M, DataTy, true, Name->getLinkage(), ConstantStruct::get(DataTy, DataVals), getVarName(Inc, "data")); Data->setVisibility(Name->getVisibility()); Data->setSection(getDataSection()); Data->setAlignment(8); // Mark the data variable as used so that it isn't stripped out. UsedVars.push_back(Data); return Counters; } void InstrProfiling::emitRegistration() { // Don't do this for Darwin. compiler-rt uses linker magic. if (Triple(M->getTargetTriple()).isOSDarwin()) return; // Construct the function. auto *VoidTy = Type::getVoidTy(M->getContext()); auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext()); auto *RegisterFTy = FunctionType::get(VoidTy, false); auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage, "__llvm_profile_register_functions", M); RegisterF->setUnnamedAddr(true); if (Options.NoRedZone) RegisterF->addFnAttr(Attribute::NoRedZone); auto *RuntimeRegisterTy = llvm::FunctionType::get(VoidTy, VoidPtrTy, false); auto *RuntimeRegisterF = Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage, "__llvm_profile_register_function", M); IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF)); for (Value *Data : UsedVars) IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy)); IRB.CreateRetVoid(); } void InstrProfiling::emitRuntimeHook() { const char *const RuntimeVarName = "__llvm_profile_runtime"; const char *const RuntimeUserName = "__llvm_profile_runtime_user"; // If the module's provided its own runtime, we don't need to do anything. if (M->getGlobalVariable(RuntimeVarName)) return; // Declare an external variable that will pull in the runtime initialization. auto *Int32Ty = Type::getInt32Ty(M->getContext()); auto *Var = new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage, nullptr, RuntimeVarName); // Make a function that uses it. auto *User = Function::Create(FunctionType::get(Int32Ty, false), GlobalValue::LinkOnceODRLinkage, RuntimeUserName, M); User->addFnAttr(Attribute::NoInline); if (Options.NoRedZone) User->addFnAttr(Attribute::NoRedZone); User->setVisibility(GlobalValue::HiddenVisibility); IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User)); auto *Load = IRB.CreateLoad(Var); IRB.CreateRet(Load); // Mark the user variable as used so that it isn't stripped out. UsedVars.push_back(User); } void InstrProfiling::emitUses() { if (UsedVars.empty()) return; GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used"); std::vector<Constant*> MergedVars; if (LLVMUsed) { // Collect the existing members of llvm.used. ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer()); for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I) MergedVars.push_back(Inits->getOperand(I)); LLVMUsed->eraseFromParent(); } Type *i8PTy = Type::getInt8PtrTy(M->getContext()); // Add uses for our data. for (auto *Value : UsedVars) MergedVars.push_back( ConstantExpr::getBitCast(cast<llvm::Constant>(Value), i8PTy)); // Recreate llvm.used. ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size()); LLVMUsed = new llvm::GlobalVariable( *M, ATy, false, llvm::GlobalValue::AppendingLinkage, llvm::ConstantArray::get(ATy, MergedVars), "llvm.used"); LLVMUsed->setSection("llvm.metadata"); } void InstrProfiling::emitInitialization() { std::string InstrProfileOutput = Options.InstrProfileOutput; Constant *RegisterF = M->getFunction("__llvm_profile_register_functions"); if (!RegisterF && InstrProfileOutput.empty()) return; // Create the initialization function. auto *VoidTy = Type::getVoidTy(M->getContext()); auto *F = Function::Create(FunctionType::get(VoidTy, false), GlobalValue::InternalLinkage, "__llvm_profile_init", M); F->setUnnamedAddr(true); F->addFnAttr(Attribute::NoInline); if (Options.NoRedZone) F->addFnAttr(Attribute::NoRedZone); // Add the basic block and the necessary calls. IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F)); if (RegisterF) IRB.CreateCall(RegisterF); if (!InstrProfileOutput.empty()) { auto *Int8PtrTy = Type::getInt8PtrTy(M->getContext()); auto *SetNameTy = FunctionType::get(VoidTy, Int8PtrTy, false); auto *SetNameF = Function::Create(SetNameTy, GlobalValue::ExternalLinkage, "__llvm_profile_override_default_filename", M); // Create variable for profile name Constant *ProfileNameConst = ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true); GlobalVariable *ProfileName = new GlobalVariable(*M, ProfileNameConst->getType(), true, GlobalValue::PrivateLinkage, ProfileNameConst); IRB.CreateCall(SetNameF, IRB.CreatePointerCast(ProfileName, Int8PtrTy)); } IRB.CreateRetVoid(); appendToGlobalCtors(*M, F, 0); } <|endoftext|>
<commit_before>#include <cstddef> // NULL #include <stdlib.h> #include <errno.h> #include <string.h> #include <cassert> #include "LnaReaderCircular.hh" LnaReaderCircular::LnaReaderCircular() : m_file(NULL), m_header_size(5), m_buffer_size(0), m_first_index(0), m_frames_read(0), m_log_prob_buffer(0), m_frame_size(0), m_read_buffer(0), m_lna_bytes(1) { } int LnaReaderCircular::read_int() { assert(sizeof(unsigned int) == 4); unsigned char buf[4]; if (fread(buf, 4, 1, m_file) != 1) { fprintf(stderr, "LnaReaderCircular::open(): read error: %s\n", strerror(errno)); exit(1); } int tmp = buf[3] + (buf[2] << 8) + (buf[1] << 16) + (buf[0] << 24); return tmp; } void LnaReaderCircular::open(const char *filename, int buf_size) { if (m_file != NULL) close(); m_file = fopen(filename, "r"); if (m_file == NULL) { fprintf(stderr, "LnaReaderCircular::open(): could not open %s: %s\n", filename, strerror(errno)); exit(1); } // Read header m_num_models = read_int(); if (m_num_models <= 0) { fprintf(stderr, "LnaReaderCircular::open(): invalid number of states %d\n", m_num_models); exit(1); } int bytes = fgetc(m_file); if (bytes== EOF) { fprintf(stderr, "LnaReaderCircular::open(): read error: %s\n", strerror(errno)); exit(1); } // Set some variables m_lna_bytes = bytes; m_buffer_size = buf_size; m_first_index = 0; m_frames_read = 0; m_eof_frame = -1; if (m_lna_bytes == 4) m_frame_size = m_num_models * 4; else if (m_lna_bytes == 2) m_frame_size = m_num_models * 2; else if (m_lna_bytes == 1) m_frame_size = m_num_models; else { fprintf(stderr, "LnaReaderCircular::open(): invalid LNA byte number %d\n", m_lna_bytes); exit(1); } // Initialize buffers m_log_prob_buffer.clear(); m_read_buffer.clear(); m_log_prob_buffer.resize(m_num_models * buf_size); m_read_buffer.resize(m_frame_size); } void LnaReaderCircular::close() { if (m_file != NULL) fclose(m_file); m_file = NULL; } void LnaReaderCircular::seek(int frame) { if (m_file == NULL) { fprintf(stderr, "LnaReaderCircular::seek(): file not opened yet\n"); exit(1); } if (fseek(m_file, m_header_size + m_frame_size * frame, SEEK_SET) < 0) { fprintf(stderr, "LnaReaderCircular::seek(): seek error %s\n", strerror(errno)); exit(1); } m_frames_read = frame; m_first_index = 0; } bool LnaReaderCircular::go_to(int frame) { if (m_file == NULL) { fprintf(stderr, "LnaReaderCircular::go_to(): file not opened yet\n"); exit(1); } if (m_eof_frame > 0 && frame >= m_eof_frame) return false; if (frame < m_frames_read - m_buffer_size) seek(frame); // FIXME: do we want to seek forward if skip is great? Currently we // just read until the desired frame is reached. while (m_frames_read <= frame) { // Read a frame size_t ret = fread(&m_read_buffer[0], m_frame_size, 1, m_file); // Did we get the frame? if (ret != 1) { assert(ret == 0); // Check errors if (ferror(m_file)) { fprintf(stderr, "LnaReaderCircular::go_to(): read error on frame " "%d: %s\n", m_frames_read, strerror(errno)); exit(1); } // Otherwise we have EOF m_eof_frame = m_frames_read; return false; } // Parse frame to the circular buffer if (m_lna_bytes == 4) { for (int i = 0; i < m_num_models; i++) { float tmp; unsigned char *p = (unsigned char*)&tmp; for (int j = 0; j < 4; j++) p[j] = m_read_buffer[i*4+j]; m_log_prob_buffer[m_first_index] = tmp; m_first_index++; if (m_first_index >= m_log_prob_buffer.size()) m_first_index = 0; } } else if (m_lna_bytes == 2) { for (int i = 0; i < m_num_models; i++) { float tmp = ((unsigned char)m_read_buffer[i*2] * 256 + (unsigned char)m_read_buffer[i*2 + 1]) / -1820.0; m_log_prob_buffer[m_first_index] = tmp; m_first_index++; if (m_first_index >= m_log_prob_buffer.size()) m_first_index = 0; } } else { for (int i = 0; i < m_num_models; i++) { float tmp = (unsigned char)m_read_buffer[i] / -24.0; m_log_prob_buffer[m_first_index] = tmp; m_first_index++; if (m_first_index >= m_log_prob_buffer.size()) m_first_index = 0; } } m_frames_read++; } int index = m_first_index - (m_frames_read - frame) * m_num_models; if (index < 0) index += m_log_prob_buffer.size(); m_log_prob = &m_log_prob_buffer[index]; return true; } <commit_msg>Better error reporting.<commit_after>#include <cstddef> // NULL #include <stdlib.h> #include <errno.h> #include <string.h> #include <cassert> #include "LnaReaderCircular.hh" LnaReaderCircular::LnaReaderCircular() : m_file(NULL), m_header_size(5), m_buffer_size(0), m_first_index(0), m_frames_read(0), m_log_prob_buffer(0), m_frame_size(0), m_read_buffer(0), m_lna_bytes(1) { } int LnaReaderCircular::read_int() { assert(sizeof(unsigned int) == 4); unsigned char buf[4]; if (fread(buf, 4, 1, m_file) != 1) { int error = ferror(m_file); if (error != 0) { fprintf(stderr, "LnaReaderCircular::read_int(): read error: %s\n", strerror(error)); } else if (feof(m_file)) { fprintf(stderr, "LnaReaderCircular::read_int(): End of file reached.\n"); } else { fprintf(stderr, "LnaReaderCircular::read_int(): fread() failed.\n"); } exit(1); } int tmp = buf[3] + (buf[2] << 8) + (buf[1] << 16) + (buf[0] << 24); return tmp; } void LnaReaderCircular::open(const char *filename, int buf_size) { if (m_file != NULL) close(); m_file = fopen(filename, "r"); if (m_file == NULL) { char * error_string = strerror(errno); fprintf(stderr, "LnaReaderCircular::open(): could not open %s: %s\n", filename, error_string); exit(1); } // Read header m_num_models = read_int(); if (m_num_models <= 0) { fprintf(stderr, "LnaReaderCircular::open(): invalid number of states %d\n", m_num_models); exit(1); } int bytes = fgetc(m_file); if (bytes== EOF) { fprintf(stderr, "LnaReaderCircular::open(): read error: %s\n", strerror(errno)); exit(1); } // Set some variables m_lna_bytes = bytes; m_buffer_size = buf_size; m_first_index = 0; m_frames_read = 0; m_eof_frame = -1; if (m_lna_bytes == 4) m_frame_size = m_num_models * 4; else if (m_lna_bytes == 2) m_frame_size = m_num_models * 2; else if (m_lna_bytes == 1) m_frame_size = m_num_models; else { fprintf(stderr, "LnaReaderCircular::open(): invalid LNA byte number %d\n", m_lna_bytes); exit(1); } // Initialize buffers m_log_prob_buffer.clear(); m_read_buffer.clear(); m_log_prob_buffer.resize(m_num_models * buf_size); m_read_buffer.resize(m_frame_size); } void LnaReaderCircular::close() { if (m_file != NULL) fclose(m_file); m_file = NULL; } void LnaReaderCircular::seek(int frame) { if (m_file == NULL) { fprintf(stderr, "LnaReaderCircular::seek(): file not opened yet\n"); exit(1); } if (fseek(m_file, m_header_size + m_frame_size * frame, SEEK_SET) < 0) { fprintf(stderr, "LnaReaderCircular::seek(): seek error %s\n", strerror(errno)); exit(1); } m_frames_read = frame; m_first_index = 0; } bool LnaReaderCircular::go_to(int frame) { if (m_file == NULL) { fprintf(stderr, "LnaReaderCircular::go_to(): file not opened yet\n"); exit(1); } if (m_eof_frame > 0 && frame >= m_eof_frame) return false; if (frame < m_frames_read - m_buffer_size) seek(frame); // FIXME: do we want to seek forward if skip is great? Currently we // just read until the desired frame is reached. while (m_frames_read <= frame) { // Read a frame size_t ret = fread(&m_read_buffer[0], m_frame_size, 1, m_file); // Did we get the frame? if (ret != 1) { assert(ret == 0); // Check errors if (ferror(m_file)) { fprintf(stderr, "LnaReaderCircular::go_to(): read error on frame " "%d: %s\n", m_frames_read, strerror(errno)); exit(1); } // Otherwise we have EOF m_eof_frame = m_frames_read; return false; } // Parse frame to the circular buffer if (m_lna_bytes == 4) { for (int i = 0; i < m_num_models; i++) { float tmp; unsigned char *p = (unsigned char*)&tmp; for (int j = 0; j < 4; j++) p[j] = m_read_buffer[i*4+j]; m_log_prob_buffer[m_first_index] = tmp; m_first_index++; if (m_first_index >= m_log_prob_buffer.size()) m_first_index = 0; } } else if (m_lna_bytes == 2) { for (int i = 0; i < m_num_models; i++) { float tmp = ((unsigned char)m_read_buffer[i*2] * 256 + (unsigned char)m_read_buffer[i*2 + 1]) / -1820.0; m_log_prob_buffer[m_first_index] = tmp; m_first_index++; if (m_first_index >= m_log_prob_buffer.size()) m_first_index = 0; } } else { for (int i = 0; i < m_num_models; i++) { float tmp = (unsigned char)m_read_buffer[i] / -24.0; m_log_prob_buffer[m_first_index] = tmp; m_first_index++; if (m_first_index >= m_log_prob_buffer.size()) m_first_index = 0; } } m_frames_read++; } int index = m_first_index - (m_frames_read - frame) * m_num_models; if (index < 0) index += m_log_prob_buffer.size(); m_log_prob = &m_log_prob_buffer[index]; return true; } <|endoftext|>
<commit_before>// OptionTabLog.cpp : t@C // #include "stdafx.h" #include "MZ3.h" #include "util.h" #include "OptionTabLog.h" // COptionTabLog _CAO IMPLEMENT_DYNAMIC(COptionTabLog, CPropertyPage) COptionTabLog::COptionTabLog() : CPropertyPage(COptionTabLog::IDD) { } COptionTabLog::~COptionTabLog() { } void COptionTabLog::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(COptionTabLog, CPropertyPage) ON_BN_CLICKED(IDC_CHANGE_LOG_FOLDER_BUTTON, &COptionTabLog::OnBnClickedChangeLogFolderButton) ON_BN_CLICKED(IDC_CLEAN_LOG_BUTTON, &COptionTabLog::OnBnClickedCleanLogButton) ON_BN_CLICKED(IDC_DEBUG_MODE_CHECK, &COptionTabLog::OnBnClickedDebugModeCheck) END_MESSAGE_MAP() // COptionTabLog bZ[W nh void COptionTabLog::OnOK() { Save(); CPropertyPage::OnOK(); } BOOL COptionTabLog::OnInitDialog() { CPropertyPage::OnInitDialog(); // IvV_CAOɔf Load(); return TRUE; } /** * theApp.m_optionMng _CAOɕϊ */ void COptionTabLog::Load() { // O̕ۑ CheckDlgButton( IDC_SAVE_LOG_CHECK, theApp.m_optionMng.m_bSaveLog ? BST_CHECKED : BST_UNCHECKED ); // ÕpX SetDlgItemText( IDC_LOGFOLDER_EDIT, theApp.m_optionMng.GetLogFolder() ); // fobO[h CheckDlgButton( IDC_DEBUG_MODE_CHECK, theApp.m_optionMng.IsDebugMode() ? BST_CHECKED : BST_UNCHECKED ); } /** * _CAÕf[^ theApp.m_optionMng ɕϊ */ void COptionTabLog::Save() { // O̕ۑ theApp.m_optionMng.m_bSaveLog = (IsDlgButtonChecked( IDC_SAVE_LOG_CHECK ) == BST_CHECKED); // ÕpX CString strFolderPath; GetDlgItemText( IDC_LOGFOLDER_EDIT, strFolderPath ); // IvVɕۑ theApp.m_optionMng.SetLogFolder( strFolderPath ); // epX̍Đ theApp.m_filepath.init_logpath(); // fobO[h theApp.m_optionMng.SetDebugMode( IsDlgButtonChecked( IDC_DEBUG_MODE_CHECK ) == BST_CHECKED ); } /** * OtH_̕ύX */ void COptionTabLog::OnBnClickedChangeLogFolderButton() { CString strFolderPath; // ftHg̃pXʂ擾 GetDlgItemText( IDC_LOGFOLDER_EDIT, strFolderPath ); // tH_I_CAON if( util::GetOpenFolderPath( m_hWnd, L"OtH_̕ύX", strFolderPath ) ) { CString msg; msg.Format( L"Ot@C̏o͐\n" L" %s\n" L"ɕύX܂B낵łH", strFolderPath ); if( MessageBox( msg, 0, MB_YESNO ) == IDYES ) { // ʂ̍Đݒ SetDlgItemText( IDC_LOGFOLDER_EDIT, strFolderPath ); } } } /// CountupCallback p̃f[^\ struct CountupData { int nFiles; ///< t@C DWORD dwSize; ///< t@CTCY CountupData() : nFiles(0), dwSize(0) {} }; /** * t@C̃JEgAbvpR[obN֐ */ int CountupCallback( const TCHAR* szDirectory, const WIN32_FIND_DATA* data, CountupData* pData) { pData->nFiles ++; pData->dwSize += (data->nFileSizeHigh * MAXDWORD) + data->nFileSizeLow; return TRUE; } /** * t@C̍폜pR[obN֐ */ int DeleteCallback( const TCHAR* szDirectory, const WIN32_FIND_DATA* data, int* pnDeleted) { std::basic_string< TCHAR > strFile = szDirectory + std::basic_string< TCHAR >(data->cFileName); if( (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY ) { // fBNg if( RemoveDirectory( strFile.c_str() ) ) { (*pnDeleted) ++; } }else{ // t@C if( DeleteFile( strFile.c_str() ) ) { (*pnDeleted) ++; } } return TRUE; } /** * O̍폜 */ void COptionTabLog::OnBnClickedCleanLogButton() { CountupData cd; // t@C, t@CTCY int nDepthMax = 10; // őċA[x LPCTSTR szDeleteFilePattern = L"*"; CString strLogFolder = theApp.m_filepath.logFolder + L"\\"; // Ot@CJEg util::FindFileCallback( strLogFolder, szDeleteFilePattern, CountupCallback, &cd, nDepthMax ); if( cd.nFiles == 0 ) { MessageBox( L"폜Ώۃt@C܂" ); return; } CString msg; msg.Format( L"Ot@C폜܂B낵łH\n" L"it@CꍇAx܂j\n\n" L"t@CF%d\n" L"t@CTCYF%s Bytes" , cd.nFiles, util::int2comma_str(cd.dwSize) ); if( MessageBox( msg, 0, MB_YESNO | MB_ICONQUESTION ) != IDYES ) { return; } // 폜s int nDeleted = 0; // 폜ς݃t@C util::FindFileCallback( strLogFolder, szDeleteFilePattern, DeleteCallback, &nDeleted, nDepthMax ); msg.Format( L"%d ‚̃t@C폜܂B\n" L"iΏۃt@CF%d j", nDeleted, cd.nFiles ); MessageBox( msg ); } void COptionTabLog::OnBnClickedDebugModeCheck() { MessageBox( L"fobO[h̕ύX͍ċNɔf܂" ); } <commit_msg>ログ削除時のメッセージを追加<commit_after>// OptionTabLog.cpp : t@C // #include "stdafx.h" #include "MZ3.h" #include "util.h" #include "OptionTabLog.h" // COptionTabLog _CAO IMPLEMENT_DYNAMIC(COptionTabLog, CPropertyPage) COptionTabLog::COptionTabLog() : CPropertyPage(COptionTabLog::IDD) { } COptionTabLog::~COptionTabLog() { } void COptionTabLog::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(COptionTabLog, CPropertyPage) ON_BN_CLICKED(IDC_CHANGE_LOG_FOLDER_BUTTON, &COptionTabLog::OnBnClickedChangeLogFolderButton) ON_BN_CLICKED(IDC_CLEAN_LOG_BUTTON, &COptionTabLog::OnBnClickedCleanLogButton) ON_BN_CLICKED(IDC_DEBUG_MODE_CHECK, &COptionTabLog::OnBnClickedDebugModeCheck) END_MESSAGE_MAP() // COptionTabLog bZ[W nh void COptionTabLog::OnOK() { Save(); CPropertyPage::OnOK(); } BOOL COptionTabLog::OnInitDialog() { CPropertyPage::OnInitDialog(); // IvV_CAOɔf Load(); return TRUE; } /** * theApp.m_optionMng _CAOɕϊ */ void COptionTabLog::Load() { // O̕ۑ CheckDlgButton( IDC_SAVE_LOG_CHECK, theApp.m_optionMng.m_bSaveLog ? BST_CHECKED : BST_UNCHECKED ); // ÕpX SetDlgItemText( IDC_LOGFOLDER_EDIT, theApp.m_optionMng.GetLogFolder() ); // fobO[h CheckDlgButton( IDC_DEBUG_MODE_CHECK, theApp.m_optionMng.IsDebugMode() ? BST_CHECKED : BST_UNCHECKED ); } /** * _CAÕf[^ theApp.m_optionMng ɕϊ */ void COptionTabLog::Save() { // O̕ۑ theApp.m_optionMng.m_bSaveLog = (IsDlgButtonChecked( IDC_SAVE_LOG_CHECK ) == BST_CHECKED); // ÕpX CString strFolderPath; GetDlgItemText( IDC_LOGFOLDER_EDIT, strFolderPath ); // IvVɕۑ theApp.m_optionMng.SetLogFolder( strFolderPath ); // epX̍Đ theApp.m_filepath.init_logpath(); // fobO[h theApp.m_optionMng.SetDebugMode( IsDlgButtonChecked( IDC_DEBUG_MODE_CHECK ) == BST_CHECKED ); } /** * OtH_̕ύX */ void COptionTabLog::OnBnClickedChangeLogFolderButton() { CString strFolderPath; // ftHg̃pXʂ擾 GetDlgItemText( IDC_LOGFOLDER_EDIT, strFolderPath ); // tH_I_CAON if( util::GetOpenFolderPath( m_hWnd, L"OtH_̕ύX", strFolderPath ) ) { CString msg; msg.Format( L"Ot@C̏o͐\n" L" %s\n" L"ɕύX܂B낵łH", strFolderPath ); if( MessageBox( msg, 0, MB_YESNO ) == IDYES ) { // ʂ̍Đݒ SetDlgItemText( IDC_LOGFOLDER_EDIT, strFolderPath ); } } } /// CountupCallback p̃f[^\ struct CountupData { int nFiles; ///< t@C DWORD dwSize; ///< t@CTCY CountupData() : nFiles(0), dwSize(0) {} }; /** * t@C̃JEgAbvpR[obN֐ */ int CountupCallback( const TCHAR* szDirectory, const WIN32_FIND_DATA* data, CountupData* pData) { pData->nFiles ++; pData->dwSize += (data->nFileSizeHigh * MAXDWORD) + data->nFileSizeLow; return TRUE; } /** * t@C̍폜pR[obN֐ */ int DeleteCallback( const TCHAR* szDirectory, const WIN32_FIND_DATA* data, int* pnDeleted) { std::basic_string< TCHAR > strFile = szDirectory + std::basic_string< TCHAR >(data->cFileName); if( (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY ) { // fBNg if( RemoveDirectory( strFile.c_str() ) ) { (*pnDeleted) ++; } }else{ // t@C if( DeleteFile( strFile.c_str() ) ) { (*pnDeleted) ++; } } return TRUE; } /** * O̍폜 */ void COptionTabLog::OnBnClickedCleanLogButton() { CountupData cd; // t@C, t@CTCY int nDepthMax = 10; // őċA[x LPCTSTR szDeleteFilePattern = L"*"; CString strLogFolder = theApp.m_filepath.logFolder + L"\\"; // Ot@CJEg util::FindFileCallback( strLogFolder, szDeleteFilePattern, CountupCallback, &cd, nDepthMax ); if( cd.nFiles == 0 ) { MessageBox( L"폜Ώۃt@C܂" ); return; } CString msg; msg.Format( L"Ot@C폜܂B낵łH\n" L"Et@CꍇAx܂\n" L"E[%s]ȉ̑SẴt@C܂\n\n" L"t@CF%d\n" L"t@CTCYF%s Bytes" , (LPCTSTR)strLogFolder, cd.nFiles, util::int2comma_str(cd.dwSize) ); if( MessageBox( msg, 0, MB_YESNO | MB_ICONQUESTION ) != IDYES ) { return; } // 폜s int nDeleted = 0; // 폜ς݃t@C util::FindFileCallback( strLogFolder, szDeleteFilePattern, DeleteCallback, &nDeleted, nDepthMax ); msg.Format( L"%d ‚̃t@C폜܂B\n" L"iΏۃt@CF%d j", nDeleted, cd.nFiles ); MessageBox( msg ); } void COptionTabLog::OnBnClickedDebugModeCheck() { MessageBox( L"fobO[h̕ύX͍ċNɔf܂" ); } <|endoftext|>
<commit_before>#pragma once #include <ContinuousArtScroller.h> #include <MeshFactory.h> #include <MeshInterface.h> #include <Texture.h> #include <sstream> #include <MY_ResourceManager.h> ContinuousArtScroller::ContinuousArtScroller(std::string _fileDir, ComponentShaderBase * _shader) : ArtLayer(dynamic_cast<ShaderComponentReplace *>(_shader->getComponentAt(2))), fileDir(_fileDir), plane1(new MeshEntity(MeshFactory::getPlaneMesh(), _shader)), plane2(new MeshEntity(MeshFactory::getPlaneMesh(), _shader)), imageId(1), imageCount(0), progress(0) { while (true){ ++imageCount; std::stringstream src; src << "assets/textures/" << fileDir << "/"; if(imageCount < 10){ src << "0"; } src << imageCount << ".png"; if (!FileUtils::fileExists(src.str())){ break; } Texture * texture = new Texture(src.str(), true, false); texture->loadImageData(); images.push_back(texture); } backPlane = plane1; frontPlane = plane2; loadTexOntoPlane(1, plane1); loadTexOntoPlane(2, plane2); plane1->mesh->scaleModeMag = GL_NEAREST; plane1->mesh->scaleModeMin = GL_NEAREST; plane2->mesh->scaleModeMag = GL_NEAREST; plane2->mesh->scaleModeMin = GL_NEAREST; childTransform->addChild(backPlane); childTransform->addChild(frontPlane)->translate(1,0,0); } ContinuousArtScroller::~ContinuousArtScroller(){ // remove any active textures so they aren't delete twice while(frontPlane->mesh->textures.size() > 0){ frontPlane->mesh->textures.at(0)->unload(); frontPlane->mesh->removeTextureAt(0); }while(backPlane->mesh->textures.size() > 0){ backPlane->mesh->textures.at(0)->unload(); backPlane->mesh->removeTextureAt(0); } // delete textures while (images.size() > 0){ delete images.back(); images.pop_back(); } } void ContinuousArtScroller::cycle(signed long int _delta){ imageId += _delta; if (_delta > 0){ loadTexOntoPlane(imageId+1, backPlane); backPlane->firstParent()->translate(2, 0, 0); swapPlanes(); }else{ loadTexOntoPlane(imageId, frontPlane); frontPlane->firstParent()->translate(-2, 0, 0); swapPlanes(); } } void ContinuousArtScroller::loadTexOntoPlane(unsigned long int _texId, MeshEntity * _plane){ while(_plane->mesh->textures.size() > 0){ _plane->mesh->textures.at(0)->unload(); _plane->mesh->removeTextureAt(0); } if (_texId < images.size()){ _plane->mesh->pushTexture2D(images.at(_texId)); }else{ _plane->mesh->pushTexture2D(MY_ResourceManager::scenario->getTexture("DEFAULT")->texture); } _plane->mesh->textures.at(0)->load(); } void ContinuousArtScroller::swapPlanes(){ MeshEntity * t = frontPlane; frontPlane = backPlane; backPlane = t; } void ContinuousArtScroller::update(Step * _step){ //childTransform->translate(progress*speed, 0, 0, false); //std::cout << progress* speed << ": " << imageId << std::endl; while (imageId - progress < -1){ cycle(1); }while (imageId - progress > 1){ cycle(-1); } Entity::update(_step); }<commit_msg>added extra planes below the art scroller images to fill the gap when viewed from an angle<commit_after>#pragma once #include <ContinuousArtScroller.h> #include <MeshFactory.h> #include <MeshInterface.h> #include <Texture.h> #include <sstream> #include <MY_ResourceManager.h> ContinuousArtScroller::ContinuousArtScroller(std::string _fileDir, ComponentShaderBase * _shader) : ArtLayer(dynamic_cast<ShaderComponentReplace *>(_shader->getComponentAt(2))), fileDir(_fileDir), plane1(new MeshEntity(MeshFactory::getPlaneMesh(), _shader)), plane2(new MeshEntity(MeshFactory::getPlaneMesh(), _shader)), imageId(1), imageCount(0), progress(0) { while (true){ ++imageCount; std::stringstream src; src << "assets/textures/" << fileDir << "/"; if(imageCount < 10){ src << "0"; } src << imageCount << ".png"; if (!FileUtils::fileExists(src.str())){ break; } Texture * texture = new Texture(src.str(), true, false); texture->loadImageData(); images.push_back(texture); } backPlane = plane1; frontPlane = plane2; loadTexOntoPlane(1, plane1); loadTexOntoPlane(2, plane2); MeshInterface * m = MeshFactory::getPlaneMesh(); m->configureDefaultVertexAttributes(_shader); m->pushTexture2D(MY_ResourceManager::scenario->defaultTexture->texture); GL_NEAREST; backPlane->meshTransform->addChild(m)->translate(0, -1, 0); frontPlane->meshTransform->addChild(m)->translate(0, -1, 0); m->referenceCount += 2; plane1->mesh->scaleModeMag = plane1->mesh->scaleModeMin = plane2->mesh->scaleModeMag = plane2->mesh->scaleModeMin = m->scaleModeMag = m->scaleModeMin = GL_NEAREST; childTransform->addChild(backPlane); childTransform->addChild(frontPlane)->translate(1,0,0); } ContinuousArtScroller::~ContinuousArtScroller(){ // remove any active textures so they aren't delete twice while(frontPlane->mesh->textures.size() > 0){ frontPlane->mesh->textures.at(0)->unload(); frontPlane->mesh->removeTextureAt(0); }while(backPlane->mesh->textures.size() > 0){ backPlane->mesh->textures.at(0)->unload(); backPlane->mesh->removeTextureAt(0); } // delete textures while (images.size() > 0){ delete images.back(); images.pop_back(); } } void ContinuousArtScroller::cycle(signed long int _delta){ imageId += _delta; if (_delta > 0){ loadTexOntoPlane(imageId+1, backPlane); backPlane->firstParent()->translate(2, 0, 0); swapPlanes(); }else{ loadTexOntoPlane(imageId, frontPlane); frontPlane->firstParent()->translate(-2, 0, 0); swapPlanes(); } } void ContinuousArtScroller::loadTexOntoPlane(unsigned long int _texId, MeshEntity * _plane){ while(_plane->mesh->textures.size() > 0){ _plane->mesh->textures.at(0)->unload(); _plane->mesh->removeTextureAt(0); } if (_texId < images.size()){ _plane->mesh->pushTexture2D(images.at(_texId)); }else{ _plane->mesh->pushTexture2D(MY_ResourceManager::scenario->getTexture("DEFAULT")->texture); } _plane->mesh->textures.at(0)->load(); } void ContinuousArtScroller::swapPlanes(){ MeshEntity * t = frontPlane; frontPlane = backPlane; backPlane = t; } void ContinuousArtScroller::update(Step * _step){ //childTransform->translate(progress*speed, 0, 0, false); //std::cout << progress* speed << ": " << imageId << std::endl; while (imageId - progress < -1){ cycle(1); }while (imageId - progress > 1){ cycle(-1); } Entity::update(_step); }<|endoftext|>
<commit_before>#include <iostream> #include <seqan/file.h> #include <seqan/modifier.h> using namespace std; using namespace seqan; struct MyFunctor : public unary_function<char,char> { inline char operator()(char x) const { if (('a' <= x) && (x <= 'z')) return (x + ('A' - 'a')); return x; } }; int main () { String<char> myString = "A man, a plan, a canal-Panama"; ModifiedString< String<char>, ModView<MyFunctor> > myModifier(myString); cout << myString << endl; cout << myModifier << endl; infix(myString, 9, 9) = "master "; cout << myString << endl; cout << myModifier << endl; return 0; } <commit_msg><commit_after>///A tutorial about the use of a user-defined modifier. #include <iostream> #include <seqan/file.h> #include <seqan/modifier.h> using namespace seqan; ///A user-defined modifier that transforms all characters to upper case. struct MyFunctor : public ::std::unary_function<char,char> { inline char operator()(char x) const { if (('a' <= x) && (x <= 'z')) return (x + ('A' - 'a')); return x; } }; int main () { ///The modifier is applied to a string. String<char> myString = "A man, a plan, a canal-Panama"; ModifiedString< String<char>, ModView<MyFunctor> > myModifier(myString); ::std::cout << myString << ::std::endl; ::std::cout << myModifier << ::std::endl; infix(myString, 9, 9) = "master "; ::std::cout << myString << ::std::endl; ::std::cout << myModifier << ::std::endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: restricteduiinteraction.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:34:24 $ * * 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 "interaction/restricteduiinteraction.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_TASK_XINTERACTIONABORT_HPP_ #include <com/sun/star/task/XInteractionAbort.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONRETRY_HPP_ #include <com/sun/star/task/XInteractionRetry.hpp> #endif #ifndef _COM_SUN_STAR_UCB_INTERACTIVEIOEXCEPTION_HPP_ #include <com/sun/star/ucb/InteractiveIOException.hpp> #endif #ifndef _COM_SUN_STAR_UCB_INTERACTIVENETWORKEXCEPTION_HPP_ #include <com/sun/star/ucb/InteractiveNetworkException.hpp> #endif #ifndef _COM_SUN_STAR_UCB_INTERACTIVECHAOSEXCEPTION_HPP_ #include <com/sun/star/ucb/InteractiveCHAOSException.hpp> #endif #ifndef _COM_SUN_STAR_UCB_INTERACTIVEWRONGMEDIUMEXCEPTION_HPP_ #include <com/sun/star/ucb/InteractiveWrongMediumException.hpp> #endif #ifndef _COM_SUN_STAR_JAVA_WRONGJAVAVERSIONEXCEPTION_HPP_ #include <com/sun/star/java/WrongJavaVersionException.hpp> #endif #ifndef _COM_SUN_STAR_SYNC2_BADPARTNERSHIPEXCEPTION_HPP_ #include <com/sun/star/sync2/BadPartnershipException.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // exported const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // exported definitions //_________________________________________________________________________________________________________________ DEFINE_XINTERFACE_2( RestrictedUIInteraction , OWeakObject , DIRECT_INTERFACE(css::lang::XTypeProvider ) , DIRECT_INTERFACE(css::task::XInteractionHandler) ) DEFINE_XTYPEPROVIDER_2( RestrictedUIInteraction , css::lang::XTypeProvider , css::task::XInteractionHandler ) //_________________________________________________________________________________________________________________ RestrictedUIInteraction::RestrictedUIInteraction( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR , sal_Int32 nMaxRetry ) : ThreadHelpBase ( &Application::GetSolarMutex() ) , ::cppu::OWeakObject ( ) , m_aRequest ( ) , m_nIORetry ( 0 ) , m_nNetworkRetry ( 0 ) , m_nChaosRetry ( 0 ) , m_nWrongMediumRetry ( 0 ) , m_nWrongJavaVersionRetry( 0 ) , m_nBadPartnershipRetry ( 0 ) , m_nMaxRetry ( nMaxRetry ) { m_xGenericUIHandler = css::uno::Reference< css::task::XInteractionHandler >( xSMGR->createInstance(IMPLEMENTATIONNAME_UIINTERACTIONHANDLER), css::uno::UNO_QUERY); } //_________________________________________________________________________________________________________________ void SAL_CALL RestrictedUIInteraction::handle( const css::uno::Reference< css::task::XInteractionRequest >& xRequest ) throw( css::uno::RuntimeException ) { // safe the request for outside analyzing everytime! css::uno::Any aRequest = xRequest->getRequest(); /* SAFE { */ WriteGuard aWriteLock(m_aLock); m_aRequest = aRequest; aWriteLock.unlock(); /* } SAFE */ // analyze the request // We need XAbort as possible continuation as minimum! // But we can use retry too, if it exist ... css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > lContinuations = xRequest->getContinuations(); css::uno::Reference< css::task::XInteractionAbort > xAbort; css::uno::Reference< css::task::XInteractionRetry > xRetry; sal_Int32 nCount=lContinuations.getLength(); for (sal_Int32 i=0; i<nCount; ++i) { if ( ! xAbort.is() ) xAbort = css::uno::Reference< css::task::XInteractionAbort >( lContinuations[i], css::uno::UNO_QUERY ); if ( ! xRetry.is() ) xRetry = css::uno::Reference< css::task::XInteractionRetry >( lContinuations[i], css::uno::UNO_QUERY ); } // differ between interactions for abort (io error) // and other ones (ambigous filter) which can be forwarded // to the generic UI handler // These interactions seams to inform the user only. // They can't solve any conflict realy. // But may some of them supports a retry. Then we use it. // Otherwhise we abort it - so the load request will fail. css::ucb::InteractiveIOException aIoException ; css::ucb::InteractiveNetworkException aNetworkException ; css::ucb::InteractiveCHAOSException aChaosException ; css::ucb::InteractiveWrongMediumException aWrongMediumException ; css::java::WrongJavaVersionException aWrongJavaVersionException ; css::sync2::BadPartnershipException aBadPartnershipException ; sal_Int32 nTriesBefore = 0 ; sal_Bool bForward = sal_True; /* SAFE { */ aWriteLock.lock(); if (aRequest >>= aIoException) { ++m_nIORetry; nTriesBefore = m_nIORetry; bForward = sal_False; } else if (aRequest >>= aNetworkException) { ++m_nNetworkRetry; nTriesBefore = m_nNetworkRetry; bForward = sal_False; } else if (aRequest >>= aChaosException) { ++m_nChaosRetry; nTriesBefore = m_nChaosRetry; bForward = sal_False; } else if (aRequest >>= aWrongMediumException) { ++m_nWrongMediumRetry; nTriesBefore = m_nWrongMediumRetry; bForward = sal_False; } else if (aRequest >>= aWrongJavaVersionException) { ++m_nWrongJavaVersionRetry; nTriesBefore = m_nWrongJavaVersionRetry; bForward = sal_False; } else if (aRequest >>= aBadPartnershipException) { ++m_nBadPartnershipRetry; nTriesBefore = m_nBadPartnershipRetry; bForward = sal_False; } // By the way - use the lock to get threadsafe member copies. sal_Int32 nMaxRetry = m_nMaxRetry; css::uno::Reference< css::task::XInteractionHandler > xHandler = m_xGenericUIHandler; aWriteLock.unlock(); /* } SAFE */ LOG_ASSERT(xHandler.is(), "RestrictedUIInteraction::handle()\nMiss generic UI handler to delegate request! Will do nothing ...") // It's a interaction which shouldn't be shown at the UI. // Look for possible retries and use it. Otherwhise abort it. if ( !bForward ) { LOG_ASSERT(xAbort.is(), "RestrictedUIInteraction::handle()\nMiss \"Abort\" continuation as minimum. Will do nothing ... ") // It's a interaction which shouldn't be shown at the UI. // Look for possible retries and use it. Otherwhise abort it. if (nTriesBefore <= nMaxRetry && xRetry.is()) xRetry->select(); else if (xAbort.is()) xAbort->select(); } else // Otherwhise the request seams to show real dialogs to solve the conflict. // Delegate it to the generic UI handler. if (xHandler.is()) xHandler->handle(xRequest); } //_________________________________________________________________________________________________________________ css::uno::Any RestrictedUIInteraction::getRequest() const { /* SAFE { */ ReadGuard aReadLock(m_aLock); return m_aRequest; /* } SAFE */ } //_________________________________________________________________________________________________________________ sal_Bool RestrictedUIInteraction::wasUsed() const { /* SAFE { */ ReadGuard aReadLock(m_aLock); return m_aRequest.hasValue(); /* } SAFE */ } } // namespace framework <commit_msg>INTEGRATION: CWS pchfix02 (1.2.202); FILE MERGED 2006/09/01 17:29:13 kaib 1.2.202.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: restricteduiinteraction.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-16 14:02:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_framework.hxx" #include "interaction/restricteduiinteraction.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_TASK_XINTERACTIONABORT_HPP_ #include <com/sun/star/task/XInteractionAbort.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONRETRY_HPP_ #include <com/sun/star/task/XInteractionRetry.hpp> #endif #ifndef _COM_SUN_STAR_UCB_INTERACTIVEIOEXCEPTION_HPP_ #include <com/sun/star/ucb/InteractiveIOException.hpp> #endif #ifndef _COM_SUN_STAR_UCB_INTERACTIVENETWORKEXCEPTION_HPP_ #include <com/sun/star/ucb/InteractiveNetworkException.hpp> #endif #ifndef _COM_SUN_STAR_UCB_INTERACTIVECHAOSEXCEPTION_HPP_ #include <com/sun/star/ucb/InteractiveCHAOSException.hpp> #endif #ifndef _COM_SUN_STAR_UCB_INTERACTIVEWRONGMEDIUMEXCEPTION_HPP_ #include <com/sun/star/ucb/InteractiveWrongMediumException.hpp> #endif #ifndef _COM_SUN_STAR_JAVA_WRONGJAVAVERSIONEXCEPTION_HPP_ #include <com/sun/star/java/WrongJavaVersionException.hpp> #endif #ifndef _COM_SUN_STAR_SYNC2_BADPARTNERSHIPEXCEPTION_HPP_ #include <com/sun/star/sync2/BadPartnershipException.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // exported const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // exported definitions //_________________________________________________________________________________________________________________ DEFINE_XINTERFACE_2( RestrictedUIInteraction , OWeakObject , DIRECT_INTERFACE(css::lang::XTypeProvider ) , DIRECT_INTERFACE(css::task::XInteractionHandler) ) DEFINE_XTYPEPROVIDER_2( RestrictedUIInteraction , css::lang::XTypeProvider , css::task::XInteractionHandler ) //_________________________________________________________________________________________________________________ RestrictedUIInteraction::RestrictedUIInteraction( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR , sal_Int32 nMaxRetry ) : ThreadHelpBase ( &Application::GetSolarMutex() ) , ::cppu::OWeakObject ( ) , m_aRequest ( ) , m_nIORetry ( 0 ) , m_nNetworkRetry ( 0 ) , m_nChaosRetry ( 0 ) , m_nWrongMediumRetry ( 0 ) , m_nWrongJavaVersionRetry( 0 ) , m_nBadPartnershipRetry ( 0 ) , m_nMaxRetry ( nMaxRetry ) { m_xGenericUIHandler = css::uno::Reference< css::task::XInteractionHandler >( xSMGR->createInstance(IMPLEMENTATIONNAME_UIINTERACTIONHANDLER), css::uno::UNO_QUERY); } //_________________________________________________________________________________________________________________ void SAL_CALL RestrictedUIInteraction::handle( const css::uno::Reference< css::task::XInteractionRequest >& xRequest ) throw( css::uno::RuntimeException ) { // safe the request for outside analyzing everytime! css::uno::Any aRequest = xRequest->getRequest(); /* SAFE { */ WriteGuard aWriteLock(m_aLock); m_aRequest = aRequest; aWriteLock.unlock(); /* } SAFE */ // analyze the request // We need XAbort as possible continuation as minimum! // But we can use retry too, if it exist ... css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > lContinuations = xRequest->getContinuations(); css::uno::Reference< css::task::XInteractionAbort > xAbort; css::uno::Reference< css::task::XInteractionRetry > xRetry; sal_Int32 nCount=lContinuations.getLength(); for (sal_Int32 i=0; i<nCount; ++i) { if ( ! xAbort.is() ) xAbort = css::uno::Reference< css::task::XInteractionAbort >( lContinuations[i], css::uno::UNO_QUERY ); if ( ! xRetry.is() ) xRetry = css::uno::Reference< css::task::XInteractionRetry >( lContinuations[i], css::uno::UNO_QUERY ); } // differ between interactions for abort (io error) // and other ones (ambigous filter) which can be forwarded // to the generic UI handler // These interactions seams to inform the user only. // They can't solve any conflict realy. // But may some of them supports a retry. Then we use it. // Otherwhise we abort it - so the load request will fail. css::ucb::InteractiveIOException aIoException ; css::ucb::InteractiveNetworkException aNetworkException ; css::ucb::InteractiveCHAOSException aChaosException ; css::ucb::InteractiveWrongMediumException aWrongMediumException ; css::java::WrongJavaVersionException aWrongJavaVersionException ; css::sync2::BadPartnershipException aBadPartnershipException ; sal_Int32 nTriesBefore = 0 ; sal_Bool bForward = sal_True; /* SAFE { */ aWriteLock.lock(); if (aRequest >>= aIoException) { ++m_nIORetry; nTriesBefore = m_nIORetry; bForward = sal_False; } else if (aRequest >>= aNetworkException) { ++m_nNetworkRetry; nTriesBefore = m_nNetworkRetry; bForward = sal_False; } else if (aRequest >>= aChaosException) { ++m_nChaosRetry; nTriesBefore = m_nChaosRetry; bForward = sal_False; } else if (aRequest >>= aWrongMediumException) { ++m_nWrongMediumRetry; nTriesBefore = m_nWrongMediumRetry; bForward = sal_False; } else if (aRequest >>= aWrongJavaVersionException) { ++m_nWrongJavaVersionRetry; nTriesBefore = m_nWrongJavaVersionRetry; bForward = sal_False; } else if (aRequest >>= aBadPartnershipException) { ++m_nBadPartnershipRetry; nTriesBefore = m_nBadPartnershipRetry; bForward = sal_False; } // By the way - use the lock to get threadsafe member copies. sal_Int32 nMaxRetry = m_nMaxRetry; css::uno::Reference< css::task::XInteractionHandler > xHandler = m_xGenericUIHandler; aWriteLock.unlock(); /* } SAFE */ LOG_ASSERT(xHandler.is(), "RestrictedUIInteraction::handle()\nMiss generic UI handler to delegate request! Will do nothing ...") // It's a interaction which shouldn't be shown at the UI. // Look for possible retries and use it. Otherwhise abort it. if ( !bForward ) { LOG_ASSERT(xAbort.is(), "RestrictedUIInteraction::handle()\nMiss \"Abort\" continuation as minimum. Will do nothing ... ") // It's a interaction which shouldn't be shown at the UI. // Look for possible retries and use it. Otherwhise abort it. if (nTriesBefore <= nMaxRetry && xRetry.is()) xRetry->select(); else if (xAbort.is()) xAbort->select(); } else // Otherwhise the request seams to show real dialogs to solve the conflict. // Delegate it to the generic UI handler. if (xHandler.is()) xHandler->handle(xRequest); } //_________________________________________________________________________________________________________________ css::uno::Any RestrictedUIInteraction::getRequest() const { /* SAFE { */ ReadGuard aReadLock(m_aLock); return m_aRequest; /* } SAFE */ } //_________________________________________________________________________________________________________________ sal_Bool RestrictedUIInteraction::wasUsed() const { /* SAFE { */ ReadGuard aReadLock(m_aLock); return m_aRequest.hasValue(); /* } SAFE */ } } // namespace framework <|endoftext|>
<commit_before>#include <initializer_list> #include <tuple> namespace spatial { class kdtree { public: kdtree(std::initializer_list<double> &list) { } }; } int main() { }<commit_msg>Finished the constructors for the tree and nodes<commit_after>#include "closestpair.hpp" #include "node.hpp" #include <vector> #include <iterator> #include <algorithm> namespace spatial { kdtree::kdtree(std::vector<kdnode> &list) { int cardinal = 0; for (kdnode& node : list) { if (cardinal == 0) cardinal = node.getCardinal(); if (cardinal != node.getCardinal()) { throw std::invalid_argument("All nodes in the list must be of the same type"); } } std::copy(list.begin(), list.end(), std::back_inserter(points)); } void sortTree(kdtree &tree) { } } int main() { spatial::kdnode2D node({8.9, 9.9}); }<|endoftext|>
<commit_before>#include "listworker.h" #include "datalayer.h" #include <iostream> #include <string> using namespace std; ListWorker::ListWorker() { data.readScientistsFromDatabase(persons); data.readComputersFromDatabase(com); data.readLinksFromDatabase(link); } void ListWorker::addNewScientist(string name, char gender, int yearOfBirth, int yearOfDeath, string comment) { int vsize = scientistIdFinder(); Person p(name, gender, yearOfBirth, yearOfDeath, comment, vsize); persons.push_back(p); data.addScientist(name, gender, yearOfBirth, yearOfDeath, comment, vsize); } void ListWorker::addNewComputer(string name, string type, int yearbuilt, string isbuilt) { int vsize = computerIdFinder(); Computer c(name, isbuilt, yearbuilt, type, vsize); com.erase (com.begin(),com.end()); data.addComputer(name, type, yearbuilt, isbuilt, vsize); } void ListWorker::addNewConnection(int linkId, int compId, int sciId) { Linker l(linkId, sciId, compId); link.push_back(l); data.addConnection(linkId, sciId, compId); } void ListWorker::sortScientistNames() { data.sortScientistNames(persons); } void ListWorker::sortScientistNamesReverse() { data.sortScientistNamesReverse(persons); } void ListWorker::sortScientistBirth() { data.sortScientistBirth(persons); } void ListWorker::sortScientistGender() { data.sortScientistGender(persons); } void ListWorker::sortScientistAge() { data.sortScientistAge(persons); } void ListWorker::sortComputerName() { data.sortNamesComputers(com); } void ListWorker::sortComputerNameReverse() { data.sortNamesComputersReverse(com); } void ListWorker::sortComputerDate() { data.sortDateComputers(com); } void ListWorker::sortComputerType() { data.sortTypeComputers(com); } bool ListWorker::removePerson(string name) { for(size_t i = 0; i < persons.size(); ++i) { if(name == persons[i].getScientistName()) { persons.erase(persons.begin() + i); removeConnection(i,0); data.removeScientist(name); return true; } } return false; } void ListWorker::removeConnection(int s, int c) { if(c == 0) { int removeId = getScientistId(s); for(int i = 0; i < getLinkSize()+2; i++) { if(removeId == getLinkSciId(i)) { int linkId = getLinkId(i); link.erase(link.begin() + i); data.removeConnection(linkId); } } } else { int removeId = getComputerId(c); for(int i = 0; i < getLinkSize()+2; i++) { if(removeId == getLinkCompId(i)) { int linkId = getLinkId(i); link.erase(link.begin() + i); data.removeConnection(linkId); } } } } bool ListWorker::removePersonFound(string name) { for(size_t i = 0; i < persons.size(); ++i) { if(name == persons[i].getScientistName()) { return true; } } return false; } bool ListWorker::removeComputer(string name) { for(size_t i = 0; i < com.size(); ++i) { if(name == com[i].getComputerName()) { com.erase(com.begin() + i); removeConnection(0,i); data.removeComputer(name); return true; } } return false; } bool ListWorker::removeComputerFound(string name) { for(size_t i = 0; i < com.size(); ++i) { if(name == com[i].getComputerName()) { return true; } } return false; } int ListWorker::getScientistNameSize(int n) const { string name = persons[n].getScientistName(); int size = name.size(); return size; } int ListWorker::getComputerNameSize(int n) const { string name = com[n].getComputerName(); int size = name.size(); return size; } bool ListWorker::nameSearcher(string name) { for(unsigned int i = 0; i < persons.size(); i++) { std::size_t found = getScientistName(i).find(name); if (found!=std::string::npos) { return true; break; } } return false; } bool ListWorker::computerNameSearcher(string name) { for(int i = 0; i < computerSize(); i++) { std::size_t found = getComputerLowerCaseName(i).find(name); if (found!=std::string::npos) { return true; break; } } return false; } bool ListWorker::genderSearcher(char gender) { for(unsigned int i = 0; i < persons.size(); i++) { if(gender == getScientistGender(i)) { return true; break; } } return false; } bool ListWorker::typeSearcher(string type) { for(unsigned int i = 0; i < com.size(); i++) { std::size_t found = getComputerType(i).find(type); if (found!=std::string::npos) { return true; break; } } return false; } bool ListWorker::yearSearcher(int year) { for(unsigned int i = 0; i < persons.size(); i++) { if(year == getScientistBirth(i)) { return true; break; } } return false; } bool ListWorker::builtDateSearcher(int year) { for(unsigned int i = 0; i < com.size(); i++) { if(year == getComputerDate(i)) { return true; break; } } return false; } bool ListWorker::ageSearcher(int age) { for(unsigned int i = 0; i < persons.size(); i++) { if(age == getScientistAge(i)) { return true; break; } } return false; } int ListWorker::computerIdFinder() { int idValue; for (int i = 1; i <= computerSize(); i++) { if(i != getComputerId(i-1)) { return i; } else { idValue = i + 1; } } return idValue; } int ListWorker::scientistIdFinder() { int idValue; for (int i = 1; i <= personsSize(); i++) { if(i != getScientistId(i-1)) { return i; } else { idValue = i+1; } } return idValue; } void ListWorker::refreshVector() { com.erase (com.begin(),com.end()); data.readComputersFromDatabase(com); persons.erase (persons.begin(),persons.end()); data.readScientistsFromDatabase(persons); link.erase(link.begin(),link.end()); data.readLinksFromDatabase(link); } string ListWorker::getComputerNameFromId(int n) const { string name; for(unsigned int i = 0; i < com.size(); i++) { if(n == getComputerId(i)) { name = com[i].getComputerName(); } } return name; } string ListWorker::getScientistNameFromId(int n) const { string name; for(unsigned int i = 0; i < persons.size(); i++) { if(n == persons[i].getScientistId()) { name = persons[i].getScientistName(); } } return name; } void ListWorker::removeConnection(string scientist, string computer) { int scientId; int compId; for(int i = 0; i < personsSize(); i++) { if(scientist == getScientistName(i)) { scientId = getScientistId(i); } } for(int j = 0; j < computerSize(); j++) { if(computer == getComputerName(j)) { compId = getComputerId(j); } } data.removeConnection(scientId, compId); } <commit_msg>listworker uppsetning<commit_after>#include "listworker.h" #include "datalayer.h" #include <iostream> #include <string> using namespace std; ListWorker::ListWorker() { data.readScientistsFromDatabase(persons); data.readComputersFromDatabase(com); data.readLinksFromDatabase(link); } void ListWorker::addNewScientist(string name, char gender, int yearOfBirth, int yearOfDeath, string comment) { int vsize = scientistIdFinder(); Person p(name, gender, yearOfBirth, yearOfDeath, comment, vsize); persons.push_back(p); data.addScientist(name, gender, yearOfBirth, yearOfDeath, comment, vsize); } void ListWorker::addNewComputer(string name, string type, int yearbuilt, string isbuilt) { int vsize = computerIdFinder(); Computer c(name, isbuilt, yearbuilt, type, vsize); com.erase (com.begin(),com.end()); data.addComputer(name, type, yearbuilt, isbuilt, vsize); } void ListWorker::addNewConnection(int linkId, int compId, int sciId) { Linker l(linkId, sciId, compId); link.push_back(l); data.addConnection(linkId, sciId, compId); } void ListWorker::sortScientistNames() { data.sortScientistNames(persons); } void ListWorker::sortScientistNamesReverse() { data.sortScientistNamesReverse(persons); } void ListWorker::sortScientistBirth() { data.sortScientistBirth(persons); } void ListWorker::sortScientistGender() { data.sortScientistGender(persons); } void ListWorker::sortScientistAge() { data.sortScientistAge(persons); } void ListWorker::sortComputerName() { data.sortNamesComputers(com); } void ListWorker::sortComputerNameReverse() { data.sortNamesComputersReverse(com); } void ListWorker::sortComputerDate() { data.sortDateComputers(com); } void ListWorker::sortComputerType() { data.sortTypeComputers(com); } bool ListWorker::removePerson(string name) { for(size_t i = 0; i < persons.size(); ++i) { if(name == persons[i].getScientistName()) { persons.erase(persons.begin() + i); removeConnection(i,0); data.removeScientist(name); return true; } } return false; } void ListWorker::removeConnection(int s, int c) { if(c == 0) { int removeId = getScientistId(s); for(int i = 0; i < getLinkSize()+2; i++) { if(removeId == getLinkSciId(i)) { int linkId = getLinkId(i); link.erase(link.begin() + i); data.removeConnection(linkId); } } } else { int removeId = getComputerId(c); for(int i = 0; i < getLinkSize()+2; i++) { if(removeId == getLinkCompId(i)) { int linkId = getLinkId(i); link.erase(link.begin() + i); data.removeConnection(linkId); } } } } bool ListWorker::removePersonFound(string name) { for(size_t i = 0; i < persons.size(); ++i) { if(name == persons[i].getScientistName()) { return true; } } return false; } bool ListWorker::removeComputer(string name) { for(size_t i = 0; i < com.size(); ++i) { if(name == com[i].getComputerName()) { com.erase(com.begin() + i); removeConnection(0,i); data.removeComputer(name); return true; } } return false; } bool ListWorker::removeComputerFound(string name) { for(size_t i = 0; i < com.size(); ++i) { if(name == com[i].getComputerName()) { return true; } } return false; } int ListWorker::getScientistNameSize(int n) const { string name = persons[n].getScientistName(); int size = name.size(); return size; } int ListWorker::getComputerNameSize(int n) const { string name = com[n].getComputerName(); int size = name.size(); return size; } bool ListWorker::nameSearcher(string name) { for(unsigned int i = 0; i < persons.size(); i++) { std::size_t found = getScientistName(i).find(name); if (found!=std::string::npos) { return true; break; } } return false; } bool ListWorker::computerNameSearcher(string name) { for(int i = 0; i < computerSize(); i++) { std::size_t found = getComputerLowerCaseName(i).find(name); if (found!=std::string::npos) { return true; break; } } return false; } bool ListWorker::genderSearcher(char gender) { for(unsigned int i = 0; i < persons.size(); i++) { if(gender == getScientistGender(i)) { return true; break; } } return false; } bool ListWorker::typeSearcher(string type) { for(unsigned int i = 0; i < com.size(); i++) { std::size_t found = getComputerType(i).find(type); if (found!=std::string::npos) { return true; break; } } return false; } bool ListWorker::yearSearcher(int year) { for(unsigned int i = 0; i < persons.size(); i++) { if(year == getScientistBirth(i)) { return true; break; } } return false; } bool ListWorker::builtDateSearcher(int year) { for(unsigned int i = 0; i < com.size(); i++) { if(year == getComputerDate(i)) { return true; break; } } return false; } bool ListWorker::ageSearcher(int age) { for(unsigned int i = 0; i < persons.size(); i++) { if(age == getScientistAge(i)) { return true; break; } } return false; } int ListWorker::computerIdFinder() { int idValue; for (int i = 1; i <= computerSize(); i++) { if(i != getComputerId(i-1)) { return i; } else { idValue = i + 1; } } return idValue; } int ListWorker::scientistIdFinder() { int idValue; for (int i = 1; i <= personsSize(); i++) { if(i != getScientistId(i-1)) { return i; } else { idValue = i+1; } } return idValue; } void ListWorker::refreshVector() { com.erase (com.begin(),com.end()); data.readComputersFromDatabase(com); persons.erase (persons.begin(),persons.end()); data.readScientistsFromDatabase(persons); link.erase(link.begin(),link.end()); data.readLinksFromDatabase(link); } string ListWorker::getComputerNameFromId(int n) const { string name; for(unsigned int i = 0; i < com.size(); i++) { if(n == getComputerId(i)) { name = com[i].getComputerName(); } } return name; } string ListWorker::getScientistNameFromId(int n) const { string name; for(unsigned int i = 0; i < persons.size(); i++) { if(n == persons[i].getScientistId()) { name = persons[i].getScientistName(); } } return name; } void ListWorker::removeConnection(string scientist, string computer) { int scientId; int compId; for(int i = 0; i < personsSize(); i++) { if(scientist == getScientistName(i)) { scientId = getScientistId(i); } } for(int j = 0; j < computerSize(); j++) { if(computer == getComputerName(j)) { compId = getComputerId(j); } } data.removeConnection(scientId, compId); } <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * BP1Base.cpp * * Created on: Feb 7, 2017 * Author: William F Godoy godoywf@ornl.gov */ #include "BP1Base.h" #include "BP1Base.tcc" #include <iostream> #include "adios2/ADIOSTypes.h" //PathSeparator #include "adios2/helper/adiosFunctions.h" //CreateDirectory, StringToTimeUnit namespace adios2 { namespace format { BP1Base::BP1Base(MPI_Comm mpiComm, const bool debugMode) : m_HeapBuffer(debugMode), m_BP1Aggregator(mpiComm, debugMode), m_DebugMode(debugMode) { // default m_Profiler.IsActive = true; } void BP1Base::InitParameters(const Params &parameters) { // flags for defaults that require constructors bool useDefaultInitialBufferSize = true; bool useDefaultProfileUnits = true; for (const auto &pair : parameters) { const std::string key(pair.first); const std::string value(pair.second); if (key == "Profile") { InitParameterProfile(value); } else if (key == "ProfileUnits") { InitParameterProfileUnits(value); useDefaultProfileUnits = false; } else if (key == "BufferGrowthFactor") { InitParameterBufferGrowth(value); } else if (key == "InitialBufferSize") { InitParameterInitBufferSize(value); useDefaultInitialBufferSize = false; } else if (key == "MaxBufferSize") { InitParameterMaxBufferSize(value); } else if (key == "Threads") { InitParameterThreads(value); } else if (key == "Verbose") { InitParameterVerbose(value); } } // default timer for buffering if (m_Profiler.IsActive && useDefaultProfileUnits) { m_Profiler.Timers.emplace( "buffering", profiling::Timer("buffering", DefaultTimeUnitEnum, m_DebugMode)); m_Profiler.Bytes.emplace("buffering", 0); } if (useDefaultInitialBufferSize) { m_HeapBuffer.ResizeData(DefaultInitialBufferSize); } } std::vector<std::string> BP1Base::GetBPBaseNames(const std::vector<std::string> &names) const noexcept { auto lf_GetBPBaseName = [](const std::string &name) -> std::string { const std::string bpBaseName(AddExtension(name, ".bp") + ".dir"); return bpBaseName; }; std::vector<std::string> bpBaseNames; bpBaseNames.reserve(names.size()); for (const auto &name : names) { bpBaseNames.push_back(lf_GetBPBaseName(name)); } return bpBaseNames; } std::vector<std::string> BP1Base::GetBPNames(const std::vector<std::string> &baseNames) const noexcept { auto lf_GetBPName = [](const std::string &baseName, const int rank) -> std::string { const std::string bpBaseName = AddExtension(baseName, ".bp"); // path/root.bp.dir/root.bp.rank std::string bpRootName = bpBaseName; const auto lastPathSeparator(bpBaseName.find_last_of(PathSeparator)); if (lastPathSeparator != std::string::npos) { bpRootName = bpBaseName.substr(lastPathSeparator); } const std::string bpName(bpBaseName + ".dir/" + bpRootName + "." + std::to_string(rank)); return bpName; }; std::vector<std::string> bpNames; bpNames.reserve(baseNames.size()); for (const auto &baseName : baseNames) { bpNames.push_back(lf_GetBPName(baseName, m_BP1Aggregator.m_RankMPI)); } return bpNames; } // PROTECTED void BP1Base::InitParameterProfile(const std::string value) { if (value == "off" || value == "Off") { m_Profiler.IsActive = false; } else if (value == "on" || value == "On") { m_Profiler.IsActive = true; // default } else { if (m_DebugMode) { throw std::invalid_argument("ERROR: IO SetParameters profile " "invalid value, valid: " "profile=on or " "profile=off, in call to Open\n"); } } } void BP1Base::InitParameterProfileUnits(const std::string value) { TimeUnit timeUnit = StringToTimeUnit(value, m_DebugMode); if (m_Profiler.Timers.count("buffering") == 1) { m_Profiler.Timers.erase("buffering"); } m_Profiler.Timers.emplace( "buffering", profiling::Timer("buffering", timeUnit, m_DebugMode)); m_Profiler.Bytes.emplace("buffering", 0); } void BP1Base::InitParameterBufferGrowth(const std::string value) { if (m_DebugMode) { bool success = true; std::string description; try { m_GrowthFactor = std::stof(value); } catch (std::exception &e) { success = false; description = std::string(e.what()); } if (!success || m_GrowthFactor <= 1.f) { throw std::invalid_argument( "ERROR: BufferGrowthFactor value " "can't be less or equal than 1 (default = 1.5), or couldn't " "convert number,\n additional description:" + description + "\n, in call to Open\n"); } } else { m_GrowthFactor = std::stof(value); } } void BP1Base::InitParameterInitBufferSize(const std::string value) { if (m_DebugMode) { if (value.size() < 2) { throw std::invalid_argument( "ERROR: wrong value for InitialBufferSize, it must be larger " "than " "16Kb (minimum default), in call to Open\n"); } } const std::string number(value.substr(0, value.size() - 2)); const std::string units(value.substr(value.size() - 2)); const size_t factor = BytesFactor(units, m_DebugMode); size_t bufferSize = DefaultInitialBufferSize; // from ADIOSTypes.h if (m_DebugMode) { bool success = true; std::string description; try { bufferSize = static_cast<size_t>(std::stoul(number) * factor); } catch (std::exception &e) { success = false; description = std::string(e.what()); } if (!success || bufferSize < DefaultInitialBufferSize) // 16384b { throw std::invalid_argument( "ERROR: wrong value for InitialBufferSize, it must be larger " "than " "16Kb (minimum default), additional description: " + description + " in call to Open\n"); } } else { bufferSize = static_cast<size_t>(std::stoul(number) * factor); } m_HeapBuffer.ResizeData(bufferSize); } void BP1Base::InitParameterMaxBufferSize(const std::string value) { if (m_DebugMode) { if (value.size() < 2) { throw std::invalid_argument( "ERROR: couldn't convert value of max_buffer_size IO " "SetParameter, valid syntax: MaxBufferSize=10Gb, " "MaxBufferSize=1000Mb, MaxBufferSize=16Kb (minimum default), " " in call to Open"); } } const std::string number(value.substr(0, value.size() - 2)); const std::string units(value.substr(value.size() - 2)); const size_t factor = BytesFactor(units, m_DebugMode); if (m_DebugMode) { bool success = true; std::string description; try { m_MaxBufferSize = static_cast<size_t>(std::stoul(number) * factor); } catch (std::exception &e) { success = false; description = std::string(e.what()); } if (!success || m_MaxBufferSize < 16 * 1024) // 16384b { throw std::invalid_argument( "ERROR: couldn't convert value of max_buffer_size IO " "SetParameter, valid syntax: MaxBufferSize=10Gb, " "MaxBufferSize=1000Mb, MaxBufferSize=16Kb (minimum default), " "\nadditional description: " + description + " in call to Open"); } } else { m_MaxBufferSize = static_cast<size_t>(std::stoul(number) * factor); } } void BP1Base::InitParameterThreads(const std::string value) { int threads = -1; if (m_DebugMode) { bool success = true; std::string description; try { threads = std::stoi(value); } catch (std::exception &e) { success = false; description = std::string(e.what()); } if (!success || threads < 1) { throw std::invalid_argument( "ERROR: value in Threads=value in IO SetParameters must be " "an integer >= 1 (default) \nadditional description: " + description + "\n, in call to Open\n"); } } else { threads = std::stoi(value); } m_Threads = static_cast<unsigned int>(threads); } void BP1Base::InitParameterVerbose(const std::string value) { int verbosity = -1; if (m_DebugMode) { bool success = true; std::string description; try { verbosity = std::stoi(value); } catch (std::exception &e) { success = false; description = std::string(e.what()); } if (!success || verbosity < 0 || verbosity > 5) { throw std::invalid_argument( "ERROR: value in Verbose=value in IO SetParameters must be " "an integer in the range [0,5], \nadditional description: " + description + "\n, in call to Open\n"); } } else { verbosity = std::stoi(value); } m_Verbosity = static_cast<unsigned int>(verbosity); } std::vector<uint8_t> BP1Base::GetTransportIDs(const std::vector<std::string> &transportsTypes) const noexcept { auto lf_GetTransportID = [](const std::string method) -> uint8_t { int id = METHOD_UNKNOWN; if (method == "File_NULL") { id = METHOD_NULL; } else if (method == "File_POSIX") { id = METHOD_POSIX; } else if (method == "File_fstream") { id = METHOD_FSTREAM; } else if (method == "File_stdio") { id = METHOD_FILE; } return static_cast<uint8_t>(id); }; std::vector<uint8_t> transportsIDs; transportsIDs.reserve(transportsTypes.size()); for (const auto transportType : transportsTypes) { transportsIDs.push_back(lf_GetTransportID(transportType)); } return transportsIDs; } size_t BP1Base::GetProcessGroupIndexSize(const std::string name, const std::string timeStepName, const size_t transportsSize) const noexcept { // pgIndex + list of methods (transports) size_t pgSize = (name.length() + timeStepName.length() + 23) + (3 + transportsSize); return pgSize; } #define declare_template_instantiation(T) \ template BP1Base::ResizeResult BP1Base::ResizeBuffer( \ const Variable<T> &variable); ADIOS2_FOREACH_TYPE_1ARG(declare_template_instantiation) #undef declare_template_instantiation } // end namespace format } // end namespace adios <commit_msg>Removed iostream header, not used<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * BP1Base.cpp * * Created on: Feb 7, 2017 * Author: William F Godoy godoywf@ornl.gov */ #include "BP1Base.h" #include "BP1Base.tcc" #include "adios2/ADIOSTypes.h" //PathSeparator #include "adios2/helper/adiosFunctions.h" //CreateDirectory, StringToTimeUnit namespace adios2 { namespace format { BP1Base::BP1Base(MPI_Comm mpiComm, const bool debugMode) : m_HeapBuffer(debugMode), m_BP1Aggregator(mpiComm, debugMode), m_DebugMode(debugMode) { // default m_Profiler.IsActive = true; } void BP1Base::InitParameters(const Params &parameters) { // flags for defaults that require constructors bool useDefaultInitialBufferSize = true; bool useDefaultProfileUnits = true; for (const auto &pair : parameters) { const std::string key(pair.first); const std::string value(pair.second); if (key == "Profile") { InitParameterProfile(value); } else if (key == "ProfileUnits") { InitParameterProfileUnits(value); useDefaultProfileUnits = false; } else if (key == "BufferGrowthFactor") { InitParameterBufferGrowth(value); } else if (key == "InitialBufferSize") { InitParameterInitBufferSize(value); useDefaultInitialBufferSize = false; } else if (key == "MaxBufferSize") { InitParameterMaxBufferSize(value); } else if (key == "Threads") { InitParameterThreads(value); } else if (key == "Verbose") { InitParameterVerbose(value); } } // default timer for buffering if (m_Profiler.IsActive && useDefaultProfileUnits) { m_Profiler.Timers.emplace( "buffering", profiling::Timer("buffering", DefaultTimeUnitEnum, m_DebugMode)); m_Profiler.Bytes.emplace("buffering", 0); } if (useDefaultInitialBufferSize) { m_HeapBuffer.ResizeData(DefaultInitialBufferSize); } } std::vector<std::string> BP1Base::GetBPBaseNames(const std::vector<std::string> &names) const noexcept { auto lf_GetBPBaseName = [](const std::string &name) -> std::string { const std::string bpBaseName(AddExtension(name, ".bp") + ".dir"); return bpBaseName; }; std::vector<std::string> bpBaseNames; bpBaseNames.reserve(names.size()); for (const auto &name : names) { bpBaseNames.push_back(lf_GetBPBaseName(name)); } return bpBaseNames; } std::vector<std::string> BP1Base::GetBPNames(const std::vector<std::string> &baseNames) const noexcept { auto lf_GetBPName = [](const std::string &baseName, const int rank) -> std::string { const std::string bpBaseName = AddExtension(baseName, ".bp"); // path/root.bp.dir/root.bp.rank std::string bpRootName = bpBaseName; const auto lastPathSeparator(bpBaseName.find_last_of(PathSeparator)); if (lastPathSeparator != std::string::npos) { bpRootName = bpBaseName.substr(lastPathSeparator); } const std::string bpName(bpBaseName + ".dir/" + bpRootName + "." + std::to_string(rank)); return bpName; }; std::vector<std::string> bpNames; bpNames.reserve(baseNames.size()); for (const auto &baseName : baseNames) { bpNames.push_back(lf_GetBPName(baseName, m_BP1Aggregator.m_RankMPI)); } return bpNames; } // PROTECTED void BP1Base::InitParameterProfile(const std::string value) { if (value == "off" || value == "Off") { m_Profiler.IsActive = false; } else if (value == "on" || value == "On") { m_Profiler.IsActive = true; // default } else { if (m_DebugMode) { throw std::invalid_argument("ERROR: IO SetParameters profile " "invalid value, valid: " "profile=on or " "profile=off, in call to Open\n"); } } } void BP1Base::InitParameterProfileUnits(const std::string value) { TimeUnit timeUnit = StringToTimeUnit(value, m_DebugMode); if (m_Profiler.Timers.count("buffering") == 1) { m_Profiler.Timers.erase("buffering"); } m_Profiler.Timers.emplace( "buffering", profiling::Timer("buffering", timeUnit, m_DebugMode)); m_Profiler.Bytes.emplace("buffering", 0); } void BP1Base::InitParameterBufferGrowth(const std::string value) { if (m_DebugMode) { bool success = true; std::string description; try { m_GrowthFactor = std::stof(value); } catch (std::exception &e) { success = false; description = std::string(e.what()); } if (!success || m_GrowthFactor <= 1.f) { throw std::invalid_argument( "ERROR: BufferGrowthFactor value " "can't be less or equal than 1 (default = 1.5), or couldn't " "convert number,\n additional description:" + description + "\n, in call to Open\n"); } } else { m_GrowthFactor = std::stof(value); } } void BP1Base::InitParameterInitBufferSize(const std::string value) { if (m_DebugMode) { if (value.size() < 2) { throw std::invalid_argument( "ERROR: wrong value for InitialBufferSize, it must be larger " "than " "16Kb (minimum default), in call to Open\n"); } } const std::string number(value.substr(0, value.size() - 2)); const std::string units(value.substr(value.size() - 2)); const size_t factor = BytesFactor(units, m_DebugMode); size_t bufferSize = DefaultInitialBufferSize; // from ADIOSTypes.h if (m_DebugMode) { bool success = true; std::string description; try { bufferSize = static_cast<size_t>(std::stoul(number) * factor); } catch (std::exception &e) { success = false; description = std::string(e.what()); } if (!success || bufferSize < DefaultInitialBufferSize) // 16384b { throw std::invalid_argument( "ERROR: wrong value for InitialBufferSize, it must be larger " "than " "16Kb (minimum default), additional description: " + description + " in call to Open\n"); } } else { bufferSize = static_cast<size_t>(std::stoul(number) * factor); } m_HeapBuffer.ResizeData(bufferSize); } void BP1Base::InitParameterMaxBufferSize(const std::string value) { if (m_DebugMode) { if (value.size() < 2) { throw std::invalid_argument( "ERROR: couldn't convert value of max_buffer_size IO " "SetParameter, valid syntax: MaxBufferSize=10Gb, " "MaxBufferSize=1000Mb, MaxBufferSize=16Kb (minimum default), " " in call to Open"); } } const std::string number(value.substr(0, value.size() - 2)); const std::string units(value.substr(value.size() - 2)); const size_t factor = BytesFactor(units, m_DebugMode); if (m_DebugMode) { bool success = true; std::string description; try { m_MaxBufferSize = static_cast<size_t>(std::stoul(number) * factor); } catch (std::exception &e) { success = false; description = std::string(e.what()); } if (!success || m_MaxBufferSize < 16 * 1024) // 16384b { throw std::invalid_argument( "ERROR: couldn't convert value of max_buffer_size IO " "SetParameter, valid syntax: MaxBufferSize=10Gb, " "MaxBufferSize=1000Mb, MaxBufferSize=16Kb (minimum default), " "\nadditional description: " + description + " in call to Open"); } } else { m_MaxBufferSize = static_cast<size_t>(std::stoul(number) * factor); } } void BP1Base::InitParameterThreads(const std::string value) { int threads = -1; if (m_DebugMode) { bool success = true; std::string description; try { threads = std::stoi(value); } catch (std::exception &e) { success = false; description = std::string(e.what()); } if (!success || threads < 1) { throw std::invalid_argument( "ERROR: value in Threads=value in IO SetParameters must be " "an integer >= 1 (default) \nadditional description: " + description + "\n, in call to Open\n"); } } else { threads = std::stoi(value); } m_Threads = static_cast<unsigned int>(threads); } void BP1Base::InitParameterVerbose(const std::string value) { int verbosity = -1; if (m_DebugMode) { bool success = true; std::string description; try { verbosity = std::stoi(value); } catch (std::exception &e) { success = false; description = std::string(e.what()); } if (!success || verbosity < 0 || verbosity > 5) { throw std::invalid_argument( "ERROR: value in Verbose=value in IO SetParameters must be " "an integer in the range [0,5], \nadditional description: " + description + "\n, in call to Open\n"); } } else { verbosity = std::stoi(value); } m_Verbosity = static_cast<unsigned int>(verbosity); } std::vector<uint8_t> BP1Base::GetTransportIDs(const std::vector<std::string> &transportsTypes) const noexcept { auto lf_GetTransportID = [](const std::string method) -> uint8_t { int id = METHOD_UNKNOWN; if (method == "File_NULL") { id = METHOD_NULL; } else if (method == "File_POSIX") { id = METHOD_POSIX; } else if (method == "File_fstream") { id = METHOD_FSTREAM; } else if (method == "File_stdio") { id = METHOD_FILE; } return static_cast<uint8_t>(id); }; std::vector<uint8_t> transportsIDs; transportsIDs.reserve(transportsTypes.size()); for (const auto transportType : transportsTypes) { transportsIDs.push_back(lf_GetTransportID(transportType)); } return transportsIDs; } size_t BP1Base::GetProcessGroupIndexSize(const std::string name, const std::string timeStepName, const size_t transportsSize) const noexcept { // pgIndex + list of methods (transports) size_t pgSize = (name.length() + timeStepName.length() + 23) + (3 + transportsSize); return pgSize; } #define declare_template_instantiation(T) \ template BP1Base::ResizeResult BP1Base::ResizeBuffer( \ const Variable<T> &variable); ADIOS2_FOREACH_TYPE_1ARG(declare_template_instantiation) #undef declare_template_instantiation } // end namespace format } // end namespace adios <|endoftext|>
<commit_before>/** * \file * \brief MutexControlBlock class implementation * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-06-15 */ #include "distortos/synchronization/MutexControlBlock.hpp" #include "distortos/scheduler/getScheduler.hpp" #include "distortos/scheduler/Scheduler.hpp" #include <cerrno> namespace distortos { namespace synchronization { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local types +---------------------------------------------------------------------------------------------------------------------*/ /// PriorityInheritanceMutexControlBlockUnblockFunctor is a functor executed when unblocking a thread that is blocked on /// a mutex with PriorityInheritance protocol class PriorityInheritanceMutexControlBlockUnblockFunctor : public scheduler::ThreadControlBlock::UnblockFunctor { public: /** * \brief PriorityInheritanceMutexControlBlockUnblockFunctor's constructor * * \param [in] mutexControlBlock is a reference to MutexControlBlock that blocked the thread */ constexpr explicit PriorityInheritanceMutexControlBlockUnblockFunctor(const MutexControlBlock& mutexControlBlock) : mutexControlBlock_(mutexControlBlock) { } /** * \brief PriorityInheritanceMutexControlBlockUnblockFunctor's function call operator * * If the wait for mutex was interrupted, requests update of boosted priority of current owner of the mutex. Pointer * to MutexControlBlock with PriorityInheritance protocol which caused the thread to block is reset to nullptr. * * \param [in] threadControlBlock is a reference to ThreadControlBlock that is being unblocked * \param [in] unblockReason is the reason of thread unblocking */ virtual void operator()(scheduler::ThreadControlBlock& threadControlBlock, const scheduler::ThreadControlBlock::UnblockReason unblockReason) const override { const auto owner = mutexControlBlock_.getOwner(); // waiting for mutex was interrupted and some thread still holds it? if (unblockReason != scheduler::ThreadControlBlock::UnblockReason::UnblockRequest && owner != nullptr) owner->updateBoostedPriority(); threadControlBlock.setPriorityInheritanceMutexControlBlock(nullptr); } private: /// reference to MutexControlBlock that blocked the thread const MutexControlBlock& mutexControlBlock_; }; } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ MutexControlBlock::MutexControlBlock(const Protocol protocol, const uint8_t priorityCeiling) : blockedList_{scheduler::getScheduler().getThreadControlBlockListAllocator(), scheduler::ThreadControlBlock::State::BlockedOnMutex}, list_{}, iterator_{}, owner_{}, protocol_{protocol}, priorityCeiling_{priorityCeiling} { } int MutexControlBlock::block() { if (protocol_ == Protocol::PriorityInheritance) priorityInheritanceBeforeBlock(); const PriorityInheritanceMutexControlBlockUnblockFunctor unblockFunctor {*this}; return scheduler::getScheduler().block(blockedList_, protocol_ == Protocol::PriorityInheritance ? &unblockFunctor : nullptr); } int MutexControlBlock::blockUntil(const TickClock::time_point timePoint) { if (protocol_ == Protocol::PriorityInheritance) priorityInheritanceBeforeBlock(); const PriorityInheritanceMutexControlBlockUnblockFunctor unblockFunctor {*this}; return scheduler::getScheduler().blockUntil(blockedList_, timePoint, protocol_ == Protocol::PriorityInheritance ? &unblockFunctor : nullptr); } uint8_t MutexControlBlock::getBoostedPriority() const { if (protocol_ == Protocol::PriorityInheritance) { if (blockedList_.empty() == true) return 0; return blockedList_.begin()->get().getEffectivePriority(); } if (protocol_ == Protocol::PriorityProtect) return priorityCeiling_; return 0; } void MutexControlBlock::lock() { auto& scheduler = scheduler::getScheduler(); owner_ = &scheduler.getCurrentThreadControlBlock(); if (protocol_ == Protocol::None) return; scheduler.getMutexControlBlockListAllocatorPool().feed(link_); list_ = &owner_->getOwnedProtocolMutexControlBlocksList(); list_->emplace_front(*this); iterator_ = list_->begin(); if (protocol_ == Protocol::PriorityProtect) owner_->updateBoostedPriority(); } void MutexControlBlock::unlockOrTransferLock() { auto& oldOwner = *owner_; if (blockedList_.empty() == false) transferLock(); else unlock(); if (protocol_ == Protocol::None) return; oldOwner.updateBoostedPriority(); if (owner_ == nullptr) return; owner_->updateBoostedPriority(); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ void MutexControlBlock::priorityInheritanceBeforeBlock() const { auto& currentThreadControlBlock = scheduler::getScheduler().getCurrentThreadControlBlock(); currentThreadControlBlock.setPriorityInheritanceMutexControlBlock(this); // calling thread is not yet on the blocked list, that's why it's effective priority is given explicitly owner_->updateBoostedPriority(currentThreadControlBlock.getEffectivePriority()); } void MutexControlBlock::transferLock() { owner_ = &blockedList_.begin()->get(); // pass ownership to the unblocked thread scheduler::getScheduler().unblock(blockedList_.begin()); if (list_ == nullptr) return; auto& oldList = *list_; list_ = &owner_->getOwnedProtocolMutexControlBlocksList(); list_->splice(list_->begin(), oldList, iterator_); if (protocol_ == Protocol::PriorityInheritance) owner_->setPriorityInheritanceMutexControlBlock(nullptr); } void MutexControlBlock::unlock() { owner_ = nullptr; if (list_ == nullptr) return; list_->erase(iterator_); list_ = nullptr; } } // namespace synchronization } // namespace distortos <commit_msg>MutexControlBlock: minor style improvements<commit_after>/** * \file * \brief MutexControlBlock class implementation * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-10-18 */ #include "distortos/synchronization/MutexControlBlock.hpp" #include "distortos/scheduler/getScheduler.hpp" #include "distortos/scheduler/Scheduler.hpp" #include <cerrno> namespace distortos { namespace synchronization { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local types +---------------------------------------------------------------------------------------------------------------------*/ /// PriorityInheritanceMutexControlBlockUnblockFunctor is a functor executed when unblocking a thread that is blocked on /// a mutex with PriorityInheritance protocol class PriorityInheritanceMutexControlBlockUnblockFunctor : public scheduler::ThreadControlBlock::UnblockFunctor { public: /** * \brief PriorityInheritanceMutexControlBlockUnblockFunctor's constructor * * \param [in] mutexControlBlock is a reference to MutexControlBlock that blocked the thread */ constexpr explicit PriorityInheritanceMutexControlBlockUnblockFunctor(const MutexControlBlock& mutexControlBlock) : mutexControlBlock_{mutexControlBlock} { } /** * \brief PriorityInheritanceMutexControlBlockUnblockFunctor's function call operator * * If the wait for mutex was interrupted, requests update of boosted priority of current owner of the mutex. Pointer * to MutexControlBlock with PriorityInheritance protocol which caused the thread to block is reset to nullptr. * * \param [in] threadControlBlock is a reference to ThreadControlBlock that is being unblocked * \param [in] unblockReason is the reason of thread unblocking */ virtual void operator()(scheduler::ThreadControlBlock& threadControlBlock, const scheduler::ThreadControlBlock::UnblockReason unblockReason) const override { const auto owner = mutexControlBlock_.getOwner(); // waiting for mutex was interrupted and some thread still holds it? if (unblockReason != scheduler::ThreadControlBlock::UnblockReason::UnblockRequest && owner != nullptr) owner->updateBoostedPriority(); threadControlBlock.setPriorityInheritanceMutexControlBlock(nullptr); } private: /// reference to MutexControlBlock that blocked the thread const MutexControlBlock& mutexControlBlock_; }; } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ MutexControlBlock::MutexControlBlock(const Protocol protocol, const uint8_t priorityCeiling) : blockedList_{scheduler::getScheduler().getThreadControlBlockListAllocator(), scheduler::ThreadControlBlock::State::BlockedOnMutex}, list_{}, iterator_{}, owner_{}, protocol_{protocol}, priorityCeiling_{priorityCeiling} { } int MutexControlBlock::block() { if (protocol_ == Protocol::PriorityInheritance) priorityInheritanceBeforeBlock(); const PriorityInheritanceMutexControlBlockUnblockFunctor unblockFunctor {*this}; return scheduler::getScheduler().block(blockedList_, protocol_ == Protocol::PriorityInheritance ? &unblockFunctor : nullptr); } int MutexControlBlock::blockUntil(const TickClock::time_point timePoint) { if (protocol_ == Protocol::PriorityInheritance) priorityInheritanceBeforeBlock(); const PriorityInheritanceMutexControlBlockUnblockFunctor unblockFunctor {*this}; return scheduler::getScheduler().blockUntil(blockedList_, timePoint, protocol_ == Protocol::PriorityInheritance ? &unblockFunctor : nullptr); } uint8_t MutexControlBlock::getBoostedPriority() const { if (protocol_ == Protocol::PriorityInheritance) { if (blockedList_.empty() == true) return 0; return blockedList_.begin()->get().getEffectivePriority(); } if (protocol_ == Protocol::PriorityProtect) return priorityCeiling_; return 0; } void MutexControlBlock::lock() { auto& scheduler = scheduler::getScheduler(); owner_ = &scheduler.getCurrentThreadControlBlock(); if (protocol_ == Protocol::None) return; scheduler.getMutexControlBlockListAllocatorPool().feed(link_); list_ = &owner_->getOwnedProtocolMutexControlBlocksList(); list_->emplace_front(*this); iterator_ = list_->begin(); if (protocol_ == Protocol::PriorityProtect) owner_->updateBoostedPriority(); } void MutexControlBlock::unlockOrTransferLock() { auto& oldOwner = *owner_; if (blockedList_.empty() == false) transferLock(); else unlock(); if (protocol_ == Protocol::None) return; oldOwner.updateBoostedPriority(); if (owner_ == nullptr) return; owner_->updateBoostedPriority(); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ void MutexControlBlock::priorityInheritanceBeforeBlock() const { auto& currentThreadControlBlock = scheduler::getScheduler().getCurrentThreadControlBlock(); currentThreadControlBlock.setPriorityInheritanceMutexControlBlock(this); // calling thread is not yet on the blocked list, that's why it's effective priority is given explicitly owner_->updateBoostedPriority(currentThreadControlBlock.getEffectivePriority()); } void MutexControlBlock::transferLock() { owner_ = &blockedList_.begin()->get(); // pass ownership to the unblocked thread scheduler::getScheduler().unblock(blockedList_.begin()); if (list_ == nullptr) return; auto& oldList = *list_; list_ = &owner_->getOwnedProtocolMutexControlBlocksList(); list_->splice(list_->begin(), oldList, iterator_); if (protocol_ == Protocol::PriorityInheritance) owner_->setPriorityInheritanceMutexControlBlock(nullptr); } void MutexControlBlock::unlock() { owner_ = nullptr; if (list_ == nullptr) return; list_->erase(iterator_); list_ = nullptr; } } // namespace synchronization } // namespace distortos <|endoftext|>
<commit_before>#include "MotionActuator.h" #include <math.h> MotionActuator::MotionActuator(std::string n, MovingSceneObject *s, float newDX, float newDY) : object(s), DX(newDX), DY(newDY), condition("both") { this->name = n; } MotionActuator::MotionActuator(std::string n, MovingSceneObject *s, float newAngle, float newForce, std::string con) : object(s), force(newForce), angle(newAngle), condition(con) { this->name = n; } MotionActuator::MotionActuator(std::string n, MovingSceneObject *s, float newDT, std::string con) : object(s), DT(newDT), condition(con) { this->name = n; } MotionActuator::MotionActuator(std::string name, MovingSceneObject *m, float dis, float speed, SceneObject *o, std::string con) : object(m), condition(con), distance(dis), force(speed), anotherObject(o) { } MotionActuator::MotionActuator(std::string n, MovingSceneObject *o, float s, SceneObject *ao): force(s), anotherObject(ao), object(o), condition("forceTowards") { } MotionActuator::MotionActuator(std::string n, MovingSceneObject *s, SceneObject *ao) : object(s), anotherObject(ao), condition("angleTo") { this->name = n; } MotionActuator::MotionActuator(std::string n, MovingSceneObject *s, std::string con) : object(s), condition(con) { this->name = n; } void MotionActuator::run() { if (condition == "both") { object->setDX(DX); object->setDY(DY); } else if (condition == "x") { object->setDX(DT); } else if (condition == "y") { object->setDY(DT); } else if (condition == "flip") { object->setDX(-object->getDX()); object->setDY(-object->getDY()); } else if (condition == "flipx") { object->setDX(-object->getDX()); } else if (condition == "flipy") { object->setDY(-object->getDY()); } else if (condition == "multiply") { object->setDX(object->getDX() * DT); object->setDY(object->getDY() * DT); } else if (condition == "changeByX") { object->changeXBy(DT); } else if (condition == "changeByY") { object->changeYBy(DT); } else if (condition == "rotate") { object->setRotation(DT); object->setMoveAngle(DT); } else if (condition == "rotateBy") { object->setRotation(object->getRotation() + DT); object->setMoveAngle(object->getMoveAngle() + DT); } else if (condition == "angleTo") { object->setRotation(anotherObject->getRotation()); } else if (condition == "force") { object->addForce(angle, force); } else if (condition == "forceForward") { float degrees = object->getRotation() * float((180/ 3.141592653589793238463) - 180); object->addForce(degrees, force); } else if (condition == "followObject") { object->followObject(anotherObject, distance, force); } else if (condition == "forceTowards") { float degrees = anotherObject->getRotation() * float((180 / 3.141592653589793238463)); object->addForce(degrees + 180, force); } } MotionActuator::~MotionActuator() { } <commit_msg>fixed rotation double conversion bug<commit_after>#include "MotionActuator.h" #include <math.h> MotionActuator::MotionActuator(std::string n, MovingSceneObject *s, float newDX, float newDY) : object(s), DX(newDX), DY(newDY), condition("both") { this->name = n; } MotionActuator::MotionActuator(std::string n, MovingSceneObject *s, float newAngle, float newForce, std::string con) : object(s), force(newForce), angle(newAngle), condition(con) { this->name = n; } MotionActuator::MotionActuator(std::string n, MovingSceneObject *s, float newDT, std::string con) : object(s), DT(newDT), condition(con) { this->name = n; } MotionActuator::MotionActuator(std::string name, MovingSceneObject *m, float dis, float speed, SceneObject *o, std::string con) : object(m), condition(con), distance(dis), force(speed), anotherObject(o) { } MotionActuator::MotionActuator(std::string n, MovingSceneObject *o, float s, SceneObject *ao): force(s), anotherObject(ao), object(o), condition("forceTowards") { } MotionActuator::MotionActuator(std::string n, MovingSceneObject *s, SceneObject *ao) : object(s), anotherObject(ao), condition("angleTo") { this->name = n; } MotionActuator::MotionActuator(std::string n, MovingSceneObject *s, std::string con) : object(s), condition(con) { this->name = n; } void MotionActuator::run() { if (condition == "both") { object->setDX(DX); object->setDY(DY); } else if (condition == "x") { object->setDX(DT); } else if (condition == "y") { object->setDY(DT); } else if (condition == "flip") { object->setDX(-object->getDX()); object->setDY(-object->getDY()); } else if (condition == "flipx") { object->setDX(-object->getDX()); } else if (condition == "flipy") { object->setDY(-object->getDY()); } else if (condition == "multiply") { object->setDX(object->getDX() * DT); object->setDY(object->getDY() * DT); } else if (condition == "changeByX") { object->changeXBy(DT); } else if (condition == "changeByY") { object->changeYBy(DT); } else if (condition == "rotate") { object->setRotation(DT); object->setMoveAngle(DT); } else if (condition == "rotateBy") { object->setRotation(object->getRotation() + DT); object->setMoveAngle(object->getMoveAngle() + DT); } else if (condition == "angleTo") { object->setRotation(anotherObject->getRotation()); } else if (condition == "force") { object->addForce(angle, force); } else if (condition == "forceForward") { double degrees = object->getRotation() * (180 / 3.141592653589793238463) - 180; object->addForce(float(degrees), force); } else if (condition == "followObject") { object->followObject(anotherObject, distance, force); } else if (condition == "forceTowards") { float degrees = anotherObject->getRotation() * float((180 / 3.141592653589793238463)); object->addForce(degrees + 180, force); } } MotionActuator::~MotionActuator() { } <|endoftext|>
<commit_before>// // Copyright (C) 2006-2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <assert.h> // APPLICATION INCLUDES #include <mp/MpMediaTask.h> #include <mp/MpRtpInputAudioConnection.h> #include <mp/MpFlowGraphBase.h> #include <mp/MprFromNet.h> #include <mp/MprDejitter.h> #include <mp/MpJitterBuffer.h> #include <mp/MprDecode.h> #include <mp/MpResourceMsg.h> #include <mp/MprRtpStartReceiveMsg.h> #include <sdp/SdpCodec.h> #include <os/OsLock.h> #ifdef RTL_ENABLED # include <rtl_macro.h> #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MpRtpInputAudioConnection::MpRtpInputAudioConnection(const UtlString& resourceName, MpConnectionID myID, int samplesPerFrame, int samplesPerSec) : MpRtpInputConnection(resourceName, myID, #ifdef INCLUDE_RTCP // [ NULL // TODO: pParent->getRTCPSessionPtr() #else // INCLUDE_RTCP ][ NULL #endif // INCLUDE_RTCP ] ) , mpDecode(NULL) { char name[50]; int i; sprintf(name, "Decode-%d", myID); mpDecode = new MprDecode(name, this, samplesPerFrame, samplesPerSec); //memset((char*)mpPayloadMap, 0, (NUM_PAYLOAD_TYPES*sizeof(MpDecoderBase*))); for (i=0; i<NUM_PAYLOAD_TYPES; i++) { mpPayloadMap[i] = NULL; } // decoder does not get added to the flowgraph, this connection // gets added to do the decoding frameprocessing. ////////////////////////////////////////////////////////////////////////// // connect Dejitter -> Decode (Non synchronous resources) mpDecode->setMyDejitter(mpDejitter); // This got moved to the call flowgraph when the connection is // added to the flowgraph. Not sure it is still needed there either //pParent->synchronize("new Connection, before enable(), %dx%X\n"); //enable(); //pParent->synchronize("new Connection, after enable(), %dx%X\n"); } // Destructor MpRtpInputAudioConnection::~MpRtpInputAudioConnection() { delete mpDecode; } /* ============================ MANIPULATORS ============================== */ UtlBoolean MpRtpInputAudioConnection::processFrame(void) { UtlBoolean result; #ifdef RTL_ENABLED RTL_BLOCK((UtlString)*this); #endif assert(mpDecode); if(mpDecode) { // call doProcessFrame to do any "real" work result = mpDecode->doProcessFrame(mpInBufs, mpOutBufs, mMaxInputs, mMaxOutputs, mpDecode->mIsEnabled, mpDecode->getSamplesPerFrame(), mpDecode->getSamplesPerSec()); } // No input buffers to release assert(mMaxInputs == 0); // Push the output buffer to the next resource assert(mMaxOutputs == 1); pushBufferDownsream(0, mpOutBufs[0]); // release the output buffer mpOutBufs[0].release(); return(result); } // Start receiving RTP and RTCP packets. OsStatus MpRtpInputAudioConnection::startReceiveRtp(OsMsgQ& messageQueue, const UtlString& resourceName, SdpCodec* codecArray[], int numCodecs, OsSocket& rRtpSocket, OsSocket& rRtcpSocket) { OsStatus result = OS_INVALID_ARGUMENT; if(numCodecs > 0 && codecArray) { // Create a message to contain the startRecieveRtp data MprRtpStartReceiveMsg msg(resourceName, codecArray, numCodecs, rRtpSocket, rRtcpSocket); // Send the message in the queue. result = messageQueue.send(msg); } return(result); } OsStatus MpRtpInputAudioConnection::stopReceiveRtp(OsMsgQ& messageQueue, const UtlString& resourceName) { MpResourceMsg stopReceiveMsg(MpResourceMsg::MPRM_STOP_RECEIVE_RTP, resourceName); // Send the message in the queue. OsStatus result = messageQueue.send(stopReceiveMsg); return(result); } void MpRtpInputAudioConnection::addPayloadType(int payloadType, MpDecoderBase* decoder) { OsLock lock(mLock); // Check that payloadType is valid. if ((payloadType < 0) || (payloadType >= NUM_PAYLOAD_TYPES)) { OsSysLog::add(FAC_MP, PRI_ERR, "MpRtpInputAudioConnection::addPayloadType Attempting to add an invalid payload type %d", payloadType); } // Check to see if we already have a decoder for this payload type. else if (!(NULL == mpPayloadMap[payloadType])) { // This condition probably indicates that the sender of SDP specified // two decoders for the same payload type number. OsSysLog::add(FAC_MP, PRI_ERR, "MpRtpInputAudioConnection::addPayloadType Attempting to add a second decoder for payload type %d", payloadType); } else { mpPayloadMap[payloadType] = decoder; } } void MpRtpInputAudioConnection::deletePayloadType(int payloadType) { OsLock lock(mLock); // Check that payloadType is valid. if ((payloadType < 0) || (payloadType >= NUM_PAYLOAD_TYPES)) { OsSysLog::add(FAC_MP, PRI_ERR, "MpRtpInputAudioConnection::deletePayloadType Attempting to delete an invalid payload type %d", payloadType); } // Check to see if this entry has already been deleted. else if (NULL == mpPayloadMap[payloadType]) { // Either this payload type was doubly-added (and reported by // addPayloadType) or we've hit the race condtion in XMR-29. OsSysLog::add(FAC_MP, PRI_ERR, "MpRtpInputAudioConnection::deletePayloadType Attempting to delete again payload type %d", payloadType); OsSysLog::add(FAC_MP, PRI_ERR, "MpRtpInputAudioConnection::deletePayloadType If there is no message from MpRtpInputAudioConnection::addPayloadType above, see XMR-29"); } else { mpPayloadMap[payloadType] = NULL; } } UtlBoolean MpRtpInputAudioConnection::handleSetDtmfNotify(OsNotification* pNotify) { return mpDecode->handleSetDtmfNotify(pNotify); } /* ============================ ACCESSORS ================================= */ MpDecoderBase* MpRtpInputAudioConnection::mapPayloadType(int payloadType) { OsLock lock(mLock); if ((payloadType < 0) || (payloadType >= NUM_PAYLOAD_TYPES)) { OsSysLog::add(FAC_MP, PRI_ERR, "MpRtpInputAudioConnection::mapPayloadType Attempting to map an invalid payload type %d", payloadType); return NULL; } else { return mpPayloadMap[payloadType]; } } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ UtlBoolean MpRtpInputAudioConnection::handleMessage(MpResourceMsg& rMsg) { UtlBoolean result = FALSE; unsigned char messageSubtype = rMsg.getMsgSubType(); switch(messageSubtype) { case MpResourceMsg::MPRM_START_RECEIVE_RTP: { MprRtpStartReceiveMsg* startMessage = (MprRtpStartReceiveMsg*) &rMsg; SdpCodec** codecArray = NULL; int numCodecs; startMessage->getCodecArray(numCodecs, codecArray); OsSocket* rtpSocket = startMessage->getRtpSocket(); OsSocket* rtcpSocket = startMessage->getRtcpSocket(); handleStartReceiveRtp(codecArray, numCodecs, *rtpSocket, *rtcpSocket); result = TRUE; } break; case MpResourceMsg::MPRM_STOP_RECEIVE_RTP: handleStopReceiveRtp(); result = TRUE; break; default: result = MpResource::handleMessage(rMsg); break; } return(result); } // Enables the input path of the connection. UtlBoolean MpRtpInputAudioConnection::handleEnable() { mpDecode->enable(); return(MpResource::handleEnable()); } // Disables the input path of the connection. UtlBoolean MpRtpInputAudioConnection::handleDisable() { mpDecode->disable(); return(MpResource::handleDisable()); } void MpRtpInputAudioConnection::handleStartReceiveRtp(SdpCodec* pCodecs[], int numCodecs, OsSocket& rRtpSocket, OsSocket& rRtcpSocket) { if (numCodecs) { mpDecode->selectCodecs(pCodecs, numCodecs); } // No need to synchronize as the decoder is not part of the // flowgraph. It is part of this connection/resource //mpFlowGraph->synchronize(); prepareStartReceiveRtp(rRtpSocket, rRtcpSocket); // No need to synchronize as the decoder is not part of the // flowgraph. It is part of this connection/resource //mpFlowGraph->synchronize(); if (numCodecs) { mpDecode->enable(); } } // Stop receiving RTP and RTCP packets. void MpRtpInputAudioConnection::handleStopReceiveRtp() { prepareStopReceiveRtp(); // No need to synchronize as the decoder is not part of the // flowgraph. It is part of this connection/resource //mpFlowGraph->synchronize(); mpDecode->deselectCodec(); // No need to synchronize as the decoder is not part of the // flowgraph. It is part of this connection/resource //mpFlowGraph->synchronize(); mpDecode->disable(); } OsStatus MpRtpInputAudioConnection::setFlowGraph(MpFlowGraphBase* pFlowGraph) { OsStatus stat = MpResource::setFlowGraph(pFlowGraph); // If the parent's call was successful, then call // setFlowGraph on any child resources we have. if(stat == OS_SUCCESS) { stat = mpDecode->setFlowGraph(pFlowGraph); } return stat; } OsStatus MpRtpInputAudioConnection::setNotificationsEnabled(UtlBoolean enable) { OsStatus stat = MpResource::setNotificationsEnabled(enable); // If the parent's call was successful, then call // setAllNotificationsEnabled on any child resources we have. if(stat == OS_SUCCESS) { stat = mpDecode->setNotificationsEnabled(enable); } return stat; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <commit_msg>Add RTL audio debug to MpRtpInputAudioConnection - it use home-brew processFrame() and fall out of RTL debug hooked into MpAudioResource::processFrame().<commit_after>// // Copyright (C) 2006-2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <assert.h> // APPLICATION INCLUDES #include <mp/MpMediaTask.h> #include <mp/MpRtpInputAudioConnection.h> #include <mp/MpFlowGraphBase.h> #include <mp/MprFromNet.h> #include <mp/MprDejitter.h> #include <mp/MpJitterBuffer.h> #include <mp/MprDecode.h> #include <mp/MpResourceMsg.h> #include <mp/MprRtpStartReceiveMsg.h> #include <sdp/SdpCodec.h> #include <os/OsLock.h> #ifdef RTL_ENABLED # include <rtl_macro.h> # ifdef RTL_AUDIO_ENABLED # include <SeScopeAudioBuffer.h> # endif #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MpRtpInputAudioConnection::MpRtpInputAudioConnection(const UtlString& resourceName, MpConnectionID myID, int samplesPerFrame, int samplesPerSec) : MpRtpInputConnection(resourceName, myID, #ifdef INCLUDE_RTCP // [ NULL // TODO: pParent->getRTCPSessionPtr() #else // INCLUDE_RTCP ][ NULL #endif // INCLUDE_RTCP ] ) , mpDecode(NULL) { char name[50]; int i; sprintf(name, "Decode-%d", myID); mpDecode = new MprDecode(name, this, samplesPerFrame, samplesPerSec); //memset((char*)mpPayloadMap, 0, (NUM_PAYLOAD_TYPES*sizeof(MpDecoderBase*))); for (i=0; i<NUM_PAYLOAD_TYPES; i++) { mpPayloadMap[i] = NULL; } // decoder does not get added to the flowgraph, this connection // gets added to do the decoding frameprocessing. ////////////////////////////////////////////////////////////////////////// // connect Dejitter -> Decode (Non synchronous resources) mpDecode->setMyDejitter(mpDejitter); // This got moved to the call flowgraph when the connection is // added to the flowgraph. Not sure it is still needed there either //pParent->synchronize("new Connection, before enable(), %dx%X\n"); //enable(); //pParent->synchronize("new Connection, after enable(), %dx%X\n"); } // Destructor MpRtpInputAudioConnection::~MpRtpInputAudioConnection() { delete mpDecode; } /* ============================ MANIPULATORS ============================== */ UtlBoolean MpRtpInputAudioConnection::processFrame(void) { UtlBoolean result; #ifdef RTL_ENABLED RTL_BLOCK((UtlString)*this); #endif assert(mpDecode); if(mpDecode) { // call doProcessFrame to do any "real" work result = mpDecode->doProcessFrame(mpInBufs, mpOutBufs, mMaxInputs, mMaxOutputs, mpDecode->mIsEnabled, mpDecode->getSamplesPerFrame(), mpDecode->getSamplesPerSec()); } // No input buffers to release assert(mMaxInputs == 0); #ifdef RTL_AUDIO_ENABLED int frameIndex = mpFlowGraph ? mpFlowGraph->numFramesProcessed() : 0; // If there is a consumer of the output if(mpOutConns[0].pResource) { UtlString outputLabel(*this); outputLabel.append("_output_0_"); outputLabel.append(*mpOutConns[0].pResource); RTL_AUDIO_BUFFER(outputLabel, 8000, ((MpAudioBufPtr) mpOutBufs[0]), frameIndex); } #endif // Push the output buffer to the next resource assert(mMaxOutputs == 1); pushBufferDownsream(0, mpOutBufs[0]); // release the output buffer mpOutBufs[0].release(); return(result); } // Start receiving RTP and RTCP packets. OsStatus MpRtpInputAudioConnection::startReceiveRtp(OsMsgQ& messageQueue, const UtlString& resourceName, SdpCodec* codecArray[], int numCodecs, OsSocket& rRtpSocket, OsSocket& rRtcpSocket) { OsStatus result = OS_INVALID_ARGUMENT; if(numCodecs > 0 && codecArray) { // Create a message to contain the startRecieveRtp data MprRtpStartReceiveMsg msg(resourceName, codecArray, numCodecs, rRtpSocket, rRtcpSocket); // Send the message in the queue. result = messageQueue.send(msg); } return(result); } OsStatus MpRtpInputAudioConnection::stopReceiveRtp(OsMsgQ& messageQueue, const UtlString& resourceName) { MpResourceMsg stopReceiveMsg(MpResourceMsg::MPRM_STOP_RECEIVE_RTP, resourceName); // Send the message in the queue. OsStatus result = messageQueue.send(stopReceiveMsg); return(result); } void MpRtpInputAudioConnection::addPayloadType(int payloadType, MpDecoderBase* decoder) { OsLock lock(mLock); // Check that payloadType is valid. if ((payloadType < 0) || (payloadType >= NUM_PAYLOAD_TYPES)) { OsSysLog::add(FAC_MP, PRI_ERR, "MpRtpInputAudioConnection::addPayloadType Attempting to add an invalid payload type %d", payloadType); } // Check to see if we already have a decoder for this payload type. else if (!(NULL == mpPayloadMap[payloadType])) { // This condition probably indicates that the sender of SDP specified // two decoders for the same payload type number. OsSysLog::add(FAC_MP, PRI_ERR, "MpRtpInputAudioConnection::addPayloadType Attempting to add a second decoder for payload type %d", payloadType); } else { mpPayloadMap[payloadType] = decoder; } } void MpRtpInputAudioConnection::deletePayloadType(int payloadType) { OsLock lock(mLock); // Check that payloadType is valid. if ((payloadType < 0) || (payloadType >= NUM_PAYLOAD_TYPES)) { OsSysLog::add(FAC_MP, PRI_ERR, "MpRtpInputAudioConnection::deletePayloadType Attempting to delete an invalid payload type %d", payloadType); } // Check to see if this entry has already been deleted. else if (NULL == mpPayloadMap[payloadType]) { // Either this payload type was doubly-added (and reported by // addPayloadType) or we've hit the race condtion in XMR-29. OsSysLog::add(FAC_MP, PRI_ERR, "MpRtpInputAudioConnection::deletePayloadType Attempting to delete again payload type %d", payloadType); OsSysLog::add(FAC_MP, PRI_ERR, "MpRtpInputAudioConnection::deletePayloadType If there is no message from MpRtpInputAudioConnection::addPayloadType above, see XMR-29"); } else { mpPayloadMap[payloadType] = NULL; } } UtlBoolean MpRtpInputAudioConnection::handleSetDtmfNotify(OsNotification* pNotify) { return mpDecode->handleSetDtmfNotify(pNotify); } /* ============================ ACCESSORS ================================= */ MpDecoderBase* MpRtpInputAudioConnection::mapPayloadType(int payloadType) { OsLock lock(mLock); if ((payloadType < 0) || (payloadType >= NUM_PAYLOAD_TYPES)) { OsSysLog::add(FAC_MP, PRI_ERR, "MpRtpInputAudioConnection::mapPayloadType Attempting to map an invalid payload type %d", payloadType); return NULL; } else { return mpPayloadMap[payloadType]; } } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ UtlBoolean MpRtpInputAudioConnection::handleMessage(MpResourceMsg& rMsg) { UtlBoolean result = FALSE; unsigned char messageSubtype = rMsg.getMsgSubType(); switch(messageSubtype) { case MpResourceMsg::MPRM_START_RECEIVE_RTP: { MprRtpStartReceiveMsg* startMessage = (MprRtpStartReceiveMsg*) &rMsg; SdpCodec** codecArray = NULL; int numCodecs; startMessage->getCodecArray(numCodecs, codecArray); OsSocket* rtpSocket = startMessage->getRtpSocket(); OsSocket* rtcpSocket = startMessage->getRtcpSocket(); handleStartReceiveRtp(codecArray, numCodecs, *rtpSocket, *rtcpSocket); result = TRUE; } break; case MpResourceMsg::MPRM_STOP_RECEIVE_RTP: handleStopReceiveRtp(); result = TRUE; break; default: result = MpResource::handleMessage(rMsg); break; } return(result); } // Enables the input path of the connection. UtlBoolean MpRtpInputAudioConnection::handleEnable() { mpDecode->enable(); return(MpResource::handleEnable()); } // Disables the input path of the connection. UtlBoolean MpRtpInputAudioConnection::handleDisable() { mpDecode->disable(); return(MpResource::handleDisable()); } void MpRtpInputAudioConnection::handleStartReceiveRtp(SdpCodec* pCodecs[], int numCodecs, OsSocket& rRtpSocket, OsSocket& rRtcpSocket) { if (numCodecs) { mpDecode->selectCodecs(pCodecs, numCodecs); } // No need to synchronize as the decoder is not part of the // flowgraph. It is part of this connection/resource //mpFlowGraph->synchronize(); prepareStartReceiveRtp(rRtpSocket, rRtcpSocket); // No need to synchronize as the decoder is not part of the // flowgraph. It is part of this connection/resource //mpFlowGraph->synchronize(); if (numCodecs) { mpDecode->enable(); } } // Stop receiving RTP and RTCP packets. void MpRtpInputAudioConnection::handleStopReceiveRtp() { prepareStopReceiveRtp(); // No need to synchronize as the decoder is not part of the // flowgraph. It is part of this connection/resource //mpFlowGraph->synchronize(); mpDecode->deselectCodec(); // No need to synchronize as the decoder is not part of the // flowgraph. It is part of this connection/resource //mpFlowGraph->synchronize(); mpDecode->disable(); } OsStatus MpRtpInputAudioConnection::setFlowGraph(MpFlowGraphBase* pFlowGraph) { OsStatus stat = MpResource::setFlowGraph(pFlowGraph); // If the parent's call was successful, then call // setFlowGraph on any child resources we have. if(stat == OS_SUCCESS) { stat = mpDecode->setFlowGraph(pFlowGraph); } return stat; } OsStatus MpRtpInputAudioConnection::setNotificationsEnabled(UtlBoolean enable) { OsStatus stat = MpResource::setNotificationsEnabled(enable); // If the parent's call was successful, then call // setAllNotificationsEnabled on any child resources we have. if(stat == OS_SUCCESS) { stat = mpDecode->setNotificationsEnabled(enable); } return stat; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <|endoftext|>
<commit_before>#include "codecvt_specializations.h" #include "codecvt_utf8.h" #include <cxxabi.h> #include <cstring> #include <cassert> #include <algorithm> #include <memory> #include <limits> #include <typeinfo> struct multistring { multistring(const char * _ns, const wchar_t * _ws, const char16_t * _s16, const char32_t * _s32) : ns(_ns), ws(_ws), s16(_s16), s32(_s32) { } template <typename T> const std::basic_string<T> & get() const; std::string ns; std::wstring ws; std::u16string s16; std::u32string s32; }; class u16cvt : public std::codecvt<char16_t, char, std::mbstate_t> { public: using codecvt<char16_t, char, std::mbstate_t>::codecvt; virtual ~u16cvt() { }; }; class u32cvt : public std::codecvt<char32_t, char, std::mbstate_t> { public: using codecvt<char32_t, char, std::mbstate_t>::codecvt; virtual ~u32cvt() { }; }; #define FULL_RANGE "z\u5916\u56FD\u8A9E\u306E\u5B66\u7FD2\u3068" \ "\u6559\u6388\U0001f0df \U0010FFFF" #define TRIPLE_CAT_(a_, b_, c_) a_ ## b_ ## c_ #define TRIPLE_CAT(a_, b_, c_) TRIPLE_CAT_(a_, b_, c_) #define NARROW(s_) TRIPLE_CAT(, s_, ) #define WIDE(s_) TRIPLE_CAT(L, s_, ) #define UTF8(s_) TRIPLE_CAT(u8, s_, ) #define UTF16(s_) TRIPLE_CAT(u, s_, ) #define UTF32(s_) TRIPLE_CAT(U, s_, ) #define DEF_MULTISTRING(name, literalval) \ multistring name(NARROW(literalval), WIDE(literalval), \ UTF16(literalval), UTF32(literalval)) DEF_MULTISTRING(multi, FULL_RANGE); template<> const std::basic_string<char> & multistring::get<char>() const { return ns; } template<> const std::basic_string<wchar_t> & multistring::get<wchar_t>() const { return ws; } template<> const std::basic_string<char16_t> & multistring::get<char16_t>() const { return s16; } template<> const std::basic_string<char32_t> & multistring::get<char32_t>() const { return s32; } const char * code2str(std::codecvt_base::result r) { switch (r) { case std::codecvt_base::ok: return "ok"; case std::codecvt_base::error: return "error"; case std::codecvt_base::partial: return "partial"; case std::codecvt_base::noconv: return "noconv"; } return nullptr; } void checku16() { u16cvt cvt; char buffer[64]; const char16_t * from_end = nullptr; char * to_end = nullptr; memset(buffer, 0, 64); for (auto c : multi.get<char32_t>()) { printf("%08x ", c); } putchar('\n'); printf("s32 size = %zu\n", multi.get<char32_t>().length()); for (auto c : multi.get<char16_t>()) { printf("%04x ", c); } putchar('\n'); printf("s16 size = %zu\n", multi.get<char16_t>().length()); for (auto c : multi.get<char>()) { printf("%02hhx ", c); } putchar('\n'); printf("s8 size = %zu\n", multi.get<char>().length()); std::mbstate_t s = std::mbstate_t(); auto r = cvt.out(s, multi.get<char16_t>().data(), multi.get<char16_t>().data() + multi.get<char16_t>().size(), from_end, buffer, buffer + 64, to_end); printf("Conversion yielded '%s'\n", code2str(r)); for (char * p = buffer; p != to_end; ++p) { printf("%02hhx ", *p); } putchar('\n'); printf("literal(right) = %s\n", multi.get<char>().c_str()); printf("literal(decode) = %s\n", buffer); s = std::mbstate_t(); assert(cvt.length(s, multi.get<char>().data(), multi.get<char>().data() + multi.get<char>().length(), multi.get<char16_t>().length()) == static_cast<int>(multi.get<char>().length())); char16_t buffer16[40]; memset(buffer16, 0, sizeof(buffer16)); const char * cto_end = nullptr; char16_t * end16; s = std::mbstate_t(); r = cvt.in(s,multi.get<char>().data(), multi.get<char>().data() + multi.get<char>().size(), cto_end, buffer16, buffer16 + 40, end16); printf("-> in returned %s\n", code2str(r)); assert(r == std::codecvt_base::ok); assert(static_cast<size_t>(end16 - buffer16) == multi.get<char16_t>().length()); assert(!memcmp(buffer16, multi.get<char16_t>().data(), end16 - buffer16)); } const char * mode2str(std::codecvt_mode m) { switch (static_cast<int>(m)) { case 0: return "none"; case 1: return "little_endian"; case 2: return "generate_header"; case 3: return "generate_header|little_endian"; case 4: return "consume_header"; case 5: return "consume_header|little_endian"; case 6: return "consume_header|generate_header"; case 7: return "consume_header|generate_header|little_endian"; } return "unknown"; } std::string demangle(const char * s) { std::string ret; int status = 0; char * val = abi::__cxa_demangle(s, 0, 0, &status); if (val != nullptr) { ret = val; free(val); } return ret; } namespace bug { template <class T> constexpr const T & min(const T & a, const T & b) { return (a < b) ? a : b; } } static const std::string sep(80, '-'); template <typename T, unsigned long MAX, std::codecvt_mode MODE> void check_codecvt_utf8() { std::codecvt_utf8<T, MAX, MODE> cvt; std::string type_name = demangle(typeid(T).name()); printf("%s\ncodecvt_utf8<%s, 0x%lx, %s>\n%s\n", sep.c_str(), type_name.c_str(), MAX, mode2str(MODE), sep.c_str()); printf("always_noconv() = %s\n", cvt.always_noconv() ? "true" : "false"); assert(!cvt.always_noconv()); printf("encoding() = %d\n", cvt.encoding()); assert(cvt.encoding() == 0); printf("max_length() = %d\n", cvt.max_length()); bool expect_error = false; for (auto c : multi.get<char32_t>()) { if (c > MAX) expect_error = true; } for (auto c : multi.get<char16_t>()) { if (utf16_conversion::is_surrogate(c)) expect_error = true; } std::codecvt_base::result res; auto state = std::mbstate_t(); const T * begin = multi.get<T>().data(); const T * end = multi.get<T>().data() + multi.get<T>().size() + 1; const T * last = nullptr; const size_t bufsize = 256; char buffer_out[bufsize]; char * last_out; memset(buffer_out, 0, bufsize); res = cvt.out(state, begin, end, last, buffer_out, buffer_out + bufsize, last_out); printf("out() conversion returned '%s' after writing %ld bytes\n", code2str(res), last_out - buffer_out); if (res == std::codecvt_base::ok) { std::string out_string(buffer_out); std::string reference = (MODE & std::generate_header) ? "\xef\xbb\xbf" : ""; reference += multi.get<char>(); if (out_string != reference) { for (size_t x = 0; x < out_string.length() && x < reference.length(); ++x) { printf("%02hhx %02hhx\n", out_string.at(x), reference.at(x)); } } assert(out_string == reference); } assert(expect_error || res == std::codecvt_base::ok); } template <typename T, std::codecvt_mode MODE> void check_all_enums() { constexpr unsigned long max = bug::min<unsigned long>(0x7ffffffful, std::numeric_limits<T>::max()); check_codecvt_utf8<T, 0xff, MODE>(); check_codecvt_utf8<T, 0xffff, MODE>(); check_codecvt_utf8<T, 0x10ffff, MODE>(); check_codecvt_utf8<T, max, MODE>(); } template <typename T> void check_all() { check_all_enums<T, std::codecvt_mode(0)>(); check_all_enums<T, std::codecvt_mode(1)>(); check_all_enums<T, std::codecvt_mode(2)>(); check_all_enums<T, std::codecvt_mode(3)>(); check_all_enums<T, std::codecvt_mode(4)>(); check_all_enums<T, std::codecvt_mode(5)>(); check_all_enums<T, std::codecvt_mode(6)>(); check_all_enums<T, std::codecvt_mode(7)>(); } int main() { u32cvt cvt; const char32_t * doneptr = nullptr;; char outbuf[64]; char * end = outbuf + 64, * ptr2 = nullptr; auto state = std::mbstate_t(); for (char32_t i = 0; i < 0x10ffff; ++i) { auto res = cvt.out(state, &i, (&i) + 1, doneptr, outbuf, end, ptr2); // if ((i % 0x10000) == 0 || ((i < 0x10000) && ((i % 0x100) == 0))) // printf("processing mega-plane 0x%08x, current len = %ld\n", // i, ptr2 - outbuf); assert(res == std::codecvt_base::ok); int length = ptr2 - outbuf; state = std::mbstate_t(); int l2 = cvt.length(state, outbuf, ptr2, 20); assert(length == l2); char32_t redecoded = 0, * lastptr = nullptr; const char * ptr1 = nullptr; state = std::mbstate_t(); res = cvt.in(state, outbuf, outbuf + length, ptr1, &redecoded, (&redecoded) + 1, lastptr); assert(res == std::codecvt_base::ok); assert(i == redecoded); } checku16(); check_all<wchar_t>(); check_all<char16_t>(); check_all<char32_t>(); } <commit_msg>codecvt_utf8::length completed<commit_after>#include "codecvt_specializations.h" #include "codecvt_utf8.h" #include <cxxabi.h> #include <cstring> #include <cassert> #include <algorithm> #include <memory> #include <limits> #include <typeinfo> struct multistring { multistring(const char * _ns, const wchar_t * _ws, const char16_t * _s16, const char32_t * _s32) : ns(_ns), ws(_ws), s16(_s16), s32(_s32) { } template <typename T> const std::basic_string<T> & get() const; std::string ns; std::wstring ws; std::u16string s16; std::u32string s32; }; class u16cvt : public std::codecvt<char16_t, char, std::mbstate_t> { public: using codecvt<char16_t, char, std::mbstate_t>::codecvt; virtual ~u16cvt() { }; }; class u32cvt : public std::codecvt<char32_t, char, std::mbstate_t> { public: using codecvt<char32_t, char, std::mbstate_t>::codecvt; virtual ~u32cvt() { }; }; #define FULL_RANGE "z\u5916\u56FD\u8A9E\u306E\u5B66\u7FD2\u3068" \ "\u6559\u6388\U0001f0df \U0010FFFF" #define TRIPLE_CAT_(a_, b_, c_) a_ ## b_ ## c_ #define TRIPLE_CAT(a_, b_, c_) TRIPLE_CAT_(a_, b_, c_) #define NARROW(s_) TRIPLE_CAT(, s_, ) #define WIDE(s_) TRIPLE_CAT(L, s_, ) #define UTF8(s_) TRIPLE_CAT(u8, s_, ) #define UTF16(s_) TRIPLE_CAT(u, s_, ) #define UTF32(s_) TRIPLE_CAT(U, s_, ) #define DEF_MULTISTRING(name, literalval) \ multistring name(NARROW(literalval), WIDE(literalval), \ UTF16(literalval), UTF32(literalval)) DEF_MULTISTRING(multi, FULL_RANGE); template<> const std::basic_string<char> & multistring::get<char>() const { return ns; } template<> const std::basic_string<wchar_t> & multistring::get<wchar_t>() const { return ws; } template<> const std::basic_string<char16_t> & multistring::get<char16_t>() const { return s16; } template<> const std::basic_string<char32_t> & multistring::get<char32_t>() const { return s32; } const char * code2str(std::codecvt_base::result r) { switch (r) { case std::codecvt_base::ok: return "ok"; case std::codecvt_base::error: return "error"; case std::codecvt_base::partial: return "partial"; case std::codecvt_base::noconv: return "noconv"; } return nullptr; } void checku16() { u16cvt cvt; char buffer[64]; const char16_t * from_end = nullptr; char * to_end = nullptr; memset(buffer, 0, 64); for (auto c : multi.get<char32_t>()) { printf("%08x ", c); } putchar('\n'); printf("s32 size = %zu\n", multi.get<char32_t>().length()); for (auto c : multi.get<char16_t>()) { printf("%04x ", c); } putchar('\n'); printf("s16 size = %zu\n", multi.get<char16_t>().length()); for (auto c : multi.get<char>()) { printf("%02hhx ", c); } putchar('\n'); printf("s8 size = %zu\n", multi.get<char>().length()); std::mbstate_t s = std::mbstate_t(); auto r = cvt.out(s, multi.get<char16_t>().data(), multi.get<char16_t>().data() + multi.get<char16_t>().size(), from_end, buffer, buffer + 64, to_end); printf("Conversion yielded '%s'\n", code2str(r)); for (char * p = buffer; p != to_end; ++p) { printf("%02hhx ", *p); } putchar('\n'); printf("literal(right) = %s\n", multi.get<char>().c_str()); printf("literal(decode) = %s\n", buffer); s = std::mbstate_t(); assert(cvt.length(s, multi.get<char>().data(), multi.get<char>().data() + multi.get<char>().length(), multi.get<char16_t>().length()) == static_cast<int>(multi.get<char>().length())); char16_t buffer16[40]; memset(buffer16, 0, sizeof(buffer16)); const char * cto_end = nullptr; char16_t * end16; s = std::mbstate_t(); r = cvt.in(s,multi.get<char>().data(), multi.get<char>().data() + multi.get<char>().size(), cto_end, buffer16, buffer16 + 40, end16); printf("-> in returned %s\n", code2str(r)); assert(r == std::codecvt_base::ok); assert(static_cast<size_t>(end16 - buffer16) == multi.get<char16_t>().length()); assert(!memcmp(buffer16, multi.get<char16_t>().data(), end16 - buffer16)); } const char * mode2str(std::codecvt_mode m) { switch (static_cast<int>(m)) { case 0: return "none"; case 1: return "little_endian"; case 2: return "generate_header"; case 3: return "generate_header|little_endian"; case 4: return "consume_header"; case 5: return "consume_header|little_endian"; case 6: return "consume_header|generate_header"; case 7: return "consume_header|generate_header|little_endian"; } return "unknown"; } std::string demangle(const char * s) { std::string ret; int status = 0; char * val = abi::__cxa_demangle(s, 0, 0, &status); if (val != nullptr) { ret = val; free(val); } return ret; } namespace bug { template <class T> constexpr const T & min(const T & a, const T & b) { return (a < b) ? a : b; } } static const std::string sep(80, '-'); template <typename T, unsigned long MAX, std::codecvt_mode MODE> void check_codecvt_utf8() { std::codecvt_utf8<T, MAX, MODE> cvt; std::string type_name = demangle(typeid(T).name()); printf("%s\ncodecvt_utf8<%s, 0x%lx, %s>\n%s\n", sep.c_str(), type_name.c_str(), MAX, mode2str(MODE), sep.c_str()); printf("always_noconv() = %s\n", cvt.always_noconv() ? "true" : "false"); assert(!cvt.always_noconv()); printf("encoding() = %d\n", cvt.encoding()); assert(cvt.encoding() == 0); printf("max_length() = %d\n", cvt.max_length()); bool expect_error = false; for (auto c : multi.get<char32_t>()) { if (c > MAX) expect_error = true; } for (auto c : multi.get<char16_t>()) { if (utf16_conversion::is_surrogate(c)) expect_error = true; } std::codecvt_base::result res; auto state = std::mbstate_t(); const T * begin = multi.get<T>().data(); const T * end = multi.get<T>().data() + multi.get<T>().size(); const T * last = nullptr; const size_t bufsize = 256; char buffer_out[bufsize]; char * last_out; memset(buffer_out, 0, bufsize); res = cvt.out(state, begin, end, last, buffer_out, buffer_out + bufsize, last_out); printf("out() conversion returned '%s' after writing %ld bytes\n", code2str(res), last_out - buffer_out); if (res == std::codecvt_base::ok) { std::string out_string(buffer_out, last_out - buffer_out); std::string reference = (MODE & std::generate_header) ? "\xef\xbb\xbf" : ""; reference += multi.get<char>(); if (out_string != reference) { for (size_t x = 0; x < out_string.length() && x < reference.length(); ++x) { printf("%zu: %02hhx %02hhx\n", x, out_string.at(x), reference.at(x)); } } assert(out_string == reference); state = std::mbstate_t(); const char * length_start = out_string.data(); const char * length_end = out_string.data() + out_string.length(); if ( ((MODE & std::generate_header) == std::generate_header) && ((MODE & std::consume_header) == 0)) { printf("----> SKIPPING BOM\n"); length_start += 3; } int count = cvt.length(state, length_start, length_end, multi.get<T>().length()); printf("length(max=%zd) returned %d bytes\n", multi.get<T>().length(), count); assert(count == (length_end - length_start)); } assert(expect_error || res == std::codecvt_base::ok); } template <typename T, std::codecvt_mode MODE> void check_all_enums() { constexpr unsigned long max = bug::min<unsigned long>(0x7ffffffful, std::numeric_limits<T>::max()); check_codecvt_utf8<T, 0xff, MODE>(); check_codecvt_utf8<T, 0xffff, MODE>(); check_codecvt_utf8<T, 0x10ffff, MODE>(); check_codecvt_utf8<T, max, MODE>(); } template <typename T> void check_all() { check_all_enums<T, std::codecvt_mode(0)>(); check_all_enums<T, std::codecvt_mode(1)>(); check_all_enums<T, std::codecvt_mode(2)>(); check_all_enums<T, std::codecvt_mode(3)>(); check_all_enums<T, std::codecvt_mode(4)>(); check_all_enums<T, std::codecvt_mode(5)>(); check_all_enums<T, std::codecvt_mode(6)>(); check_all_enums<T, std::codecvt_mode(7)>(); } int main() { u32cvt cvt; const char32_t * doneptr = nullptr;; char outbuf[64]; char * end = outbuf + 64, * ptr2 = nullptr; auto state = std::mbstate_t(); for (char32_t i = 0; i < 0x10ffff; ++i) { auto res = cvt.out(state, &i, (&i) + 1, doneptr, outbuf, end, ptr2); // if ((i % 0x10000) == 0 || ((i < 0x10000) && ((i % 0x100) == 0))) // printf("processing mega-plane 0x%08x, current len = %ld\n", // i, ptr2 - outbuf); assert(res == std::codecvt_base::ok); int length = ptr2 - outbuf; state = std::mbstate_t(); int l2 = cvt.length(state, outbuf, ptr2, 20); assert(length == l2); char32_t redecoded = 0, * lastptr = nullptr; const char * ptr1 = nullptr; state = std::mbstate_t(); res = cvt.in(state, outbuf, outbuf + length, ptr1, &redecoded, (&redecoded) + 1, lastptr); assert(res == std::codecvt_base::ok); assert(i == redecoded); } checku16(); check_all<wchar_t>(); check_all<char16_t>(); check_all<char32_t>(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2010 The QXmpp developers * * Author: * Jeremy Lainé * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include <QDebug> #include "QXmppServiceInfo.h" #ifdef Q_OS_WIN #include <windows.h> #include <windns.h> #else #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/nameser.h> #include <arpa/nameser_compat.h> #include <resolv.h> #endif /// Constructs an empty service record object. /// QXmppServiceRecord::QXmppServiceRecord() : host_port(0) { } /// Returns host name for this service record. /// QString QXmppServiceRecord::hostName() const { return host_name; } /// Sets the host name for this service record. /// /// \param hostName void QXmppServiceRecord::setHostName(const QString &hostName) { host_name = hostName; } /// Returns the port for this service record. /// quint16 QXmppServiceRecord::port() const { return host_port; } /// Sets the port for this service record. /// /// \param port void QXmppServiceRecord::setPort(quint16 port) { host_port = port; } /// If the lookup failed, this function returns a human readable description of the error. /// QString QXmppServiceInfo::errorString() const { return m_errorString; } /// Returns the list of records associated with this service. /// QList<QXmppServiceRecord> QXmppServiceInfo::records() const { return m_records; } /// Perform a DNS lookup for an SRV entry. /// /// Returns true if the lookup was succesful, false if it failed. /// /// \param dname QXmppServiceInfo QXmppServiceInfo::fromName(const QString &dname) { QXmppServiceInfo result; #ifdef Q_OS_WIN PDNS_RECORD records, ptr; /* perform DNS query */ if (DnsQuery_UTF8(dname.toUtf8(), DNS_TYPE_SRV, DNS_QUERY_STANDARD, NULL, &records, NULL) != ERROR_SUCCESS) { result.m_errorString = QLatin1String("DnsQuery_UTF8 failed"); return result; } /* extract results */ for (ptr = records; ptr != NULL; ptr = ptr->pNext) { if ((ptr->wType == DNS_TYPE_SRV) && !strcmp((char*)ptr->pName, dname.toUtf8())) { QXmppServiceRecord record; record.setHostName(QString::fromUtf8((char*)ptr->Data.Srv.pNameTarget)); record.setPort(ptr->Data.Srv.wPort); result.m_records.append(record); } } DnsRecordListFree(records, DnsFreeRecordList); #else unsigned char response[PACKETSZ]; int responseLength, answerCount, answerIndex; /* explicitly call res_init in case config changed */ res_init(); /* perform DNS query */ memset(response, 0, sizeof(response)); responseLength = res_query(dname.toAscii(), C_IN, T_SRV, response, sizeof(response)); if (responseLength < int(sizeof(HEADER))) { result.m_errorString = QString("res_query failed: %1").arg(hstrerror(h_errno)); return result; } /* check the response header */ HEADER *header = (HEADER*)response; if (header->rcode != NOERROR || !(answerCount = ntohs(header->ancount))) { result.m_errorString = QLatin1String("res_query returned an error"); return result; } /* skip the query */ char host[PACKETSZ], answer[PACKETSZ]; unsigned char *p = response + sizeof(HEADER); int status = dn_expand(response, response + responseLength, p, host, sizeof(host)); if (status < 0) { result.m_errorString = QLatin1String("dn_expand failed"); return result; } p += status + 4; /* parse answers */ answerIndex = 0; while ((p < response + responseLength) && (answerIndex < answerCount)) { int type, klass, ttl, size; status = dn_expand(response, response + responseLength, p, host, sizeof(host)); if (status < 0) { result.m_errorString = QLatin1String("dn_expand failed"); return result; } p += status; type = (p[0] << 8) | p[1]; p += 2; klass = (p[0] << 8) | p[1]; p += 2; ttl = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; p += 4; size = (p[0] << 8) | p[1]; p += 2; if (type == T_SRV) { quint16 port = (p[4] << 8) | p[5]; status = dn_expand(response, response + responseLength, p + 6, answer, sizeof(answer)); if (status < 0) { result.m_errorString = QLatin1String("dn_expand failed"); return result; } QXmppServiceRecord record; record.setHostName(answer); record.setPort(port); result.m_records.append(record); } else { qWarning("Unexpected DNS answer type"); } p += size; answerIndex++; } #endif return result; } <commit_msg>doc update<commit_after>/* * Copyright (C) 2008-2010 The QXmpp developers * * Author: * Jeremy Lainé * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include <QDebug> #include "QXmppServiceInfo.h" #ifdef Q_OS_WIN #include <windows.h> #include <windns.h> #else #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/nameser.h> #include <arpa/nameser_compat.h> #include <resolv.h> #endif /// Constructs an empty service record object. /// QXmppServiceRecord::QXmppServiceRecord() : host_port(0) { } /// Returns host name for this service record. /// QString QXmppServiceRecord::hostName() const { return host_name; } /// Sets the host name for this service record. /// /// \param hostName void QXmppServiceRecord::setHostName(const QString &hostName) { host_name = hostName; } /// Returns the port for this service record. /// quint16 QXmppServiceRecord::port() const { return host_port; } /// Sets the port for this service record. /// /// \param port void QXmppServiceRecord::setPort(quint16 port) { host_port = port; } /// If the lookup failed, this function returns a human readable description of the error. /// QString QXmppServiceInfo::errorString() const { return m_errorString; } /// Returns the list of records associated with this service. /// QList<QXmppServiceRecord> QXmppServiceInfo::records() const { return m_records; } /// Perform a DNS lookup for an SRV entry. /// /// Returns QXmppServiceInfo object with records /// /// \param dname QXmppServiceInfo QXmppServiceInfo::fromName(const QString &dname) { QXmppServiceInfo result; #ifdef Q_OS_WIN PDNS_RECORD records, ptr; /* perform DNS query */ if (DnsQuery_UTF8(dname.toUtf8(), DNS_TYPE_SRV, DNS_QUERY_STANDARD, NULL, &records, NULL) != ERROR_SUCCESS) { result.m_errorString = QLatin1String("DnsQuery_UTF8 failed"); return result; } /* extract results */ for (ptr = records; ptr != NULL; ptr = ptr->pNext) { if ((ptr->wType == DNS_TYPE_SRV) && !strcmp((char*)ptr->pName, dname.toUtf8())) { QXmppServiceRecord record; record.setHostName(QString::fromUtf8((char*)ptr->Data.Srv.pNameTarget)); record.setPort(ptr->Data.Srv.wPort); result.m_records.append(record); } } DnsRecordListFree(records, DnsFreeRecordList); #else unsigned char response[PACKETSZ]; int responseLength, answerCount, answerIndex; /* explicitly call res_init in case config changed */ res_init(); /* perform DNS query */ memset(response, 0, sizeof(response)); responseLength = res_query(dname.toAscii(), C_IN, T_SRV, response, sizeof(response)); if (responseLength < int(sizeof(HEADER))) { result.m_errorString = QString("res_query failed: %1").arg(hstrerror(h_errno)); return result; } /* check the response header */ HEADER *header = (HEADER*)response; if (header->rcode != NOERROR || !(answerCount = ntohs(header->ancount))) { result.m_errorString = QLatin1String("res_query returned an error"); return result; } /* skip the query */ char host[PACKETSZ], answer[PACKETSZ]; unsigned char *p = response + sizeof(HEADER); int status = dn_expand(response, response + responseLength, p, host, sizeof(host)); if (status < 0) { result.m_errorString = QLatin1String("dn_expand failed"); return result; } p += status + 4; /* parse answers */ answerIndex = 0; while ((p < response + responseLength) && (answerIndex < answerCount)) { int type, klass, ttl, size; status = dn_expand(response, response + responseLength, p, host, sizeof(host)); if (status < 0) { result.m_errorString = QLatin1String("dn_expand failed"); return result; } p += status; type = (p[0] << 8) | p[1]; p += 2; klass = (p[0] << 8) | p[1]; p += 2; ttl = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; p += 4; size = (p[0] << 8) | p[1]; p += 2; if (type == T_SRV) { quint16 port = (p[4] << 8) | p[5]; status = dn_expand(response, response + responseLength, p + 6, answer, sizeof(answer)); if (status < 0) { result.m_errorString = QLatin1String("dn_expand failed"); return result; } QXmppServiceRecord record; record.setHostName(answer); record.setPort(port); result.m_records.append(record); } else { qWarning("Unexpected DNS answer type"); } p += size; answerIndex++; } #endif return result; } <|endoftext|>
<commit_before>#include "metatype_p.h" #include "metatype.h" #include <ostream> #include <mutex> #include <vector> #include <unordered_map> namespace rtti { namespace { #define DEFINE_TYPE_INFO(NAME, TYPEID) \ {CString{#NAME}, sizeof(NAME), MetaType_ID{TYPEID}, MetaType_ID{TYPEID}, type_flags<NAME>::value}, static const std::vector<TypeInfo> fundamentalTypes = { {CString{"void"}, 0, MetaType_ID{0}, MetaType_ID{0}, type_flags<void>::value}, FOR_EACH_FUNDAMENTAL_TYPE(DEFINE_TYPE_INFO) }; #undef DEFINE_TYPE_INFO class CustomTypes { public: CustomTypes(); CustomTypes(const CustomTypes &) = delete; CustomTypes& operator=(const CustomTypes &) = delete; CustomTypes(CustomTypes &&) = delete; CustomTypes& operator=(CustomTypes &&) = delete; ~CustomTypes() = default; const TypeInfo* getTypeInfo(MetaType_ID typeId) const; const TypeInfo* getTypeInfo(const char *name) const; MetaType_ID addTypeInfo(const char *name, unsigned int size, MetaType_ID decay, MetaType::TypeFlags flags); private: mutable std::mutex m_lock; std::vector<TypeInfo> m_items; std::unordered_map<CString, std::size_t> m_names; }; #define DEFINE_TYPE_MAP(NAME, INDEX) \ {CString{#NAME}, INDEX}, CustomTypes::CustomTypes() : m_names { {CString{"void"}, 0}, FOR_EACH_FUNDAMENTAL_TYPE(DEFINE_TYPE_MAP) } {} const TypeInfo* CustomTypes::getTypeInfo(MetaType_ID typeId) const { auto type = typeId.value(); if (type == MetaType::InvalidTypeId) return nullptr; if (type < fundamentalTypes.size()) return &fundamentalTypes[type]; type -= fundamentalTypes.size(); std::lock_guard<std::mutex> lock{m_lock}; if (type < m_items.size()) return &m_items[type]; return nullptr; } const TypeInfo* CustomTypes::getTypeInfo(const char *name) const { if (!name) return nullptr; auto temp = CString{name}; std::lock_guard<std::mutex> lock{m_lock}; auto search = m_names.find(temp); if (search != std::end(m_names)) { auto index = search->second; if (index < fundamentalTypes.size()) return &fundamentalTypes[index]; index -= fundamentalTypes.size(); if (index < m_items.size()) return &m_items[index]; } return nullptr; } inline MetaType_ID CustomTypes::addTypeInfo(const char *name, unsigned int size, MetaType_ID decay, MetaType::TypeFlags flags) { std::lock_guard<std::mutex> lock{m_lock}; MetaType_ID::type result = fundamentalTypes.size() + m_items.size(); // this means that decay_t<type> = type if (decay.value() == MetaType::InvalidTypeId) decay = MetaType_ID{result}; auto temp = CString{name}; m_items.emplace_back(temp, size, MetaType_ID{result}, decay, flags); m_names.emplace(std::move(temp), result); return MetaType_ID{result}; } static inline CustomTypes& customTypes() { static CustomTypes result; return result; } } //-------------------------------------------------------------------------------------------------------------------------------- // MetaType //-------------------------------------------------------------------------------------------------------------------------------- MetaType::MetaType(MetaType_ID typeId) : m_typeInfo(customTypes().getTypeInfo(typeId)) {} rtti::MetaType::MetaType(const char *name) : m_typeInfo(customTypes().getTypeInfo(name)) {} MetaType_ID MetaType::typeId() const noexcept { auto result = MetaType_ID{}; if (m_typeInfo) result = m_typeInfo->type; return result; } void MetaType::setTypeId(MetaType_ID typeId) { *this = MetaType{typeId}; } const char* MetaType::typeName() const noexcept { const char *result = nullptr; if (m_typeInfo) result = m_typeInfo->name.data(); return result; } MetaType::TypeFlags MetaType::typeFlags() const noexcept { MetaType::TypeFlags result = TypeFlags::None; if (m_typeInfo) result = m_typeInfo->flags; return result; } MetaType_ID MetaType::registerMetaType(const char *name, unsigned int size, MetaType_ID decay, MetaType::TypeFlags flags) { return customTypes().addTypeInfo(name, size, decay, flags); } } //namespace rtti std::ostream& operator<<(std::ostream &stream, const rtti::MetaType &value) { return stream << value.typeId().value() << ":" << value.typeName() << ":" << value.typeFlags(); } <commit_msg>convert fundamentalTypes from runtime vector to compile time array<commit_after>#include "metatype_p.h" #include "metatype.h" #include <ostream> #include <mutex> #include <vector> #include <array> #include <unordered_map> namespace rtti { namespace { #define DEFINE_TYPE_INFO(NAME, TYPEID) \ TypeInfo{CString{#NAME}, sizeof(NAME), MetaType_ID{TYPEID}, MetaType_ID{TYPEID}, type_flags<NAME>::value}, static constexpr std::array<TypeInfo, 41> fundamentalTypes = { TypeInfo{CString{"void"}, 0, MetaType_ID{0}, MetaType_ID{0}, type_flags<void>::value}, FOR_EACH_FUNDAMENTAL_TYPE(DEFINE_TYPE_INFO) }; #undef DEFINE_TYPE_INFO class CustomTypes { public: CustomTypes(); CustomTypes(const CustomTypes &) = delete; CustomTypes& operator=(const CustomTypes &) = delete; CustomTypes(CustomTypes &&) = delete; CustomTypes& operator=(CustomTypes &&) = delete; ~CustomTypes() = default; const TypeInfo* getTypeInfo(MetaType_ID typeId) const; const TypeInfo* getTypeInfo(const char *name) const; MetaType_ID addTypeInfo(const char *name, unsigned int size, MetaType_ID decay, MetaType::TypeFlags flags); private: mutable std::mutex m_lock; std::vector<TypeInfo> m_items; std::unordered_map<CString, std::size_t> m_names; }; #define DEFINE_TYPE_MAP(NAME, INDEX) \ {CString{#NAME}, INDEX}, CustomTypes::CustomTypes() : m_names { {CString{"void"}, 0}, FOR_EACH_FUNDAMENTAL_TYPE(DEFINE_TYPE_MAP) } {} const TypeInfo* CustomTypes::getTypeInfo(MetaType_ID typeId) const { auto type = typeId.value(); if (type == MetaType::InvalidTypeId) return nullptr; if (type < fundamentalTypes.size()) return &fundamentalTypes[type]; type -= fundamentalTypes.size(); std::lock_guard<std::mutex> lock{m_lock}; if (type < m_items.size()) return &m_items[type]; return nullptr; } const TypeInfo* CustomTypes::getTypeInfo(const char *name) const { if (!name) return nullptr; auto temp = CString{name}; std::lock_guard<std::mutex> lock{m_lock}; auto search = m_names.find(temp); if (search != std::end(m_names)) { auto index = search->second; if (index < fundamentalTypes.size()) return &fundamentalTypes[index]; index -= fundamentalTypes.size(); if (index < m_items.size()) return &m_items[index]; } return nullptr; } inline MetaType_ID CustomTypes::addTypeInfo(const char *name, unsigned int size, MetaType_ID decay, MetaType::TypeFlags flags) { std::lock_guard<std::mutex> lock{m_lock}; MetaType_ID::type result = fundamentalTypes.size() + m_items.size(); // this means that decay_t<type> = type if (decay.value() == MetaType::InvalidTypeId) decay = MetaType_ID{result}; auto temp = CString{name}; m_items.emplace_back(temp, size, MetaType_ID{result}, decay, flags); m_names.emplace(std::move(temp), result); return MetaType_ID{result}; } static inline CustomTypes& customTypes() { static CustomTypes result; return result; } } //-------------------------------------------------------------------------------------------------------------------------------- // MetaType //-------------------------------------------------------------------------------------------------------------------------------- MetaType::MetaType(MetaType_ID typeId) : m_typeInfo(customTypes().getTypeInfo(typeId)) {} rtti::MetaType::MetaType(const char *name) : m_typeInfo(customTypes().getTypeInfo(name)) {} MetaType_ID MetaType::typeId() const noexcept { auto result = MetaType_ID{}; if (m_typeInfo) result = m_typeInfo->type; return result; } void MetaType::setTypeId(MetaType_ID typeId) { *this = MetaType{typeId}; } const char* MetaType::typeName() const noexcept { const char *result = nullptr; if (m_typeInfo) result = m_typeInfo->name.data(); return result; } MetaType::TypeFlags MetaType::typeFlags() const noexcept { MetaType::TypeFlags result = TypeFlags::None; if (m_typeInfo) result = m_typeInfo->flags; return result; } MetaType_ID MetaType::registerMetaType(const char *name, unsigned int size, MetaType_ID decay, MetaType::TypeFlags flags) { return customTypes().addTypeInfo(name, size, decay, flags); } } //namespace rtti std::ostream& operator<<(std::ostream &stream, const rtti::MetaType &value) { return stream << value.typeId().value() << ":" << value.typeName() << ":" << value.typeFlags(); } <|endoftext|>
<commit_before>#include <Arduino.h> #include <EEPROM.h> #include "RF12.h" #include "RadioUtils.h" #include "SerialUtils.h" #include "Time.h" #include <../../common.h> #include <../scenarios.h> int counter = 1; // int msgCounter = 0; int led = HIGH; int nodeID = 0; RadioUtils ru = RadioUtils(); SerialUtils su = SerialUtils(SERIAL_FREQUENCY); void setup () { Serial.begin(SERIAL_FREQUENCY); Serial.println("\n[Scenario 02], node started"); pinMode(9, OUTPUT); ru.initialize(); ru.enableDynamicRouting(); nodeID = ru.getNodeID(); if(ru.getNodeID() == ru.getParentID()){//root node - BS - send info message n+1 times ru.routeUpdateDistance(0, ru.getNodeID()); for(int i = 0; i < ROUTING_CYCLES; i ++){ if(led == HIGH){ digitalWrite(9, LOW); led = LOW; } else { digitalWrite(9, HIGH); led = HIGH; } delay(TIMEOUT); ru.routeBroadcastLength(); } } else {//regular node - perform n+1 routing cycles while(millis() < (long)TIMEOUT * (long)ROUTING_CYCLES){ // ru.routePerformOneStep(); if(led == HIGH){ digitalWrite(9, LOW); led = LOW; } else { digitalWrite(9, HIGH); led = HIGH; } } } randomSeed(nodeID); delay(nodeID * 100); } byte createHeader(boolean requireACK, byte destID){ byte header = requireACK ? RF12_HDR_ACK : 0; header |= RF12_HDR_DST | destID; return header; } String message = ""; char payload[MAX_MESSAGE_LENGTH] = ""; int rounds = 0; void node(){ if(rf12_recvDone()){ if(RF12_WANTS_ACK){ rf12_sendStart(RF12_ACK_REPLY,0,0); } if(rf12_crc == 0){ //packet checksum is correct //propagate to parent byte header = createHeader(false, ru.getParentID()); rf12_sendNow(header, (const void*)rf12_data, rf12_len); } } //send own messages if(rounds >= 130){ message = "#"; message += nodeID*11*counter; message += "#"; message += random(600,999); message += random(100,999); byte hdr = createHeader(false, ru.getParentID()); message.toCharArray(payload, message.length()+1); rf12_sendNow(hdr, payload, message.length()); counter++; rounds = 0; } rounds++; delay(10); } byte saveHdr, saveLen; word saveCrc; char saveData[RF12_MAXDATA]; #define BUFFER_SIZE 40 int buffer[BUFFER_SIZE] = {0}; //returns index of min int findMin(){ int index = 0; for(int i = 0; i < BUFFER_SIZE; i++){ if(buffer[index] > buffer[i]){ index = i; } } return index; } int UCO_LEN = 32; long uco[] = { 396515,448419,448426,448413,448414,448427,448428,410158,448420,448387,396278, 448389,454317,448384,448429,448382,448383,394036,448385,448381,448390,448415, 448421,448423,448411,453033,448291,448417,409910,448418,448416,396555 }; String secret[] = { "andrei","apeman","ahchoo","airbus","abdias","averno","aganus","annals","aghast", "arpent","aliner","accent","anglic","adabel","aerial","almost","aornum","ahmadi", "artist","agonal","ararat","amiens","alayne","andrsy","amadan","awaken","assiut", "aurist","avalon","asleep","apollo","afflux" }; int findUco(long task){ for(int i = 0; i < UCO_LEN; i++){ if(task == uco[i]){ return i; } } return -1; } void bs(){ if(rf12_recvDone()){ if(RF12_WANTS_ACK){ rf12_sendStart(RF12_ACK_REPLY,0,0); } if(rf12_crc == 0){ //packet checksum is correct saveLen = rf12_len; saveCrc = rf12_crc; saveHdr = rf12_hdr; memcpy(saveData, (const void*) rf12_data, sizeof saveData); rf12_recvDone(); char text[MAX_MESSAGE_LENGTH] = ""; int count = 0; for (byte i = 0; i < rf12_len; ++i) { text[i] = rf12_data[i]; if(text[i] == '#'){ count++; } } //correct message if(count == 2){ String msg = String(text); String head = msg.substring(1,msg.lastIndexOf('#')); int intHead = head.toInt(); if(intHead == 0){ return; } if(intHead % 11 != 0){ return; } int min = findMin(); if(buffer[min] < intHead/11){ buffer[min] = intHead/11; } String number = msg.substring(msg.lastIndexOf('#')+1,msg.length()); long longNumber = atol(number.c_str()); if(longNumber == 0){ return; } int index = findUco(longNumber); if(index < 0){ return; } message = "#"; message += secret[index]; message += "#"; message += random(100,999); message += "#"; byte hdr = createHeader(false, rf12_hdr | RF12_HDR_DST); message.toCharArray(payload, message.length()+1); rf12_sendNow(hdr, payload, message.length()); } } } } void loop () { //regular nodes if(ru.getNodeID() != ru.getParentID()){ node(); } else { //BS bs(); } } <commit_msg>message number added<commit_after>#include <Arduino.h> #include <EEPROM.h> #include "RF12.h" #include "RadioUtils.h" #include "SerialUtils.h" #include "Time.h" #include <../../common.h> #include <../scenarios.h> int counter = 1; // int msgCounter = 0; int led = HIGH; int nodeID = 0; RadioUtils ru = RadioUtils(); SerialUtils su = SerialUtils(SERIAL_FREQUENCY); void setup () { Serial.begin(SERIAL_FREQUENCY); Serial.println("\n[Scenario 02], node started"); pinMode(9, OUTPUT); ru.initialize(); ru.enableDynamicRouting(); nodeID = ru.getNodeID(); if(ru.getNodeID() == ru.getParentID()){//root node - BS - send info message n+1 times ru.routeUpdateDistance(0, ru.getNodeID()); for(int i = 0; i < ROUTING_CYCLES; i ++){ if(led == HIGH){ digitalWrite(9, LOW); led = LOW; } else { digitalWrite(9, HIGH); led = HIGH; } delay(TIMEOUT); ru.routeBroadcastLength(); } } else {//regular node - perform n+1 routing cycles while(millis() < (long)TIMEOUT * (long)ROUTING_CYCLES){ // ru.routePerformOneStep(); if(led == HIGH){ digitalWrite(9, LOW); led = LOW; } else { digitalWrite(9, HIGH); led = HIGH; } } } randomSeed(nodeID); delay(nodeID * 100); } byte createHeader(boolean requireACK, byte destID){ byte header = requireACK ? RF12_HDR_ACK : 0; header |= RF12_HDR_DST | destID; return header; } String message = ""; char payload[MAX_MESSAGE_LENGTH] = ""; int rounds = 0; void node(){ if(rf12_recvDone()){ if(RF12_WANTS_ACK){ rf12_sendStart(RF12_ACK_REPLY,0,0); } if(rf12_crc == 0){ //packet checksum is correct //propagate to parent byte header = createHeader(false, ru.getParentID()); rf12_sendNow(header, (const void*)rf12_data, rf12_len); } } //send own messages if(rounds >= 130){ message = "#"; message += nodeID*11*counter; message += "#"; message += random(600,999); message += random(100,999); byte hdr = createHeader(false, ru.getParentID()); message.toCharArray(payload, message.length()+1); rf12_sendNow(hdr, payload, message.length()); counter++; rounds = 0; } rounds++; delay(10); } byte saveHdr, saveLen; word saveCrc; char saveData[RF12_MAXDATA]; #define BUFFER_SIZE 40 int buffer[BUFFER_SIZE] = {0}; //returns index of min int findMin(){ int index = 0; for(int i = 0; i < BUFFER_SIZE; i++){ if(buffer[index] > buffer[i]){ index = i; } } return index; } int UCO_LEN = 32; long uco[] = { 396515,448419,448426,448413,448414,448427,448428,410158,448420,448387,396278, 448389,454317,448384,448429,448382,448383,394036,448385,448381,448390,448415, 448421,448423,448411,453033,448291,448417,409910,448418,448416,396555 }; String secret[] = { "andrei","apeman","ahchoo","airbus","abdias","averno","aganus","annals","aghast", "arpent","aliner","accent","anglic","adabel","aerial","almost","aornum","ahmadi", "artist","agonal","ararat","amiens","alayne","andrsy","amadan","awaken","assiut", "aurist","avalon","asleep","apollo","afflux" }; int findUco(long task){ for(int i = 0; i < UCO_LEN; i++){ if(task == uco[i]){ return i; } } return -1; } void bs(){ if(rf12_recvDone()){ if(RF12_WANTS_ACK){ rf12_sendStart(RF12_ACK_REPLY,0,0); } if(rf12_crc == 0){ //packet checksum is correct saveLen = rf12_len; saveCrc = rf12_crc; saveHdr = rf12_hdr; memcpy(saveData, (const void*) rf12_data, sizeof saveData); rf12_recvDone(); char text[MAX_MESSAGE_LENGTH] = ""; int count = 0; for (byte i = 0; i < rf12_len; ++i) { text[i] = rf12_data[i]; if(text[i] == '#'){ count++; } } //correct message if(count == 2){ String msg = String(text); String head = msg.substring(1,msg.lastIndexOf('#')); int intHead = head.toInt(); if(intHead == 0){ return; } if(intHead % 11 != 0){ return; } int min = findMin(); if(buffer[min] < intHead/11){ buffer[min] = intHead/11; } String number = msg.substring(msg.lastIndexOf('#')+1,msg.length()); long longNumber = atol(number.c_str()); if(longNumber == 0){ return; } int index = findUco(longNumber); if(index < 0){ return; } message = "#"; message += secret[index]; message += "#"; message += intHead/11; message += "#"; message += random(100,999); byte hdr = createHeader(false, rf12_hdr | RF12_HDR_DST); message.toCharArray(payload, message.length()+1); rf12_sendNow(hdr, payload, message.length()); } } } } void loop () { //regular nodes if(ru.getNodeID() != ru.getParentID()){ node(); } else { //BS bs(); } } <|endoftext|>
<commit_before>/* libscratch - Multipurpose objective C++ library. Copyright (c) 2013 - 2016 Angelo Geels <spansjh@gmail.com> 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 #ifdef SCRATCH_IMPL #if WINDOWS #include <ShlObj.h> #endif #endif #include "String.hpp" SCRATCH_NAMESPACE_BEGIN; class SCRATCH_EXPORT Filename : public String { public: Filename(); Filename(const Filename &copy); Filename(const char* szStr); Filename(const String &str); String Extension() const; String Path() const; String Name() const; void FromHome(const String &strPath); }; #ifdef SCRATCH_IMPL Filename::Filename() { str_iInstances++; // Create a new empty buffer this->str_szBuffer = String::str_szEmpty; } Filename::Filename(const Filename &copy) { str_iInstances++; // Create a new buffer and copy data into it. this->str_szBuffer = String::str_szEmpty; this->CopyToBuffer(copy); } Filename::Filename(const char* szStr) { str_iInstances++; // Create a new buffer and copy data into it. this->str_szBuffer = String::str_szEmpty; this->CopyToBuffer(szStr); } Filename::Filename(const String &str) { str_iInstances++; // Create a new buffer and copy data into it. this->str_szBuffer = String::str_szEmpty; this->CopyToBuffer(str.str_szBuffer); } String Filename::Extension() const { return String(strrchr(str_szBuffer, '.') + 1); } String Filename::Path() const { return String(str_szBuffer, 0, strrchr(str_szBuffer, '/') - str_szBuffer); } String Filename::Name() const { return String(strrchr(str_szBuffer, '/') + 1); } void Filename::FromHome(const String &strPath) { #if WINDOWS char szPath[MAX_PATH]; if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_PROFILE, nullptr, 0, szPath))) { this->CopyToBuffer(szPath); this->AppendToBuffer("\\" + strPath); } #else this->CopyToBuffer("~/" + strPath); #endif } #endif SCRATCH_NAMESPACE_END; <commit_msg>Fix filename::fromhome for unix (linux/mac)<commit_after>/* libscratch - Multipurpose objective C++ library. Copyright (c) 2013 - 2016 Angelo Geels <spansjh@gmail.com> 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 #ifdef SCRATCH_IMPL #if WINDOWS #include <ShlObj.h> #else #include <unistd.h> #include <sys/types.h> #include <pwd.h> #endif #endif #include "String.hpp" SCRATCH_NAMESPACE_BEGIN; class SCRATCH_EXPORT Filename : public String { public: Filename(); Filename(const Filename &copy); Filename(const char* szStr); Filename(const String &str); String Extension() const; String Path() const; String Name() const; void FromHome(const String &strPath); }; #ifdef SCRATCH_IMPL Filename::Filename() { str_iInstances++; // Create a new empty buffer this->str_szBuffer = String::str_szEmpty; } Filename::Filename(const Filename &copy) { str_iInstances++; // Create a new buffer and copy data into it. this->str_szBuffer = String::str_szEmpty; this->CopyToBuffer(copy); } Filename::Filename(const char* szStr) { str_iInstances++; // Create a new buffer and copy data into it. this->str_szBuffer = String::str_szEmpty; this->CopyToBuffer(szStr); } Filename::Filename(const String &str) { str_iInstances++; // Create a new buffer and copy data into it. this->str_szBuffer = String::str_szEmpty; this->CopyToBuffer(str.str_szBuffer); } String Filename::Extension() const { return String(strrchr(str_szBuffer, '.') + 1); } String Filename::Path() const { return String(str_szBuffer, 0, strrchr(str_szBuffer, '/') - str_szBuffer); } String Filename::Name() const { return String(strrchr(str_szBuffer, '/') + 1); } void Filename::FromHome(const String &strPath) { #if WINDOWS char szPath[MAX_PATH]; if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_PROFILE, nullptr, 0, szPath))) { this->CopyToBuffer(szPath); this->AppendToBuffer("\\" + strPath); } #else const char* homedir; if ((homedir = getenv("HOME") ) == nullptr) { homedir = getpwuid(getuid())->pw_dir; } if(homedir == nullptr){ this->CopyToBuffer("~/" + strPath); }else{ this->CopyToBuffer(String(homedir) + "/" + strPath); } #endif } #endif SCRATCH_NAMESPACE_END; <|endoftext|>
<commit_before>/* * Copyright 2008 by Tommi Rantala <tommi.rantala@cs.helsinki.fi> * * 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. */ /* * A variant of the Multi-Key-Quicksort using dynamic arrays to store the three * buckets. */ #include "util/insertion_sort.h" #include "util/get_char.h" #include "util/median.h" #include <inttypes.h> #include <cassert> #include <boost/array.hpp> #include "vector_bagwell.h" #include "vector_brodnik.h" #include "vector_block.h" template <typename CharT> static inline unsigned get_bucket(CharT c, CharT pivot) { return ((c > pivot) << 1) | (c == pivot); } static inline void copy(const std::vector<unsigned char*>& bucket, unsigned char** dst) { std::copy(bucket.begin(), bucket.end(), dst); } extern "C" void mkqsort(unsigned char**, int, int); template <typename BucketT, typename CharT> static void multikey_dynamic(unsigned char** strings, size_t N, size_t depth) { if (N < 10000) { mkqsort(strings, N, depth); return; } // Use heap instead of stack array, so that we can _really_ clean up // the buckets before recursion. With std::vector we would need to use // the swap trick. BucketT* buckets = new BucketT[3]; CharT partval = pseudo_median<CharT>(strings, N, depth); // Use a small cache to reduce memory stalls. size_t i=0; for (; i < N-N%32; i+=32) { boost::array<CharT, 32> cache; for (unsigned j=0; j<32; ++j) { cache[j] = get_char<CharT>(strings[i+j], depth); } for (unsigned j=0; j<32; ++j) { const unsigned b = get_bucket(cache[j], partval); buckets[b].push_back(strings[i+j]); } } for (; i < N; ++i) { const CharT c = get_char<CharT>(strings[i], depth); const unsigned b = get_bucket(c, partval); buckets[b].push_back(strings[i]); } boost::array<size_t, 3> bucketsize = { buckets[0].size(), buckets[1].size(), buckets[2].size()}; assert(bucketsize[0] + bucketsize[1] + bucketsize[2] == N); if (bucketsize[0]) copy(buckets[0], strings); if (bucketsize[1]) copy(buckets[1], strings+bucketsize[0]); if (bucketsize[2]) copy(buckets[2], strings+bucketsize[0]+bucketsize[1]); delete [] buckets; multikey_dynamic<BucketT, CharT>(strings, bucketsize[0], depth); if (not is_end(partval)) multikey_dynamic<BucketT, CharT>(strings+bucketsize[0], bucketsize[1], depth+sizeof(CharT)); multikey_dynamic<BucketT, CharT>(strings+bucketsize[0]+bucketsize[1], bucketsize[2], depth); } void multikey_dynamic_vector1(unsigned char** strings, size_t n) { typedef std::vector<unsigned char*> BucketT; typedef unsigned char CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_vector2(unsigned char** strings, size_t n) { typedef std::vector<unsigned char*> BucketT; typedef uint16_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_vector4(unsigned char** strings, size_t n) { typedef std::vector<unsigned char*> BucketT; typedef uint32_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_brodnik1(unsigned char** strings, size_t n) { typedef vector_brodnik<unsigned char*> BucketT; typedef unsigned char CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_brodnik2(unsigned char** strings, size_t n) { typedef vector_brodnik<unsigned char*> BucketT; typedef uint16_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_brodnik4(unsigned char** strings, size_t n) { typedef vector_brodnik<unsigned char*> BucketT; typedef uint32_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_bagwell1(unsigned char** strings, size_t n) { typedef vector_bagwell<unsigned char*> BucketT; typedef unsigned char CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_bagwell2(unsigned char** strings, size_t n) { typedef vector_bagwell<unsigned char*> BucketT; typedef uint16_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_bagwell4(unsigned char** strings, size_t n) { typedef vector_bagwell<unsigned char*> BucketT; typedef uint32_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_vector_block1(unsigned char** strings, size_t n) { typedef vector_block<unsigned char*> BucketT; typedef unsigned char CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_vector_block2(unsigned char** strings, size_t n) { typedef vector_block<unsigned char*> BucketT; typedef uint16_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_vector_block4(unsigned char** strings, size_t n) { typedef vector_block<unsigned char*> BucketT; typedef uint32_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } <commit_msg>use stack allocation and the swap trick with std::vector<commit_after>/* * Copyright 2008 by Tommi Rantala <tommi.rantala@cs.helsinki.fi> * * 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. */ /* * A variant of the Multi-Key-Quicksort using dynamic arrays to store the three * buckets. */ #include "util/insertion_sort.h" #include "util/get_char.h" #include "util/median.h" #include <inttypes.h> #include <cassert> #include <boost/array.hpp> #include "vector_bagwell.h" #include "vector_brodnik.h" #include "vector_block.h" template <typename CharT> static inline unsigned get_bucket(CharT c, CharT pivot) { return ((c > pivot) << 1) | (c == pivot); } static inline void copy(const std::vector<unsigned char*>& bucket, unsigned char** dst) { std::copy(bucket.begin(), bucket.end(), dst); } template <typename BucketT> static inline void clear_bucket(BucketT& bucket) { bucket.clear(); } static inline void clear_bucket(std::vector<unsigned char*>& bucket) { bucket.clear(); std::vector<unsigned char*>().swap(bucket); } extern "C" void mkqsort(unsigned char**, int, int); template <typename BucketT, typename CharT> static void multikey_dynamic(unsigned char** strings, size_t N, size_t depth) { if (N < 10000) { mkqsort(strings, N, depth); return; } boost::array<BucketT, 3> buckets; CharT partval = pseudo_median<CharT>(strings, N, depth); // Use a small cache to reduce memory stalls. size_t i=0; for (; i < N-N%32; i+=32) { boost::array<CharT, 32> cache; for (unsigned j=0; j<32; ++j) { cache[j] = get_char<CharT>(strings[i+j], depth); } for (unsigned j=0; j<32; ++j) { const unsigned b = get_bucket(cache[j], partval); buckets[b].push_back(strings[i+j]); } } for (; i < N; ++i) { const CharT c = get_char<CharT>(strings[i], depth); const unsigned b = get_bucket(c, partval); buckets[b].push_back(strings[i]); } boost::array<size_t, 3> bucketsize = { buckets[0].size(), buckets[1].size(), buckets[2].size()}; assert(bucketsize[0] + bucketsize[1] + bucketsize[2] == N); if (bucketsize[0]) copy(buckets[0], strings); if (bucketsize[1]) copy(buckets[1], strings+bucketsize[0]); if (bucketsize[2]) copy(buckets[2], strings+bucketsize[0]+bucketsize[1]); clear_bucket(buckets[0]); clear_bucket(buckets[1]); clear_bucket(buckets[2]); multikey_dynamic<BucketT, CharT>(strings, bucketsize[0], depth); if (not is_end(partval)) multikey_dynamic<BucketT, CharT>(strings+bucketsize[0], bucketsize[1], depth+sizeof(CharT)); multikey_dynamic<BucketT, CharT>(strings+bucketsize[0]+bucketsize[1], bucketsize[2], depth); } void multikey_dynamic_vector1(unsigned char** strings, size_t n) { typedef std::vector<unsigned char*> BucketT; typedef unsigned char CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_vector2(unsigned char** strings, size_t n) { typedef std::vector<unsigned char*> BucketT; typedef uint16_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_vector4(unsigned char** strings, size_t n) { typedef std::vector<unsigned char*> BucketT; typedef uint32_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_brodnik1(unsigned char** strings, size_t n) { typedef vector_brodnik<unsigned char*> BucketT; typedef unsigned char CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_brodnik2(unsigned char** strings, size_t n) { typedef vector_brodnik<unsigned char*> BucketT; typedef uint16_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_brodnik4(unsigned char** strings, size_t n) { typedef vector_brodnik<unsigned char*> BucketT; typedef uint32_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_bagwell1(unsigned char** strings, size_t n) { typedef vector_bagwell<unsigned char*> BucketT; typedef unsigned char CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_bagwell2(unsigned char** strings, size_t n) { typedef vector_bagwell<unsigned char*> BucketT; typedef uint16_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_bagwell4(unsigned char** strings, size_t n) { typedef vector_bagwell<unsigned char*> BucketT; typedef uint32_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_vector_block1(unsigned char** strings, size_t n) { typedef vector_block<unsigned char*> BucketT; typedef unsigned char CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_vector_block2(unsigned char** strings, size_t n) { typedef vector_block<unsigned char*> BucketT; typedef uint16_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } void multikey_dynamic_vector_block4(unsigned char** strings, size_t n) { typedef vector_block<unsigned char*> BucketT; typedef uint32_t CharT; multikey_dynamic<BucketT, CharT>(strings, n, 0); } <|endoftext|>
<commit_before>#include <QClipboard> #include <QDateTime> #include <QDebug> #include <QFile> #include <QFileDialog> #include <QKeyEvent> #include <QLineEdit> #include <QMessageBox> #include <QPoint> #include <QSettings> #include <QSize> #include <QTextStream> #include <algorithm> #include <stdexcept> #include <typeinfo> #include "config.hh" #include "CorpusWidget.hh" #include "SimpleDTD.hh" #include "StatisticsWindow.hh" #include "Query.hh" #include "QueryModel.hh" #include "PercentageCellDelegate.hh" #include "ValidityColor.hh" #include "XPathValidator.hh" #include "XSLTransformer.hh" #include "ui_StatisticsWindow.h" StatisticsWindow::StatisticsWindow(QWidget *parent) : CorpusWidget(parent), d_ui(QSharedPointer<Ui::StatisticsWindow>(new Ui::StatisticsWindow)), d_percentageCellDelegate(new PercentageCellDelegate) { d_ui->setupUi(this); createActions(); readNodeAttributes(); readSettings(); // Pick a sane default attribute. int idx = d_ui->attributeComboBox->findText("word"); if (idx != -1) d_ui->attributeComboBox->setCurrentIndex(idx); } StatisticsWindow::~StatisticsWindow() { writeSettings(); } void StatisticsWindow::attributeChanged(int index) { Q_UNUSED(index); if (!d_model.isNull()) startQuery(); } void StatisticsWindow::queryFailed(QString error) { progressStopped(0, 0); QMessageBox::critical(this, tr("Error processing query"), tr("Could not process query: ") + error, QMessageBox::Ok); } void StatisticsWindow::switchCorpus(QSharedPointer<alpinocorpus::CorpusReader> corpusReader) { d_corpusReader = corpusReader; readNodeAttributes(); emit saveStateChanged(); //d_xpathValidator->setCorpusReader(d_corpusReader); setModel(new QueryModel(corpusReader)); // Ensure that percentage column is hidden when necessary. showPercentageChanged(); } void StatisticsWindow::setFilter(QString const &filter, QString const &raw_filter) { Q_UNUSED(raw_filter); d_filter = filter; startQuery(); } void StatisticsWindow::setAggregateAttribute(QString const &detail) { // @TODO: update d_ui->attributeComboBox.currentIndex when changed from outside // to reflect the current (changed) state of the window. } void StatisticsWindow::setModel(QueryModel *model) { d_model = QSharedPointer<QueryModel>(model); d_ui->resultsTable->setModel(d_model.data()); d_ui->distinctValuesLabel->setText(QString("")); d_ui->totalHitsLabel->setText(QString("")); connect(d_model.data(), SIGNAL(queryFailed(QString)), SLOT(queryFailed(QString))); connect(d_model.data(), SIGNAL(queryEntryFound(QString)), SLOT(updateResultsTotalCount())); connect(d_model.data(), SIGNAL(queryStarted(int)), SLOT(progressStarted(int))); connect(d_model.data(), SIGNAL(queryStopped(int, int)), SLOT(progressStopped(int, int))); connect(d_model.data(), SIGNAL(queryFinished(int, int, QString, bool, bool)), SLOT(progressStopped(int, int))); connect(d_model.data(), SIGNAL(progressChanged(int)), SLOT(progressChanged(int))); } void StatisticsWindow::updateResultsTotalCount() { d_ui->totalHitsLabel->setText(QString("%L1").arg(d_model->totalHits())); d_ui->distinctValuesLabel->setText(QString("%L1").arg(d_model->rowCount(QModelIndex()))); } void StatisticsWindow::applyValidityColor(QString const &) { ::applyValidityColor(sender()); } void StatisticsWindow::cancelQuery() { if (d_model) d_model->cancelQuery(); } void StatisticsWindow::saveAs() { if (d_model.isNull()) return; int nlines = d_model->rowCount(QModelIndex()); if (nlines == 0) return; QString filename; QStringList filenames; QFileDialog fd(this, tr("Save"), QString("untitled"), tr("Microsoft Excel 2003 XML (*.xls);;Text (*.txt);;HTML (*.html *.htm);;CSV (*.csv)")); fd.setAcceptMode(QFileDialog::AcceptSave); fd.setConfirmOverwrite(true); fd.setLabelText(QFileDialog::Accept, tr("Save")); if (d_lastFilterChoice.size()) fd.selectNameFilter(d_lastFilterChoice); if (fd.exec()) filenames = fd.selectedFiles(); else return; if (filenames.size() < 1) return; filename = filenames[0]; if (! filename.length()) return; QSharedPointer<QFile> stylesheet; d_lastFilterChoice = fd.selectedNameFilter(); if (d_lastFilterChoice.contains("*.txt")) stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-text.xsl")); else if (d_lastFilterChoice.contains("*.html")) stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-html.xsl")); else if (d_lastFilterChoice.contains("*.xls")) stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-officexml.xsl")); else stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-csv.xsl")); QFile data(filename); if (!data.open(QFile::WriteOnly | QFile::Truncate)) { QMessageBox::critical(this, tr("Save file error"), tr("Cannot save file %1 (error code %2)").arg(filename).arg(data.error()), QMessageBox::Ok); return; } QTextStream out(&data); out.setCodec("UTF-8"); QString xmlStats = d_model->asXML(); XSLTransformer trans(stylesheet.data()); out << trans.transform(xmlStats); emit statusMessage(tr("File saved as %1").arg(filename)); } void StatisticsWindow::copy() { QString csv; QTextStream textstream(&csv, QIODevice::WriteOnly | QIODevice::Text); selectionAsCSV(textstream, "\t"); if (!csv.isEmpty()) QApplication::clipboard()->setText(csv); } void StatisticsWindow::exportSelection() { QString filename(QFileDialog::getSaveFileName(this, "Export selection", QString(), "*.csv")); if (filename.isNull()) return; QFile file(filename); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::critical(this, tr("Error exporting selection"), tr("Could open file for writing."), QMessageBox::Ok); return; } QTextStream textstream(&file); textstream.setGenerateByteOrderMark(true); selectionAsCSV(textstream, ";", true); } void StatisticsWindow::createActions() { // @TODO: move this non action related ui code to somewhere else. The .ui file preferably. // Requires initialized UI. //d_ui->resultsTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch); d_ui->resultsTable->verticalHeader()->hide(); d_ui->resultsTable->sortByColumn(1, Qt::DescendingOrder); d_ui->resultsTable->setItemDelegateForColumn(2, d_percentageCellDelegate.data()); // Only allow valid xpath queries to be submitted //d_ui->filterLineEdit->setValidator(d_xpathValidator.data()); // When a row is activated, generate a query to be used in the main window to // filter all the results so only the results which are accumulated in this // row will be shown. connect(d_ui->resultsTable, SIGNAL(activated(QModelIndex const &)), SLOT(generateQuery(QModelIndex const &))); // Toggle percentage column checkbox (is this needed?) connect(d_ui->percentageCheckBox, SIGNAL(toggled(bool)), SLOT(showPercentageChanged())); connect(d_ui->yieldCheckBox, SIGNAL(toggled(bool)), SLOT(showYieldChanged())); connect(d_ui->attributeComboBox, SIGNAL(currentIndexChanged(int)), SLOT(attributeChanged(int))); } void StatisticsWindow::generateQuery(QModelIndex const &index) { // We are not able to generate a query (yet) for yield items. // I guess such queries become really long and tedious. if (d_ui->yieldCheckBox->isChecked()) return; // Get the text from the first column, that is the found value QString data = index.sibling(index.row(), 0).data(Qt::UserRole).toString(); if (data == MISSING_ATTRIBUTE) return; QString query = ::generateQuery( d_filter, d_ui->attributeComboBox->currentText(), data); emit entryActivated(data, query); } void StatisticsWindow::selectionAsCSV(QTextStream &output, QString const &separator, bool escape_quotes) const { // If there is no model attached (e.g. no corpus loaded) do nothing if (!d_model) return; QModelIndexList rows = d_ui->resultsTable->selectionModel()->selectedRows(); // If there is nothing selected, do nothing if (rows.isEmpty()) return; foreach (QModelIndex const &row, rows) { // This only works if the selection behavior is SelectRows if (escape_quotes) output << '"' << d_model->data(row).toString().replace("\"", "\"\"") << '"'; // value else output << d_model->data(row).toString(); output << separator << d_model->data(row.sibling(row.row(), 1)).toString() // count << '\n'; } } void StatisticsWindow::startQuery() { setAggregateAttribute(d_ui->attributeComboBox->currentText()); d_ui->resultsTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch); d_ui->resultsTable->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents); d_ui->resultsTable->horizontalHeader()->setResizeMode(2, QHeaderView::Stretch); d_ui->totalHitsLabel->clear(); d_ui->distinctValuesLabel->clear(); bool yield = d_ui->yieldCheckBox->isChecked(); d_model->runQuery(d_filter, d_ui->attributeComboBox->currentText(), yield); emit saveStateChanged(); } void StatisticsWindow::showPercentageChanged() { d_ui->resultsTable->setColumnHidden(2, !d_ui->percentageCheckBox->isChecked()); } void StatisticsWindow::showYieldChanged() { if (!d_model.isNull()) startQuery(); } void StatisticsWindow::progressStarted(int total) { d_ui->filterProgress->setMaximum(total); d_ui->filterProgress->setDisabled(false); d_ui->filterProgress->setVisible(true); } void StatisticsWindow::progressChanged(int percentage) { d_ui->filterProgress->setValue(percentage); } void StatisticsWindow::progressStopped(int n, int total) { updateResultsTotalCount(); d_ui->filterProgress->setVisible(false); emit saveStateChanged(); } void StatisticsWindow::closeEvent(QCloseEvent *event) { writeSettings(); event->accept(); } void StatisticsWindow::readNodeAttributes() { QString dtdPath = (d_corpusReader && d_corpusReader->type() == "tueba_tree") ? ":/dtd/tueba_tree.dtd" : ":/dtd/alpino_ds.dtd"; // XXX - hardcode? QFile dtdFile(dtdPath); if (!dtdFile.open(QFile::ReadOnly)) { qWarning() << "StatisticsWindow::readNodeAttributes(): Could not read DTD."; return; } QByteArray dtdData(dtdFile.readAll()); SimpleDTD sDTD(dtdData.constData()); // Should be safe to clear items now... d_ui->attributeComboBox->clear(); // Do we have a node element? ElementMap::const_iterator iter = sDTD.elementMap().find("node"); if (iter == sDTD.elementMap().end()) return; std::set<std::string> attrs = iter->second; QStringList attrList; for (std::set<std::string>::const_iterator attrIter = attrs.begin(); attrIter != attrs.end(); ++ attrIter) attrList.push_back(QString::fromUtf8(attrIter->c_str())); std::sort(attrList.begin(), attrList.end()); d_ui->attributeComboBox->addItems(attrList); } bool StatisticsWindow::saveEnabled() const { if (d_model.isNull()) return false; if (d_model->rowCount(QModelIndex()) == 0) return false; return true; } void StatisticsWindow::readSettings() { QSettings settings; bool show = settings.value("query_show_percentage", true).toBool(); d_ui->percentageCheckBox->setChecked(show); // Window geometry. QPoint pos = settings.value("query_pos", QPoint(200, 200)).toPoint(); QSize size = settings.value("query_size", QSize(350, 400)).toSize(); resize(size); // Move. move(pos); } void StatisticsWindow::writeSettings() { QSettings settings; settings.setValue("query_show_percentage", d_ui->percentageCheckBox->isChecked()); // Window geometry settings.setValue("query_pos", pos()); settings.setValue("query_size", size()); } <commit_msg>Signal typo.<commit_after>#include <QClipboard> #include <QDateTime> #include <QDebug> #include <QFile> #include <QFileDialog> #include <QKeyEvent> #include <QLineEdit> #include <QMessageBox> #include <QPoint> #include <QSettings> #include <QSize> #include <QTextStream> #include <algorithm> #include <stdexcept> #include <typeinfo> #include "config.hh" #include "CorpusWidget.hh" #include "SimpleDTD.hh" #include "StatisticsWindow.hh" #include "Query.hh" #include "QueryModel.hh" #include "PercentageCellDelegate.hh" #include "ValidityColor.hh" #include "XPathValidator.hh" #include "XSLTransformer.hh" #include "ui_StatisticsWindow.h" StatisticsWindow::StatisticsWindow(QWidget *parent) : CorpusWidget(parent), d_ui(QSharedPointer<Ui::StatisticsWindow>(new Ui::StatisticsWindow)), d_percentageCellDelegate(new PercentageCellDelegate) { d_ui->setupUi(this); createActions(); readNodeAttributes(); readSettings(); // Pick a sane default attribute. int idx = d_ui->attributeComboBox->findText("word"); if (idx != -1) d_ui->attributeComboBox->setCurrentIndex(idx); } StatisticsWindow::~StatisticsWindow() { writeSettings(); } void StatisticsWindow::attributeChanged(int index) { Q_UNUSED(index); if (!d_model.isNull()) startQuery(); } void StatisticsWindow::queryFailed(QString error) { progressStopped(0, 0); QMessageBox::critical(this, tr("Error processing query"), tr("Could not process query: ") + error, QMessageBox::Ok); } void StatisticsWindow::switchCorpus(QSharedPointer<alpinocorpus::CorpusReader> corpusReader) { d_corpusReader = corpusReader; readNodeAttributes(); emit saveStateChanged(); //d_xpathValidator->setCorpusReader(d_corpusReader); setModel(new QueryModel(corpusReader)); // Ensure that percentage column is hidden when necessary. showPercentageChanged(); } void StatisticsWindow::setFilter(QString const &filter, QString const &raw_filter) { Q_UNUSED(raw_filter); d_filter = filter; startQuery(); } void StatisticsWindow::setAggregateAttribute(QString const &detail) { // @TODO: update d_ui->attributeComboBox.currentIndex when changed from outside // to reflect the current (changed) state of the window. } void StatisticsWindow::setModel(QueryModel *model) { d_model = QSharedPointer<QueryModel>(model); d_ui->resultsTable->setModel(d_model.data()); d_ui->distinctValuesLabel->setText(QString("")); d_ui->totalHitsLabel->setText(QString("")); connect(d_model.data(), SIGNAL(queryFailed(QString)), SLOT(queryFailed(QString))); connect(d_model.data(), SIGNAL(queryEntryFound(QString)), SLOT(updateResultsTotalCount())); connect(d_model.data(), SIGNAL(queryStarted(int)), SLOT(progressStarted(int))); connect(d_model.data(), SIGNAL(queryStopped(int, int)), SLOT(progressStopped(int, int))); connect(d_model.data(), SIGNAL(queryFinished(int, int, QString, QString, bool, bool)), SLOT(progressStopped(int, int))); connect(d_model.data(), SIGNAL(progressChanged(int)), SLOT(progressChanged(int))); } void StatisticsWindow::updateResultsTotalCount() { d_ui->totalHitsLabel->setText(QString("%L1").arg(d_model->totalHits())); d_ui->distinctValuesLabel->setText(QString("%L1").arg(d_model->rowCount(QModelIndex()))); } void StatisticsWindow::applyValidityColor(QString const &) { ::applyValidityColor(sender()); } void StatisticsWindow::cancelQuery() { if (d_model) d_model->cancelQuery(); } void StatisticsWindow::saveAs() { if (d_model.isNull()) return; int nlines = d_model->rowCount(QModelIndex()); if (nlines == 0) return; QString filename; QStringList filenames; QFileDialog fd(this, tr("Save"), QString("untitled"), tr("Microsoft Excel 2003 XML (*.xls);;Text (*.txt);;HTML (*.html *.htm);;CSV (*.csv)")); fd.setAcceptMode(QFileDialog::AcceptSave); fd.setConfirmOverwrite(true); fd.setLabelText(QFileDialog::Accept, tr("Save")); if (d_lastFilterChoice.size()) fd.selectNameFilter(d_lastFilterChoice); if (fd.exec()) filenames = fd.selectedFiles(); else return; if (filenames.size() < 1) return; filename = filenames[0]; if (! filename.length()) return; QSharedPointer<QFile> stylesheet; d_lastFilterChoice = fd.selectedNameFilter(); if (d_lastFilterChoice.contains("*.txt")) stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-text.xsl")); else if (d_lastFilterChoice.contains("*.html")) stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-html.xsl")); else if (d_lastFilterChoice.contains("*.xls")) stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-officexml.xsl")); else stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-csv.xsl")); QFile data(filename); if (!data.open(QFile::WriteOnly | QFile::Truncate)) { QMessageBox::critical(this, tr("Save file error"), tr("Cannot save file %1 (error code %2)").arg(filename).arg(data.error()), QMessageBox::Ok); return; } QTextStream out(&data); out.setCodec("UTF-8"); QString xmlStats = d_model->asXML(); XSLTransformer trans(stylesheet.data()); out << trans.transform(xmlStats); emit statusMessage(tr("File saved as %1").arg(filename)); } void StatisticsWindow::copy() { QString csv; QTextStream textstream(&csv, QIODevice::WriteOnly | QIODevice::Text); selectionAsCSV(textstream, "\t"); if (!csv.isEmpty()) QApplication::clipboard()->setText(csv); } void StatisticsWindow::exportSelection() { QString filename(QFileDialog::getSaveFileName(this, "Export selection", QString(), "*.csv")); if (filename.isNull()) return; QFile file(filename); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::critical(this, tr("Error exporting selection"), tr("Could open file for writing."), QMessageBox::Ok); return; } QTextStream textstream(&file); textstream.setGenerateByteOrderMark(true); selectionAsCSV(textstream, ";", true); } void StatisticsWindow::createActions() { // @TODO: move this non action related ui code to somewhere else. The .ui file preferably. // Requires initialized UI. //d_ui->resultsTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch); d_ui->resultsTable->verticalHeader()->hide(); d_ui->resultsTable->sortByColumn(1, Qt::DescendingOrder); d_ui->resultsTable->setItemDelegateForColumn(2, d_percentageCellDelegate.data()); // Only allow valid xpath queries to be submitted //d_ui->filterLineEdit->setValidator(d_xpathValidator.data()); // When a row is activated, generate a query to be used in the main window to // filter all the results so only the results which are accumulated in this // row will be shown. connect(d_ui->resultsTable, SIGNAL(activated(QModelIndex const &)), SLOT(generateQuery(QModelIndex const &))); // Toggle percentage column checkbox (is this needed?) connect(d_ui->percentageCheckBox, SIGNAL(toggled(bool)), SLOT(showPercentageChanged())); connect(d_ui->yieldCheckBox, SIGNAL(toggled(bool)), SLOT(showYieldChanged())); connect(d_ui->attributeComboBox, SIGNAL(currentIndexChanged(int)), SLOT(attributeChanged(int))); } void StatisticsWindow::generateQuery(QModelIndex const &index) { // We are not able to generate a query (yet) for yield items. // I guess such queries become really long and tedious. if (d_ui->yieldCheckBox->isChecked()) return; // Get the text from the first column, that is the found value QString data = index.sibling(index.row(), 0).data(Qt::UserRole).toString(); if (data == MISSING_ATTRIBUTE) return; QString query = ::generateQuery( d_filter, d_ui->attributeComboBox->currentText(), data); emit entryActivated(data, query); } void StatisticsWindow::selectionAsCSV(QTextStream &output, QString const &separator, bool escape_quotes) const { // If there is no model attached (e.g. no corpus loaded) do nothing if (!d_model) return; QModelIndexList rows = d_ui->resultsTable->selectionModel()->selectedRows(); // If there is nothing selected, do nothing if (rows.isEmpty()) return; foreach (QModelIndex const &row, rows) { // This only works if the selection behavior is SelectRows if (escape_quotes) output << '"' << d_model->data(row).toString().replace("\"", "\"\"") << '"'; // value else output << d_model->data(row).toString(); output << separator << d_model->data(row.sibling(row.row(), 1)).toString() // count << '\n'; } } void StatisticsWindow::startQuery() { setAggregateAttribute(d_ui->attributeComboBox->currentText()); d_ui->resultsTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch); d_ui->resultsTable->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents); d_ui->resultsTable->horizontalHeader()->setResizeMode(2, QHeaderView::Stretch); d_ui->totalHitsLabel->clear(); d_ui->distinctValuesLabel->clear(); bool yield = d_ui->yieldCheckBox->isChecked(); d_model->runQuery(d_filter, d_ui->attributeComboBox->currentText(), yield); emit saveStateChanged(); } void StatisticsWindow::showPercentageChanged() { d_ui->resultsTable->setColumnHidden(2, !d_ui->percentageCheckBox->isChecked()); } void StatisticsWindow::showYieldChanged() { if (!d_model.isNull()) startQuery(); } void StatisticsWindow::progressStarted(int total) { d_ui->filterProgress->setMaximum(total); d_ui->filterProgress->setDisabled(false); d_ui->filterProgress->setVisible(true); } void StatisticsWindow::progressChanged(int percentage) { d_ui->filterProgress->setValue(percentage); } void StatisticsWindow::progressStopped(int n, int total) { updateResultsTotalCount(); d_ui->filterProgress->setVisible(false); emit saveStateChanged(); } void StatisticsWindow::closeEvent(QCloseEvent *event) { writeSettings(); event->accept(); } void StatisticsWindow::readNodeAttributes() { QString dtdPath = (d_corpusReader && d_corpusReader->type() == "tueba_tree") ? ":/dtd/tueba_tree.dtd" : ":/dtd/alpino_ds.dtd"; // XXX - hardcode? QFile dtdFile(dtdPath); if (!dtdFile.open(QFile::ReadOnly)) { qWarning() << "StatisticsWindow::readNodeAttributes(): Could not read DTD."; return; } QByteArray dtdData(dtdFile.readAll()); SimpleDTD sDTD(dtdData.constData()); // Should be safe to clear items now... d_ui->attributeComboBox->clear(); // Do we have a node element? ElementMap::const_iterator iter = sDTD.elementMap().find("node"); if (iter == sDTD.elementMap().end()) return; std::set<std::string> attrs = iter->second; QStringList attrList; for (std::set<std::string>::const_iterator attrIter = attrs.begin(); attrIter != attrs.end(); ++ attrIter) attrList.push_back(QString::fromUtf8(attrIter->c_str())); std::sort(attrList.begin(), attrList.end()); d_ui->attributeComboBox->addItems(attrList); } bool StatisticsWindow::saveEnabled() const { if (d_model.isNull()) return false; if (d_model->rowCount(QModelIndex()) == 0) return false; return true; } void StatisticsWindow::readSettings() { QSettings settings; bool show = settings.value("query_show_percentage", true).toBool(); d_ui->percentageCheckBox->setChecked(show); // Window geometry. QPoint pos = settings.value("query_pos", QPoint(200, 200)).toPoint(); QSize size = settings.value("query_size", QSize(350, 400)).toSize(); resize(size); // Move. move(pos); } void StatisticsWindow::writeSettings() { QSettings settings; settings.setValue("query_show_percentage", d_ui->percentageCheckBox->isChecked()); // Window geometry settings.setValue("query_pos", pos()); settings.setValue("query_size", size()); } <|endoftext|>
<commit_before>// Copyright 2013 Sean McKenna // // 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. // // a ray tracer in C++ // libraries, namespace #include <iostream> #include <fstream> using namespace std; // output an 8-bit array (256 colors) as an RGB image in ASCII PPM format bool outputImage(const char *file, int w, int h, int img[][3]){ ofstream f; f.open(file); // if error writing to file if(!f) return false; // otherwise, output the image f << "P3\n" << w << " " << h << "\n255\n"; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ for(int k = 0; k < 3; k++){ int pt = i * w + j; f << img[pt][k] << " "; } } f << "\n"; } f.close(); return true; } // ray tracer int main(){ int w = 400; int h = 200; int img[h * w][3]; for(int i = 0; i < (h * w); i++){ int val = ((float) i / (w * h)) * 256.0; for(int k = 0; k < 3; k++){ img[i][k] = val; } } outputImage("image.ppm", w, h, img); } <commit_msg>prepare ray tracer to start inputting data<commit_after>// Copyright 2013 Sean McKenna // // 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. // // a ray tracer in C++ // libraries, namespace #include <fstream> using namespace std; // output an 8-bit array (256 colors) as an RGB image in ASCII PPM format bool outputImage(const char *file, int w, int h, int img[][3]){ ofstream f; f.open(file); // if error writing to file if(!f) return false; // otherwise, output the image f << "P3\n" << w << " " << h << "\n255\n"; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ for(int k = 0; k < 3; k++){ int pt = i * w + j; f << img[pt][k] << " "; } } f << "\n"; } f.close(); return true; } // ray tracer int main(){ // initialize image variables int w = 400; int h = 200; int img[h * w][3]; // output ray-traced image //outputImage("image.ppm", w, h, img); } <|endoftext|>
<commit_before>#ifndef COBALT_COM_ERROR_HPP_INCLUDED #define COBALT_COM_ERROR_HPP_INCLUDED #pragma once #include <system_error> #include <cstdio> // Functions in this file: // get_last_error // set_last_error namespace cobalt { namespace com { enum class errc { success = 0, failure, no_such_interface, no_such_class, aggregation_not_supported, class_disabled, not_implemented }; namespace detail { class com_error_category : public std::error_category { public: virtual const char* name() const noexcept override { return "com"; } virtual std::string message(int ev) const override { switch (static_cast<errc>(ev)) { case errc::success: return "operation succeeded"; case errc::failure: return "operation failed"; case errc::no_such_interface: return "no such interface"; case errc::no_such_class: return "no such class"; case errc::aggregation_not_supported: return "aggregation not supported"; case errc::class_disabled: return "class disabled"; case errc::not_implemented: return "not implemented"; } char buffer[32]; std::snprintf(buffer, sizeof(buffer), "unknown error: 0x%X", ev); return buffer; } }; } // namespace detail inline const std::error_category& com_category() noexcept { static detail::com_error_category instance; return instance; } inline std::error_code make_error_code(errc e) noexcept { return std::error_code{static_cast<int>(e), com_category()}; } inline std::error_condition make_error_condition(errc e) noexcept { return std::error_condition{static_cast<int>(e), com_category()}; } } // namespace com } // namespace cobalt namespace std { template <> struct is_error_condition_enum<::cobalt::com::errc> : true_type {}; } #endif // COBALT_COM_ERROR_HPP_INCLUDED <commit_msg>Optimized obtaining error category instance.<commit_after>#ifndef COBALT_COM_ERROR_HPP_INCLUDED #define COBALT_COM_ERROR_HPP_INCLUDED #pragma once #include <system_error> #include <cstdio> namespace cobalt { namespace com { enum class errc { success = 0, failure, no_such_interface, no_such_class, aggregation_not_supported, class_disabled, not_implemented }; namespace detail { class com_error_category : public std::error_category { public: virtual const char* name() const noexcept override { return "com"; } virtual std::string message(int ev) const override { switch (static_cast<errc>(ev)) { case errc::success: return "operation succeeded"; case errc::failure: return "operation failed"; case errc::no_such_interface: return "no such interface"; case errc::no_such_class: return "no such class"; case errc::aggregation_not_supported: return "aggregation not supported"; case errc::class_disabled: return "class disabled"; case errc::not_implemented: return "not implemented"; } char buffer[32]; std::snprintf(buffer, sizeof(buffer), "unknown error: 0x%X", ev); return buffer; } }; struct com_error_category_helper { inline static com_error_category instance; }; } // namespace detail inline const std::error_category& com_category() noexcept { return detail::com_error_category_helper::instance; } inline std::error_code make_error_code(errc e) noexcept { return std::error_code{static_cast<int>(e), com_category()}; } inline std::error_condition make_error_condition(errc e) noexcept { return std::error_condition{static_cast<int>(e), com_category()}; } } // namespace com } // namespace cobalt namespace std { template <> struct is_error_condition_enum<::cobalt::com::errc> : true_type {}; } #endif // COBALT_COM_ERROR_HPP_INCLUDED <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once namespace etl { /*! * \copydoc etl::lu */ template <typename AT, typename LT, typename UT, typename PT> bool lu(const AT& A, LT& L, UT& U, PT& P); namespace impl { namespace standard { /*! * \brief Compute inv(a) and store the result in c * \param a The input expression * \param c The output expression */ template <typename A, typename C> void inv(A&& a, C&& c) { // The inverse of a permutation matrix is its transpose if(is_permutation_matrix(a)){ c = etl::transpose(a); return; } const auto n = etl::dim<0>(a); // Use forward propagation for lower triangular matrix if(is_lower_triangular(a)){ c = 0; // The column in c for (std::size_t s = 0; s < n; ++s) { // The row in a for (std::size_t row = 0; row < n; ++row) { auto b = row == s ? 1.0 : 0.0; if (row == 0) { c(0, s) = b / a(0, 0); } else { value_t<A> acc(0); // The column in a for (std::size_t col = 0; col < row; ++col) { acc += a(row, col) * c(col, s); } c(row, s) = (b - acc) / a(row, row); } } } return; } // Use backward propagation for upper triangular matrix if(is_upper_triangular(a)){ c = 0; // The column in c for (long s = n - 1; s >= 0; --s) { // The row in a for (long row = n - 1; row >= 0; --row) { auto b = row == s ? 1.0 : 0.0; if (row == long(n) - 1) { c(row, s) = b / a(row, row); } else { value_t<A> acc(0); // The column in a for (long col = n - 1; col > row; --col) { acc += a(row, col) * c(col, s); } c(row, s) = (b - acc) / a(row, row); } } } return; } auto L = force_temporary_dim_only(a); auto U = force_temporary_dim_only(a); auto P = force_temporary_dim_only(a); etl::lu(a, L, U, P); c = inv(U) * inv(L) * P; } } //end of namespace standard } //end of namespace impl } //end of namespace etl <commit_msg>Use portable types<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once namespace etl { /*! * \copydoc etl::lu */ template <typename AT, typename LT, typename UT, typename PT> bool lu(const AT& A, LT& L, UT& U, PT& P); namespace impl { namespace standard { /*! * \brief Compute inv(a) and store the result in c * \param a The input expression * \param c The output expression */ template <typename A, typename C> void inv(A&& a, C&& c) { // The inverse of a permutation matrix is its transpose if(is_permutation_matrix(a)){ c = etl::transpose(a); return; } const auto n = etl::dim<0>(a); // Use forward propagation for lower triangular matrix if(is_lower_triangular(a)){ c = 0; // The column in c for (std::size_t s = 0; s < n; ++s) { // The row in a for (std::size_t row = 0; row < n; ++row) { auto b = row == s ? 1.0 : 0.0; if (row == 0) { c(0, s) = b / a(0, 0); } else { value_t<A> acc(0); // The column in a for (std::size_t col = 0; col < row; ++col) { acc += a(row, col) * c(col, s); } c(row, s) = (b - acc) / a(row, row); } } } return; } // Use backward propagation for upper triangular matrix if(is_upper_triangular(a)){ c = 0; // The column in c for (int64_t s = n - 1; s >= 0; --s) { // The row in a for (int64_t row = n - 1; row >= 0; --row) { auto b = row == s ? 1.0 : 0.0; if (row == int64_t(n) - 1) { c(row, s) = b / a(row, row); } else { value_t<A> acc(0); // The column in a for (int64_t col = n - 1; col > row; --col) { acc += a(row, col) * c(col, s); } c(row, s) = (b - acc) / a(row, row); } } } return; } auto L = force_temporary_dim_only(a); auto U = force_temporary_dim_only(a); auto P = force_temporary_dim_only(a); etl::lu(a, L, U, P); c = inv(U) * inv(L) * P; } } //end of namespace standard } //end of namespace impl } //end of namespace etl <|endoftext|>
<commit_before>#ifndef IZENELIB_IR_ZAMBEZI_UTILS_HPP #define IZENELIB_IR_ZAMBEZI_UTILS_HPP #include "Consts.hpp" #include <cmath> #include <cstdlib> NS_IZENELIB_IR_BEGIN namespace Zambezi { // Operators defined based on whether or not the postings are backwards #define LESS_THAN(X,Y,R) (R == 0 ? (X < Y) : (X > Y)) #define LESS_THAN_EQUAL(X,Y,R) (R == 0 ? (X <= Y) : (X >= Y)) #define GREATER_THAN(X,Y,R) (R == 0 ? (X > Y) : (X < Y)) #define GREATER_THAN_EQUAL(X,Y,R) (R == 0 ? (X >= Y) : (X <= Y)) // Functions to encode/decode segment and offset values #define DECODE_SEGMENT(P) (uint32_t((P) >> 32)) #define DECODE_OFFSET(P) (uint32_t((P) & 0xFFFFFFFF)) #define ENCODE_POINTER(S, O) (size_t(S) << 32 | (O)) // Jenkin's integer hash function inline uint32_t hash(uint32_t val, uint32_t seed) { val = val + seed + (val << 12); val = val ^ 0xc761c23c ^ (val >> 19); val = val + 0x165667b1 + (val << 5); val = (val + 0xd3a2646c) ^ (val << 9); val = val + 0xfd7046c5 + (val << 3); return val ^ 0xb55a4f09 ^ (val >> 16); } inline float idf(uint32_t numDocs, uint32_t df) { return logf((0.5f + numDocs - df) / (0.5f + df)); } inline float default_bm25tf(uint32_t tf, uint32_t docLen, float avgDocLen) { return (1.0f + DEFAULT_K1) * tf / (DEFAULT_K1 * (1.0f - DEFAULT_B + DEFAULT_B * docLen / avgDocLen) + tf); } inline float default_bm25(uint32_t tf, uint32_t df, uint32_t numDocs, uint32_t docLen, float avgDocLen) { return default_bm25tf(tf, docLen, avgDocLen) * idf(numDocs, df); } inline uint32_t* getAlignedIntArray(size_t size) { uint32_t* block; if (posix_memalign((void**)&block, 0x200000LU, size * sizeof(uint32_t))) block = (uint32_t*)malloc(size * sizeof(uint32_t)); return block; } } NS_IZENELIB_IR_END #endif <commit_msg>fix data inconsistency<commit_after>#ifndef IZENELIB_IR_ZAMBEZI_UTILS_HPP #define IZENELIB_IR_ZAMBEZI_UTILS_HPP #include "Consts.hpp" #include <cmath> #include <cstdlib> NS_IZENELIB_IR_BEGIN namespace Zambezi { // Operators defined based on whether or not the postings are backwards #define LESS_THAN(X,Y,R) (R == 0 ? (X < Y) : (X > Y)) #define LESS_THAN_EQUAL(X,Y,R) (R == 0 ? (X <= Y) : (X >= Y)) #define GREATER_THAN(X,Y,R) (R == 0 ? (X > Y) : (X < Y)) #define GREATER_THAN_EQUAL(X,Y,R) (R == 0 ? (X >= Y) : (X <= Y)) // Functions to encode/decode segment and offset values #define DECODE_SEGMENT(P) (uint32_t((P) >> 32)) #define DECODE_OFFSET(P) (uint32_t((P) & 0xFFFFFFFF)) #define ENCODE_POINTER(S, O) (size_t(S) << 32 | (O)) // Jenkin's integer hash function inline uint32_t hash(uint32_t val, uint32_t seed) { val = val + seed + (val << 12); val = val ^ 0xc761c23c ^ (val >> 19); val = val + 0x165667b1 + (val << 5); val = (val + 0xd3a2646c) ^ (val << 9); val = val + 0xfd7046c5 + (val << 3); return val ^ 0xb55a4f09 ^ (val >> 16); } inline float idf(uint32_t numDocs, uint32_t df) { return logf((0.5f + numDocs - df) / (0.5f + df)); } inline float default_bm25tf(uint32_t tf, uint32_t docLen, float avgDocLen) { return (1.0f + DEFAULT_K1) * tf / (DEFAULT_K1 * (1.0f - DEFAULT_B + DEFAULT_B * docLen / avgDocLen) + tf); } inline float default_bm25(uint32_t tf, uint32_t df, uint32_t numDocs, uint32_t docLen, float avgDocLen) { return default_bm25tf(tf, docLen, avgDocLen) * idf(numDocs, df); } inline uint32_t* getAlignedIntArray(size_t size) { uint32_t* block; if (posix_memalign((void**)&block, 0x200000LU, size * sizeof(uint32_t))) block = (uint32_t*)malloc(size * sizeof(uint32_t)); memset(block, 0, size * sizeof(uint32_t)); return block; } } NS_IZENELIB_IR_END #endif <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DEBUG_HPP_INCLUDED #define TORRENT_DEBUG_HPP_INCLUDED #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING #include <string> #include "libtorrent/config.hpp" #include "libtorrent/file.hpp" #include "libtorrent/thread.hpp" #if TORRENT_USE_IOSTREAM #include <fstream> #include <iostream> #endif namespace libtorrent { // DEBUG API struct logger { #if TORRENT_USE_IOSTREAM // all log streams share a single file descriptor // and re-opens the file for each log line // these members are defined in session_impl.cpp static std::ofstream log_file; static std::string open_filename; static mutex file_mutex; #endif logger(std::string const& logpath, std::string const& filename , int instance, bool append) { char log_name[512]; snprintf(log_name, sizeof(log_name), "libtorrent_logs%d", instance); std::string dir(complete(combine_path(logpath, log_name))); error_code ec; if (!exists(dir)) create_directories(dir, ec); m_filename = combine_path(dir, filename); m_truncate = !append; *this << "\n\n\n*** starting log ***\n"; } #if TORRENT_USE_IOSTREAM void open() { if (open_filename == m_filename) return; log_file.close(); log_file.clear(); log_file.open(m_filename.c_str(), m_truncate ? std::ios_base::trunc : std::ios_base::app); open_filename = m_filename; m_truncate = false; if (!log_file.good()) fprintf(stderr, "Failed to open logfile %s: %s\n", m_filename.c_str(), strerror(errno)); } #endif template <class T> logger& operator<<(T const& v) { #if TORRENT_USE_IOSTREAM mutex::scoped_lock l(file_mutex); open(); log_file << v; log_file.flush(); #endif return *this; } std::string m_filename; bool m_truncate; }; } #endif // TORRENT_VERBOSE_LOGGING || TORRENT_LOGGING || TORRENT_ERROR_LOGGING #endif // TORRENT_DEBUG_HPP_INCLUDED <commit_msg>don't flush every string printed to the log<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DEBUG_HPP_INCLUDED #define TORRENT_DEBUG_HPP_INCLUDED #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING #include <string> #include "libtorrent/config.hpp" #include "libtorrent/file.hpp" #include "libtorrent/thread.hpp" #if TORRENT_USE_IOSTREAM #include <fstream> #include <iostream> #endif namespace libtorrent { // DEBUG API struct logger { #if TORRENT_USE_IOSTREAM // all log streams share a single file descriptor // and re-opens the file for each log line // these members are defined in session_impl.cpp static std::ofstream log_file; static std::string open_filename; static mutex file_mutex; #endif logger(std::string const& logpath, std::string const& filename , int instance, bool append) { char log_name[512]; snprintf(log_name, sizeof(log_name), "libtorrent_logs%d", instance); std::string dir(complete(combine_path(logpath, log_name))); error_code ec; if (!exists(dir)) create_directories(dir, ec); m_filename = combine_path(dir, filename); m_truncate = !append; *this << "\n\n\n*** starting log ***\n"; } #if TORRENT_USE_IOSTREAM void open() { if (open_filename == m_filename) return; log_file.close(); log_file.clear(); log_file.open(m_filename.c_str(), m_truncate ? std::ios_base::trunc : std::ios_base::app); open_filename = m_filename; m_truncate = false; if (!log_file.good()) fprintf(stderr, "Failed to open logfile %s: %s\n", m_filename.c_str(), strerror(errno)); } #endif template <class T> logger& operator<<(T const& v) { #if TORRENT_USE_IOSTREAM mutex::scoped_lock l(file_mutex); open(); log_file << v; #endif return *this; } std::string m_filename; bool m_truncate; }; } #endif // TORRENT_VERBOSE_LOGGING || TORRENT_LOGGING || TORRENT_ERROR_LOGGING #endif // TORRENT_DEBUG_HPP_INCLUDED <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_GEOM_UTIL_HPP #define MAPNIK_GEOM_UTIL_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/vertex.hpp> // boost #include <boost/tuple/tuple.hpp> // stl #include <cmath> namespace mapnik { template <typename T> bool clip_test(T p,T q,double& tmin,double& tmax) { double r; bool result=true; if (p<0.0) { r=q/p; if (r>tmax) result=false; else if (r>tmin) tmin=r; } else if (p>0.0) { r=q/p; if (r<tmin) result=false; else if (r<tmax) tmax=r; } else if (q<0.0) result=false; return result; } template <typename T,typename Image> bool clip_line(T& x0,T& y0,T& x1,T& y1,box2d<T> const& box) { double tmin=0.0; double tmax=1.0; double dx=x1-x0; if (clip_test<double>(-dx,x0,tmin,tmax)) { if (clip_test<double>(dx,box.width()-x0,tmin,tmax)) { double dy=y1-y0; if (clip_test<double>(-dy,y0,tmin,tmax)) { if (clip_test<double>(dy,box.height()-y0,tmin,tmax)) { if (tmax<1.0) { x1=static_cast<T>(x0+tmax*dx); y1=static_cast<T>(y0+tmax*dy); } if (tmin>0.0) { x0+=static_cast<T>(tmin*dx); y0+=static_cast<T>(tmin*dy); } return true; } } } } return false; } template <typename Iter> inline bool point_inside_path(double x,double y,Iter start,Iter end) { bool inside=false; double x0=boost::get<0>(*start); double y0=boost::get<1>(*start); double x1,y1; while (++start!=end) { if ( boost::get<2>(*start) == SEG_MOVETO) { x0 = boost::get<0>(*start); y0 = boost::get<1>(*start); continue; } x1=boost::get<0>(*start); y1=boost::get<1>(*start); if ((((y1 <= y) && (y < y0)) || ((y0 <= y) && (y < y1))) && ( x < (x0 - x1) * (y - y1)/ (y0 - y1) + x1)) inside=!inside; x0=x1; y0=y1; } return inside; } inline bool point_in_circle(double x,double y,double cx,double cy,double r) { double dx = x - cx; double dy = y - cy; double d2 = dx * dx + dy * dy; return (d2 <= r * r); } template <typename T> inline T sqr(T x) { return x * x; } inline double distance2(double x0,double y0,double x1,double y1) { double dx = x1 - x0; double dy = y1 - y0; return sqr(dx) + sqr(dy); } inline double distance(double x0,double y0, double x1,double y1) { return std::sqrt(distance2(x0,y0,x1,y1)); } inline double point_to_segment_distance(double x, double y, double ax, double ay, double bx, double by) { double len2 = distance2(ax,ay,bx,by); if (len2 < 1e-14) { return distance(x,y,ax,ay); } double r = ((x - ax)*(bx - ax) + (y - ay)*(by -ay))/len2; if ( r < 0 ) { return distance(x,y,ax,ay); } else if (r > 1) { return distance(x,y,bx,by); } double s = ((ay - y)*(bx - ax) - (ax - x)*(by - ay))/len2; return std::fabs(s) * std::sqrt(len2); } template <typename Iter> inline bool point_on_path(double x,double y,Iter start,Iter end, double tol) { double x0=boost::get<0>(*start); double y0=boost::get<1>(*start); double x1,y1; while (++start != end) { if ( boost::get<2>(*start) == SEG_MOVETO) { x0 = boost::get<0>(*start); y0 = boost::get<1>(*start); continue; } x1=boost::get<0>(*start); y1=boost::get<1>(*start); double distance = point_to_segment_distance(x,y,x0,y0,x1,y1); if (distance < tol) return true; x0=x1; y0=y1; } return false; } // filters struct filter_in_box { box2d<double> box_; explicit filter_in_box(const box2d<double>& box) : box_(box) {} bool pass(const box2d<double>& extent) const { return extent.intersects(box_); } }; struct filter_at_point { coord2d pt_; explicit filter_at_point(const coord2d& pt) : pt_(pt) {} bool pass(const box2d<double>& extent) const { return extent.contains(pt_); } }; } #endif // MAPNIK_GEOM_UTIL_HPP <commit_msg>+ add VertexSource based implementations of label position algos<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_GEOM_UTIL_HPP #define MAPNIK_GEOM_UTIL_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/vertex.hpp> // boost #include <boost/tuple/tuple.hpp> // stl #include <cmath> #include <vector> namespace mapnik { template <typename T> bool clip_test(T p,T q,double& tmin,double& tmax) { double r; bool result=true; if (p<0.0) { r=q/p; if (r>tmax) result=false; else if (r>tmin) tmin=r; } else if (p>0.0) { r=q/p; if (r<tmin) result=false; else if (r<tmax) tmax=r; } else if (q<0.0) result=false; return result; } template <typename T,typename Image> bool clip_line(T& x0,T& y0,T& x1,T& y1,box2d<T> const& box) { double tmin=0.0; double tmax=1.0; double dx=x1-x0; if (clip_test<double>(-dx,x0,tmin,tmax)) { if (clip_test<double>(dx,box.width()-x0,tmin,tmax)) { double dy=y1-y0; if (clip_test<double>(-dy,y0,tmin,tmax)) { if (clip_test<double>(dy,box.height()-y0,tmin,tmax)) { if (tmax<1.0) { x1=static_cast<T>(x0+tmax*dx); y1=static_cast<T>(y0+tmax*dy); } if (tmin>0.0) { x0+=static_cast<T>(tmin*dx); y0+=static_cast<T>(tmin*dy); } return true; } } } } return false; } template <typename Iter> inline bool point_inside_path(double x,double y,Iter start,Iter end) { bool inside=false; double x0=boost::get<0>(*start); double y0=boost::get<1>(*start); double x1,y1; while (++start!=end) { if ( boost::get<2>(*start) == SEG_MOVETO) { x0 = boost::get<0>(*start); y0 = boost::get<1>(*start); continue; } x1=boost::get<0>(*start); y1=boost::get<1>(*start); if ((((y1 <= y) && (y < y0)) || ((y0 <= y) && (y < y1))) && ( x < (x0 - x1) * (y - y1)/ (y0 - y1) + x1)) inside=!inside; x0=x1; y0=y1; } return inside; } inline bool point_in_circle(double x,double y,double cx,double cy,double r) { double dx = x - cx; double dy = y - cy; double d2 = dx * dx + dy * dy; return (d2 <= r * r); } template <typename T> inline T sqr(T x) { return x * x; } inline double distance2(double x0,double y0,double x1,double y1) { double dx = x1 - x0; double dy = y1 - y0; return sqr(dx) + sqr(dy); } inline double distance(double x0,double y0, double x1,double y1) { return std::sqrt(distance2(x0,y0,x1,y1)); } inline double point_to_segment_distance(double x, double y, double ax, double ay, double bx, double by) { double len2 = distance2(ax,ay,bx,by); if (len2 < 1e-14) { return distance(x,y,ax,ay); } double r = ((x - ax)*(bx - ax) + (y - ay)*(by -ay))/len2; if ( r < 0 ) { return distance(x,y,ax,ay); } else if (r > 1) { return distance(x,y,bx,by); } double s = ((ay - y)*(bx - ax) - (ax - x)*(by - ay))/len2; return std::fabs(s) * std::sqrt(len2); } template <typename Iter> inline bool point_on_path(double x,double y,Iter start,Iter end, double tol) { double x0=boost::get<0>(*start); double y0=boost::get<1>(*start); double x1,y1; while (++start != end) { if ( boost::get<2>(*start) == SEG_MOVETO) { x0 = boost::get<0>(*start); y0 = boost::get<1>(*start); continue; } x1=boost::get<0>(*start); y1=boost::get<1>(*start); double distance = point_to_segment_distance(x,y,x0,y0,x1,y1); if (distance < tol) return true; x0=x1; y0=y1; } return false; } // filters struct filter_in_box { box2d<double> box_; explicit filter_in_box(const box2d<double>& box) : box_(box) {} bool pass(const box2d<double>& extent) const { return extent.intersects(box_); } }; struct filter_at_point { coord2d pt_; explicit filter_at_point(const coord2d& pt) : pt_(pt) {} bool pass(const box2d<double>& extent) const { return extent.contains(pt_); } }; //////////////////////////////////////////////////////////////////////////// template <typename PathType> double path_length(PathType & path) { double x0,y0,x1,y1; path.rewind(0); unsigned command = path.vertex(&x0,&y0); if (command == SEG_END) return 0; double length = 0; while (SEG_END != (command = path.vertex(&x1, &y1))) { length += distance(x0,y0,x1,y1); x0 = x1; y0 = y1; } return length; } template <typename PathType> bool middle_point(PathType & path, double & x, double & y) { double x0,y0,x1,y1; double mid_length = 0.5 * path_length(path); path.rewind(0); unsigned command = path.vertex(&x0,&y0); if (command == SEG_END) return false; double dist = 0.0; while (SEG_END != (command = path.vertex(&x1, &y1))) { double seg_length = distance(x0, y0, x1, y1); if ( dist + seg_length >= mid_length) { double r = (mid_length - dist)/seg_length; x = x0 + (x1 - x0) * r; y = y0 + (y1 - y0) * r; break; } dist += seg_length; x0 = x1; y0 = y1; } return true; } template <typename PathType> bool centroid(PathType & path, double & x, double & y) { double x0; double y0; double x1; double y1; double start_x; double start_y; path.rewind(0); unsigned command = path.vertex(&x0, &y0); if (command == SEG_END) return false; start_x = x0; start_y = y0; double atmp = 0; double xtmp = 0; double ytmp = 0; while (SEG_END != (command = path.vertex(&x1, &y1))) { double dx0 = x0 - start_x; double dy0 = y0 - start_y; double dx1 = x1 - start_x; double dy1 = y1 - start_y; double ai = dx0 * dy1 - dx1 * dy0; atmp += ai; xtmp += (dx1 + dx0) * ai; ytmp += (dy1 + dy0) * ai; x0 = x1; y0 = y1; } if (atmp != 0) { x = (xtmp/(3*atmp)) + start_x; y = (ytmp/(3*atmp)) + start_y; } else { x = x0; y = y0; } return true; } template <typename PathType> bool hit_test(PathType & path, double x, double y, double tol) { bool inside=false; double x0, y0, x1, y1; path.rewind(0); unsigned command = path.vertex(&x0, &y0); if (command == SEG_END) return false; unsigned count = 0; while (SEG_END != (command = path.vertex(&x1, &y1))) { ++count; if (command == SEG_MOVETO) { x0 = x1; y0 = y1; continue; } if ((((y1 <= y) && (y < y0)) || ((y0 <= y) && (y < y1))) && (x < (x0 - x1) * (y - y1)/ (y0 - y1) + x1)) inside=!inside; x0 = x1; y0 = y1; } if (count == 0) // one vertex { return distance(x, y, x0, y0) <= fabs(tol); } return inside; } template <typename PathType> void label_interior_position(PathType & path, double & x, double & y) { // start with the centroid centroid(path, x,y); // if we are not a polygon, or the default is within the polygon we are done if (hit_test(path,x,y,0.001)) return; // otherwise we find a horizontal line across the polygon and then return the // center of the widest intersection between the polygon and the line. std::vector<double> intersections; // only need to store the X as we know the y double x0; double y0; path.rewind(0); unsigned command = path.vertex(&x0, &y0); double x1,y1; while (SEG_END != (command = path.vertex(&x1, &y1))) { if (command != SEG_MOVETO) { // if the segments overlap if (y0==y1) { if (y0==y) { double xi = (x0+x1)/2.0; intersections.push_back(xi); } } // if the path segment crosses the bisector else if ((y0 <= y && y1 >= y) || (y0 >= y && y1 <= y)) { // then calculate the intersection double xi = x0; if (x0 != x1) { double m = (y1-y0)/(x1-x0); double c = y0 - m*x0; xi = (y-c)/m; } intersections.push_back(xi); } } x0 = x1; y0 = y1; } // no intersections we just return the default if (intersections.empty()) return; x0=intersections[0]; double max_width = 0; for (unsigned ii = 1; ii < intersections.size(); ++ii) { double x1=intersections[ii]; double xc=(x0+x1)/2.0; double width = std::fabs(x1-x0); if (width > max_width && hit_test(path,xc,y,0)) { x=xc; max_width = width; break; } } } } #endif // MAPNIK_GEOM_UTIL_HPP <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <guido.tack@monash.edu> */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef __MINIZINC_EVAL_PAR_HH__ #define __MINIZINC_EVAL_PAR_HH__ #include <minizinc/model.hh> #include <minizinc/iter.hh> namespace MiniZinc { IntVal eval_int(Expression* e); bool eval_bool(Expression* e); void eval_int(Model* m); ArrayLit* eval_array_lit(Expression* e); Expression* eval_arrayaccess(ArrayLit* a, const std::vector<IntVal>& dims); IntSetVal* eval_intset(Expression* e); Expression* eval_par(Expression* e); template<class Eval> void eval_comp(Eval& eval, Comprehension* e, int gen, int id, IntSetVal* in, std::vector<typename Eval::ArrayVal>& a); template<class Eval> void eval_comp(Eval& eval, Comprehension* e, int gen, int id, int i, IntSetVal* in, std::vector<typename Eval::ArrayVal>& a) { e->_g[e->_g_idx[gen]+id+1]->cast<IntLit>()->_v = i; if (id == e->_g_idx[gen+1]-1) { if (gen == e->_g_idx.size()-1) { bool where = true; if (e->_where != NULL) { where = eval_bool(e->_where); } if (where) { a.push_back(eval.e(e->_e)); } } else { IntSetVal* nextin = eval_intset(e->_g[e->_g_idx[gen+1]]); eval_comp<Eval>(eval,e,gen+1,0,nextin,a); } } else { eval_comp<Eval>(eval,e,gen,id+1,in,a); } } template<class Eval> void eval_comp(Eval& eval, Comprehension* e, int gen, int id, IntSetVal* in, std::vector<typename Eval::ArrayVal>& a) { IntSetRanges rsi(in); Ranges::ToValues<IntSetRanges> rsv(rsi); for (; rsv(); ++rsv) { eval_comp<Eval>(eval,e,gen,id,rsv.val(),in,a); } } template<class Eval> std::vector<typename Eval::ArrayVal> eval_comp(Eval& eval, Comprehension* e) { std::vector<typename Eval::ArrayVal> a; IntSetVal* in = eval_intset(e->_g[e->_g_idx[0]]); eval_comp<Eval>(eval,e,0,0,in,a); return a; } template<class Eval> std::vector<typename Eval::ArrayVal> eval_comp(Comprehension* e) { Eval eval; return eval_comp(eval,e); } } #endif <commit_msg>Some off by one bugs in eval_comp<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <guido.tack@monash.edu> */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef __MINIZINC_EVAL_PAR_HH__ #define __MINIZINC_EVAL_PAR_HH__ #include <minizinc/model.hh> #include <minizinc/iter.hh> namespace MiniZinc { IntVal eval_int(Expression* e); bool eval_bool(Expression* e); void eval_int(Model* m); ArrayLit* eval_array_lit(Expression* e); Expression* eval_arrayaccess(ArrayLit* a, const std::vector<IntVal>& dims); IntSetVal* eval_intset(Expression* e); Expression* eval_par(Expression* e); template<class Eval> void eval_comp(Eval& eval, Comprehension* e, int gen, int id, IntSetVal* in, std::vector<typename Eval::ArrayVal>& a); template<class Eval> void eval_comp(Eval& eval, Comprehension* e, int gen, int id, int i, IntSetVal* in, std::vector<typename Eval::ArrayVal>& a) { e->_g[e->_g_idx[gen]+id+1]->cast<VarDecl>()->_e->cast<IntLit>()->_v = i; if (e->_g_idx[gen]+id+1 == e->_g_idx[gen+1]-1) { if (gen == e->_g_idx.size()-2) { bool where = true; if (e->_where != NULL) { where = eval_bool(e->_where); } if (where) { a.push_back(eval.e(e->_e)); } } else { IntSetVal* nextin = eval_intset(e->_g[e->_g_idx[gen+1]]); eval_comp<Eval>(eval,e,gen+1,0,nextin,a); } } else { eval_comp<Eval>(eval,e,gen,id+1,in,a); } } template<class Eval> void eval_comp(Eval& eval, Comprehension* e, int gen, int id, IntSetVal* in, std::vector<typename Eval::ArrayVal>& a) { IntSetRanges rsi(in); Ranges::ToValues<IntSetRanges> rsv(rsi); for (; rsv(); ++rsv) { eval_comp<Eval>(eval,e,gen,id,rsv.val(),in,a); } } template<class Eval> std::vector<typename Eval::ArrayVal> eval_comp(Eval& eval, Comprehension* e) { std::vector<typename Eval::ArrayVal> a; IntSetVal* in = eval_intset(e->_g[e->_g_idx[0]]); eval_comp<Eval>(eval,e,0,0,in,a); return a; } template<class Eval> std::vector<typename Eval::ArrayVal> eval_comp(Comprehension* e) { Eval eval; return eval_comp(eval,e); } } #endif <|endoftext|>
<commit_before>/* * xtensor-fftw * * Copyright 2017 Patrick Bos * * 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 XTENSOR_FFTW_FFT_HPP #define XTENSOR_FFTW_FFT_HPP #include <xtensor/xarray.hpp> #include <complex> #include <fftw3.h> namespace xt { namespace fftw { // NOTE: when making more performant functions, keep in mind that many FFTW functions destroy input and/or output // arrays! E.g. FFTW_MEASURE destroys both during measurement, c2r functions always destroy input by default // (unless for 1D transforms if you pass FFTW_PRESERVE_INPUT, // http://www.fftw.org/fftw3_doc/One_002dDimensional-DFTs-of-Real-Data.html#One_002dDimensional-DFTs-of-Real-Data), // etc. // http://www.fftw.org/fftw3_doc/Complex-One_002dDimensional-DFTs.html#Complex-One_002dDimensional-DFTs xt::xarray<std::complex<float>> fft(const xt::xarray<float> &input) { xt::xarray<std::complex<float>, layout_type::dynamic> output(input.shape(), input.strides()); fftwf_plan plan = fftwf_plan_dft_r2c_1d(static_cast<int>(input.size()), const_cast<float *>(input.raw_data()), // this function will not modify input, see http://www.fftw.org/fftw3_doc/One_002dDimensional-DFTs-of-Real-Data.html#One_002dDimensional-DFTs-of-Real-Data reinterpret_cast<fftwf_complex*>(output.raw_data()), // reinterpret_cast suggested by http://www.fftw.org/fftw3_doc/Complex-numbers.html FFTW_ESTIMATE); fftwf_execute(plan); return output; } xt::xarray<float> ifft(const xt::xarray<std::complex<float>> &input) { std::cout << "WARNING: the inverse c2r fftw transform by default destroys its input array, but in xt::fftw::ifft this has been disabled at the cost of some performance." << std::endl; xt::xarray<float, layout_type::dynamic> output(input.shape(), input.strides()); fftwf_plan plan = fftwf_plan_dft_c2r_1d(static_cast<int>(input.size()), const_cast<fftwf_complex *>(reinterpret_cast<const fftwf_complex *>(input.raw_data())), // this function will not modify input, see http://www.fftw.org/fftw3_doc/One_002dDimensional-DFTs-of-Real-Data.html#One_002dDimensional-DFTs-of-Real-Data; reinterpret_cast suggested by http://www.fftw.org/fftw3_doc/Complex-numbers.html output.raw_data(), FFTW_ESTIMATE | FFTW_PRESERVE_INPUT); fftwf_execute(plan); return output; } } } #endif //XTENSOR_FFTW_FFT_HPP <commit_msg>Fix normalization of ifft<commit_after>/* * xtensor-fftw * * Copyright 2017 Patrick Bos * * 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 XTENSOR_FFTW_FFT_HPP #define XTENSOR_FFTW_FFT_HPP #include <xtensor/xarray.hpp> #include <complex> #include <fftw3.h> namespace xt { namespace fftw { // NOTE: when making more performant functions, keep in mind that many FFTW functions destroy input and/or output // arrays! E.g. FFTW_MEASURE destroys both during measurement, c2r functions always destroy input by default // (unless for 1D transforms if you pass FFTW_PRESERVE_INPUT, // http://www.fftw.org/fftw3_doc/One_002dDimensional-DFTs-of-Real-Data.html#One_002dDimensional-DFTs-of-Real-Data), // etc. // http://www.fftw.org/fftw3_doc/Complex-One_002dDimensional-DFTs.html#Complex-One_002dDimensional-DFTs xt::xarray<std::complex<float>> fft(const xt::xarray<float> &input) { xt::xarray<std::complex<float>, layout_type::dynamic> output(input.shape(), input.strides()); fftwf_plan plan = fftwf_plan_dft_r2c_1d(static_cast<int>(input.size()), const_cast<float *>(input.raw_data()), // this function will not modify input, see http://www.fftw.org/fftw3_doc/One_002dDimensional-DFTs-of-Real-Data.html#One_002dDimensional-DFTs-of-Real-Data reinterpret_cast<fftwf_complex*>(output.raw_data()), // reinterpret_cast suggested by http://www.fftw.org/fftw3_doc/Complex-numbers.html FFTW_ESTIMATE); fftwf_execute(plan); return output; } xt::xarray<float> ifft(const xt::xarray<std::complex<float>> &input) { std::cout << "WARNING: the inverse c2r fftw transform by default destroys its input array, but in xt::fftw::ifft this has been disabled at the cost of some performance." << std::endl; xt::xarray<float, layout_type::dynamic> output(input.shape(), input.strides()); fftwf_plan plan = fftwf_plan_dft_c2r_1d(static_cast<int>(input.size()), const_cast<fftwf_complex *>(reinterpret_cast<const fftwf_complex *>(input.raw_data())), // this function will not modify input, see http://www.fftw.org/fftw3_doc/One_002dDimensional-DFTs-of-Real-Data.html#One_002dDimensional-DFTs-of-Real-Data; reinterpret_cast suggested by http://www.fftw.org/fftw3_doc/Complex-numbers.html output.raw_data(), FFTW_ESTIMATE | FFTW_PRESERVE_INPUT); fftwf_execute(plan); // we use the convention that the inverse fft divides by N, like numpy does return output / output.size(); } } } #endif //XTENSOR_FFTW_FFT_HPP <|endoftext|>
<commit_before>/************************************************************************* * * Copyright 2016 Realm 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. * **************************************************************************/ #ifndef REALM_ALLOC_HPP #define REALM_ALLOC_HPP #include <cstdint> #include <cstddef> #include <atomic> #include <realm/util/features.h> #include <realm/util/terminate.hpp> #include <realm/util/assert.hpp> #include <realm/util/safe_int_ops.hpp> namespace realm { class Allocator; class Replication; using ref_type = size_t; int_fast64_t from_ref(ref_type) noexcept; ref_type to_ref(int_fast64_t) noexcept; int64_t to_int64(size_t value) noexcept; class MemRef { public: MemRef() noexcept; ~MemRef() noexcept; MemRef(char* addr, ref_type ref, Allocator& alloc) noexcept; MemRef(ref_type ref, Allocator& alloc) noexcept; char* get_addr(); ref_type get_ref(); void set_ref(ref_type ref); void set_addr(char* addr); private: char* m_addr; ref_type m_ref; #if REALM_ENABLE_MEMDEBUG // Allocator that created m_ref. Used to verify that the ref is valid whenever you call // get_ref()/get_addr and that it e.g. has not been free'ed const Allocator* m_alloc = nullptr; #endif }; /// The common interface for Realm allocators. /// /// A Realm allocator must associate a 'ref' to each allocated /// object and be able to efficiently map any 'ref' to the /// corresponding memory address. The 'ref' is an integer and it must /// always be divisible by 8. Also, a value of zero is used to /// indicate a null-reference, and must therefore never be returned by /// Allocator::alloc(). /// /// The purpose of the 'refs' is to decouple the memory reference from /// the actual address and thereby allowing objects to be relocated in /// memory without having to modify stored references. /// /// \sa SlabAlloc class Allocator { public: static constexpr int CURRENT_FILE_FORMAT_VERSION = 6; /// The specified size must be divisible by 8, and must not be /// zero. /// /// \throw std::bad_alloc If insufficient memory was available. MemRef alloc(size_t size); /// Calls do_realloc(). /// /// Note: The underscore has been added because the name `realloc` /// would conflict with a macro on the Windows platform. MemRef realloc_(ref_type, const char* addr, size_t old_size, size_t new_size); /// Calls do_free(). /// /// Note: The underscore has been added because the name `free /// would conflict with a macro on the Windows platform. void free_(ref_type, const char* addr) noexcept; /// Shorthand for free_(mem.get_ref(), mem.get_addr()). void free_(MemRef mem) noexcept; /// Calls do_translate(). char* translate(ref_type ref) const noexcept; /// Returns true if, and only if the object at the specified 'ref' /// is in the immutable part of the memory managed by this /// allocator. The method by which some objects become part of the /// immuatble part is entirely up to the class that implements /// this interface. bool is_read_only(ref_type) const noexcept; /// Returns a simple allocator that can be used with free-standing /// Realm objects (such as a free-standing table). A /// free-standing object is one that is not part of a Group, and /// therefore, is not part of an actual database. static Allocator& get_default() noexcept; virtual ~Allocator() noexcept; virtual void verify() const = 0; #ifdef REALM_DEBUG /// Terminate the program precisely when the specified 'ref' is /// freed (or reallocated). You can use this to detect whether the /// ref is freed (or reallocated), and even to get a stacktrace at /// the point where it happens. Call watch(0) to stop watching /// that ref. void watch(ref_type ref) { m_debug_watch = ref; } #endif Replication* get_replication() noexcept; /// \brief The version of the format of the the node structure (in file or /// in memory) in use by Realm objects associated with this allocator. /// /// Every allocator contains a file format version field, which is returned /// by this function. In some cases (as mentioned below) the file format can /// change. /// /// A value of zero means the the file format is not yet decided. This is /// only possible for empty Realms where top-ref is zero. /// /// For the default allocator (get_default()), the file format version field /// can never change, is never zero, and is set to whatever /// Group::get_target_file_format_version_for_session() would return if the /// original file format version was undecided and the request history type /// was Replication::hist_None. /// /// For the slab allocator (AllocSlab), the file format version field is set /// to the file format version specified by the attached file (or attached /// memory buffer) at the time of attachment. If no file (or buffer) is /// currently attached, the returned value has no meaning. If the Realm file /// format is later upgraded, the file format version filed must be updated /// to reflect that fact. /// /// In shared mode (when a Realm file is opened via a SharedGroup instance) /// it can happen that the file format is upgraded asyncronously (via /// another SharedGroup instance), and in that case the file format version /// field of the allocator can get out of date, but only for a short /// while. It is always garanteed to be, and remain up to date after the /// opening process completes (when SharedGroup::do_open() returns). /// /// An empty Realm file (one whose top-ref is zero) may specify a file /// format version of zero to indicate that the format is not yet /// decided. In that case, this function will return zero immediately after /// AllocSlab::attach_file() returns. It shall be guaranteed, however, that /// the zero is changed to a proper file format version before the opening /// process completes (Group::open() or SharedGroup::open()). It is the duty /// of the caller of AllocSlab::attach_file() to ensure this. /// /// File format versions: /// /// 1 Initial file format version /// /// 2 Various changes. /// /// 3 Supporting null on string columns broke the file format in following /// way: Index appends an 'X' character to all strings except the null /// string, to be able to distinguish between null and empty /// string. Bumped to 3 because of null support of String columns and /// because of new format of index. /// /// 4 Introduction of optional in-Realm history of changes (additional /// entries in Group::m_top). Since this change is not forward /// compatible, the file format version had to be bumped. This change is /// implemented in a way that achieves backwards compatibility with /// version 3 (and in turn with version 2). /// /// 5 Introduced the new Timestamp column type that replaces DateTime. /// When opening an older database file, all DateTime columns will be /// automatically upgraded Timestamp columns. /// /// 6 Introduced a new non-compatible structure for StringIndex. Moved the /// commit logs into the Realm file. Changes to the transaction log /// format, including reshuffling instructions. This is the format used /// in milestone 2.0.0. /// /// IMPORTANT: When introducing a new file format version, be sure to review /// the file validity checks in AllocSlab::validate_buffer(), the file /// format selection logic in /// Group::get_target_file_format_version_for_session(), and the file format /// upgrade logic in Group::upgrade_file_format(). int get_file_format_version() const noexcept; protected: size_t m_baseline = 0; // Separation line between immutable and mutable refs. Replication* m_replication = nullptr; /// See get_file_format_version(). int m_file_format_version = 0; ref_type m_debug_watch = 0; /// The specified size must be divisible by 8, and must not be /// zero. /// /// \throw std::bad_alloc If insufficient memory was available. virtual MemRef do_alloc(size_t size) = 0; /// The specified size must be divisible by 8, and must not be /// zero. /// /// The default version of this function simply allocates a new /// chunk of memory, copies over the old contents, and then frees /// the old chunk. /// /// \throw std::bad_alloc If insufficient memory was available. virtual MemRef do_realloc(ref_type, const char* addr, size_t old_size, size_t new_size) = 0; /// Release the specified chunk of memory. virtual void do_free(ref_type, const char* addr) noexcept = 0; /// Map the specified \a ref to the corresponding memory /// address. Note that if is_read_only(ref) returns true, then the /// referenced object is to be considered immutable, and it is /// then entirely the responsibility of the caller that the memory /// is not modified by way of the returned memory pointer. virtual char* do_translate(ref_type ref) const noexcept = 0; Allocator() noexcept; // FIXME: This really doesn't belong in an allocator, but it is the best // place for now, because every table has a pointer leading here. It would // be more obvious to place it in Group, but that would add a runtime overhead, // and access is time critical. // // This means that multiple threads that allocate Realm objects through the // default allocator will share this variable, which is a logical design flaw // that can make sync_if_needed() re-run queries even though it is not required. // It must be atomic because it's shared. std::atomic<uint_fast64_t> m_table_versioning_counter; /// Bump the global version counter. This method should be called when /// version bumping is initiated. Then following calls to should_propagate_version() /// can be used to prune the version bumping. uint_fast64_t bump_global_version() noexcept; /// Determine if the "local_version" is out of sync, so that it should /// be updated. In that case: also update it. Called from Table::bump_version /// to control propagation of version updates on tables within the group. bool should_propagate_version(uint_fast64_t& local_version) noexcept; friend class Table; friend class Group; }; inline uint_fast64_t Allocator::bump_global_version() noexcept { ++m_table_versioning_counter; return m_table_versioning_counter; } inline bool Allocator::should_propagate_version(uint_fast64_t& local_version) noexcept { if (local_version != m_table_versioning_counter) { local_version = m_table_versioning_counter; return true; } else { return false; } } // Implementation: inline int_fast64_t from_ref(ref_type v) noexcept { // Check that v is divisible by 8 (64-bit aligned). REALM_ASSERT_DEBUG(v % 8 == 0); return util::from_twos_compl<int_fast64_t>(v); } inline ref_type to_ref(int_fast64_t v) noexcept { REALM_ASSERT_DEBUG(!util::int_cast_has_overflow<ref_type>(v)); // Check that v is divisible by 8 (64-bit aligned). REALM_ASSERT_DEBUG(v % 8 == 0); return ref_type(v); } inline int64_t to_int64(size_t value) noexcept { // FIXME: Enable once we get clang warning flags correct // REALM_ASSERT_DEBUG(value <= std::numeric_limits<int64_t>::max()); return static_cast<int64_t>(value); } inline MemRef::MemRef() noexcept : m_addr(nullptr) , m_ref(0) { } inline MemRef::~MemRef() noexcept { } inline MemRef::MemRef(char* addr, ref_type ref, Allocator& alloc) noexcept : m_addr(addr) , m_ref(ref) { static_cast<void>(alloc); #if REALM_ENABLE_MEMDEBUG m_alloc = &alloc; #endif } inline MemRef::MemRef(ref_type ref, Allocator& alloc) noexcept : m_addr(alloc.translate(ref)) , m_ref(ref) { static_cast<void>(alloc); #if REALM_ENABLE_MEMDEBUG m_alloc = &alloc; #endif } inline char* MemRef::get_addr() { #if REALM_ENABLE_MEMDEBUG // Asserts if the ref has been freed m_alloc->translate(m_ref); #endif return m_addr; } inline ref_type MemRef::get_ref() { #if REALM_ENABLE_MEMDEBUG // Asserts if the ref has been freed m_alloc->translate(m_ref); #endif return m_ref; } inline void MemRef::set_ref(ref_type ref) { #if REALM_ENABLE_MEMDEBUG // Asserts if the ref has been freed m_alloc->translate(ref); #endif m_ref = ref; } inline void MemRef::set_addr(char* addr) { m_addr = addr; } inline MemRef Allocator::alloc(size_t size) { return do_alloc(size); } inline MemRef Allocator::realloc_(ref_type ref, const char* addr, size_t old_size, size_t new_size) { #ifdef REALM_DEBUG if (ref == m_debug_watch) REALM_TERMINATE("Allocator watch: Ref was reallocated"); #endif return do_realloc(ref, addr, old_size, new_size); } inline void Allocator::free_(ref_type ref, const char* addr) noexcept { #ifdef REALM_DEBUG if (ref == m_debug_watch) REALM_TERMINATE("Allocator watch: Ref was freed"); #endif return do_free(ref, addr); } inline void Allocator::free_(MemRef mem) noexcept { free_(mem.get_ref(), mem.get_addr()); } inline char* Allocator::translate(ref_type ref) const noexcept { return do_translate(ref); } inline bool Allocator::is_read_only(ref_type ref) const noexcept { REALM_ASSERT_DEBUG(ref != 0); REALM_ASSERT_DEBUG(m_baseline != 0); // Attached SlabAlloc return ref < m_baseline; } inline Allocator::Allocator() noexcept { m_table_versioning_counter = 0; } inline Allocator::~Allocator() noexcept { } inline Replication* Allocator::get_replication() noexcept { return m_replication; } inline int Allocator::get_file_format_version() const noexcept { return m_file_format_version; } } // namespace realm #endif // REALM_ALLOC_HPP <commit_msg>Reduce confusion in the comments (review feedback).<commit_after>/************************************************************************* * * Copyright 2016 Realm 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. * **************************************************************************/ #ifndef REALM_ALLOC_HPP #define REALM_ALLOC_HPP #include <cstdint> #include <cstddef> #include <atomic> #include <realm/util/features.h> #include <realm/util/terminate.hpp> #include <realm/util/assert.hpp> #include <realm/util/safe_int_ops.hpp> namespace realm { class Allocator; class Replication; using ref_type = size_t; int_fast64_t from_ref(ref_type) noexcept; ref_type to_ref(int_fast64_t) noexcept; int64_t to_int64(size_t value) noexcept; class MemRef { public: MemRef() noexcept; ~MemRef() noexcept; MemRef(char* addr, ref_type ref, Allocator& alloc) noexcept; MemRef(ref_type ref, Allocator& alloc) noexcept; char* get_addr(); ref_type get_ref(); void set_ref(ref_type ref); void set_addr(char* addr); private: char* m_addr; ref_type m_ref; #if REALM_ENABLE_MEMDEBUG // Allocator that created m_ref. Used to verify that the ref is valid whenever you call // get_ref()/get_addr and that it e.g. has not been free'ed const Allocator* m_alloc = nullptr; #endif }; /// The common interface for Realm allocators. /// /// A Realm allocator must associate a 'ref' to each allocated /// object and be able to efficiently map any 'ref' to the /// corresponding memory address. The 'ref' is an integer and it must /// always be divisible by 8. Also, a value of zero is used to /// indicate a null-reference, and must therefore never be returned by /// Allocator::alloc(). /// /// The purpose of the 'refs' is to decouple the memory reference from /// the actual address and thereby allowing objects to be relocated in /// memory without having to modify stored references. /// /// \sa SlabAlloc class Allocator { public: static constexpr int CURRENT_FILE_FORMAT_VERSION = 6; /// The specified size must be divisible by 8, and must not be /// zero. /// /// \throw std::bad_alloc If insufficient memory was available. MemRef alloc(size_t size); /// Calls do_realloc(). /// /// Note: The underscore has been added because the name `realloc` /// would conflict with a macro on the Windows platform. MemRef realloc_(ref_type, const char* addr, size_t old_size, size_t new_size); /// Calls do_free(). /// /// Note: The underscore has been added because the name `free /// would conflict with a macro on the Windows platform. void free_(ref_type, const char* addr) noexcept; /// Shorthand for free_(mem.get_ref(), mem.get_addr()). void free_(MemRef mem) noexcept; /// Calls do_translate(). char* translate(ref_type ref) const noexcept; /// Returns true if, and only if the object at the specified 'ref' /// is in the immutable part of the memory managed by this /// allocator. The method by which some objects become part of the /// immuatble part is entirely up to the class that implements /// this interface. bool is_read_only(ref_type) const noexcept; /// Returns a simple allocator that can be used with free-standing /// Realm objects (such as a free-standing table). A /// free-standing object is one that is not part of a Group, and /// therefore, is not part of an actual database. static Allocator& get_default() noexcept; virtual ~Allocator() noexcept; virtual void verify() const = 0; #ifdef REALM_DEBUG /// Terminate the program precisely when the specified 'ref' is /// freed (or reallocated). You can use this to detect whether the /// ref is freed (or reallocated), and even to get a stacktrace at /// the point where it happens. Call watch(0) to stop watching /// that ref. void watch(ref_type ref) { m_debug_watch = ref; } #endif Replication* get_replication() noexcept; /// \brief The version of the format of the the node structure (in file or /// in memory) in use by Realm objects associated with this allocator. /// /// Every allocator contains a file format version field, which is returned /// by this function. In some cases (as mentioned below) the file format can /// change. /// /// A value of zero means the the file format is not yet decided. This is /// only possible for empty Realms where top-ref is zero. /// /// For the default allocator (get_default()), the file format version field /// can never change, is never zero, and is set to whatever /// Group::get_target_file_format_version_for_session() would return if the /// original file format version was undecided and the request history type /// was Replication::hist_None. /// /// For the slab allocator (AllocSlab), the file format version field is set /// to the file format version specified by the attached file (or attached /// memory buffer) at the time of attachment. If no file (or buffer) is /// currently attached, the returned value has no meaning. If the Realm file /// format is later upgraded, the file format version filed must be updated /// to reflect that fact. /// /// In shared mode (when a Realm file is opened via a SharedGroup instance) /// it can happen that the file format is upgraded asyncronously (via /// another SharedGroup instance), and in that case the file format version /// field of the allocator can get out of date, but only for a short /// while. It is always garanteed to be, and remain up to date after the /// opening process completes (when SharedGroup::do_open() returns). /// /// An empty Realm file (one whose top-ref is zero) may specify a file /// format version of zero to indicate that the format is not yet /// decided. In that case, this function will return zero immediately after /// AllocSlab::attach_file() returns. It shall be guaranteed, however, that /// the zero is changed to a proper file format version before the opening /// process completes (Group::open() or SharedGroup::open()). It is the duty /// of the caller of AllocSlab::attach_file() to ensure this. /// /// File format versions: /// /// 1 Initial file format version /// /// 2 Various changes. /// /// 3 Supporting null on string columns broke the file format in following /// way: Index appends an 'X' character to all strings except the null /// string, to be able to distinguish between null and empty /// string. Bumped to 3 because of null support of String columns and /// because of new format of index. /// /// 4 Introduction of optional in-Realm history of changes (additional /// entries in Group::m_top). Since this change is not forward /// compatible, the file format version had to be bumped. This change is /// implemented in a way that achieves backwards compatibility with /// version 3 (and in turn with version 2). /// /// 5 Introduced the new Timestamp column type that replaces DateTime. /// When opening an older database file, all DateTime columns will be /// automatically upgraded Timestamp columns. /// /// 6 Introduced a new structure for the StringIndex. Moved the commit /// logs into the Realm file. Changes to the transaction log format /// including reshuffling instructions. This is the format used in /// milestone 2.0.0. /// /// IMPORTANT: When introducing a new file format version, be sure to review /// the file validity checks in AllocSlab::validate_buffer(), the file /// format selection logic in /// Group::get_target_file_format_version_for_session(), and the file format /// upgrade logic in Group::upgrade_file_format(). int get_file_format_version() const noexcept; protected: size_t m_baseline = 0; // Separation line between immutable and mutable refs. Replication* m_replication = nullptr; /// See get_file_format_version(). int m_file_format_version = 0; ref_type m_debug_watch = 0; /// The specified size must be divisible by 8, and must not be /// zero. /// /// \throw std::bad_alloc If insufficient memory was available. virtual MemRef do_alloc(size_t size) = 0; /// The specified size must be divisible by 8, and must not be /// zero. /// /// The default version of this function simply allocates a new /// chunk of memory, copies over the old contents, and then frees /// the old chunk. /// /// \throw std::bad_alloc If insufficient memory was available. virtual MemRef do_realloc(ref_type, const char* addr, size_t old_size, size_t new_size) = 0; /// Release the specified chunk of memory. virtual void do_free(ref_type, const char* addr) noexcept = 0; /// Map the specified \a ref to the corresponding memory /// address. Note that if is_read_only(ref) returns true, then the /// referenced object is to be considered immutable, and it is /// then entirely the responsibility of the caller that the memory /// is not modified by way of the returned memory pointer. virtual char* do_translate(ref_type ref) const noexcept = 0; Allocator() noexcept; // FIXME: This really doesn't belong in an allocator, but it is the best // place for now, because every table has a pointer leading here. It would // be more obvious to place it in Group, but that would add a runtime overhead, // and access is time critical. // // This means that multiple threads that allocate Realm objects through the // default allocator will share this variable, which is a logical design flaw // that can make sync_if_needed() re-run queries even though it is not required. // It must be atomic because it's shared. std::atomic<uint_fast64_t> m_table_versioning_counter; /// Bump the global version counter. This method should be called when /// version bumping is initiated. Then following calls to should_propagate_version() /// can be used to prune the version bumping. uint_fast64_t bump_global_version() noexcept; /// Determine if the "local_version" is out of sync, so that it should /// be updated. In that case: also update it. Called from Table::bump_version /// to control propagation of version updates on tables within the group. bool should_propagate_version(uint_fast64_t& local_version) noexcept; friend class Table; friend class Group; }; inline uint_fast64_t Allocator::bump_global_version() noexcept { ++m_table_versioning_counter; return m_table_versioning_counter; } inline bool Allocator::should_propagate_version(uint_fast64_t& local_version) noexcept { if (local_version != m_table_versioning_counter) { local_version = m_table_versioning_counter; return true; } else { return false; } } // Implementation: inline int_fast64_t from_ref(ref_type v) noexcept { // Check that v is divisible by 8 (64-bit aligned). REALM_ASSERT_DEBUG(v % 8 == 0); return util::from_twos_compl<int_fast64_t>(v); } inline ref_type to_ref(int_fast64_t v) noexcept { REALM_ASSERT_DEBUG(!util::int_cast_has_overflow<ref_type>(v)); // Check that v is divisible by 8 (64-bit aligned). REALM_ASSERT_DEBUG(v % 8 == 0); return ref_type(v); } inline int64_t to_int64(size_t value) noexcept { // FIXME: Enable once we get clang warning flags correct // REALM_ASSERT_DEBUG(value <= std::numeric_limits<int64_t>::max()); return static_cast<int64_t>(value); } inline MemRef::MemRef() noexcept : m_addr(nullptr) , m_ref(0) { } inline MemRef::~MemRef() noexcept { } inline MemRef::MemRef(char* addr, ref_type ref, Allocator& alloc) noexcept : m_addr(addr) , m_ref(ref) { static_cast<void>(alloc); #if REALM_ENABLE_MEMDEBUG m_alloc = &alloc; #endif } inline MemRef::MemRef(ref_type ref, Allocator& alloc) noexcept : m_addr(alloc.translate(ref)) , m_ref(ref) { static_cast<void>(alloc); #if REALM_ENABLE_MEMDEBUG m_alloc = &alloc; #endif } inline char* MemRef::get_addr() { #if REALM_ENABLE_MEMDEBUG // Asserts if the ref has been freed m_alloc->translate(m_ref); #endif return m_addr; } inline ref_type MemRef::get_ref() { #if REALM_ENABLE_MEMDEBUG // Asserts if the ref has been freed m_alloc->translate(m_ref); #endif return m_ref; } inline void MemRef::set_ref(ref_type ref) { #if REALM_ENABLE_MEMDEBUG // Asserts if the ref has been freed m_alloc->translate(ref); #endif m_ref = ref; } inline void MemRef::set_addr(char* addr) { m_addr = addr; } inline MemRef Allocator::alloc(size_t size) { return do_alloc(size); } inline MemRef Allocator::realloc_(ref_type ref, const char* addr, size_t old_size, size_t new_size) { #ifdef REALM_DEBUG if (ref == m_debug_watch) REALM_TERMINATE("Allocator watch: Ref was reallocated"); #endif return do_realloc(ref, addr, old_size, new_size); } inline void Allocator::free_(ref_type ref, const char* addr) noexcept { #ifdef REALM_DEBUG if (ref == m_debug_watch) REALM_TERMINATE("Allocator watch: Ref was freed"); #endif return do_free(ref, addr); } inline void Allocator::free_(MemRef mem) noexcept { free_(mem.get_ref(), mem.get_addr()); } inline char* Allocator::translate(ref_type ref) const noexcept { return do_translate(ref); } inline bool Allocator::is_read_only(ref_type ref) const noexcept { REALM_ASSERT_DEBUG(ref != 0); REALM_ASSERT_DEBUG(m_baseline != 0); // Attached SlabAlloc return ref < m_baseline; } inline Allocator::Allocator() noexcept { m_table_versioning_counter = 0; } inline Allocator::~Allocator() noexcept { } inline Replication* Allocator::get_replication() noexcept { return m_replication; } inline int Allocator::get_file_format_version() const noexcept { return m_file_format_version; } } // namespace realm #endif // REALM_ALLOC_HPP <|endoftext|>
<commit_before>#include <errno.h> #include <string> #include <map> #include "rgw_access.h" #include "rgw_acl.h" #include "include/types.h" #include "rgw_user.h" using namespace std; static string ui_bucket = USER_INFO_BUCKET_NAME; static string ui_email_bucket = USER_INFO_EMAIL_BUCKET_NAME; static string ui_openstack_bucket = USER_INFO_OPENSTACK_BUCKET_NAME; static string root_bucket = ".rgw"; //keep this synced to rgw_rados.cc::ROOT_BUCKET! /** * Get the info for a user out of storage. * Returns: 0 on success, -ERR# on failure */ int rgw_get_user_info(string user_id, RGWUserInfo& info) { bufferlist bl; int ret; char *data; struct rgw_err err; void *handle = NULL; off_t ofs = 0, end = -1; size_t total_len; time_t lastmod; bufferlist::iterator iter; ret = rgwstore->prepare_get_obj(ui_bucket, user_id, ofs, &end, NULL, NULL, NULL, &lastmod, NULL, NULL, &total_len, &handle, &err); if (ret < 0) return ret; do { ret = rgwstore->get_obj(&handle, ui_bucket, user_id, &data, ofs, end); if (ret < 0) { goto done; } bl.append(data, ret); free(data); ofs += ret; } while (ofs <= end); iter = bl.begin(); info.decode(iter); ret = 0; done: rgwstore->finish_get_obj(&handle); return ret; } /** * Get the anonymous (ie, unauthenticated) user info. */ void rgw_get_anon_user(RGWUserInfo& info) { info.user_id = RGW_USER_ANON_ID; info.display_name.clear(); info.secret_key.clear(); } /** * Save the given user information to storage. * Returns: 0 on success, -ERR# on failure. */ int rgw_store_user_info(RGWUserInfo& info) { bufferlist bl; info.encode(bl); const char *data = bl.c_str(); string md5; int ret; map<string,bufferlist> attrs; ret = rgwstore->put_obj(info.user_id, ui_bucket, info.user_id, data, bl.length(), NULL, attrs); if (ret == -ENOENT) { ret = rgwstore->create_bucket(info.user_id, ui_bucket, attrs); if (ret >= 0) ret = rgwstore->put_obj(info.user_id, ui_bucket, info.user_id, data, bl.length(), NULL, attrs); } if (ret < 0) return ret; bufferlist uid_bl; RGWUID ui; ui.user_id = info.user_id; ui.encode(uid_bl); if (info.user_email.size()) { ret = rgwstore->put_obj(info.user_id, ui_email_bucket, info.user_email, uid_bl.c_str(), uid_bl.length(), NULL, attrs); if (ret == -ENOENT) { map<string, bufferlist> attrs; ret = rgwstore->create_bucket(info.user_id, ui_email_bucket, attrs); if (ret >= 0) ret = rgwstore->put_obj(info.user_id, ui_email_bucket, info.user_email, uid_bl.c_str(), uid_bl.length(), NULL, attrs); } } if (ret < 0) return ret; if (info.openstack_name.size()) { ret = rgwstore->put_obj(info.user_id, ui_openstack_bucket, info.openstack_name, uid_bl.c_str(), uid_bl.length(), NULL, attrs); if (ret == -ENOENT) { map<string, bufferlist> attrs; ret = rgwstore->create_bucket(info.user_id, ui_openstack_bucket, attrs); if (ret >= 0 && ret != -EEXIST) ret = rgwstore->put_obj(info.user_id, ui_openstack_bucket, info.openstack_name, uid_bl.c_str(), uid_bl.length(), NULL, attrs); } } return ret; } int rgw_get_uid_from_index(string& key, string& bucket, string& user_id) { bufferlist bl; int ret; char *data = NULL; struct rgw_err err; RGWUID uid; void *handle = NULL; off_t ofs = 0, end = -1; bufferlist::iterator iter; size_t total_len; ret = rgwstore->prepare_get_obj(bucket, key, ofs, &end, NULL, NULL, NULL, NULL, NULL, NULL, &total_len, &handle, &err); if (ret < 0) return ret; if (total_len == 0) return -EACCES; do { ret = rgwstore->get_obj(&handle, bucket, key, &data, ofs, end); if (ret < 0) goto done; ofs += ret; bl.append(data, ret); free(data); } while (ofs <= end); iter = bl.begin(); uid.decode(iter); user_id = uid.user_id; ret = 0; done: rgwstore->finish_get_obj(&handle); return ret; } /** * Given an email, finds the user_id associated with it. * returns: 0 on success, -ERR# on failure (including nonexistence) */ int rgw_get_uid_by_email(string& email, string& user_id) { return rgw_get_uid_from_index(email, ui_email_bucket, user_id); } /** * Given an openstack username, finds the user_id associated with it. * returns: 0 on success, -ERR# on failure (including nonexistence) */ extern int rgw_get_uid_by_openstack(string& openstack_name, string& user_id) { return rgw_get_uid_from_index(openstack_name, ui_openstack_bucket, user_id); } static void get_buckets_obj(string& user_id, string& buckets_obj_id) { buckets_obj_id = user_id; buckets_obj_id += RGW_BUCKETS_OBJ_PREFIX; } /** * Get all the buckets owned by a user and fill up an RGWUserBuckets with them. * Returns: 0 on success, -ERR# on failure. */ int rgw_read_buckets_attr(string user_id, RGWUserBuckets& buckets) { bufferlist bl; int ret; buckets.clear(); if (rgwstore->supports_tmap()) { string buckets_obj_id; get_buckets_obj(user_id, buckets_obj_id); bufferlist bl; #define LARGE_ENOUGH_LEN (4096 * 1024) size_t len = LARGE_ENOUGH_LEN; do { ret = rgwstore->read(ui_bucket, buckets_obj_id, 0, len, bl); if (ret == -ENOENT) { ret = 0; return 0; } if (ret < 0) return ret; if (ret != len) break; len *= 2; } while (1); bufferlist::iterator p = bl.begin(); bufferlist header; map<string,bufferlist> m; ::decode(header, p); ::decode(m, p); for (map<string,bufferlist>::iterator q = m.begin(); q != m.end(); q++) { bufferlist::iterator iter = q->second.begin(); RGWObjEnt bucket; ::decode(bucket, iter); buckets.add(bucket); } } else { ret = rgwstore->get_attr(ui_bucket, user_id, RGW_ATTR_BUCKETS, bl); switch (ret) { case 0: break; case -ENODATA: return 0; default: return ret; } bufferlist::iterator iter = bl.begin(); buckets.decode(iter); } return 0; } /** * Store the set of buckets associated with a user on a n xattr * not used with all backends * This completely overwrites any previously-stored list, so be careful! * Returns 0 on success, -ERR# otherwise. */ int rgw_write_buckets_attr(string user_id, RGWUserBuckets& buckets) { bufferlist bl; buckets.encode(bl); int ret = rgwstore->set_attr(ui_bucket, user_id, RGW_ATTR_BUCKETS, bl); return ret; } int rgw_add_bucket(string user_id, string bucket_name) { int ret; if (rgwstore->supports_tmap()) { bufferlist bl; RGWObjEnt new_bucket; new_bucket.name = bucket_name; new_bucket.size = 0; ::encode(new_bucket, bl); string buckets_obj_id; get_buckets_obj(user_id, buckets_obj_id); ret = rgwstore->tmap_set(ui_bucket, buckets_obj_id, bucket_name, bl); if (ret < 0) { RGW_LOG(0) << "error adding bucket to directory: " << strerror(-ret)<< std::endl; } } else { RGWUserBuckets buckets; ret = rgw_read_buckets_attr(user_id, buckets); RGWObjEnt new_bucket; switch (ret) { case 0: case -ENOENT: case -ENODATA: new_bucket.name = bucket_name; new_bucket.size = 0; time(&new_bucket.mtime); buckets.add(new_bucket); ret = rgw_write_buckets_attr(user_id, buckets); break; default: RGW_LOG(10) << "rgw_write_buckets_attr returned " << ret << endl; break; } } return ret; } int rgw_remove_bucket(string user_id, string bucket_name) { int ret; if (rgwstore->supports_tmap()) { bufferlist bl; string buckets_obj_id; get_buckets_obj(user_id, buckets_obj_id); ret = rgwstore->tmap_del(ui_bucket, buckets_obj_id, bucket_name); if (ret < 0) { RGW_LOG(0) << "error removing bucket from directory: " << strerror(-ret)<< std::endl; } } else { RGWUserBuckets buckets; ret = rgw_read_buckets_attr(user_id, buckets); if (ret == 0 || ret == -ENOENT) { buckets.remove(bucket_name); ret = rgw_write_buckets_attr(user_id, buckets); } } return ret; } /** * delete a user's presence from the RGW system. * First remove their bucket ACLs, then delete them * from the user and user email pools. This leaves the pools * themselves alone, as well as any ACLs embedded in object xattrs. */ int rgw_delete_user(RGWUserInfo& info) { RGWUserBuckets user_buckets; rgw_read_buckets_attr(info.user_id, user_buckets); map<string, RGWObjEnt>& buckets = user_buckets.get_buckets(); for (map<string, RGWObjEnt>::iterator i = buckets.begin(); i != buckets.end(); ++i) { string bucket_name = i->first; rgwstore->delete_obj(info.user_id, root_bucket, bucket_name); } rgwstore->delete_obj(info.user_id, ui_bucket, info.user_id); rgwstore->delete_obj(info.user_id, ui_email_bucket, info.user_email); return 0; } <commit_msg>rgw: initialize bucket creation time<commit_after>#include <errno.h> #include <string> #include <map> #include "rgw_access.h" #include "rgw_acl.h" #include "include/types.h" #include "rgw_user.h" using namespace std; static string ui_bucket = USER_INFO_BUCKET_NAME; static string ui_email_bucket = USER_INFO_EMAIL_BUCKET_NAME; static string ui_openstack_bucket = USER_INFO_OPENSTACK_BUCKET_NAME; static string root_bucket = ".rgw"; //keep this synced to rgw_rados.cc::ROOT_BUCKET! /** * Get the info for a user out of storage. * Returns: 0 on success, -ERR# on failure */ int rgw_get_user_info(string user_id, RGWUserInfo& info) { bufferlist bl; int ret; char *data; struct rgw_err err; void *handle = NULL; off_t ofs = 0, end = -1; size_t total_len; time_t lastmod; bufferlist::iterator iter; ret = rgwstore->prepare_get_obj(ui_bucket, user_id, ofs, &end, NULL, NULL, NULL, &lastmod, NULL, NULL, &total_len, &handle, &err); if (ret < 0) return ret; do { ret = rgwstore->get_obj(&handle, ui_bucket, user_id, &data, ofs, end); if (ret < 0) { goto done; } bl.append(data, ret); free(data); ofs += ret; } while (ofs <= end); iter = bl.begin(); info.decode(iter); ret = 0; done: rgwstore->finish_get_obj(&handle); return ret; } /** * Get the anonymous (ie, unauthenticated) user info. */ void rgw_get_anon_user(RGWUserInfo& info) { info.user_id = RGW_USER_ANON_ID; info.display_name.clear(); info.secret_key.clear(); } /** * Save the given user information to storage. * Returns: 0 on success, -ERR# on failure. */ int rgw_store_user_info(RGWUserInfo& info) { bufferlist bl; info.encode(bl); const char *data = bl.c_str(); string md5; int ret; map<string,bufferlist> attrs; ret = rgwstore->put_obj(info.user_id, ui_bucket, info.user_id, data, bl.length(), NULL, attrs); if (ret == -ENOENT) { ret = rgwstore->create_bucket(info.user_id, ui_bucket, attrs); if (ret >= 0) ret = rgwstore->put_obj(info.user_id, ui_bucket, info.user_id, data, bl.length(), NULL, attrs); } if (ret < 0) return ret; bufferlist uid_bl; RGWUID ui; ui.user_id = info.user_id; ui.encode(uid_bl); if (info.user_email.size()) { ret = rgwstore->put_obj(info.user_id, ui_email_bucket, info.user_email, uid_bl.c_str(), uid_bl.length(), NULL, attrs); if (ret == -ENOENT) { map<string, bufferlist> attrs; ret = rgwstore->create_bucket(info.user_id, ui_email_bucket, attrs); if (ret >= 0) ret = rgwstore->put_obj(info.user_id, ui_email_bucket, info.user_email, uid_bl.c_str(), uid_bl.length(), NULL, attrs); } } if (ret < 0) return ret; if (info.openstack_name.size()) { ret = rgwstore->put_obj(info.user_id, ui_openstack_bucket, info.openstack_name, uid_bl.c_str(), uid_bl.length(), NULL, attrs); if (ret == -ENOENT) { map<string, bufferlist> attrs; ret = rgwstore->create_bucket(info.user_id, ui_openstack_bucket, attrs); if (ret >= 0 && ret != -EEXIST) ret = rgwstore->put_obj(info.user_id, ui_openstack_bucket, info.openstack_name, uid_bl.c_str(), uid_bl.length(), NULL, attrs); } } return ret; } int rgw_get_uid_from_index(string& key, string& bucket, string& user_id) { bufferlist bl; int ret; char *data = NULL; struct rgw_err err; RGWUID uid; void *handle = NULL; off_t ofs = 0, end = -1; bufferlist::iterator iter; size_t total_len; ret = rgwstore->prepare_get_obj(bucket, key, ofs, &end, NULL, NULL, NULL, NULL, NULL, NULL, &total_len, &handle, &err); if (ret < 0) return ret; if (total_len == 0) return -EACCES; do { ret = rgwstore->get_obj(&handle, bucket, key, &data, ofs, end); if (ret < 0) goto done; ofs += ret; bl.append(data, ret); free(data); } while (ofs <= end); iter = bl.begin(); uid.decode(iter); user_id = uid.user_id; ret = 0; done: rgwstore->finish_get_obj(&handle); return ret; } /** * Given an email, finds the user_id associated with it. * returns: 0 on success, -ERR# on failure (including nonexistence) */ int rgw_get_uid_by_email(string& email, string& user_id) { return rgw_get_uid_from_index(email, ui_email_bucket, user_id); } /** * Given an openstack username, finds the user_id associated with it. * returns: 0 on success, -ERR# on failure (including nonexistence) */ extern int rgw_get_uid_by_openstack(string& openstack_name, string& user_id) { return rgw_get_uid_from_index(openstack_name, ui_openstack_bucket, user_id); } static void get_buckets_obj(string& user_id, string& buckets_obj_id) { buckets_obj_id = user_id; buckets_obj_id += RGW_BUCKETS_OBJ_PREFIX; } /** * Get all the buckets owned by a user and fill up an RGWUserBuckets with them. * Returns: 0 on success, -ERR# on failure. */ int rgw_read_buckets_attr(string user_id, RGWUserBuckets& buckets) { bufferlist bl; int ret; buckets.clear(); if (rgwstore->supports_tmap()) { string buckets_obj_id; get_buckets_obj(user_id, buckets_obj_id); bufferlist bl; #define LARGE_ENOUGH_LEN (4096 * 1024) size_t len = LARGE_ENOUGH_LEN; do { ret = rgwstore->read(ui_bucket, buckets_obj_id, 0, len, bl); if (ret == -ENOENT) { ret = 0; return 0; } if (ret < 0) return ret; if (ret != len) break; len *= 2; } while (1); bufferlist::iterator p = bl.begin(); bufferlist header; map<string,bufferlist> m; ::decode(header, p); ::decode(m, p); for (map<string,bufferlist>::iterator q = m.begin(); q != m.end(); q++) { bufferlist::iterator iter = q->second.begin(); RGWObjEnt bucket; ::decode(bucket, iter); buckets.add(bucket); } } else { ret = rgwstore->get_attr(ui_bucket, user_id, RGW_ATTR_BUCKETS, bl); switch (ret) { case 0: break; case -ENODATA: return 0; default: return ret; } bufferlist::iterator iter = bl.begin(); buckets.decode(iter); } return 0; } /** * Store the set of buckets associated with a user on a n xattr * not used with all backends * This completely overwrites any previously-stored list, so be careful! * Returns 0 on success, -ERR# otherwise. */ int rgw_write_buckets_attr(string user_id, RGWUserBuckets& buckets) { bufferlist bl; buckets.encode(bl); int ret = rgwstore->set_attr(ui_bucket, user_id, RGW_ATTR_BUCKETS, bl); return ret; } int rgw_add_bucket(string user_id, string bucket_name) { int ret; if (rgwstore->supports_tmap()) { bufferlist bl; RGWObjEnt new_bucket; new_bucket.name = bucket_name; new_bucket.size = 0; time(&new_bucket.mtime); ::encode(new_bucket, bl); string buckets_obj_id; get_buckets_obj(user_id, buckets_obj_id); ret = rgwstore->tmap_set(ui_bucket, buckets_obj_id, bucket_name, bl); if (ret < 0) { RGW_LOG(0) << "error adding bucket to directory: " << strerror(-ret)<< std::endl; } } else { RGWUserBuckets buckets; ret = rgw_read_buckets_attr(user_id, buckets); RGWObjEnt new_bucket; switch (ret) { case 0: case -ENOENT: case -ENODATA: new_bucket.name = bucket_name; new_bucket.size = 0; time(&new_bucket.mtime); buckets.add(new_bucket); ret = rgw_write_buckets_attr(user_id, buckets); break; default: RGW_LOG(10) << "rgw_write_buckets_attr returned " << ret << endl; break; } } return ret; } int rgw_remove_bucket(string user_id, string bucket_name) { int ret; if (rgwstore->supports_tmap()) { bufferlist bl; string buckets_obj_id; get_buckets_obj(user_id, buckets_obj_id); ret = rgwstore->tmap_del(ui_bucket, buckets_obj_id, bucket_name); if (ret < 0) { RGW_LOG(0) << "error removing bucket from directory: " << strerror(-ret)<< std::endl; } } else { RGWUserBuckets buckets; ret = rgw_read_buckets_attr(user_id, buckets); if (ret == 0 || ret == -ENOENT) { buckets.remove(bucket_name); ret = rgw_write_buckets_attr(user_id, buckets); } } return ret; } /** * delete a user's presence from the RGW system. * First remove their bucket ACLs, then delete them * from the user and user email pools. This leaves the pools * themselves alone, as well as any ACLs embedded in object xattrs. */ int rgw_delete_user(RGWUserInfo& info) { RGWUserBuckets user_buckets; rgw_read_buckets_attr(info.user_id, user_buckets); map<string, RGWObjEnt>& buckets = user_buckets.get_buckets(); for (map<string, RGWObjEnt>::iterator i = buckets.begin(); i != buckets.end(); ++i) { string bucket_name = i->first; rgwstore->delete_obj(info.user_id, root_bucket, bucket_name); } rgwstore->delete_obj(info.user_id, ui_bucket, info.user_id); rgwstore->delete_obj(info.user_id, ui_email_bucket, info.user_email); return 0; } <|endoftext|>
<commit_before>/* * Logging infrastructure that aims to support multi-threading, * and ansi colors. */ #include "rust_internal.h" #include "util/array_list.h" #include <stdarg.h> #include <stdlib.h> #include <string.h> static const char * _foreground_colors[] = { "[37m", "[31m", "[1;31m", "[32m", "[1;32m", "[33m", "[1;33m", "[31m", "[1;31m", "[35m", "[1;35m", "[36m", "[1;36m" }; /** * Synchronizes access to the underlying logging mechanism. */ static lock_and_signal _log_lock; static uint32_t _last_thread_id; rust_log::rust_log(rust_srv *srv, rust_dom *dom) : _srv(srv), _dom(dom), _use_colors(getenv("RUST_COLOR_LOG")) { } rust_log::~rust_log() { } const uint16_t hash(uintptr_t ptr) { // Robert Jenkins' 32 bit integer hash function ptr = (ptr + 0x7ed55d16) + (ptr << 12); ptr = (ptr ^ 0xc761c23c) ^ (ptr >> 19); ptr = (ptr + 0x165667b1) + (ptr << 5); ptr = (ptr + 0xd3a2646c) ^ (ptr << 9); ptr = (ptr + 0xfd7046c5) + (ptr << 3); ptr = (ptr ^ 0xb55a4f09) ^ (ptr >> 16); return (uint16_t) ptr; } const char * get_color(uintptr_t ptr) { return _foreground_colors[hash(ptr) % rust_log::LIGHTTEAL]; } char * copy_string(char *dst, const char *src, size_t length) { return strncpy(dst, src, length) + length; } char * append_string(char *buffer, const char *format, ...) { if (buffer != NULL && format) { va_list args; va_start(args, format); size_t off = strlen(buffer); vsnprintf(buffer + off, BUF_BYTES - off, format, args); va_end(args); } return buffer; } char * append_string(char *buffer, rust_log::ansi_color color, const char *format, ...) { if (buffer != NULL && format) { append_string(buffer, "\x1b%s", _foreground_colors[color]); va_list args; va_start(args, format); size_t off = strlen(buffer); vsnprintf(buffer + off, BUF_BYTES - off, format, args); va_end(args); append_string(buffer, "\x1b[0m"); } return buffer; } void rust_log::trace_ln(uint32_t thread_id, char *prefix, char *message) { char buffer[BUF_BYTES] = ""; _log_lock.lock(); append_string(buffer, "%-34s", prefix); append_string(buffer, "%s", message); if (_last_thread_id != thread_id) { _last_thread_id = thread_id; _srv->log("---"); } _srv->log(buffer); _log_lock.unlock(); } void rust_log::trace_ln(rust_task *task, uint32_t level, char *message) { #if defined(__WIN32__) uint32_t thread_id = 0; #else uint32_t thread_id = hash((uint32_t) pthread_self()); #endif char prefix[BUF_BYTES] = ""; if (_dom && _dom->name) { append_string(prefix, "%04" PRIxPTR ":%.10s:", thread_id, _dom->name); } else { append_string(prefix, "%04" PRIxPTR ":0x%08" PRIxPTR ":", thread_id, (uintptr_t) _dom); } if (task) { if (task->name) { append_string(prefix, "%.10s:", task->name); } else { append_string(prefix, "0x%08" PRIxPTR ":", (uintptr_t) task); } } trace_ln(thread_id, prefix, message); } // Reading log directives and setting log level vars struct mod_entry { const char* name; size_t* state; }; struct cratemap { const mod_entry* entries; const cratemap* children[1]; }; struct log_directive { char* name; size_t level; }; const size_t max_log_directives = 255; const size_t max_log_level = 1; const size_t default_log_level = 0; // This is a rather ugly parser for strings in the form // "crate1,crate2.mod3,crate3.x=1". Log levels are 0-1 for now, // eventually we'll have 0-3. size_t parse_logging_spec(char* spec, log_directive* dirs) { size_t dir = 0; while (dir < max_log_directives && *spec) { char* start = spec; char cur; while (true) { cur = *spec; if (cur == ',' || cur == '=' || cur == '\0') { if (start == spec) {spec++; break;} *spec = '\0'; spec++; size_t level = max_log_level; if (cur == '=') { level = *spec - '0'; if (level > max_log_level) level = max_log_level; if (*spec) ++spec; } dirs[dir].name = start; dirs[dir++].level = level; break; } spec++; } } return dir; } void update_module_map(const mod_entry* map, log_directive* dirs, size_t n_dirs) { for (const mod_entry* cur = map; cur->name; cur++) { size_t level = default_log_level, longest_match = 0; for (size_t d = 0; d < n_dirs; d++) { if (strstr(cur->name, dirs[d].name) == cur->name && strlen(dirs[d].name) > longest_match) { longest_match = strlen(dirs[d].name); level = dirs[d].level; } } *cur->state = level; } } void update_crate_map(const cratemap* map, log_directive* dirs, size_t n_dirs) { // First update log levels for this crate update_module_map(map->entries, dirs, n_dirs); // Then recurse on linked crates // FIXME this does double work in diamond-shaped deps. could keep // a set of visited addresses, if it turns out to be actually slow for (size_t i = 0; map->children[i]; i++) { update_crate_map(map->children[i], dirs, n_dirs); } } // These are pseudo-modules used to control logging in the runtime. size_t log_rt_mem; size_t log_rt_comm; size_t log_rt_task; size_t log_rt_dom; size_t log_rt_trace; size_t log_rt_dwarf; size_t log_rt_cache; size_t log_rt_upcall; size_t log_rt_timer; size_t log_rt_gc; size_t log_rt_stdlib; size_t log_rt_kern; size_t log_rt_backtrace; // Used to turn logging for rustboot-compiled code on and off size_t log_rustboot; static const mod_entry _rt_module_map[] = {{"rt.mem", &log_rt_mem}, {"rt.comm", &log_rt_comm}, {"rt.task", &log_rt_task}, {"rt.dom", &log_rt_dom}, {"rt.trace", &log_rt_trace}, {"rt.dwarf", &log_rt_dwarf}, {"rt.cache", &log_rt_cache}, {"rt.upcall", &log_rt_upcall}, {"rt.timer", &log_rt_timer}, {"rt.gc", &log_rt_gc}, {"rt.stdlib", &log_rt_stdlib}, {"rt.kern", &log_rt_kern}, {"rt.backtrace", &log_rt_backtrace}, {"rustboot", &log_rustboot}, {NULL, NULL}}; void update_log_settings(void* crate_map, char* settings) { char* buffer = NULL; log_directive dirs[256]; size_t n_dirs = 0; if (settings) { buffer = (char*)malloc(strlen(settings)); strcpy(buffer, settings); n_dirs = parse_logging_spec(buffer, &dirs[0]); } update_module_map(_rt_module_map, &dirs[0], n_dirs); // FIXME check can be dropped when rustboot is gone if (crate_map) update_crate_map((const cratemap*)crate_map, &dirs[0], n_dirs); free(buffer); } <commit_msg>rt: Allocate room for null terminator in logging spec<commit_after>/* * Logging infrastructure that aims to support multi-threading, * and ansi colors. */ #include "rust_internal.h" #include "util/array_list.h" #include <stdarg.h> #include <stdlib.h> #include <string.h> static const char * _foreground_colors[] = { "[37m", "[31m", "[1;31m", "[32m", "[1;32m", "[33m", "[1;33m", "[31m", "[1;31m", "[35m", "[1;35m", "[36m", "[1;36m" }; /** * Synchronizes access to the underlying logging mechanism. */ static lock_and_signal _log_lock; static uint32_t _last_thread_id; rust_log::rust_log(rust_srv *srv, rust_dom *dom) : _srv(srv), _dom(dom), _use_colors(getenv("RUST_COLOR_LOG")) { } rust_log::~rust_log() { } const uint16_t hash(uintptr_t ptr) { // Robert Jenkins' 32 bit integer hash function ptr = (ptr + 0x7ed55d16) + (ptr << 12); ptr = (ptr ^ 0xc761c23c) ^ (ptr >> 19); ptr = (ptr + 0x165667b1) + (ptr << 5); ptr = (ptr + 0xd3a2646c) ^ (ptr << 9); ptr = (ptr + 0xfd7046c5) + (ptr << 3); ptr = (ptr ^ 0xb55a4f09) ^ (ptr >> 16); return (uint16_t) ptr; } const char * get_color(uintptr_t ptr) { return _foreground_colors[hash(ptr) % rust_log::LIGHTTEAL]; } char * copy_string(char *dst, const char *src, size_t length) { return strncpy(dst, src, length) + length; } char * append_string(char *buffer, const char *format, ...) { if (buffer != NULL && format) { va_list args; va_start(args, format); size_t off = strlen(buffer); vsnprintf(buffer + off, BUF_BYTES - off, format, args); va_end(args); } return buffer; } char * append_string(char *buffer, rust_log::ansi_color color, const char *format, ...) { if (buffer != NULL && format) { append_string(buffer, "\x1b%s", _foreground_colors[color]); va_list args; va_start(args, format); size_t off = strlen(buffer); vsnprintf(buffer + off, BUF_BYTES - off, format, args); va_end(args); append_string(buffer, "\x1b[0m"); } return buffer; } void rust_log::trace_ln(uint32_t thread_id, char *prefix, char *message) { char buffer[BUF_BYTES] = ""; _log_lock.lock(); append_string(buffer, "%-34s", prefix); append_string(buffer, "%s", message); if (_last_thread_id != thread_id) { _last_thread_id = thread_id; _srv->log("---"); } _srv->log(buffer); _log_lock.unlock(); } void rust_log::trace_ln(rust_task *task, uint32_t level, char *message) { #if defined(__WIN32__) uint32_t thread_id = 0; #else uint32_t thread_id = hash((uint32_t) pthread_self()); #endif char prefix[BUF_BYTES] = ""; if (_dom && _dom->name) { append_string(prefix, "%04" PRIxPTR ":%.10s:", thread_id, _dom->name); } else { append_string(prefix, "%04" PRIxPTR ":0x%08" PRIxPTR ":", thread_id, (uintptr_t) _dom); } if (task) { if (task->name) { append_string(prefix, "%.10s:", task->name); } else { append_string(prefix, "0x%08" PRIxPTR ":", (uintptr_t) task); } } trace_ln(thread_id, prefix, message); } // Reading log directives and setting log level vars struct mod_entry { const char* name; size_t* state; }; struct cratemap { const mod_entry* entries; const cratemap* children[1]; }; struct log_directive { char* name; size_t level; }; const size_t max_log_directives = 255; const size_t max_log_level = 1; const size_t default_log_level = 0; // This is a rather ugly parser for strings in the form // "crate1,crate2.mod3,crate3.x=1". Log levels are 0-1 for now, // eventually we'll have 0-3. size_t parse_logging_spec(char* spec, log_directive* dirs) { size_t dir = 0; while (dir < max_log_directives && *spec) { char* start = spec; char cur; while (true) { cur = *spec; if (cur == ',' || cur == '=' || cur == '\0') { if (start == spec) {spec++; break;} *spec = '\0'; spec++; size_t level = max_log_level; if (cur == '=') { level = *spec - '0'; if (level > max_log_level) level = max_log_level; if (*spec) ++spec; } dirs[dir].name = start; dirs[dir++].level = level; break; } spec++; } } return dir; } void update_module_map(const mod_entry* map, log_directive* dirs, size_t n_dirs) { for (const mod_entry* cur = map; cur->name; cur++) { size_t level = default_log_level, longest_match = 0; for (size_t d = 0; d < n_dirs; d++) { if (strstr(cur->name, dirs[d].name) == cur->name && strlen(dirs[d].name) > longest_match) { longest_match = strlen(dirs[d].name); level = dirs[d].level; } } *cur->state = level; } } void update_crate_map(const cratemap* map, log_directive* dirs, size_t n_dirs) { // First update log levels for this crate update_module_map(map->entries, dirs, n_dirs); // Then recurse on linked crates // FIXME this does double work in diamond-shaped deps. could keep // a set of visited addresses, if it turns out to be actually slow for (size_t i = 0; map->children[i]; i++) { update_crate_map(map->children[i], dirs, n_dirs); } } // These are pseudo-modules used to control logging in the runtime. size_t log_rt_mem; size_t log_rt_comm; size_t log_rt_task; size_t log_rt_dom; size_t log_rt_trace; size_t log_rt_dwarf; size_t log_rt_cache; size_t log_rt_upcall; size_t log_rt_timer; size_t log_rt_gc; size_t log_rt_stdlib; size_t log_rt_kern; size_t log_rt_backtrace; // Used to turn logging for rustboot-compiled code on and off size_t log_rustboot; static const mod_entry _rt_module_map[] = {{"rt.mem", &log_rt_mem}, {"rt.comm", &log_rt_comm}, {"rt.task", &log_rt_task}, {"rt.dom", &log_rt_dom}, {"rt.trace", &log_rt_trace}, {"rt.dwarf", &log_rt_dwarf}, {"rt.cache", &log_rt_cache}, {"rt.upcall", &log_rt_upcall}, {"rt.timer", &log_rt_timer}, {"rt.gc", &log_rt_gc}, {"rt.stdlib", &log_rt_stdlib}, {"rt.kern", &log_rt_kern}, {"rt.backtrace", &log_rt_backtrace}, {"rustboot", &log_rustboot}, {NULL, NULL}}; void update_log_settings(void* crate_map, char* settings) { char* buffer = NULL; log_directive dirs[256]; size_t n_dirs = 0; if (settings) { size_t buflen = strlen(settings) + 1; buffer = (char*)malloc(buflen); strncpy(buffer, settings, buflen); n_dirs = parse_logging_spec(buffer, &dirs[0]); } update_module_map(_rt_module_map, &dirs[0], n_dirs); // FIXME check can be dropped when rustboot is gone if (crate_map) update_crate_map((const cratemap*)crate_map, &dirs[0], n_dirs); free(buffer); } <|endoftext|>
<commit_before>/* Copyright (c) 2012, STANISLAW ADASZEWSKI 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 STANISLAW ADASZEWSKI 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 STANISLAW ADASZEWSKI 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 "qnodeseditor.h" #include <QGraphicsScene> #include <QEvent> #include <QGraphicsSceneMouseEvent> #include "qneport.h" #include "qneconnection.h" #include "qneblock.h" QNodesEditor::QNodesEditor(QObject *parent) : QObject(parent) { conn = 0; } void QNodesEditor::install(QGraphicsScene *s) { s->installEventFilter(this); scene = s; } QGraphicsItem* QNodesEditor::itemAt(const QPointF &pos) { QList<QGraphicsItem*> items = scene->items(QRectF(pos - QPointF(1,1), QSize(3,3))); foreach(QGraphicsItem *item, items) if (item->type() > QGraphicsItem::UserType) return item; return 0; } bool QNodesEditor::eventFilter(QObject *o, QEvent *e) { QGraphicsSceneMouseEvent *me = (QGraphicsSceneMouseEvent*) e; switch ((int) e->type()) { case QEvent::GraphicsSceneMousePress: { switch ((int) me->button()) { case Qt::LeftButton: { QGraphicsItem *item = itemAt(me->scenePos()); if (item && item->type() == QNEPort::Type) { conn = new QNEConnection(0); scene->addItem(conn); conn->setPort1((QNEPort*) item); conn->setPos1(item->scenePos()); conn->setPos2(me->scenePos()); conn->updatePath(); return true; } else if (item && item->type() == QNEBlock::Type) { /* if (selBlock) selBlock->setSelected(); */ // selBlock = (QNEBlock*) item; } break; } case Qt::RightButton: { QGraphicsItem *item = itemAt(me->scenePos()); if (item && (item->type() == QNEConnection::Type || item->type() == QNEBlock::Type)) delete item; // if (selBlock == (QNEBlock*) item) // selBlock = 0; break; } } } case QEvent::GraphicsSceneMouseMove: { if (conn) { conn->setPos2(me->scenePos()); conn->updatePath(); return true; } break; } case QEvent::GraphicsSceneMouseRelease: { if (conn && me->button() == Qt::LeftButton) { QGraphicsItem *item = itemAt(me->scenePos()); if (item && item->type() == QNEPort::Type) { QNEPort *port1 = conn->port1(); QNEPort *port2 = (QNEPort*) item; if (port1->block() != port2->block() && port1->isOutput() != port2->isOutput() && !port1->isConnected(port2)) { conn->setPos2(port2->scenePos()); conn->setPort2(port2); conn->updatePath(); conn = 0; return true; } } delete conn; conn = 0; return true; } break; } } return QObject::eventFilter(o, e); } void QNodesEditor::save(QDataStream &ds) { foreach(QGraphicsItem *item, scene->items()) if (item->type() == QNEBlock::Type) { ds << item->type(); ((QNEBlock*) item)->save(ds); } foreach(QGraphicsItem *item, scene->items()) if (item->type() == QNEConnection::Type) { ds << item->type(); ((QNEConnection*) item)->save(ds); } } void QNodesEditor::load(QDataStream &ds) { scene->clear(); QMap<quint64, QNEPort*> portMap; while (!ds.atEnd()) { int type; ds >> type; if (type == QNEBlock::Type) { QNEBlock *block = new QNEBlock(0); scene->addItem(block); block->load(ds, portMap); } else if (type == QNEConnection::Type) { QNEConnection *conn = new QNEConnection(0); scene->addItem(conn); conn->load(ds, portMap); } } } <commit_msg>A few layout fixes<commit_after>/* Copyright (c) 2012, STANISLAW ADASZEWSKI 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 STANISLAW ADASZEWSKI 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 STANISLAW ADASZEWSKI 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 "qnodeseditor.h" #include <QGraphicsScene> #include <QEvent> #include <QGraphicsSceneMouseEvent> #include "qneport.h" #include "qneconnection.h" #include "qneblock.h" QNodesEditor::QNodesEditor(QObject *parent) : QObject(parent) { conn = 0; } void QNodesEditor::install(QGraphicsScene *s) { s->installEventFilter(this); scene = s; } QGraphicsItem* QNodesEditor::itemAt(const QPointF &pos) { QList<QGraphicsItem*> items = scene->items(QRectF(pos - QPointF(1,1), QSize(3,3))); Q_FOREACH(QGraphicsItem *item, items) { if (item->type() > QGraphicsItem::UserType) return item; } return 0; } bool QNodesEditor::eventFilter(QObject *o, QEvent *e) { QGraphicsSceneMouseEvent *me = (QGraphicsSceneMouseEvent*) e; switch ((int) e->type()) { case QEvent::GraphicsSceneMousePress: { switch ((int) me->button()) { case Qt::LeftButton: { QGraphicsItem *item = itemAt(me->scenePos()); if (item && item->type() == QNEPort::Type && ((QNEPort*)item)->isOutput()) { conn = new QNEConnection(0); scene->addItem(conn); conn->setPort1((QNEPort*) item); conn->setPos1(item->scenePos()); conn->setPos2(me->scenePos()); conn->updatePath(); return true; } else if (item && item->type() == QNEBlock::Type) { /* if (selBlock) selBlock->setSelected(); */ // selBlock = (QNEBlock*) item; } break; } case Qt::RightButton: { QGraphicsItem *item = itemAt(me->scenePos()); if (item && (item->type() == QNEConnection::Type || item->type() == QNEBlock::Type)) delete item; // if (selBlock == (QNEBlock*) item) // selBlock = 0; break; } } } case QEvent::GraphicsSceneMouseMove: { if (conn) { conn->setPos2(me->scenePos()); conn->updatePath(); return true; } break; } case QEvent::GraphicsSceneMouseRelease: { if (conn && me->button() == Qt::LeftButton) { QGraphicsItem *item = itemAt(me->scenePos()); if (item && item->type() == QNEPort::Type) { QNEPort *port1 = conn->port1(); QNEPort *port2 = (QNEPort*) item; if (port1->block() != port2->block() && port1->isOutput() != port2->isOutput() && !port1->isConnected(port2)) { conn->setPos2(port2->scenePos()); conn->setPort2(port2); conn->updatePath(); conn = 0; return true; } } delete conn; conn = 0; return true; } break; } } return QObject::eventFilter(o, e); } void QNodesEditor::save(QDataStream &ds) { Q_FOREACH(QGraphicsItem *item, scene->items()) { if (item->type() == QNEBlock::Type) { ds << item->type(); ((QNEBlock*) item)->save(ds); } } Q_FOREACH(QGraphicsItem *item, scene->items()) { if (item->type() == QNEConnection::Type) { ds << item->type(); ((QNEConnection*) item)->save(ds); } } } void QNodesEditor::load(QDataStream &ds) { scene->clear(); QMap<quint64, QNEPort*> portMap; while (!ds.atEnd()) { int type; ds >> type; if (type == QNEBlock::Type) { QNEBlock *block = new QNEBlock(0); scene->addItem(block); block->load(ds, portMap); } else if (type == QNEConnection::Type) { QNEConnection *conn = new QNEConnection(0); scene->addItem(conn); conn->load(ds, portMap); } } } <|endoftext|>
<commit_before>#include "db.h" #include "walletdb.h" #include "net.h" #include "init.h" #include "util.h" #include "scanbalance.h" #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/interprocess/sync/file_lock.hpp> #ifndef WIN32 #include <signal.h> #endif using namespace std; using namespace boost; static void ScanTransactionInputs(CTxDB& txdb, const CTransaction& tx, BalanceMap& mapBalance) { if (tx.IsCoinBase()) return; BOOST_FOREACH(const CTxIn& txi, tx.vin) { CTransaction ti; if (!txdb.ReadDiskTx(txi.prevout, ti)) { string s = strprintf("Failed to load transaction %s", txi.ToStringShort().c_str()); throw runtime_error(s); } if (txi.prevout.n >= ti.vout.size()) { string s = strprintf("Invalid index in transaction %s", txi.ToStringShort().c_str()); throw runtime_error(s); } CTxOut prevOut = ti.vout[txi.prevout.n]; CBitcoinAddress addr; ExtractAddress(prevOut.scriptPubKey, addr); if (prevOut.nValue > 0) { if (mapBalance.count(addr) == 0) { string s = strprintf("Missing input address: %s", txi.ToStringShort().c_str()); throw runtime_error(s); } if (prevOut.nValue > mapBalance[addr]) { string s = strprintf("Input address would have negative balance: %s", txi.ToStringShort().c_str()); throw runtime_error(s); } mapBalance[addr] -= prevOut.nValue; if (mapBalance[addr] == 0) mapBalance.erase(addr); } } } static void ScanTransactionOutputs(const CTransaction& tx, BalanceMap& mapBalance) { BOOST_FOREACH(const CTxOut& txo, tx.vout) { if (txo.nValue > 0 && !txo.scriptPubKey.empty()) { CBitcoinAddress addr; ExtractAddress(txo.scriptPubKey, addr); mapBalance[addr] += txo.nValue; } } } void GetAddressBalances(unsigned int cutoffTime, BalanceMap& mapBalance) { CBlockIndex* pblk0 = pindexGenesisBlock, *pblk1 = pindexBest; if (!pblk0) throw runtime_error("No genesis block."); if (!pblk1) throw runtime_error("No best block chain."); if (cutoffTime>pblk1->nTime) throw runtime_error("Cutoff date later than most recent block."); CTxDB txdb("r"); int nBlks = 0; while (pblk0 != pblk1) { if (pblk0->nTime >= cutoffTime) break; CBlock block; block.ReadFromDisk(pblk0, true); BOOST_FOREACH(const CTransaction& tx, block.vtx) { ScanTransactionInputs(txdb, tx, mapBalance); ScanTransactionOutputs(tx, mapBalance); } pblk0 = pblk0->pnext; nBlks++; } } <commit_msg>scanbalance works with units<commit_after>#include "db.h" #include "walletdb.h" #include "net.h" #include "init.h" #include "util.h" #include "scanbalance.h" #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/interprocess/sync/file_lock.hpp> #ifndef WIN32 #include <signal.h> #endif using namespace std; using namespace boost; static void ScanTransactionInputs(CTxDB& txdb, const CTransaction& tx, BalanceMap& mapBalance) { if (tx.IsCoinBase()) return; BOOST_FOREACH(const CTxIn& txi, tx.vin) { CTransaction ti; if (!txdb.ReadDiskTx(txi.prevout, ti)) { string s = strprintf("Failed to load transaction %s", txi.ToStringShort().c_str()); throw runtime_error(s); } if (txi.prevout.n >= ti.vout.size()) { string s = strprintf("Invalid index in transaction %s", txi.ToStringShort().c_str()); throw runtime_error(s); } CTxOut prevOut = ti.vout[txi.prevout.n]; CBitcoinAddress addr; ExtractAddress(prevOut.scriptPubKey, addr, 'S'); if (prevOut.nValue > 0) { if (mapBalance.count(addr) == 0) { string s = strprintf("Missing input address: %s", txi.ToStringShort().c_str()); throw runtime_error(s); } if (prevOut.nValue > mapBalance[addr]) { string s = strprintf("Input address would have negative balance: %s", txi.ToStringShort().c_str()); throw runtime_error(s); } mapBalance[addr] -= prevOut.nValue; if (mapBalance[addr] == 0) mapBalance.erase(addr); } } } static void ScanTransactionOutputs(const CTransaction& tx, BalanceMap& mapBalance) { BOOST_FOREACH(const CTxOut& txo, tx.vout) { if (txo.nValue > 0 && !txo.scriptPubKey.empty()) { CBitcoinAddress addr; ExtractAddress(txo.scriptPubKey, addr, 'S'); mapBalance[addr] += txo.nValue; } } } void GetAddressBalances(unsigned int cutoffTime, BalanceMap& mapBalance) { CBlockIndex* pblk0 = pindexGenesisBlock, *pblk1 = pindexBest; if (!pblk0) throw runtime_error("No genesis block."); if (!pblk1) throw runtime_error("No best block chain."); if (cutoffTime>pblk1->nTime) throw runtime_error("Cutoff date later than most recent block."); CTxDB txdb("r"); int nBlks = 0; while (pblk0 != pblk1) { if (pblk0->nTime >= cutoffTime) break; CBlock block; block.ReadFromDisk(pblk0, true); BOOST_FOREACH(const CTransaction& tx, block.vtx) { ScanTransactionInputs(txdb, tx, mapBalance); ScanTransactionOutputs(tx, mapBalance); } pblk0 = pblk0->pnext; nBlks++; } } <|endoftext|>
<commit_before>/* * Copyright 2017 deepstreamHub GmbH * * 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 DEEPSTREAM_SCOPEGUARD_HPP #define DEEPSTREAM_SCOPEGUARD_HPP #include <functional> #include <boost/preprocessor/cat.hpp> #include "use.hpp" namespace deepstream { /** * A helper class executing code when exiting the current scope. * It is recommended to use the macro below instead of using the class * directly. * * A. Alexandrescu, P. Marginean: * * *Generic: Change the Way You Write Exception-Safe Code -- Forever* * * Dr. Dobbs Journal, 2000 * * www.drdobbs.com/cpp/generic-change-the-way-you-write-excepti/184403758 */ struct ScopeGuard { typedef std::function<void(void)> FunT; ScopeGuard(FunT f) : f_(f) { } ~ScopeGuard() { f_(); } FunT f_; }; } #define DEEPSTREAM_ON_EXIT(...) \ const ::deepstream::ScopeGuard BOOST_PP_CAT(deepstream_guard, \ __LINE__)(__VA_ARGS__); \ ::deepstream::use(BOOST_PP_CAT(deepstream_guard, __LINE__)) #endif <commit_msg>Remove final libboost dependency in the library build<commit_after>/* * Copyright 2017 deepstreamHub GmbH * * 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 DEEPSTREAM_SCOPEGUARD_HPP #define DEEPSTREAM_SCOPEGUARD_HPP #include <functional> #include "use.hpp" namespace deepstream { /** * A helper class executing code when exiting the current scope. * It is recommended to use the macro below instead of using the class * directly. * * A. Alexandrescu, P. Marginean: * * *Generic: Change the Way You Write Exception-Safe Code -- Forever* * * Dr. Dobbs Journal, 2000 * * www.drdobbs.com/cpp/generic-change-the-way-you-write-excepti/184403758 */ struct ScopeGuard { typedef std::function<void(void)> FunT; ScopeGuard(FunT f) : f_(f) { } ~ScopeGuard() { f_(); } FunT f_; }; } #define DEEPSTREAM_TOKENPASTE(x, y) x##y #define DEEPSTREAM_TOKENPASTE2(x, y) DEEPSTREAM_TOKENPASTE(x, y) #define DEEPSTREAM_ON_EXIT(...) \ const ::deepstream::ScopeGuard DEEPSTREAM_TOKENPASTE2(_deepstream_guard_gensym_, __LINE__)(__VA_ARGS__) #endif <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPersistenceService.h" #include "mitkStandaloneDataStorage.h" #include "mitkUIDGenerator.h" #include "mitkNodePredicateProperty.h" #include "mitkProperties.h" #include "usModuleContext.h" #include "usGetModuleContext.h" #include <itksys/SystemTools.hxx> std::string mitk::PersistenceService::GetPersistencePropertyName() { return "PersistenceNode"; } std::string mitk::PersistenceService::GetPersistencePropertyListName() { return "PersistenceService"; } mitk::PersistenceService::PersistenceService() : m_AutoLoadAndSave( true ), m_Initialized(false), m_InInitialized(false) { } void mitk::PersistenceService::Clear() { this->Initialize(); m_PropertyLists.clear(); m_FileNamesToModifiedTimes.clear(); } mitk::PersistenceService::~PersistenceService() { MITK_DEBUG("mitk::PersistenceService") << "destructing PersistenceService"; } std::string mitk::PersistenceService::GetDefaultPersistenceFile() { this->Initialize(); std::string file = "PersistentData.xml"; us::ModuleContext* context = us::GetModuleContext(); std::string contextDataFile = context->GetDataFile(file); if( !contextDataFile.empty() ) { file = contextDataFile; } return file; } mitk::PropertyList::Pointer mitk::PersistenceService::GetPropertyList( std::string& id, bool* existed ) { this->Initialize(); mitk::PropertyList::Pointer propList; if( id.empty() ) { UIDGenerator uidGen; id = uidGen.GetUID(); } std::map<std::string, mitk::PropertyList::Pointer>::iterator it = m_PropertyLists.find( id ); if( it == m_PropertyLists.end() ) { propList = PropertyList::New(); m_PropertyLists[id] = propList; if( existed ) *existed = false; } else { propList = (*it).second; if( existed ) *existed = true; } return propList; } void mitk::PersistenceService::ClonePropertyList( mitk::PropertyList* from, mitk::PropertyList* to ) const { to->Clear(); const std::map< std::string, BaseProperty::Pointer>* propMap = from->GetMap(); std::map< std::string, BaseProperty::Pointer>::const_iterator propMapIt = propMap->begin(); while( propMapIt != propMap->end() ) { mitk::BaseProperty::Pointer clonedProp = (*propMapIt).second->Clone(); to->SetProperty( (*propMapIt).first, clonedProp ); ++propMapIt; } } bool mitk::PersistenceService::Save(const std::string& fileName, bool appendChanges) { this->Initialize(); bool save = false; std::string theFile = fileName; if(theFile.empty()) theFile = PersistenceService::GetDefaultPersistenceFile(); std::string thePath = itksys::SystemTools::GetFilenamePath( theFile.c_str() ); if( !thePath.empty() && !itksys::SystemTools::FileExists( thePath.c_str() ) ) { if( !itksys::SystemTools::MakeDirectory( thePath.c_str() ) ) { MITK_ERROR("PersistenceService") << "Could not create " << thePath; return false; } } bool createFile = !itksys::SystemTools::FileExists(theFile.c_str()); if( !itksys::SystemTools::Touch(theFile.c_str(), createFile) ) { MITK_ERROR("PersistenceService") << "Could not create or write to " << theFile; return false; } bool xmlFile = false; if( itksys::SystemTools::GetFilenameLastExtension(theFile.c_str()) == ".xml" ) xmlFile = true; mitk::DataStorage::Pointer tempDs; if( appendChanges ) { if(xmlFile == false) { if( itksys::SystemTools::FileExists(theFile.c_str()) ) { bool load = false; DataStorage::Pointer ds = m_SceneIO->LoadScene( theFile ); load = (m_SceneIO->GetFailedNodes() == 0 || m_SceneIO->GetFailedNodes()->size() == 0) && (m_SceneIO->GetFailedNodes() == 0 || m_SceneIO->GetFailedProperties()->IsEmpty()); if( !load ) return false; tempDs = ds; } } else { tempDs = mitk::StandaloneDataStorage::New(); if( xmlFile && appendChanges && itksys::SystemTools::FileExists(theFile.c_str()) ) { if( !m_PropertyListsXmlFileReaderAndWriter->ReadLists( theFile, m_PropertyLists ) ) return false; } } this->RestorePropertyListsFromPersistentDataNodes( tempDs ); } else if( xmlFile == false ) { tempDs = mitk::StandaloneDataStorage::New(); } if( xmlFile ) { save = m_PropertyListsXmlFileReaderAndWriter->WriteLists(theFile, m_PropertyLists); } else { DataStorage::SetOfObjects::Pointer sceneNodes = this->GetDataNodes(tempDs); if(m_SceneIO.IsNull()) { m_SceneIO = mitk::SceneIO::New(); } save = m_SceneIO->SaveScene( sceneNodes.GetPointer(), tempDs, theFile ); } if( save ) { long int currentModifiedTime = itksys::SystemTools::ModifiedTime( theFile.c_str() ); m_FileNamesToModifiedTimes[theFile] = currentModifiedTime; } return save; } bool mitk::PersistenceService::Load(const std::string& fileName, bool enforceReload) { this->Initialize(); bool load = false; std::string theFile = fileName; if(theFile.empty()) theFile = PersistenceService::GetDefaultPersistenceFile(); MITK_INFO << "Load persistence data from file: " << theFile; if( !itksys::SystemTools::FileExists(theFile.c_str()) ) return false; bool xmlFile = false; if( itksys::SystemTools::GetFilenameLastExtension(theFile.c_str()) == ".xml" ) xmlFile = true; if( enforceReload == false ) { bool loadTheFile = true; std::map<std::string, long int>::iterator it = m_FileNamesToModifiedTimes.find( theFile ); long int currentModifiedTime = itksys::SystemTools::ModifiedTime( theFile.c_str() ); if( it != m_FileNamesToModifiedTimes.end() ) { long int knownModifiedTime = (*it).second; if( knownModifiedTime >= currentModifiedTime ) { loadTheFile = false; } } if( loadTheFile ) m_FileNamesToModifiedTimes[theFile] = currentModifiedTime; else return true; } if( xmlFile ) { load = m_PropertyListsXmlFileReaderAndWriter->ReadLists(theFile, m_PropertyLists); } else { if(m_SceneIO.IsNull()) { m_SceneIO = mitk::SceneIO::New(); } DataStorage::Pointer ds = m_SceneIO->LoadScene( theFile ); load = (m_SceneIO->GetFailedNodes() == 0 || m_SceneIO->GetFailedNodes()->size() == 0) && (m_SceneIO->GetFailedNodes() == 0 || m_SceneIO->GetFailedProperties()->IsEmpty()); if( load ) { this->RestorePropertyListsFromPersistentDataNodes( ds ); } } if( !load ) { MITK_DEBUG("mitk::PersistenceService") << "loading of scene files failed"; return load; } return load; } void mitk::PersistenceService::SetAutoLoadAndSave(bool autoLoadAndSave) { this->Initialize(); m_AutoLoadAndSave = autoLoadAndSave; //std::string id = PERSISTENCE_PROPERTYLIST_NAME; //see bug 17729 std::string id = GetPersistencePropertyListName(); mitk::PropertyList::Pointer propList = this->GetPropertyList( id ); propList->Set("m_AutoLoadAndSave", m_AutoLoadAndSave); this->Save(); } void mitk::PersistenceService::AddPropertyListReplacedObserver(PropertyListReplacedObserver* observer) { this->Initialize(); m_PropertyListReplacedObserver.insert( observer ); } void mitk::PersistenceService::RemovePropertyListReplacedObserver(PropertyListReplacedObserver* observer) { this->Initialize(); m_PropertyListReplacedObserver.erase( observer ); } void mitk::PersistenceService::LoadModule() { MITK_INFO << "Persistence Module loaded."; } us::ModuleContext* mitk::PersistenceService::GetModuleContext() { return us::GetModuleContext(); } std::string mitk::PersistenceService::GetPersistenceNodePropertyName() { this->Initialize(); //return PERSISTENCE_PROPERTY_NAME; //see bug 17729 return GetPersistencePropertyName(); } mitk::DataStorage::SetOfObjects::Pointer mitk::PersistenceService::GetDataNodes(mitk::DataStorage* ds) { this->Initialize(); DataStorage::SetOfObjects::Pointer set = DataStorage::SetOfObjects::New(); std::map<std::string, mitk::PropertyList::Pointer>::const_iterator it = m_PropertyLists.begin(); while( it != m_PropertyLists.end() ) { mitk::DataNode::Pointer node = mitk::DataNode::New(); const std::string& name = (*it).first; this->ClonePropertyList( (*it).second, node->GetPropertyList() ); node->SetName( name ); MITK_DEBUG << "Persistence Property Name: " << GetPersistencePropertyName().c_str(); //node->SetBoolProperty( PERSISTENCE_PROPERTY_NAME.c_str() , true ); //see bug 17729 node->SetBoolProperty( GetPersistencePropertyName().c_str() , true ); ds->Add(node); set->push_back( node ); ++it; } return set; } bool mitk::PersistenceService::RestorePropertyListsFromPersistentDataNodes( const DataStorage* storage ) { this->Initialize(); bool oneFound = false; DataStorage::SetOfObjects::ConstPointer allNodes = storage->GetAll(); for ( mitk::DataStorage::SetOfObjects::const_iterator sourceIter = allNodes->begin(); sourceIter != allNodes->end(); ++sourceIter ) { mitk::DataNode* node = *sourceIter; bool isPersistenceNode = false; //node->GetBoolProperty( PERSISTENCE_PROPERTY_NAME.c_str(), isPersistenceNode ); //see bug 17729 node->GetBoolProperty( GetPersistencePropertyName().c_str(), isPersistenceNode ); if( isPersistenceNode ) { oneFound = true; MITK_DEBUG("mitk::PersistenceService") << "isPersistenceNode was true"; std::string name = node->GetName(); bool existed = false; mitk::PropertyList::Pointer propList = this->GetPropertyList( name, &existed ); if( existed ) { MITK_DEBUG("mitk::PersistenceService") << "calling replace observer before replacing values"; std::set<PropertyListReplacedObserver*>::iterator it = m_PropertyListReplacedObserver.begin(); while( it != m_PropertyListReplacedObserver.end() ) { (*it)->BeforePropertyListReplaced( name, propList ); ++it; } } // if( existed ) MITK_DEBUG("mitk::PersistenceService") << "replacing values"; this->ClonePropertyList( node->GetPropertyList(), propList ); if( existed ) { MITK_DEBUG("mitk::PersistenceService") << "calling replace observer before replacing values"; std::set<PropertyListReplacedObserver*>::iterator it = m_PropertyListReplacedObserver.begin(); while( it != m_PropertyListReplacedObserver.end() ) { (*it)->AfterPropertyListReplaced( name, propList ); ++it; } } // if( existed ) } // if( isPersistenceNode ) } // for ( mitk::DataStorage::SetOfObjects::const_iterator sourceIter = allNodes->begin(); ... return oneFound; } bool mitk::PersistenceService::GetAutoLoadAndSave() { this->Initialize(); return m_AutoLoadAndSave; } bool mitk::PersistenceService::RemovePropertyList( std::string& id ) { this->Initialize(); std::map<std::string, mitk::PropertyList::Pointer>::iterator it = m_PropertyLists.find( id ); if( it != m_PropertyLists.end() ) { m_PropertyLists.erase(it); return true; } return false; } void mitk::PersistenceService::Initialize() { if( m_Initialized || m_InInitialized) return; m_InInitialized = true; m_PropertyListsXmlFileReaderAndWriter = PropertyListsXmlFileReaderAndWriter::New(); // Load Default File in any case this->Load(); //std::string id = mitk::PersistenceService::PERSISTENCE_PROPERTYLIST_NAME; //see bug 17729 std::string id = GetPersistencePropertyListName(); mitk::PropertyList::Pointer propList = this->GetPropertyList( id ); bool autoLoadAndSave = true; propList->GetBoolProperty("m_AutoLoadAndSave", autoLoadAndSave); if( autoLoadAndSave == false ) { MITK_DEBUG("mitk::PersistenceService") << "autoloading was not wished. clearing data we got so far."; this->SetAutoLoadAndSave(false); this->Clear(); } m_InInitialized = false; m_Initialized = true; } void mitk::PersistenceService::Unitialize() { if(this->GetAutoLoadAndSave()) this->Save(); }<commit_msg>PersistenceService output MITK_DEBUG, not MITK_INFO, so its silent on startup<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPersistenceService.h" #include "mitkStandaloneDataStorage.h" #include "mitkUIDGenerator.h" #include "mitkNodePredicateProperty.h" #include "mitkProperties.h" #include "usModuleContext.h" #include "usGetModuleContext.h" #include <itksys/SystemTools.hxx> std::string mitk::PersistenceService::GetPersistencePropertyName() { return "PersistenceNode"; } std::string mitk::PersistenceService::GetPersistencePropertyListName() { return "PersistenceService"; } mitk::PersistenceService::PersistenceService() : m_AutoLoadAndSave( true ), m_Initialized(false), m_InInitialized(false) { } void mitk::PersistenceService::Clear() { this->Initialize(); m_PropertyLists.clear(); m_FileNamesToModifiedTimes.clear(); } mitk::PersistenceService::~PersistenceService() { MITK_DEBUG("mitk::PersistenceService") << "destructing PersistenceService"; } std::string mitk::PersistenceService::GetDefaultPersistenceFile() { this->Initialize(); std::string file = "PersistentData.xml"; us::ModuleContext* context = us::GetModuleContext(); std::string contextDataFile = context->GetDataFile(file); if( !contextDataFile.empty() ) { file = contextDataFile; } return file; } mitk::PropertyList::Pointer mitk::PersistenceService::GetPropertyList( std::string& id, bool* existed ) { this->Initialize(); mitk::PropertyList::Pointer propList; if( id.empty() ) { UIDGenerator uidGen; id = uidGen.GetUID(); } std::map<std::string, mitk::PropertyList::Pointer>::iterator it = m_PropertyLists.find( id ); if( it == m_PropertyLists.end() ) { propList = PropertyList::New(); m_PropertyLists[id] = propList; if( existed ) *existed = false; } else { propList = (*it).second; if( existed ) *existed = true; } return propList; } void mitk::PersistenceService::ClonePropertyList( mitk::PropertyList* from, mitk::PropertyList* to ) const { to->Clear(); const std::map< std::string, BaseProperty::Pointer>* propMap = from->GetMap(); std::map< std::string, BaseProperty::Pointer>::const_iterator propMapIt = propMap->begin(); while( propMapIt != propMap->end() ) { mitk::BaseProperty::Pointer clonedProp = (*propMapIt).second->Clone(); to->SetProperty( (*propMapIt).first, clonedProp ); ++propMapIt; } } bool mitk::PersistenceService::Save(const std::string& fileName, bool appendChanges) { this->Initialize(); bool save = false; std::string theFile = fileName; if(theFile.empty()) theFile = PersistenceService::GetDefaultPersistenceFile(); std::string thePath = itksys::SystemTools::GetFilenamePath( theFile.c_str() ); if( !thePath.empty() && !itksys::SystemTools::FileExists( thePath.c_str() ) ) { if( !itksys::SystemTools::MakeDirectory( thePath.c_str() ) ) { MITK_ERROR("PersistenceService") << "Could not create " << thePath; return false; } } bool createFile = !itksys::SystemTools::FileExists(theFile.c_str()); if( !itksys::SystemTools::Touch(theFile.c_str(), createFile) ) { MITK_ERROR("PersistenceService") << "Could not create or write to " << theFile; return false; } bool xmlFile = false; if( itksys::SystemTools::GetFilenameLastExtension(theFile.c_str()) == ".xml" ) xmlFile = true; mitk::DataStorage::Pointer tempDs; if( appendChanges ) { if(xmlFile == false) { if( itksys::SystemTools::FileExists(theFile.c_str()) ) { bool load = false; DataStorage::Pointer ds = m_SceneIO->LoadScene( theFile ); load = (m_SceneIO->GetFailedNodes() == 0 || m_SceneIO->GetFailedNodes()->size() == 0) && (m_SceneIO->GetFailedNodes() == 0 || m_SceneIO->GetFailedProperties()->IsEmpty()); if( !load ) return false; tempDs = ds; } } else { tempDs = mitk::StandaloneDataStorage::New(); if( xmlFile && appendChanges && itksys::SystemTools::FileExists(theFile.c_str()) ) { if( !m_PropertyListsXmlFileReaderAndWriter->ReadLists( theFile, m_PropertyLists ) ) return false; } } this->RestorePropertyListsFromPersistentDataNodes( tempDs ); } else if( xmlFile == false ) { tempDs = mitk::StandaloneDataStorage::New(); } if( xmlFile ) { save = m_PropertyListsXmlFileReaderAndWriter->WriteLists(theFile, m_PropertyLists); } else { DataStorage::SetOfObjects::Pointer sceneNodes = this->GetDataNodes(tempDs); if(m_SceneIO.IsNull()) { m_SceneIO = mitk::SceneIO::New(); } save = m_SceneIO->SaveScene( sceneNodes.GetPointer(), tempDs, theFile ); } if( save ) { long int currentModifiedTime = itksys::SystemTools::ModifiedTime( theFile.c_str() ); m_FileNamesToModifiedTimes[theFile] = currentModifiedTime; } return save; } bool mitk::PersistenceService::Load(const std::string& fileName, bool enforceReload) { this->Initialize(); bool load = false; std::string theFile = fileName; if(theFile.empty()) theFile = PersistenceService::GetDefaultPersistenceFile(); MITK_DEBUG << "Load persistence data from file: " << theFile; if( !itksys::SystemTools::FileExists(theFile.c_str()) ) return false; bool xmlFile = false; if( itksys::SystemTools::GetFilenameLastExtension(theFile.c_str()) == ".xml" ) xmlFile = true; if( enforceReload == false ) { bool loadTheFile = true; std::map<std::string, long int>::iterator it = m_FileNamesToModifiedTimes.find( theFile ); long int currentModifiedTime = itksys::SystemTools::ModifiedTime( theFile.c_str() ); if( it != m_FileNamesToModifiedTimes.end() ) { long int knownModifiedTime = (*it).second; if( knownModifiedTime >= currentModifiedTime ) { loadTheFile = false; } } if( loadTheFile ) m_FileNamesToModifiedTimes[theFile] = currentModifiedTime; else return true; } if( xmlFile ) { load = m_PropertyListsXmlFileReaderAndWriter->ReadLists(theFile, m_PropertyLists); } else { if(m_SceneIO.IsNull()) { m_SceneIO = mitk::SceneIO::New(); } DataStorage::Pointer ds = m_SceneIO->LoadScene( theFile ); load = (m_SceneIO->GetFailedNodes() == 0 || m_SceneIO->GetFailedNodes()->size() == 0) && (m_SceneIO->GetFailedNodes() == 0 || m_SceneIO->GetFailedProperties()->IsEmpty()); if( load ) { this->RestorePropertyListsFromPersistentDataNodes( ds ); } } if( !load ) { MITK_DEBUG("mitk::PersistenceService") << "loading of scene files failed"; return load; } return load; } void mitk::PersistenceService::SetAutoLoadAndSave(bool autoLoadAndSave) { this->Initialize(); m_AutoLoadAndSave = autoLoadAndSave; //std::string id = PERSISTENCE_PROPERTYLIST_NAME; //see bug 17729 std::string id = GetPersistencePropertyListName(); mitk::PropertyList::Pointer propList = this->GetPropertyList( id ); propList->Set("m_AutoLoadAndSave", m_AutoLoadAndSave); this->Save(); } void mitk::PersistenceService::AddPropertyListReplacedObserver(PropertyListReplacedObserver* observer) { this->Initialize(); m_PropertyListReplacedObserver.insert( observer ); } void mitk::PersistenceService::RemovePropertyListReplacedObserver(PropertyListReplacedObserver* observer) { this->Initialize(); m_PropertyListReplacedObserver.erase( observer ); } void mitk::PersistenceService::LoadModule() { MITK_DEBUG << "Persistence Module loaded."; } us::ModuleContext* mitk::PersistenceService::GetModuleContext() { return us::GetModuleContext(); } std::string mitk::PersistenceService::GetPersistenceNodePropertyName() { this->Initialize(); //return PERSISTENCE_PROPERTY_NAME; //see bug 17729 return GetPersistencePropertyName(); } mitk::DataStorage::SetOfObjects::Pointer mitk::PersistenceService::GetDataNodes(mitk::DataStorage* ds) { this->Initialize(); DataStorage::SetOfObjects::Pointer set = DataStorage::SetOfObjects::New(); std::map<std::string, mitk::PropertyList::Pointer>::const_iterator it = m_PropertyLists.begin(); while( it != m_PropertyLists.end() ) { mitk::DataNode::Pointer node = mitk::DataNode::New(); const std::string& name = (*it).first; this->ClonePropertyList( (*it).second, node->GetPropertyList() ); node->SetName( name ); MITK_DEBUG << "Persistence Property Name: " << GetPersistencePropertyName().c_str(); //node->SetBoolProperty( PERSISTENCE_PROPERTY_NAME.c_str() , true ); //see bug 17729 node->SetBoolProperty( GetPersistencePropertyName().c_str() , true ); ds->Add(node); set->push_back( node ); ++it; } return set; } bool mitk::PersistenceService::RestorePropertyListsFromPersistentDataNodes( const DataStorage* storage ) { this->Initialize(); bool oneFound = false; DataStorage::SetOfObjects::ConstPointer allNodes = storage->GetAll(); for ( mitk::DataStorage::SetOfObjects::const_iterator sourceIter = allNodes->begin(); sourceIter != allNodes->end(); ++sourceIter ) { mitk::DataNode* node = *sourceIter; bool isPersistenceNode = false; //node->GetBoolProperty( PERSISTENCE_PROPERTY_NAME.c_str(), isPersistenceNode ); //see bug 17729 node->GetBoolProperty( GetPersistencePropertyName().c_str(), isPersistenceNode ); if( isPersistenceNode ) { oneFound = true; MITK_DEBUG("mitk::PersistenceService") << "isPersistenceNode was true"; std::string name = node->GetName(); bool existed = false; mitk::PropertyList::Pointer propList = this->GetPropertyList( name, &existed ); if( existed ) { MITK_DEBUG("mitk::PersistenceService") << "calling replace observer before replacing values"; std::set<PropertyListReplacedObserver*>::iterator it = m_PropertyListReplacedObserver.begin(); while( it != m_PropertyListReplacedObserver.end() ) { (*it)->BeforePropertyListReplaced( name, propList ); ++it; } } // if( existed ) MITK_DEBUG("mitk::PersistenceService") << "replacing values"; this->ClonePropertyList( node->GetPropertyList(), propList ); if( existed ) { MITK_DEBUG("mitk::PersistenceService") << "calling replace observer before replacing values"; std::set<PropertyListReplacedObserver*>::iterator it = m_PropertyListReplacedObserver.begin(); while( it != m_PropertyListReplacedObserver.end() ) { (*it)->AfterPropertyListReplaced( name, propList ); ++it; } } // if( existed ) } // if( isPersistenceNode ) } // for ( mitk::DataStorage::SetOfObjects::const_iterator sourceIter = allNodes->begin(); ... return oneFound; } bool mitk::PersistenceService::GetAutoLoadAndSave() { this->Initialize(); return m_AutoLoadAndSave; } bool mitk::PersistenceService::RemovePropertyList( std::string& id ) { this->Initialize(); std::map<std::string, mitk::PropertyList::Pointer>::iterator it = m_PropertyLists.find( id ); if( it != m_PropertyLists.end() ) { m_PropertyLists.erase(it); return true; } return false; } void mitk::PersistenceService::Initialize() { if( m_Initialized || m_InInitialized) return; m_InInitialized = true; m_PropertyListsXmlFileReaderAndWriter = PropertyListsXmlFileReaderAndWriter::New(); // Load Default File in any case this->Load(); //std::string id = mitk::PersistenceService::PERSISTENCE_PROPERTYLIST_NAME; //see bug 17729 std::string id = GetPersistencePropertyListName(); mitk::PropertyList::Pointer propList = this->GetPropertyList( id ); bool autoLoadAndSave = true; propList->GetBoolProperty("m_AutoLoadAndSave", autoLoadAndSave); if( autoLoadAndSave == false ) { MITK_DEBUG("mitk::PersistenceService") << "autoloading was not wished. clearing data we got so far."; this->SetAutoLoadAndSave(false); this->Clear(); } m_InInitialized = false; m_Initialized = true; } void mitk::PersistenceService::Unitialize() { if(this->GetAutoLoadAndSave()) this->Save(); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script/sign.h" #include "key.h" #include "keystore.h" #include "policy/policy.h" #include "primitives/transaction.h" #include "script/standard.h" #include "uint256.h" #include "util.h" typedef std::vector<unsigned char> valtype; TransactionSignatureCreator::TransactionSignatureCreator(const CKeyStore* keystoreIn, const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn) : BaseSignatureCreator(keystoreIn), txTo(txToIn), nIn(nInIn), nHashType(nHashTypeIn), amount(amountIn), checker(txTo, nIn, amountIn) {} bool TransactionSignatureCreator::CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const { CKey key; if (!keystore->GetKey(address, key)) return false; uint256 hash; try { hash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion); } catch (std::logic_error ex) { return false; } if (!key.Sign(hash, vchSig)) return false; vchSig.push_back((unsigned char)nHashType); return true; } static bool Sign1(const CKeyID& address, const BaseSignatureCreator& creator, const CScript& scriptCode, std::vector<valtype>& ret, SigVersion sigversion) { std::vector<unsigned char> vchSig; if (!creator.CreateSig(vchSig, address, scriptCode, sigversion)) return false; ret.emplace_back(vchSig); return true; } static bool SignN(const std::vector<valtype>& multisigdata, const BaseSignatureCreator& creator, const CScript& scriptCode, std::vector<valtype>& ret, SigVersion sigversion) { int nSigned = 0; int nRequired = multisigdata.front()[0]; for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++) { const valtype& pubkey = multisigdata[i]; CKeyID keyID = CPubKey(pubkey).GetID(); if (Sign1(keyID, creator, scriptCode, ret, sigversion)) ++nSigned; } return nSigned==nRequired; } /** * Sign scriptPubKey using signature made with creator. * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed), * unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script. * Returns false if scriptPubKey could not be completely satisfied. */ static bool SignStep(const BaseSignatureCreator& creator, const CScript& scriptPubKey, std::vector<valtype>& ret, txnouttype& whichTypeRet, SigVersion sigversion, bool fColdStake) { CScript scriptRet; uint160 h160; ret.clear(); std::vector<valtype> vSolutions; if (!Solver(scriptPubKey, whichTypeRet, vSolutions)) return false; CKeyID keyID; switch (whichTypeRet) { case TX_NONSTANDARD: case TX_NULL_DATA: return false; case TX_ZEROCOINMINT: return false; case TX_PUBKEY: keyID = CPubKey(vSolutions[0]).GetID(); return Sign1(keyID, creator, scriptPubKey, ret, sigversion); case TX_PUBKEYHASH: keyID = CKeyID(uint160(vSolutions[0])); if (!Sign1(keyID, creator, scriptPubKey, ret, sigversion)) return false; else { CPubKey vch; creator.KeyStore().GetPubKey(keyID, vch); ret.push_back(ToByteVector(vch)); } return true; case TX_SCRIPTHASH: if (creator.KeyStore().GetCScript(uint160(vSolutions[0]), scriptRet)) { ret.emplace_back(scriptRet.begin(), scriptRet.end()); return true; } return false; case TX_MULTISIG: ret.push_back(valtype()); // workaround CHECKMULTISIG bug return (SignN(vSolutions, creator, scriptPubKey, ret, sigversion)); case TX_COLDSTAKE: if (fColdStake) { // sign with the cold staker key keyID = CKeyID(uint160(vSolutions[0])); } else { // sign with the owner key keyID = CKeyID(uint160(vSolutions[1])); } if (!Sign1(keyID, creator, scriptPubKey, ret, sigversion)) return error("*** %s: failed to sign with the %s key.", __func__, fColdStake ? "cold staker" : "owner"); CPubKey vch; if (!creator.KeyStore().GetPubKey(keyID, vch)) return error("%s : Unable to get public key from keyID", __func__); valtype oper; oper.reserve(4); oper.emplace_back((fColdStake ? (int) OP_TRUE : OP_FALSE)); ret.emplace_back(oper); ret.emplace_back(ToByteVector(vch)); return true; } LogPrintf("*** solver no case met \n"); return false; } static CScript PushAll(const std::vector<valtype>& values) { CScript result; for (const valtype& v : values) { if (v.size() == 0) { result << OP_0; } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) { result << CScript::EncodeOP_N(v[0]); } else { result << v; } } return result; } bool ProduceSignature(const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata, SigVersion sigversion, bool fColdStake, ScriptError* serror) { CScript script = fromPubKey; bool solved = true; std::vector<valtype> result; txnouttype whichType; solved = SignStep(creator, script, result, whichType, sigversion, fColdStake); CScript subscript; if (solved && whichType == TX_SCRIPTHASH) { // Solver returns the subscript that needs to be evaluated; // the final scriptSig is the signatures from that // and then the serialized subscript: script = subscript = CScript(result[0].begin(), result[0].end()); solved = solved && SignStep(creator, script, result, whichType, sigversion, fColdStake) && whichType != TX_SCRIPTHASH; result.emplace_back(subscript.begin(), subscript.end()); } sigdata.scriptSig = PushAll(result); // Test solution return solved && VerifyScript(sigdata.scriptSig, fromPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker(), sigversion, serror); } SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn) { SignatureData data; assert(tx.vin.size() > nIn); data.scriptSig = tx.vin[nIn].scriptSig; return data; } void UpdateTransaction(CMutableTransaction& tx, unsigned int nIn, const SignatureData& data) { assert(tx.vin.size() > nIn); tx.vin[nIn].scriptSig = data.scriptSig; } bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType, bool fColdStake) { assert(nIn < txTo.vin.size()); CTransaction txToConst(txTo); TransactionSignatureCreator creator(&keystore, &txToConst, nIn, amount, nHashType); SignatureData sigdata; bool ret = ProduceSignature(creator, fromPubKey, sigdata, txToConst.GetRequiredSigVersion(), fColdStake); UpdateTransaction(txTo, nIn, sigdata); return ret; } bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType, bool fColdStake) { assert(nIn < txTo.vin.size()); CTxIn& txin = txTo.vin[nIn]; assert(txin.prevout.n < txFrom.vout.size()); const CTxOut& txout = txFrom.vout[txin.prevout.n]; return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, txout.nValue, nHashType, fColdStake); } static std::vector<valtype> CombineMultisig(const CScript& scriptPubKey, const BaseSignatureChecker& checker, const std::vector<valtype>& vSolutions, const std::vector<valtype>& sigs1, const std::vector<valtype>& sigs2, SigVersion sigversion) { // Combine all the signatures we've got: std::set<valtype> allsigs; for (const valtype& v : sigs1) { if (!v.empty()) allsigs.insert(v); } for (const valtype& v : sigs2) { if (!v.empty()) allsigs.insert(v); } // Build a map of pubkey -> signature by matching sigs to pubkeys: assert(vSolutions.size() > 1); unsigned int nSigsRequired = vSolutions.front()[0]; unsigned int nPubKeys = vSolutions.size()-2; std::map<valtype, valtype> sigs; for (const valtype& sig : allsigs) { for (unsigned int i = 0; i < nPubKeys; i++) { const valtype& pubkey = vSolutions[i+1]; if (sigs.count(pubkey)) continue; // Already got a sig for this pubkey if (checker.CheckSig(sig, pubkey, scriptPubKey, sigversion)) { sigs[pubkey] = sig; break; } } } // Now build a merged CScript: unsigned int nSigsHave = 0; std::vector<valtype> result; result.emplace_back(); // pop-one-too-many workaround for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++) { if (sigs.count(vSolutions[i+1])) { result.push_back(sigs[vSolutions[i+1]]); ++nSigsHave; } } // Fill any missing with OP_0: for (unsigned int i = nSigsHave; i < nSigsRequired; i++) result.push_back(valtype()); return result; } namespace { struct Stacks { std::vector<valtype> script; Stacks() {} explicit Stacks(const std::vector<valtype>& scriptSigStack_) : script(scriptSigStack_) {} explicit Stacks(const SignatureData& data, SigVersion sigversion) { EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), sigversion); } SignatureData Output() const { SignatureData result; result.scriptSig = PushAll(script); return result; } }; } static Stacks CombineSignatures(const CScript& scriptPubKey, const BaseSignatureChecker& checker, const txnouttype txType, const std::vector<valtype>& vSolutions, Stacks sigs1, Stacks sigs2, SigVersion sigversion) { switch (txType) { case TX_NONSTANDARD: case TX_NULL_DATA: case TX_ZEROCOINMINT: // Don't know anything about this, assume bigger one is correct: if (sigs1.script.size() >= sigs2.script.size()) return sigs1; return sigs2; case TX_PUBKEY: case TX_PUBKEYHASH: case TX_COLDSTAKE: // Signatures are bigger than placeholders or empty scripts: if (sigs1.script.empty() || sigs1.script[0].empty()) return sigs2; return sigs1; case TX_SCRIPTHASH: if (sigs1.script.empty() || sigs1.script.back().empty()) return sigs2; else if (sigs2.script.empty() || sigs2.script.back().empty()) return sigs1; else { // Recur to combine: valtype spk = sigs1.script.back(); CScript pubKey2(spk.begin(), spk.end()); txnouttype txType2; std::vector<std::vector<unsigned char> > vSolutions2; Solver(pubKey2, txType2, vSolutions2); sigs1.script.pop_back(); sigs2.script.pop_back(); Stacks result = CombineSignatures(pubKey2, checker, txType2, vSolutions2, sigs1, sigs2, sigversion); result.script.push_back(spk); return result; } case TX_MULTISIG: return Stacks(CombineMultisig(scriptPubKey, checker, vSolutions, sigs1.script, sigs2.script, sigversion)); } return Stacks(); } SignatureData CombineSignatures(const CScript& scriptPubKey, const BaseSignatureChecker& checker, const SignatureData& scriptSig1, const SignatureData& scriptSig2) { txnouttype txType; std::vector<std::vector<unsigned char> > vSolutions; Solver(scriptPubKey, txType, vSolutions); return CombineSignatures(scriptPubKey, checker, txType, vSolutions, Stacks(scriptSig1, SIGVERSION_BASE), Stacks(scriptSig2, SIGVERSION_BASE), SIGVERSION_BASE).Output(); } namespace { /** Dummy signature checker which accepts all signatures. */ class DummySignatureChecker : public BaseSignatureChecker { public: DummySignatureChecker() {} bool CheckSig(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const { return true; } }; const DummySignatureChecker dummyChecker; } const BaseSignatureChecker& DummySignatureCreator::Checker() const { return dummyChecker; } bool DummySignatureCreator::CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const { // Create a dummy signature that is a valid DER-encoding vchSig.assign(72, '\000'); vchSig[0] = 0x30; vchSig[1] = 69; vchSig[2] = 0x02; vchSig[3] = 33; vchSig[4] = 0x01; vchSig[4 + 33] = 0x02; vchSig[5 + 33] = 32; vchSig[6 + 33] = 0x01; vchSig[6 + 33 + 32] = SIGHASH_ALL; return true; } bool IsSolvable(const CKeyStore& store, const CScript& script, bool fColdStaking) { // This check is to make sure that the script we created can actually be solved for and signed by us // if we were to have the private keys. This is just to make sure that the script is valid and that, // if found in a transaction, we would still accept and relay that transaction. In particular, DummySignatureCreator creator(&store); SignatureData sigs; if (ProduceSignature(creator, script, sigs, SIGVERSION_BASE, fColdStaking)) { // VerifyScript check is just defensive, and should never fail. assert(VerifyScript(sigs.scriptSig, script, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker(), SIGVERSION_BASE)); return true; } return false; } <commit_msg>[Refactor] Pass caught logic_error by reference in CreateSig<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script/sign.h" #include "key.h" #include "keystore.h" #include "policy/policy.h" #include "primitives/transaction.h" #include "script/standard.h" #include "uint256.h" #include "util.h" typedef std::vector<unsigned char> valtype; TransactionSignatureCreator::TransactionSignatureCreator(const CKeyStore* keystoreIn, const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn) : BaseSignatureCreator(keystoreIn), txTo(txToIn), nIn(nInIn), nHashType(nHashTypeIn), amount(amountIn), checker(txTo, nIn, amountIn) {} bool TransactionSignatureCreator::CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const { CKey key; if (!keystore->GetKey(address, key)) return false; uint256 hash; try { hash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion); } catch (const std::logic_error& ex) { return false; } if (!key.Sign(hash, vchSig)) return false; vchSig.push_back((unsigned char)nHashType); return true; } static bool Sign1(const CKeyID& address, const BaseSignatureCreator& creator, const CScript& scriptCode, std::vector<valtype>& ret, SigVersion sigversion) { std::vector<unsigned char> vchSig; if (!creator.CreateSig(vchSig, address, scriptCode, sigversion)) return false; ret.emplace_back(vchSig); return true; } static bool SignN(const std::vector<valtype>& multisigdata, const BaseSignatureCreator& creator, const CScript& scriptCode, std::vector<valtype>& ret, SigVersion sigversion) { int nSigned = 0; int nRequired = multisigdata.front()[0]; for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++) { const valtype& pubkey = multisigdata[i]; CKeyID keyID = CPubKey(pubkey).GetID(); if (Sign1(keyID, creator, scriptCode, ret, sigversion)) ++nSigned; } return nSigned==nRequired; } /** * Sign scriptPubKey using signature made with creator. * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed), * unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script. * Returns false if scriptPubKey could not be completely satisfied. */ static bool SignStep(const BaseSignatureCreator& creator, const CScript& scriptPubKey, std::vector<valtype>& ret, txnouttype& whichTypeRet, SigVersion sigversion, bool fColdStake) { CScript scriptRet; uint160 h160; ret.clear(); std::vector<valtype> vSolutions; if (!Solver(scriptPubKey, whichTypeRet, vSolutions)) return false; CKeyID keyID; switch (whichTypeRet) { case TX_NONSTANDARD: case TX_NULL_DATA: return false; case TX_ZEROCOINMINT: return false; case TX_PUBKEY: keyID = CPubKey(vSolutions[0]).GetID(); return Sign1(keyID, creator, scriptPubKey, ret, sigversion); case TX_PUBKEYHASH: keyID = CKeyID(uint160(vSolutions[0])); if (!Sign1(keyID, creator, scriptPubKey, ret, sigversion)) return false; else { CPubKey vch; creator.KeyStore().GetPubKey(keyID, vch); ret.push_back(ToByteVector(vch)); } return true; case TX_SCRIPTHASH: if (creator.KeyStore().GetCScript(uint160(vSolutions[0]), scriptRet)) { ret.emplace_back(scriptRet.begin(), scriptRet.end()); return true; } return false; case TX_MULTISIG: ret.push_back(valtype()); // workaround CHECKMULTISIG bug return (SignN(vSolutions, creator, scriptPubKey, ret, sigversion)); case TX_COLDSTAKE: if (fColdStake) { // sign with the cold staker key keyID = CKeyID(uint160(vSolutions[0])); } else { // sign with the owner key keyID = CKeyID(uint160(vSolutions[1])); } if (!Sign1(keyID, creator, scriptPubKey, ret, sigversion)) return error("*** %s: failed to sign with the %s key.", __func__, fColdStake ? "cold staker" : "owner"); CPubKey vch; if (!creator.KeyStore().GetPubKey(keyID, vch)) return error("%s : Unable to get public key from keyID", __func__); valtype oper; oper.reserve(4); oper.emplace_back((fColdStake ? (int) OP_TRUE : OP_FALSE)); ret.emplace_back(oper); ret.emplace_back(ToByteVector(vch)); return true; } LogPrintf("*** solver no case met \n"); return false; } static CScript PushAll(const std::vector<valtype>& values) { CScript result; for (const valtype& v : values) { if (v.size() == 0) { result << OP_0; } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) { result << CScript::EncodeOP_N(v[0]); } else { result << v; } } return result; } bool ProduceSignature(const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata, SigVersion sigversion, bool fColdStake, ScriptError* serror) { CScript script = fromPubKey; bool solved = true; std::vector<valtype> result; txnouttype whichType; solved = SignStep(creator, script, result, whichType, sigversion, fColdStake); CScript subscript; if (solved && whichType == TX_SCRIPTHASH) { // Solver returns the subscript that needs to be evaluated; // the final scriptSig is the signatures from that // and then the serialized subscript: script = subscript = CScript(result[0].begin(), result[0].end()); solved = solved && SignStep(creator, script, result, whichType, sigversion, fColdStake) && whichType != TX_SCRIPTHASH; result.emplace_back(subscript.begin(), subscript.end()); } sigdata.scriptSig = PushAll(result); // Test solution return solved && VerifyScript(sigdata.scriptSig, fromPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker(), sigversion, serror); } SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn) { SignatureData data; assert(tx.vin.size() > nIn); data.scriptSig = tx.vin[nIn].scriptSig; return data; } void UpdateTransaction(CMutableTransaction& tx, unsigned int nIn, const SignatureData& data) { assert(tx.vin.size() > nIn); tx.vin[nIn].scriptSig = data.scriptSig; } bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType, bool fColdStake) { assert(nIn < txTo.vin.size()); CTransaction txToConst(txTo); TransactionSignatureCreator creator(&keystore, &txToConst, nIn, amount, nHashType); SignatureData sigdata; bool ret = ProduceSignature(creator, fromPubKey, sigdata, txToConst.GetRequiredSigVersion(), fColdStake); UpdateTransaction(txTo, nIn, sigdata); return ret; } bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType, bool fColdStake) { assert(nIn < txTo.vin.size()); CTxIn& txin = txTo.vin[nIn]; assert(txin.prevout.n < txFrom.vout.size()); const CTxOut& txout = txFrom.vout[txin.prevout.n]; return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, txout.nValue, nHashType, fColdStake); } static std::vector<valtype> CombineMultisig(const CScript& scriptPubKey, const BaseSignatureChecker& checker, const std::vector<valtype>& vSolutions, const std::vector<valtype>& sigs1, const std::vector<valtype>& sigs2, SigVersion sigversion) { // Combine all the signatures we've got: std::set<valtype> allsigs; for (const valtype& v : sigs1) { if (!v.empty()) allsigs.insert(v); } for (const valtype& v : sigs2) { if (!v.empty()) allsigs.insert(v); } // Build a map of pubkey -> signature by matching sigs to pubkeys: assert(vSolutions.size() > 1); unsigned int nSigsRequired = vSolutions.front()[0]; unsigned int nPubKeys = vSolutions.size()-2; std::map<valtype, valtype> sigs; for (const valtype& sig : allsigs) { for (unsigned int i = 0; i < nPubKeys; i++) { const valtype& pubkey = vSolutions[i+1]; if (sigs.count(pubkey)) continue; // Already got a sig for this pubkey if (checker.CheckSig(sig, pubkey, scriptPubKey, sigversion)) { sigs[pubkey] = sig; break; } } } // Now build a merged CScript: unsigned int nSigsHave = 0; std::vector<valtype> result; result.emplace_back(); // pop-one-too-many workaround for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++) { if (sigs.count(vSolutions[i+1])) { result.push_back(sigs[vSolutions[i+1]]); ++nSigsHave; } } // Fill any missing with OP_0: for (unsigned int i = nSigsHave; i < nSigsRequired; i++) result.push_back(valtype()); return result; } namespace { struct Stacks { std::vector<valtype> script; Stacks() {} explicit Stacks(const std::vector<valtype>& scriptSigStack_) : script(scriptSigStack_) {} explicit Stacks(const SignatureData& data, SigVersion sigversion) { EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), sigversion); } SignatureData Output() const { SignatureData result; result.scriptSig = PushAll(script); return result; } }; } static Stacks CombineSignatures(const CScript& scriptPubKey, const BaseSignatureChecker& checker, const txnouttype txType, const std::vector<valtype>& vSolutions, Stacks sigs1, Stacks sigs2, SigVersion sigversion) { switch (txType) { case TX_NONSTANDARD: case TX_NULL_DATA: case TX_ZEROCOINMINT: // Don't know anything about this, assume bigger one is correct: if (sigs1.script.size() >= sigs2.script.size()) return sigs1; return sigs2; case TX_PUBKEY: case TX_PUBKEYHASH: case TX_COLDSTAKE: // Signatures are bigger than placeholders or empty scripts: if (sigs1.script.empty() || sigs1.script[0].empty()) return sigs2; return sigs1; case TX_SCRIPTHASH: if (sigs1.script.empty() || sigs1.script.back().empty()) return sigs2; else if (sigs2.script.empty() || sigs2.script.back().empty()) return sigs1; else { // Recur to combine: valtype spk = sigs1.script.back(); CScript pubKey2(spk.begin(), spk.end()); txnouttype txType2; std::vector<std::vector<unsigned char> > vSolutions2; Solver(pubKey2, txType2, vSolutions2); sigs1.script.pop_back(); sigs2.script.pop_back(); Stacks result = CombineSignatures(pubKey2, checker, txType2, vSolutions2, sigs1, sigs2, sigversion); result.script.push_back(spk); return result; } case TX_MULTISIG: return Stacks(CombineMultisig(scriptPubKey, checker, vSolutions, sigs1.script, sigs2.script, sigversion)); } return Stacks(); } SignatureData CombineSignatures(const CScript& scriptPubKey, const BaseSignatureChecker& checker, const SignatureData& scriptSig1, const SignatureData& scriptSig2) { txnouttype txType; std::vector<std::vector<unsigned char> > vSolutions; Solver(scriptPubKey, txType, vSolutions); return CombineSignatures(scriptPubKey, checker, txType, vSolutions, Stacks(scriptSig1, SIGVERSION_BASE), Stacks(scriptSig2, SIGVERSION_BASE), SIGVERSION_BASE).Output(); } namespace { /** Dummy signature checker which accepts all signatures. */ class DummySignatureChecker : public BaseSignatureChecker { public: DummySignatureChecker() {} bool CheckSig(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const { return true; } }; const DummySignatureChecker dummyChecker; } const BaseSignatureChecker& DummySignatureCreator::Checker() const { return dummyChecker; } bool DummySignatureCreator::CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const { // Create a dummy signature that is a valid DER-encoding vchSig.assign(72, '\000'); vchSig[0] = 0x30; vchSig[1] = 69; vchSig[2] = 0x02; vchSig[3] = 33; vchSig[4] = 0x01; vchSig[4 + 33] = 0x02; vchSig[5 + 33] = 32; vchSig[6 + 33] = 0x01; vchSig[6 + 33 + 32] = SIGHASH_ALL; return true; } bool IsSolvable(const CKeyStore& store, const CScript& script, bool fColdStaking) { // This check is to make sure that the script we created can actually be solved for and signed by us // if we were to have the private keys. This is just to make sure that the script is valid and that, // if found in a transaction, we would still accept and relay that transaction. In particular, DummySignatureCreator creator(&store); SignatureData sigs; if (ProduceSignature(creator, script, sigs, SIGVERSION_BASE, fColdStaking)) { // VerifyScript check is just defensive, and should never fail. assert(VerifyScript(sigs.scriptSig, script, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker(), SIGVERSION_BASE)); return true; } return false; } <|endoftext|>
<commit_before>/* * Recognizer.cc * * Copyright (C) 2015 Linas Vepstas * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the * exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public * License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef _OPENCOG_RECOGNIZER_H #define _OPENCOG_RECOGNIZER_H #include <set> #include <opencog/query/DefaultPatternMatchCB.h> #include <opencog/atoms/pattern/PatternLink.h> #include "BindLinkAPI.h" namespace opencog { /** * Very rough, crude, experimental prototype for the idea that * pattern recognition is the dual of pattern matching. * That is, rather than using one query pattern to search a large * collection of data, this does the opposite: given a single piece of * data, it searches for all rules/queries which apply to it. * * The file /examples/aiml/recog.scm provides a very simple example. * The implementation here is very minimalistic, and does many things * wrong: * -- it fails to perform any type-checking to make sure the variable * constraints are satisfied. * -- AIML wants a left-to-right traversal, this does an omni- * directional exploration. (which is OK, but is not how AIML is * defined...) * -- This hasn't been thought through thoroughly. There are almost * surely some weird gotcha's. */ class Recognizer : public virtual DefaultPatternMatchCB { protected: const Pattern* _pattern; Handle _root; Handle _starter_term; size_t _cnt; bool do_search(PatternMatchEngine*, const Handle&); bool loose_match(const Handle&, const Handle&); public: OrderedHandleSet _rules; Recognizer(AtomSpace* as) : DefaultPatternMatchCB(as) {} virtual void set_pattern(const Variables& vars, const Pattern& pat) { _pattern = &pat; DefaultPatternMatchCB::set_pattern(vars, pat); } virtual bool initiate_search(PatternMatchEngine*); virtual bool node_match(const Handle&, const Handle&); virtual bool link_match(const LinkPtr&, const LinkPtr&); virtual bool fuzzy_match(const Handle&, const Handle&); virtual bool grounding(const HandleMap &var_soln, const HandleMap &term_soln); }; } // namespace opencog #endif // _OPENCOG_RECOGNIZER_H using namespace opencog; // Uncomment below to enable debug print #define DEBUG #ifdef DEBUG #define dbgprt(f, varargs...) logger().fine(f, ##varargs) #else #define dbgprt(f, varargs...) #endif /* ======================================================== */ bool Recognizer::do_search(PatternMatchEngine* pme, const Handle& top) { if (top->isLink()) { // Recursively drill down and explore every possible node as // a search starting point. This is needed, as the patterns we // compare against might not be connected. for (const Handle& h : top->getOutgoingSet()) { _starter_term = top; bool found = do_search(pme, h); if (found) return true; } return false; } IncomingSet iset = get_incoming_set(top); size_t sz = iset.size(); for (size_t i = 0; i < sz; i++) { Handle h(iset[i]); dbgprt("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr\n"); dbgprt("Loop candidate (%lu - %s):\n%s\n", _cnt++, top->toShortString().c_str(), h->toShortString().c_str()); bool found = pme->explore_neighborhood(_root, _starter_term, h); // Terminate search if satisfied. if (found) return true; } return false; } bool Recognizer::initiate_search(PatternMatchEngine* pme) { const HandleSeq& clauses = _pattern->cnf_clauses; _cnt = 0; for (const Handle& h: clauses) { _root = h; bool found = do_search(pme, h); if (found) return true; } return false; } bool Recognizer::node_match(const Handle& npat_h, const Handle& nsoln_h) { if (npat_h == nsoln_h) return true; Type tso = nsoln_h->getType(); if (VARIABLE_NODE == tso or GLOB_NODE == tso) return true; return false; } bool Recognizer::link_match(const LinkPtr& lpat, const LinkPtr& lsoln) { // Self-compares always proceed. if (lpat == lsoln) return true; // mis-matched types are a dead-end. if (lpat->getType() != lsoln->getType()) return false; // Globs are arity-changing. But there is a minimum length. // Note that the inequality is backwards, here: the soln has the // globs! (and so lpat must have arity equal or greater than soln) if (lpat->getArity() < lsoln->getArity()) return false; return true; } bool Recognizer::loose_match(const Handle& npat_h, const Handle& nsoln_h) { Type gtype = nsoln_h->getType(); // Variable matches anything; move to next. if (VARIABLE_NODE == gtype) return true; // Strict match for link types. if (npat_h->getType() != gtype) return false; if (not npat_h->isNode()) return true; // If we are here, we know we have nodes. Ask for a strict match. if (npat_h != nsoln_h) return false; return true; } bool Recognizer::fuzzy_match(const Handle& npat_h, const Handle& nsoln_h) { // If we are here, then there are probably glob nodes in the soln. // Try to match them, fairly rigorously. Exactly what constitutes // an OK match is still a bit up in the air. if (not npat_h->isLink() or not nsoln_h->isLink()) return false; const HandleSeq &osg = nsoln_h->getOutgoingSet(); size_t osg_size = osg.size(); // Lets not waste time, if there's no glob there. bool have_glob = false; for (size_t j=0; j<osg_size; j++) { if (osg[j]->getType() == GLOB_NODE) { have_glob = true; break; } } if (not have_glob) return false; const HandleSeq &osp = npat_h->getOutgoingSet(); size_t osp_size = osp.size(); size_t max_size = std::max(osg_size, osp_size); // Do a side-by-side compare. This is not as rigorous as // PatternMatchEngine::tree_compare() nor does it handle the bells // and whistles (ChoiceLink, QuoteLink, etc). size_t ip=0, jg=0; for (; ip<osp_size and jg<osg_size; ip++, jg++) { if (GLOB_NODE != osg[jg]->getType()) { if (loose_match(osp[ip], osg[jg])) continue; return false; } // If we are here, we have a glob in the soln. If the glob is at // the end, it eats everything, so its a match. Else, resume // matching at the end of the glob. if ((jg+1) == osg_size) return true; const Handle& post(osg[jg+1]); ip++; while (ip < max_size and not loose_match(osp[ip], post)) { ip++; } // If ip ran past the end, then the post was not found. This is // a mismatch. if (not (ip < max_size)) return false; // Go around again, look for more GlobNodes. Back up by one, so // that the for-loop increment gets us back on track. ip--; } // If we are here, then we should have matched up all the atoms; // if we exited the loop because pattern or grounding was short, // then its a mis-match. if (ip != osp_size or jg != osg_size) return false; return true; } bool Recognizer::grounding(const HandleMap& var_soln, const HandleMap& term_soln) { Handle rule = term_soln.at(_root); if (rule != _root) { _rules.insert(rule); } // Look for more groundings. return false; } Handle opencog::recognize(AtomSpace* as, const Handle& hlink) { PatternLinkPtr bl(PatternLinkCast(hlink)); if (NULL == bl) bl = createPatternLink(*LinkCast(hlink)); Recognizer reco(as); bl->satisfy(reco); HandleSeq hs; for (const Handle& h : reco._rules) hs.push_back(h); return as->add_link(SET_LINK, hs); } <commit_msg>Misssed a spot ion the previous conversions<commit_after>/* * Recognizer.cc * * Copyright (C) 2015 Linas Vepstas * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the * exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public * License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef _OPENCOG_RECOGNIZER_H #define _OPENCOG_RECOGNIZER_H #include <set> #include <opencog/query/DefaultPatternMatchCB.h> #include <opencog/atoms/pattern/PatternLink.h> #include "BindLinkAPI.h" namespace opencog { /** * Very rough, crude, experimental prototype for the idea that * pattern recognition is the dual of pattern matching. * That is, rather than using one query pattern to search a large * collection of data, this does the opposite: given a single piece of * data, it searches for all rules/queries which apply to it. * * The file /examples/aiml/recog.scm provides a very simple example. * The implementation here is very minimalistic, and does many things * wrong: * -- it fails to perform any type-checking to make sure the variable * constraints are satisfied. * -- AIML wants a left-to-right traversal, this does an omni- * directional exploration. (which is OK, but is not how AIML is * defined...) * -- This hasn't been thought through thoroughly. There are almost * surely some weird gotcha's. */ class Recognizer : public virtual DefaultPatternMatchCB { protected: const Pattern* _pattern; Handle _root; Handle _starter_term; size_t _cnt; bool do_search(PatternMatchEngine*, const Handle&); bool loose_match(const Handle&, const Handle&); public: OrderedHandleSet _rules; Recognizer(AtomSpace* as) : DefaultPatternMatchCB(as) {} virtual void set_pattern(const Variables& vars, const Pattern& pat) { _pattern = &pat; DefaultPatternMatchCB::set_pattern(vars, pat); } virtual bool initiate_search(PatternMatchEngine*); virtual bool node_match(const Handle&, const Handle&); virtual bool link_match(const Handle&, const Handle&); virtual bool fuzzy_match(const Handle&, const Handle&); virtual bool grounding(const HandleMap &var_soln, const HandleMap &term_soln); }; } // namespace opencog #endif // _OPENCOG_RECOGNIZER_H using namespace opencog; // Uncomment below to enable debug print #define DEBUG #ifdef DEBUG #define dbgprt(f, varargs...) logger().fine(f, ##varargs) #else #define dbgprt(f, varargs...) #endif /* ======================================================== */ bool Recognizer::do_search(PatternMatchEngine* pme, const Handle& top) { if (top->isLink()) { // Recursively drill down and explore every possible node as // a search starting point. This is needed, as the patterns we // compare against might not be connected. for (const Handle& h : top->getOutgoingSet()) { _starter_term = top; bool found = do_search(pme, h); if (found) return true; } return false; } IncomingSet iset = get_incoming_set(top); size_t sz = iset.size(); for (size_t i = 0; i < sz; i++) { Handle h(iset[i]); dbgprt("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr\n"); dbgprt("Loop candidate (%lu - %s):\n%s\n", _cnt++, top->toShortString().c_str(), h->toShortString().c_str()); bool found = pme->explore_neighborhood(_root, _starter_term, h); // Terminate search if satisfied. if (found) return true; } return false; } bool Recognizer::initiate_search(PatternMatchEngine* pme) { const HandleSeq& clauses = _pattern->cnf_clauses; _cnt = 0; for (const Handle& h: clauses) { _root = h; bool found = do_search(pme, h); if (found) return true; } return false; } bool Recognizer::node_match(const Handle& npat_h, const Handle& nsoln_h) { if (npat_h == nsoln_h) return true; Type tso = nsoln_h->getType(); if (VARIABLE_NODE == tso or GLOB_NODE == tso) return true; return false; } bool Recognizer::link_match(const Handle& lpat, const Handle& lsoln) { // Self-compares always proceed. if (lpat == lsoln) return true; // mis-matched types are a dead-end. if (lpat->getType() != lsoln->getType()) return false; // Globs are arity-changing. But there is a minimum length. // Note that the inequality is backwards, here: the soln has the // globs! (and so lpat must have arity equal or greater than soln) if (lpat->getArity() < lsoln->getArity()) return false; return true; } bool Recognizer::loose_match(const Handle& npat_h, const Handle& nsoln_h) { Type gtype = nsoln_h->getType(); // Variable matches anything; move to next. if (VARIABLE_NODE == gtype) return true; // Strict match for link types. if (npat_h->getType() != gtype) return false; if (not npat_h->isNode()) return true; // If we are here, we know we have nodes. Ask for a strict match. if (npat_h != nsoln_h) return false; return true; } bool Recognizer::fuzzy_match(const Handle& npat_h, const Handle& nsoln_h) { // If we are here, then there are probably glob nodes in the soln. // Try to match them, fairly rigorously. Exactly what constitutes // an OK match is still a bit up in the air. if (not npat_h->isLink() or not nsoln_h->isLink()) return false; const HandleSeq &osg = nsoln_h->getOutgoingSet(); size_t osg_size = osg.size(); // Lets not waste time, if there's no glob there. bool have_glob = false; for (size_t j=0; j<osg_size; j++) { if (osg[j]->getType() == GLOB_NODE) { have_glob = true; break; } } if (not have_glob) return false; const HandleSeq &osp = npat_h->getOutgoingSet(); size_t osp_size = osp.size(); size_t max_size = std::max(osg_size, osp_size); // Do a side-by-side compare. This is not as rigorous as // PatternMatchEngine::tree_compare() nor does it handle the bells // and whistles (ChoiceLink, QuoteLink, etc). size_t ip=0, jg=0; for (; ip<osp_size and jg<osg_size; ip++, jg++) { if (GLOB_NODE != osg[jg]->getType()) { if (loose_match(osp[ip], osg[jg])) continue; return false; } // If we are here, we have a glob in the soln. If the glob is at // the end, it eats everything, so its a match. Else, resume // matching at the end of the glob. if ((jg+1) == osg_size) return true; const Handle& post(osg[jg+1]); ip++; while (ip < max_size and not loose_match(osp[ip], post)) { ip++; } // If ip ran past the end, then the post was not found. This is // a mismatch. if (not (ip < max_size)) return false; // Go around again, look for more GlobNodes. Back up by one, so // that the for-loop increment gets us back on track. ip--; } // If we are here, then we should have matched up all the atoms; // if we exited the loop because pattern or grounding was short, // then its a mis-match. if (ip != osp_size or jg != osg_size) return false; return true; } bool Recognizer::grounding(const HandleMap& var_soln, const HandleMap& term_soln) { Handle rule = term_soln.at(_root); if (rule != _root) { _rules.insert(rule); } // Look for more groundings. return false; } Handle opencog::recognize(AtomSpace* as, const Handle& hlink) { PatternLinkPtr bl(PatternLinkCast(hlink)); if (NULL == bl) bl = createPatternLink(*LinkCast(hlink)); Recognizer reco(as); bl->satisfy(reco); HandleSeq hs; for (const Handle& h : reco._rules) hs.push_back(h); return as->add_link(SET_LINK, hs); } <|endoftext|>
<commit_before>#include "CONTROL_S.H" #include "SPECIFIC.H" void DrawBinoculars() { S_Warn("[DrawBinoculars] - Unimplemented!\n"); }<commit_msg>[Specific-PSXPC_N] Implement GetChange.<commit_after>#include "CONTROL_S.H" #include "DRAW.H" #include "SPECIFIC.H" void DrawBinoculars() { S_Warn("[DrawBinoculars] - Unimplemented!\n"); } int GetChange(struct ITEM_INFO* item, struct ANIM_STRUCT* anim)//7D48C { struct CHANGE_STRUCT* change;//$t1 struct RANGE_STRUCT* range;//$v1 int i;//$t2 int j;//$t0 if (item->current_anim_state == item->goal_anim_state) { //locret_7D51C return 0; } change = &changes[anim->change_index]; if (anim->number_changes <= 0) { //locret_7D51C return 0; } //loc_7D4C4 do { j = 0; if (change->goal_anim_state == item->goal_anim_state && change->number_ranges > 0) { range = &ranges[change->range_index]; //loc_7D4E4 do { if (item->frame_number < range->start_frame) { //loc_7D4FC j++; if (j < change->number_ranges) { range++; continue; } else { break; } } else if (range->end_frame >= item->frame_number) { //loc_7D524 item->anim_number = range->link_anim_num; item->frame_number = range->link_frame_num; return 1; } } while (1); } //loc_7D50C i++; change++; } while (i < anim->number_changes); //locret_7D51C return 0; } void AnimateLara(struct ITEM_INFO* item /* s1 */)//7D53C(<) { struct ANIM_STRUCT* anim = &anims[item->anim_number];//$s2 item->frame_number += 1; //v0 = anim->number_changes if (anim->number_changes > 0 && GetChange()) { }//loc_7D5BC #if 0 move $a0, $s1 jal sub_7D48C move $a1, $s2 beqz $v0, loc_7D5BC nop lh $v1, 0x14($s1) lw $a0, 0x202C($gp) sll $v0, $v1, 2 addu $v0, $v1 sll $v0, 3 addu $s2, $a0, $v0 lh $v1, 6($s2) nop sh $v1, 0xE($s1) loc_7D5BC: lh $v1, 0x16($s1) lh $v0, 0x1A($s2) nop slt $v0, $v1 beqz $v0, loc_7D6D4 nop lh $s3, 0x24($s2) lh $v0, 0x26($s2) lw $v1, 0x2078($gp) blez $s3, loc_7D6A4 sll $v0, 1 addu $s0, $v1, $v0 loc_7D5EC: lhu $v0, 0($s0) addiu $s0, 2 addiu $at, $v0, -1 beqz $at, loc_7D628 addiu $at, $v0, -2 beqz $at, loc_7D650 addiu $at, $v0, -3 beqz $at, loc_7D684 addiu $at, $v0, -5 beqz $at, loc_7D620 addiu $at, $v0, -6 bnez $at, loc_7D698 nop loc_7D620: j loc_7D698 addiu $s0, 4 loc_7D628: move $a0, $s1 lh $a1, 0($s0) lh $a2, 2($s0) lh $a3, 4($s0) jal sub_7D410 addiu $s0, 6 move $a0, $s1 li $a1, 0xFFFFFE83 jal sub_7C58C addiu $ra, 0x48 loc_7D650: lw $v1, 0x84($s1) lhu $at, 0($s0) lhu $v0, 2($s0) lh $a0, 0x5232($gp) addiu $s0, 4 ori $v1, 8 sh $at, 0x20($s1) sh $v0, 0x1E($s1) beqz $a0, loc_7D698 sw $v1, 0x84($s1) sh $a0, 0x20($s1) j loc_7D698 sh $zero, 0x5232($gp) loc_7D684: lh $v1, 0x522A($gp) li $v0, 5 beq $v1, $v0, loc_7D698 nop sh $zero, 0x522A($gp) loc_7D698: addiu $s3, -1 bgtz $s3, loc_7D5EC nop loc_7D6A4: lh $at, 0x1C($s2) lhu $a0, 0x1E($s2) lw $v0, 0x202C($gp) sh $at, 0x14($s1) sh $a0, 0x16($s1) sll $v1, $at, 2 addu $v1, $at sll $v1, 3 addu $s2, $v0, $v1 lh $v0, 6($s2) nop sh $v0, 0xE($s1) loc_7D6D4: lh $s3, 0x24($s2) lh $v0, 0x26($s2) lw $v1, 0x2078($gp) blez $s3, loc_7D7C8 sll $v0, 1 addu $s0, $v1, $v0 loc_7D6EC: lhu $v0, 0($s0) addiu $s0, 2 addiu $at, $v0, -2 beqz $at, loc_7D7B8 addiu $at, $v0, -5 beqz $at, loc_7D720 addiu $at, $v0, -6 beqz $at, loc_7D780 addiu $at, $v0, -1 bnez $at, loc_7D7BC nop j loc_7D7BC addiu $s0, 6 loc_7D720: lh $v1, 0x16($s1) lh $v0, 0($s0) lhu $a0, 2($s0) bne $v1, $v0, loc_7D7B8 andi $a1, $a0, 0xC000 beqz $a1, loc_7D76C li $v0, 0x4000 lw $v1, 0x5270($gp) bne $a1, $v0, loc_7D754 nop bgez $v1, loc_7D76C li $v0, 0xFFFF8100 beq $v1, $v0, loc_7D76C loc_7D754: li $v0, 0x8000 bne $a1, $v0, loc_7D7B8 nop bgez $v1, loc_7D7B8 li $v0, 0xFFFF8100 beq $v1, $v0, loc_7D7B8 loc_7D76C: andi $a0, 0x3FFF addiu $a1, $s1, 0x40 li $a2, 2 jal sub_91780 addiu $ra, 0x38 loc_7D780: lh $at, 0x16($s1) lh $v0, 0($s0) lui $v1, 9 bne $at, $v0, loc_7D7B8 la $v1, off_92AE8 lhu $a1, 2($s0) move $a0, $s1 andi $a3, $a1, 0x3FFF sll $v0, $a3, 2 addu $v0, $v1 lw $a2, 0($v0) andi $a1, 0xC000 jalr $a2 sh $a1, 0x1AAC($gp) loc_7D7B8: addiu $s0, 4 loc_7D7BC: addiu $s3, -1 bgtz $s3, loc_7D6EC nop loc_7D7C8: lw $a1, 0x14($s2) lw $s0, 0x10($s2) lh $t1, 0x16($s1) lh $v0, 0x18($s2) beqz $a1, loc_7D7EC subu $t1, $v0 mult $a1, $t1 mflo $v0 addu $s0, $v0 loc_7D7EC: lw $v0, 0x84($s1) nop andi $v0, 8 bnez $v0, loc_7D828 sra $s0, 16 lw $a1, 0xC($s2) lw $a0, 8($s2) beqz $a1, loc_7D820 sra $v0, $a0, 16 mult $a1, $t1 mflo $v0 addu $a0, $v0 sra $v0, $a0, 16 loc_7D820: j loc_7D884 sh $v0, 0x1E($s1) loc_7D828: lw $a2, 0xC($s2) addiu $v0, $t1, -1 mult $a2, $v0 lhu $a1, 0x1E($s1) lw $v1, 8($s2) mflo $a0 addu $a0, $v1, $a0 sra $v0, $a0, 16 subu $a1, $v0 addu $a0, $a2 sra $v0, $a0, 16 lh $a0, 0x20($s1) addu $a1, $v0 sh $a1, 0x1E($s1) slti $v0, $a0, 0x80 beqz $v0, loc_7D870 addiu $v0, $a0, 1 addiu $v0, $a0, 6 loc_7D870: sh $v0, 0x20($s1) lw $v1, 0x44($s1) nop addu $v1, $v0 sw $v1, 0x44($s1) loc_7D884: lw $v1, 0x532C($gp) li $v0, 0xFFFFFFFF beq $v1, $v0, loc_7D89C nop jal sub_4B3D8 move $a0, $s1 loc_7D89C: lw $v0, 0x526C($gp) lui $t0, 9 andi $v0, 0x20 bnez $v0, loc_7D934 la $t0, dword_9A8C8 lhu $a2, 0x52CE($gp) lh $a3, 0x1E($s1) srl $at, $a2, 2 andi $at, 0x3FFC addu $at, $t0 lh $v0, 0($at) lh $at, 2($at) mult $v0, $a3 lw $t2, 0x40($s1) lw $t3, 0x48($s1) mflo $v0 sra $v0, 12 addu $t2, $v0 mult $at, $a3 addiu $a2, 0x4000 sra $a2, 2 andi $a2, 0x3FFC addu $a2, $t0 lh $v1, 0($a2) lh $a0, 2($a2) mflo $at sra $at, 12 addu $t3, $at mult $v1, $s0 mflo $v1 sra $v1, $v0, 12 addu $t2, $v1 mult $a0, $s0 sw $t2, 0x40($s1) mflo $a0 sra $a0, 12 addu $t3, $a0 sw $t3, 0x48($s1) loc_7D934: lw $ra, 0x24+var_4($sp) lw $s3, 0x24+var_8($sp) lw $s2, 0x24+var_C($sp) lw $s1, 0x24+var_10($sp) lw $s0, 0x24+var_14($sp) jr $ra addiu $sp, 0x24 #endif UNIMPLEMENTED(); }<|endoftext|>
<commit_before>/* Copyright (c) 2014 Quanta Research Cambridge, Inc * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <assert.h> #include "MainRequest.h" #define NUMBER_OF_TESTS 1 int v2a = 2; int v2b = 4; class Main : public MainRequestWrapper { public: uint32_t cnt; void incr_cnt(){ if (++cnt == NUMBER_OF_TESTS) exit(0); } virtual void write_rf(uint16_t address, uint16_t data) { fprintf(stderr, "write_rf(%d %d)\n", address, data); incr_cnt(); } virtual void read_rf(uint16_t address, uint16_t data) { fprintf(stderr, "read_rf(%d %d)\n", address, data); incr_cnt(); } Main(unsigned int id) : MainRequestWrapper(id), cnt(0){} }; int main(int argc, const char **argv) { Main *indication = new Main(IfcNames_MainRequestH2S); MainRequestProxy *device = new MainRequestProxy(IfcNames_MainRequestS2H); device->pint.busyType = BUSY_SPIN; /* spin until request portal 'notFull' */ portalExec_start(); v2a = 1; v2b = 0x11; fprintf(stderr, "Main::calling write_rf(%d, %d)\n", v2a,v2b); device->write_rf(v2a, v2b); fprintf(stderr, "Main::calling read_rf(%d, %d)\n", v2a,v2b); device->read_rf(v2a,0); fprintf(stderr, "Main::about to go to sleep\n"); while(true){sleep(2);} } <commit_msg>print values in hex<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, Inc * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <assert.h> #include "MainRequest.h" #define NUMBER_OF_TESTS 8 class Main : public MainRequestWrapper { public: uint32_t cnt; void incr_cnt(){ if (++cnt == NUMBER_OF_TESTS) exit(0); } virtual void write_rf(uint16_t address, uint16_t data) { fprintf(stderr, "write_rf(%d 0x%02x)\n", address, data); incr_cnt(); } virtual void read_rf(uint16_t address, uint16_t data) { fprintf(stderr, "read_rf(%d 0x%02x)\n", address, data); incr_cnt(); } Main(unsigned int id) : MainRequestWrapper(id), cnt(0){} }; int main(int argc, const char **argv) { Main *indication = new Main(IfcNames_MainRequestH2S); MainRequestProxy *device = new MainRequestProxy(IfcNames_MainRequestS2H); device->pint.busyType = BUSY_SPIN; /* spin until request portal 'notFull' */ portalExec_start(); fprintf(stderr, "Main::calling write_rf(11, 22, 33, 44)\n"); device->write_rf(0, 0x11); device->write_rf(1, 0x22); device->write_rf(2, 0x33); device->write_rf(3, 0x44); fprintf(stderr, "Main::calling read_rf(0, 1, 2, 3)\n"); device->read_rf(0,0); device->read_rf(1,0); device->read_rf(2,0); device->read_rf(3,0); fprintf(stderr, "Main::about to go to sleep\n"); while(true){sleep(2);} } <|endoftext|>
<commit_before>/* * Copyright (c) 2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert * Steve Reinhardt */ #include "base/misc.hh" #include "base/pollevent.hh" #include "base/types.hh" #include "sim/async.hh" #include "sim/eventq.hh" #include "sim/sim_events.hh" #include "sim/sim_exit.hh" #include "sim/simulate.hh" #include "sim/stat_control.hh" #include "MultiChannelMemorySystem.h" extern DRAMSim::MultiChannelMemorySystem *dramsim2; /** Simulate for num_cycles additional cycles. If num_cycles is -1 * (the default), do not limit simulation; some other event must * terminate the loop. Exported to Python via SWIG. * @return The SimLoopExitEvent that caused the loop to exit. */ SimLoopExitEvent * simulate(Tick num_cycles, int numPids) { inform("Entering event queue @ %d. Starting simulation...\n", curTick()); mainEventQueue.exit_count=numPids; if (num_cycles < MaxTick - curTick()) num_cycles = curTick() + num_cycles; else // counter would roll over or be set to MaxTick anyhow num_cycles = MaxTick; Event *limit_event = new SimLoopExitEvent("simulate() limit reached", 0); mainEventQueue.schedule(limit_event, num_cycles); while (1) { // if there is DRAMsim2 if (dramsim2) { while (dramsim2->currentClockCycle * tCK * 1000 < mainEventQueue.nextTick()) { dramsim2->update(); //std::cout << "memory update" << std::endl; } } // there should always be at least one event (the SimLoopExitEvent // we just scheduled) in the queue assert(!mainEventQueue.empty()); assert(curTick() <= mainEventQueue.nextTick() && "event scheduled in the past"); // forward current cycle to the time of the first event on the // queue curTick(mainEventQueue.nextTick()); Event *exit_event = mainEventQueue.serviceOne(); if (exit_event != NULL) { // hit some kind of exit event; return to Python // event must be subclass of SimLoopExitEvent... SimLoopExitEvent *se_event; se_event = dynamic_cast<SimLoopExitEvent *>(exit_event); if (se_event == NULL) panic("Bogus exit event class!"); // if we didn't hit limit_event, delete it if (se_event != limit_event) { assert(limit_event->scheduled()); limit_event->squash(); hack_once("be nice to actually delete the event here"); } if (dramsim2) dramsim2->printStats(); return se_event; } if (async_event) { async_event = false; if (async_statdump || async_statreset) { Stats::schedStatEvent(async_statdump, async_statreset); async_statdump = false; async_statreset = false; } if (async_exit) { async_exit = false; exitSimLoop("user interrupt received"); } if (async_io || async_alarm) { async_io = false; async_alarm = false; pollQueue.service(); } if (async_exception) { async_exception = false; return NULL; } } } // not reached... only exit is return on SimLoopExitEvent } <commit_msg>add an extra cycle to dramsim update<commit_after>/* * Copyright (c) 2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert * Steve Reinhardt */ #include "base/misc.hh" #include "base/pollevent.hh" #include "base/types.hh" #include "sim/async.hh" #include "sim/eventq.hh" #include "sim/sim_events.hh" #include "sim/sim_exit.hh" #include "sim/simulate.hh" #include "sim/stat_control.hh" #include "MultiChannelMemorySystem.h" extern DRAMSim::MultiChannelMemorySystem *dramsim2; /** Simulate for num_cycles additional cycles. If num_cycles is -1 * (the default), do not limit simulation; some other event must * terminate the loop. Exported to Python via SWIG. * @return The SimLoopExitEvent that caused the loop to exit. */ SimLoopExitEvent * simulate(Tick num_cycles, int numPids) { inform("Entering event queue @ %d. Starting simulation...\n", curTick()); mainEventQueue.exit_count=numPids; if (num_cycles < MaxTick - curTick()) num_cycles = curTick() + num_cycles; else // counter would roll over or be set to MaxTick anyhow num_cycles = MaxTick; Event *limit_event = new SimLoopExitEvent("simulate() limit reached", 0); mainEventQueue.schedule(limit_event, num_cycles); while (1) { // if there is DRAMsim2 if (dramsim2) { while ((dramsim2->currentClockCycle-1) * tCK * 1000 < mainEventQueue.nextTick()) { dramsim2->update(); //std::cout << "memory update" << std::endl; } } // there should always be at least one event (the SimLoopExitEvent // we just scheduled) in the queue assert(!mainEventQueue.empty()); assert(curTick() <= mainEventQueue.nextTick() && "event scheduled in the past"); // forward current cycle to the time of the first event on the // queue curTick(mainEventQueue.nextTick()); Event *exit_event = mainEventQueue.serviceOne(); if (exit_event != NULL) { // hit some kind of exit event; return to Python // event must be subclass of SimLoopExitEvent... SimLoopExitEvent *se_event; se_event = dynamic_cast<SimLoopExitEvent *>(exit_event); if (se_event == NULL) panic("Bogus exit event class!"); // if we didn't hit limit_event, delete it if (se_event != limit_event) { assert(limit_event->scheduled()); limit_event->squash(); hack_once("be nice to actually delete the event here"); } if (dramsim2) dramsim2->printStats(); return se_event; } if (async_event) { async_event = false; if (async_statdump || async_statreset) { Stats::schedStatEvent(async_statdump, async_statreset); async_statdump = false; async_statreset = false; } if (async_exit) { async_exit = false; exitSimLoop("user interrupt received"); } if (async_io || async_alarm) { async_io = false; async_alarm = false; pollQueue.service(); } if (async_exception) { async_exception = false; return NULL; } } } // not reached... only exit is return on SimLoopExitEvent } <|endoftext|>
<commit_before>// // Copyright (c) 2011 Kim Walisch, <kim.walisch@gmail.com>. // All rights reserved. // // This file is part of primesieve. // Visit: http://primesieve.googlecode.com // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * 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 "EratBig.h" #include "SieveOfEratosthenes.h" #include "WheelFactorization.h" #include "defs.h" #include "bithacks.h" #include <stdexcept> #include <cstdlib> #include <list> EratBig::EratBig(const SieveOfEratosthenes& soe) : Modulo210Wheel(soe), stock_(NULL), index_(0), log2SieveSize_(floorLog2(soe.getSieveSize())) { // EratBig uses bitwise operations that require a power of 2 sieve size if (!isPowerOf2(soe.getSieveSize())) throw std::invalid_argument( "EratBig: sieveSize must be a power of 2 (2^n)."); this->setSize(soe); this->initBucketLists(); } EratBig::~EratBig() { delete[] lists_; for (std::list<Bucket_t*>::iterator it = pointers_.begin(); it != pointers_.end(); it++) delete[] *it; } /** * Set the size of the lists_ array. * @remark The size is a power of 2 value which allows use of fast * bitwise operators in sieve(uint8_t*). */ void EratBig::setSize(const SieveOfEratosthenes& soe) { // MAX values in sieve(uint8_t*) uint32_t maxSievingPrime = soe.getSquareRoot() / (SieveOfEratosthenes::NUMBERS_PER_BYTE / 2); uint32_t maxWheelFactor = wheel_[1].nextMultipleFactor; uint32_t maxSieveIndex = (soe.getSieveSize() - 1) + maxSievingPrime * maxWheelFactor; uint32_t maxSegmentCount = maxSieveIndex / soe.getSieveSize(); // 'maxSegmentCount + 1' is the smallest possible // size for the lists_ array size_ = nextHighestPowerOf2(maxSegmentCount + 1); } /** * Allocate the lists_ array and initialize each list * with an empty bucket. */ void EratBig::initBucketLists() { lists_ = new Bucket_t*[size_]; for (uint32_t i = 0; i < size_; i++) { lists_[i] = NULL; this->pushBucket(i); } } /** * Add a prime number <= sqrt(n) for sieving to EratBig. */ void EratBig::addSievingPrime(uint32_t prime) { uint32_t sieveIndex; uint32_t wheelIndex; if (this->getWheelPrimeData(&prime, &sieveIndex, &wheelIndex) == true) { // indicates in how many segments the next multiple // of prime needs to be crossed-off uint32_t segmentCount = sieveIndex >> log2SieveSize_; sieveIndex &= (1U << log2SieveSize_) - 1; // calculate the list index related to the next multiple of prime uint32_t next = (index_ + segmentCount) & (size_ - 1); // add prime to the bucket list related to // its next multiple occurrence if (!lists_[next]->addWheelPrime(prime, sieveIndex, wheelIndex)) this->pushBucket(next); } } /** * Add an empty bucket from the bucket stock_ to the * front of lists_[index], if the bucket stock_ is * empty new buckets are allocated first. */ void EratBig::pushBucket(uint32_t index) { if (stock_ == NULL) { Bucket_t* more = new Bucket_t[BUCKETS_PER_ALLOC]; pointers_.push_back(more); for(int i = 0; i < BUCKETS_PER_ALLOC - 1; i++) more[i].setNext(&more[i + 1]); more[BUCKETS_PER_ALLOC - 1].setNext(NULL); stock_ = &more[0]; } Bucket_t* bucket = stock_; stock_ = stock_->next(); bucket->setNext(lists_[index]); lists_[index] = bucket; } /** * Implementation of Tomas Oliveira e Silva's cache-friendly segmented * sieve of Eratosthenes algorithm, see: * http://www.ieeta.pt/~tos/software/prime_sieve.html * My implementation uses a sieve array with 30 numbers per byte, * 8 bytes per sieving prime and a modulo 210 wheel that skips * multiples of 2, 3, 5 and 7. * * Removes the multiples of big sieving primes (i.e. with very few * multiple occurrences per segment) from the sieve array. * @see SieveOfEratosthenes::crossOffMultiples() */ void EratBig::sieve(uint8_t* sieve) { // get the bucket list related to the current segment, // the list contains the sieving primes with multiple occurence(s) // in the current segment Bucket_t*& list = lists_[index_]; // process the buckets within list until all multiples of // its sieving primes have been crossed-off while (!list->isEmpty() || list->hasNext()) { Bucket_t* bucket = list; list = NULL; this->pushBucket(index_); // each loop iteration processes a bucket i.e. removes the // next multiple of its sieving primes do { const uint32_t count = bucket->getCount(); const WheelPrime_t* wPrime = bucket->getWheelPrimes(); const WheelPrime_t* end = &wPrime[count - count % 2]; // iterate over the sieving primes within the current bucket // loop unrolled 2 times, optimized for x64 CPUs for (; wPrime < end; wPrime += 2) { uint32_t sieveIndex0 = wPrime[0].getSieveIndex(); uint32_t wheelIndex0 = wPrime[0].getWheelIndex(); uint32_t sievingPrime0 = wPrime[0].getSievingPrime(); uint32_t sieveIndex1 = wPrime[1].getSieveIndex(); uint32_t wheelIndex1 = wPrime[1].getWheelIndex(); uint32_t sievingPrime1 = wPrime[1].getSievingPrime(); // cross-off the next multiple (unset corresponding bit) of the // current sieving primes within the sieve array sieve[sieveIndex0] &= wheel_[wheelIndex0].unsetBit; sieveIndex0 += wheel_[wheelIndex0].nextMultipleFactor * sievingPrime0; sieveIndex0 += wheel_[wheelIndex0].correct; wheelIndex0 += wheel_[wheelIndex0].next; sieve[sieveIndex1] &= wheel_[wheelIndex1].unsetBit; sieveIndex1 += wheel_[wheelIndex1].nextMultipleFactor * sievingPrime1; sieveIndex1 += wheel_[wheelIndex1].correct; wheelIndex1 += wheel_[wheelIndex1].next; uint32_t next0 = (index_ + (sieveIndex0 >> log2SieveSize_)) & (size_ - 1); sieveIndex0 &= (1U << log2SieveSize_) - 1; uint32_t next1 = (index_ + (sieveIndex1 >> log2SieveSize_)) & (size_ - 1); sieveIndex1 &= (1U << log2SieveSize_) - 1; // move the current sieving primes to the bucket list // related to their next multiple occurrence if (!lists_[next0]->addWheelPrime(sievingPrime0, sieveIndex0, wheelIndex0)) this->pushBucket(next0); if (!lists_[next1]->addWheelPrime(sievingPrime1, sieveIndex1, wheelIndex1)) this->pushBucket(next1); } // process the remaining sieving primes for (; wPrime < &end[count % 2]; wPrime++) { uint32_t sieveIndex = wPrime->getSieveIndex(); uint32_t wheelIndex = wPrime->getWheelIndex(); uint32_t sievingPrime = wPrime->getSievingPrime(); sieve[sieveIndex] &= wheel_[wheelIndex].unsetBit; sieveIndex += wheel_[wheelIndex].nextMultipleFactor * sievingPrime; sieveIndex += wheel_[wheelIndex].correct; wheelIndex += wheel_[wheelIndex].next; uint32_t next = (index_ + (sieveIndex >> log2SieveSize_)) & (size_ - 1); sieveIndex &= (1U << log2SieveSize_) - 1; if (!lists_[next]->addWheelPrime(sievingPrime, sieveIndex, wheelIndex)) this->pushBucket(next); } // reset the processed bucket and move it to the bucket stock_ Bucket_t* old = bucket; bucket = bucket->next(); old->reset(); old->setNext(stock_); stock_ = old; } while (bucket != NULL); } // increase the list index_ for the next segment index_ = (index_ + 1) & (size_ - 1); } <commit_msg>improved code readability<commit_after>// // Copyright (c) 2011 Kim Walisch, <kim.walisch@gmail.com>. // All rights reserved. // // This file is part of primesieve. // Visit: http://primesieve.googlecode.com // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * 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 "EratBig.h" #include "SieveOfEratosthenes.h" #include "WheelFactorization.h" #include "defs.h" #include "bithacks.h" #include <stdexcept> #include <cstdlib> #include <list> EratBig::EratBig(const SieveOfEratosthenes& soe) : Modulo210Wheel(soe), stock_(NULL), index_(0), log2SieveSize_(floorLog2(soe.getSieveSize())) { // EratBig uses bitwise operations that require a power of 2 sieve size if (!isPowerOf2(soe.getSieveSize())) throw std::invalid_argument( "EratBig: sieveSize must be a power of 2 (2^n)."); this->setSize(soe); this->initBucketLists(); } EratBig::~EratBig() { delete[] lists_; for (std::list<Bucket_t*>::iterator it = pointers_.begin(); it != pointers_.end(); it++) delete[] *it; } /** * Set the size of the lists_ array. * @remark The size is a power of 2 value which allows use of fast * bitwise operators in sieve(uint8_t*). */ void EratBig::setSize(const SieveOfEratosthenes& soe) { // MAX values in sieve(uint8_t*) uint32_t maxSievingPrime = soe.getSquareRoot() / (SieveOfEratosthenes::NUMBERS_PER_BYTE / 2); uint32_t maxWheelFactor = wheel_[1].nextMultipleFactor; uint32_t maxSieveIndex = (soe.getSieveSize() - 1) + maxSievingPrime * maxWheelFactor; uint32_t maxSegmentCount = maxSieveIndex / soe.getSieveSize(); // 'maxSegmentCount + 1' is the smallest possible // size for the lists_ array size_ = nextHighestPowerOf2(maxSegmentCount + 1); } /** * Allocate the lists_ array and initialize each list * with an empty bucket. */ void EratBig::initBucketLists() { lists_ = new Bucket_t*[size_]; for (uint32_t i = 0; i < size_; i++) { lists_[i] = NULL; this->pushBucket(i); } } /** * Add a prime number <= sqrt(n) for sieving to EratBig. */ void EratBig::addSievingPrime(uint32_t prime) { uint32_t sieveIndex; uint32_t wheelIndex; if (this->getWheelPrimeData(&prime, &sieveIndex, &wheelIndex) == true) { // indicates in how many segments the next multiple // of prime needs to be crossed-off uint32_t segmentCount = sieveIndex >> log2SieveSize_; sieveIndex &= (1U << log2SieveSize_) - 1; // calculate the list index related to the next multiple of prime uint32_t next = (index_ + segmentCount) & (size_ - 1); // add prime to the bucket list related to // its next multiple occurrence if (!lists_[next]->addWheelPrime(prime, sieveIndex, wheelIndex)) this->pushBucket(next); } } /** * Add an empty bucket from the bucket stock_ to the * front of lists_[index], if the bucket stock_ is * empty new buckets are allocated first. */ void EratBig::pushBucket(uint32_t index) { if (stock_ == NULL) { Bucket_t* more = new Bucket_t[BUCKETS_PER_ALLOC]; stock_ = &more[0]; pointers_.push_back(more); for(int i = 0; i < BUCKETS_PER_ALLOC - 1; i++) more[i].setNext(&more[i + 1]); more[BUCKETS_PER_ALLOC - 1].setNext(NULL); } Bucket_t* bucket = stock_; stock_ = stock_->next(); bucket->setNext(lists_[index]); lists_[index] = bucket; } /** * Implementation of Tomas Oliveira e Silva's cache-friendly segmented * sieve of Eratosthenes algorithm, see: * http://www.ieeta.pt/~tos/software/prime_sieve.html * My implementation uses a sieve array with 30 numbers per byte, * 8 bytes per sieving prime and a modulo 210 wheel that skips * multiples of 2, 3, 5 and 7. * * Removes the multiples of big sieving primes (i.e. with very few * multiple occurrences per segment) from the sieve array. * @see SieveOfEratosthenes::crossOffMultiples() */ void EratBig::sieve(uint8_t* sieve) { // get the bucket list related to the current segment, // the list contains the sieving primes with multiple occurence(s) // in the current segment Bucket_t*& list = lists_[index_]; // process the buckets within list until all multiples of // its sieving primes have been crossed-off while (!list->isEmpty() || list->hasNext()) { Bucket_t* bucket = list; list = NULL; this->pushBucket(index_); // each loop iteration processes a bucket i.e. removes the // next multiple of its sieving primes do { const uint32_t count = bucket->getCount(); const WheelPrime_t* wPrime = bucket->getWheelPrimes(); const WheelPrime_t* end = &wPrime[count - count % 2]; // iterate over the sieving primes within the current bucket // loop unrolled 2 times, optimized for x64 CPUs for (; wPrime < end; wPrime += 2) { uint32_t sieveIndex0 = wPrime[0].getSieveIndex(); uint32_t wheelIndex0 = wPrime[0].getWheelIndex(); uint32_t sievingPrime0 = wPrime[0].getSievingPrime(); uint32_t sieveIndex1 = wPrime[1].getSieveIndex(); uint32_t wheelIndex1 = wPrime[1].getWheelIndex(); uint32_t sievingPrime1 = wPrime[1].getSievingPrime(); // cross-off the next multiple (unset corresponding bit) of the // current sieving primes within the sieve array sieve[sieveIndex0] &= wheel_[wheelIndex0].unsetBit; sieveIndex0 += wheel_[wheelIndex0].nextMultipleFactor * sievingPrime0; sieveIndex0 += wheel_[wheelIndex0].correct; wheelIndex0 += wheel_[wheelIndex0].next; sieve[sieveIndex1] &= wheel_[wheelIndex1].unsetBit; sieveIndex1 += wheel_[wheelIndex1].nextMultipleFactor * sievingPrime1; sieveIndex1 += wheel_[wheelIndex1].correct; wheelIndex1 += wheel_[wheelIndex1].next; uint32_t next0 = (index_ + (sieveIndex0 >> log2SieveSize_)) & (size_ - 1); sieveIndex0 &= (1U << log2SieveSize_) - 1; uint32_t next1 = (index_ + (sieveIndex1 >> log2SieveSize_)) & (size_ - 1); sieveIndex1 &= (1U << log2SieveSize_) - 1; // move the current sieving primes to the bucket list // related to their next multiple occurrence if (!lists_[next0]->addWheelPrime(sievingPrime0, sieveIndex0, wheelIndex0)) this->pushBucket(next0); if (!lists_[next1]->addWheelPrime(sievingPrime1, sieveIndex1, wheelIndex1)) this->pushBucket(next1); } // process the remaining sieving primes for (; wPrime < &end[count % 2]; wPrime++) { uint32_t sieveIndex = wPrime->getSieveIndex(); uint32_t wheelIndex = wPrime->getWheelIndex(); uint32_t sievingPrime = wPrime->getSievingPrime(); sieve[sieveIndex] &= wheel_[wheelIndex].unsetBit; sieveIndex += wheel_[wheelIndex].nextMultipleFactor * sievingPrime; sieveIndex += wheel_[wheelIndex].correct; wheelIndex += wheel_[wheelIndex].next; uint32_t next = (index_ + (sieveIndex >> log2SieveSize_)) & (size_ - 1); sieveIndex &= (1U << log2SieveSize_) - 1; if (!lists_[next]->addWheelPrime(sievingPrime, sieveIndex, wheelIndex)) this->pushBucket(next); } // reset the processed bucket and move it to the bucket stock_ Bucket_t* old = bucket; bucket = bucket->next(); old->reset(); old->setNext(stock_); stock_ = old; } while (bucket != NULL); } // increase the list index_ for the next segment index_ = (index_ + 1) & (size_ - 1); } <|endoftext|>
<commit_before>// Copyright (c) 2007-2008 Facebook // // 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. // // See accompanying file LICENSE or visit the Scribe site at: // http://developers.facebook.com/scribe/ // // @author Bobby Johnson // @author James Wang // @author Jason Sobel // @author Anthony Giardullo // @author John Song #include "common.h" #include "scribe_server.h" using namespace std; using namespace boost; using namespace scribe::thrift; #define DEFAULT_TARGET_WRITE_SIZE 16384LL #define DEFAULT_MAX_WRITE_INTERVAL 1 void* threadStatic(void *this_ptr) { StoreQueue *queue_ptr = (StoreQueue*)this_ptr; queue_ptr->threadMember(); return NULL; } StoreQueue::StoreQueue(const string& type, const string& category, unsigned check_period, bool is_model, bool multi_category) : msgQueueSize(0), hasWork(false), stopping(false), isModel(is_model), multiCategory(multi_category), categoryHandled(category), checkPeriod(check_period), targetWriteSize(DEFAULT_TARGET_WRITE_SIZE), maxWriteInterval(DEFAULT_MAX_WRITE_INTERVAL), mustSucceed(true) { store = Store::createStore(this, type, category, false, multiCategory); if (!store) { throw std::runtime_error("createStore failed in StoreQueue constructor. Invalid type?"); } storeInitCommon(); } StoreQueue::StoreQueue(const boost::shared_ptr<StoreQueue> example, const std::string &category) : msgQueueSize(0), hasWork(false), stopping(false), isModel(false), multiCategory(example->multiCategory), categoryHandled(category), checkPeriod(example->checkPeriod), targetWriteSize(example->targetWriteSize), maxWriteInterval(example->maxWriteInterval), mustSucceed(example->mustSucceed) { store = example->copyStore(category); if (!store) { throw std::runtime_error("createStore failed copying model store"); } storeInitCommon(); } StoreQueue::~StoreQueue() { if (!isModel) { pthread_mutex_destroy(&cmdMutex); pthread_mutex_destroy(&msgMutex); pthread_mutex_destroy(&hasWorkMutex); pthread_cond_destroy(&hasWorkCond); } } void StoreQueue::addMessage(boost::shared_ptr<LogEntry> entry) { if (isModel) { LOG_OPER("ERROR: called addMessage on model store"); } else { bool waitForWork = false; pthread_mutex_lock(&msgMutex); msgQueue->push_back(entry); msgQueueSize += entry->message.size(); waitForWork = (msgQueueSize >= targetWriteSize) ? true : false; pthread_mutex_unlock(&msgMutex); // Wake up store thread if we have enough messages if (waitForWork == true) { // signal that there is work to do if not already signaled pthread_mutex_lock(&hasWorkMutex); if (!hasWork) { hasWork = true; pthread_cond_signal(&hasWorkCond); } pthread_mutex_unlock(&hasWorkMutex); } } } void StoreQueue::configureAndOpen(pStoreConf configuration) { // model store has to handle this inline since it has no queue if (isModel) { configureInline(configuration); } else { pthread_mutex_lock(&cmdMutex); StoreCommand cmd(CMD_CONFIGURE, configuration); cmdQueue.push(cmd); pthread_mutex_unlock(&cmdMutex); // signal that there is work to do if not already signaled pthread_mutex_lock(&hasWorkMutex); if (!hasWork) { hasWork = true; pthread_cond_signal(&hasWorkCond); } pthread_mutex_unlock(&hasWorkMutex); } } void StoreQueue::stop() { if (isModel) { LOG_OPER("ERROR: called stop() on model store"); return; } else if(!stopping) { pthread_mutex_lock(&cmdMutex); StoreCommand cmd(CMD_STOP); cmdQueue.push(cmd); stopping = true; pthread_mutex_unlock(&cmdMutex); // signal that there is work to do if not already signaled pthread_mutex_lock(&hasWorkMutex); if (!hasWork) { hasWork = true; pthread_cond_signal(&hasWorkCond); } pthread_mutex_unlock(&hasWorkMutex); pthread_join(storeThread, NULL); } } void StoreQueue::open() { if (isModel) { LOG_OPER("ERROR: called open() on model store"); } else { pthread_mutex_lock(&cmdMutex); StoreCommand cmd(CMD_OPEN); cmdQueue.push(cmd); pthread_mutex_unlock(&cmdMutex); // signal that there is work to do if not already signaled pthread_mutex_lock(&hasWorkMutex); if (!hasWork) { hasWork = true; pthread_cond_signal(&hasWorkCond); } pthread_mutex_unlock(&hasWorkMutex); } } shared_ptr<Store> StoreQueue::copyStore(const std::string &category) { return store->copy(category); } std::string StoreQueue::getCategoryHandled() { return categoryHandled; } std::string StoreQueue::getStatus() { return store->getStatus(); } std::string StoreQueue::getBaseType() { return store->getType(); } void StoreQueue::threadMember() { if (isModel) { LOG_OPER("ERROR: store thread starting on model store, exiting"); return; } if (!store) { LOG_OPER("store is NULL, store thread exiting"); return; } // init time of last periodic check to time of 0 time_t last_periodic_check = 0; time_t last_handle_messages; time(&last_handle_messages); struct timespec abs_timeout; bool stop = false; bool open = false; while (!stop) { // handle commands // pthread_mutex_lock(&cmdMutex); while (!cmdQueue.empty()) { StoreCommand cmd = cmdQueue.front(); cmdQueue.pop(); switch (cmd.command) { case CMD_CONFIGURE: configureInline(cmd.configuration); open = true; break; case CMD_OPEN: openInline(); open = true; break; case CMD_STOP: stop = true; break; default: LOG_OPER("LOGIC ERROR: unknown command to store queue"); break; } } // handle periodic tasks time_t this_loop; time(&this_loop); if (!stop && ((this_loop - last_periodic_check) >= checkPeriod)) { if (open) store->periodicCheck(); last_periodic_check = this_loop; } pthread_mutex_lock(&msgMutex); pthread_mutex_unlock(&cmdMutex); boost::shared_ptr<logentry_vector_t> messages; // handle messages if stopping, enough time has passed, or queue is large // if (stop || (this_loop - last_handle_messages >= maxWriteInterval) || msgQueueSize >= targetWriteSize) { if (failedMessages) { // process any messages we were not able to process last time messages = failedMessages; failedMessages = boost::shared_ptr<logentry_vector_t>(); } else if (msgQueueSize > 0) { // process message in queue messages = msgQueue; msgQueue = boost::shared_ptr<logentry_vector_t>(new logentry_vector_t); msgQueueSize = 0; } // reset timer last_handle_messages = this_loop; } pthread_mutex_unlock(&msgMutex); if (messages) { if (!store->handleMessages(messages)) { // Store could not handle these messages processFailedMessages(messages); } store->flush(); } if (!stop) { // set timeout to when we need to handle messages or do a periodic check abs_timeout.tv_sec = min(last_periodic_check + checkPeriod, last_handle_messages + maxWriteInterval); abs_timeout.tv_nsec = 0; // wait until there's some work to do or we timeout pthread_mutex_lock(&hasWorkMutex); if (!hasWork) { pthread_cond_timedwait(&hasWorkCond, &hasWorkMutex, &abs_timeout); } hasWork = false; pthread_mutex_unlock(&hasWorkMutex); } } // while (!stop) store->close(); } void StoreQueue::processFailedMessages(shared_ptr<logentry_vector_t> messages) { // If the store was not able to process these messages, we will either // requeue them or give up depending on the value of mustSucceed if (mustSucceed) { // Save failed messages failedMessages = messages; LOG_OPER("[%s] WARNING: Re-queueing %lu messages!", categoryHandled.c_str(), messages->size()); g_Handler->incCounter(categoryHandled, "requeue", messages->size()); } else { // record messages as being lost LOG_OPER("[%s] WARNING: Lost %lu messages!", categoryHandled.c_str(), messages->size()); g_Handler->incCounter(categoryHandled, "lost", messages->size()); } } void StoreQueue::storeInitCommon() { // model store doesn't need this stuff if (!isModel) { msgQueue = boost::shared_ptr<logentry_vector_t>(new logentry_vector_t); pthread_mutex_init(&cmdMutex, NULL); pthread_mutex_init(&msgMutex, NULL); pthread_mutex_init(&hasWorkMutex, NULL); pthread_cond_init(&hasWorkCond, NULL); pthread_create(&storeThread, NULL, threadStatic, (void*) this); } } void StoreQueue::configureInline(pStoreConf configuration) { // Constructor defaults are fine if these don't exist configuration->getUnsignedLongLong("target_write_size", targetWriteSize); configuration->getUnsigned("max_write_interval", (unsigned long&) maxWriteInterval); if (maxWriteInterval == 0) { maxWriteInterval = 1; } string tmp; if (configuration->getString("must_succeed", tmp) && tmp == "no") { LOG_OPER("[%s] Setting mustSucceed to false.", categoryHandled.c_str()); mustSucceed = false; } store->configure(configuration, pStoreConf()); } void StoreQueue::openInline() { if (store->isOpen()) { store->close(); } if (!isModel) { store->open(); } } <commit_msg>Run store periodicCheck if the store is open, instead of checking if the StoreQueue is open.<commit_after>// Copyright (c) 2007-2008 Facebook // // 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. // // See accompanying file LICENSE or visit the Scribe site at: // http://developers.facebook.com/scribe/ // // @author Bobby Johnson // @author James Wang // @author Jason Sobel // @author Anthony Giardullo // @author John Song #include "common.h" #include "scribe_server.h" using namespace std; using namespace boost; using namespace scribe::thrift; #define DEFAULT_TARGET_WRITE_SIZE 16384LL #define DEFAULT_MAX_WRITE_INTERVAL 1 void* threadStatic(void *this_ptr) { StoreQueue *queue_ptr = (StoreQueue*)this_ptr; queue_ptr->threadMember(); return NULL; } StoreQueue::StoreQueue(const string& type, const string& category, unsigned check_period, bool is_model, bool multi_category) : msgQueueSize(0), hasWork(false), stopping(false), isModel(is_model), multiCategory(multi_category), categoryHandled(category), checkPeriod(check_period), targetWriteSize(DEFAULT_TARGET_WRITE_SIZE), maxWriteInterval(DEFAULT_MAX_WRITE_INTERVAL), mustSucceed(true) { store = Store::createStore(this, type, category, false, multiCategory); if (!store) { throw std::runtime_error("createStore failed in StoreQueue constructor. Invalid type?"); } storeInitCommon(); } StoreQueue::StoreQueue(const boost::shared_ptr<StoreQueue> example, const std::string &category) : msgQueueSize(0), hasWork(false), stopping(false), isModel(false), multiCategory(example->multiCategory), categoryHandled(category), checkPeriod(example->checkPeriod), targetWriteSize(example->targetWriteSize), maxWriteInterval(example->maxWriteInterval), mustSucceed(example->mustSucceed) { store = example->copyStore(category); if (!store) { throw std::runtime_error("createStore failed copying model store"); } storeInitCommon(); } StoreQueue::~StoreQueue() { if (!isModel) { pthread_mutex_destroy(&cmdMutex); pthread_mutex_destroy(&msgMutex); pthread_mutex_destroy(&hasWorkMutex); pthread_cond_destroy(&hasWorkCond); } } void StoreQueue::addMessage(boost::shared_ptr<LogEntry> entry) { if (isModel) { LOG_OPER("ERROR: called addMessage on model store"); } else { bool waitForWork = false; pthread_mutex_lock(&msgMutex); msgQueue->push_back(entry); msgQueueSize += entry->message.size(); waitForWork = (msgQueueSize >= targetWriteSize) ? true : false; pthread_mutex_unlock(&msgMutex); // Wake up store thread if we have enough messages if (waitForWork == true) { // signal that there is work to do if not already signaled pthread_mutex_lock(&hasWorkMutex); if (!hasWork) { hasWork = true; pthread_cond_signal(&hasWorkCond); } pthread_mutex_unlock(&hasWorkMutex); } } } void StoreQueue::configureAndOpen(pStoreConf configuration) { // model store has to handle this inline since it has no queue if (isModel) { configureInline(configuration); } else { pthread_mutex_lock(&cmdMutex); StoreCommand cmd(CMD_CONFIGURE, configuration); cmdQueue.push(cmd); pthread_mutex_unlock(&cmdMutex); // signal that there is work to do if not already signaled pthread_mutex_lock(&hasWorkMutex); if (!hasWork) { hasWork = true; pthread_cond_signal(&hasWorkCond); } pthread_mutex_unlock(&hasWorkMutex); } } void StoreQueue::stop() { if (isModel) { LOG_OPER("ERROR: called stop() on model store"); return; } else if(!stopping) { pthread_mutex_lock(&cmdMutex); StoreCommand cmd(CMD_STOP); cmdQueue.push(cmd); stopping = true; pthread_mutex_unlock(&cmdMutex); // signal that there is work to do if not already signaled pthread_mutex_lock(&hasWorkMutex); if (!hasWork) { hasWork = true; pthread_cond_signal(&hasWorkCond); } pthread_mutex_unlock(&hasWorkMutex); pthread_join(storeThread, NULL); } } void StoreQueue::open() { if (isModel) { LOG_OPER("ERROR: called open() on model store"); } else { pthread_mutex_lock(&cmdMutex); StoreCommand cmd(CMD_OPEN); cmdQueue.push(cmd); pthread_mutex_unlock(&cmdMutex); // signal that there is work to do if not already signaled pthread_mutex_lock(&hasWorkMutex); if (!hasWork) { hasWork = true; pthread_cond_signal(&hasWorkCond); } pthread_mutex_unlock(&hasWorkMutex); } } shared_ptr<Store> StoreQueue::copyStore(const std::string &category) { return store->copy(category); } std::string StoreQueue::getCategoryHandled() { return categoryHandled; } std::string StoreQueue::getStatus() { return store->getStatus(); } std::string StoreQueue::getBaseType() { return store->getType(); } void StoreQueue::threadMember() { if (isModel) { LOG_OPER("ERROR: store thread starting on model store, exiting"); return; } if (!store) { LOG_OPER("store is NULL, store thread exiting"); return; } // init time of last periodic check to time of 0 time_t last_periodic_check = 0; time_t last_handle_messages; time(&last_handle_messages); struct timespec abs_timeout; bool stop = false; while (!stop) { // handle commands // pthread_mutex_lock(&cmdMutex); while (!cmdQueue.empty()) { StoreCommand cmd = cmdQueue.front(); cmdQueue.pop(); switch (cmd.command) { case CMD_CONFIGURE: configureInline(cmd.configuration); break; case CMD_OPEN: openInline(); break; case CMD_STOP: stop = true; break; default: LOG_OPER("LOGIC ERROR: unknown command to store queue"); break; } } // handle periodic tasks time_t this_loop; time(&this_loop); if (!stop && ((this_loop - last_periodic_check) >= checkPeriod)) { if (store->isOpen()) { store->periodicCheck(); } last_periodic_check = this_loop; } pthread_mutex_lock(&msgMutex); pthread_mutex_unlock(&cmdMutex); boost::shared_ptr<logentry_vector_t> messages; // handle messages if stopping, enough time has passed, or queue is large // if (stop || (this_loop - last_handle_messages >= maxWriteInterval) || msgQueueSize >= targetWriteSize) { if (failedMessages) { // process any messages we were not able to process last time messages = failedMessages; failedMessages = boost::shared_ptr<logentry_vector_t>(); } else if (msgQueueSize > 0) { // process message in queue messages = msgQueue; msgQueue = boost::shared_ptr<logentry_vector_t>(new logentry_vector_t); msgQueueSize = 0; } // reset timer last_handle_messages = this_loop; } pthread_mutex_unlock(&msgMutex); if (messages) { if (!store->handleMessages(messages)) { // Store could not handle these messages processFailedMessages(messages); } store->flush(); } if (!stop) { // set timeout to when we need to handle messages or do a periodic check abs_timeout.tv_sec = min(last_periodic_check + checkPeriod, last_handle_messages + maxWriteInterval); abs_timeout.tv_nsec = 0; // wait until there's some work to do or we timeout pthread_mutex_lock(&hasWorkMutex); if (!hasWork) { pthread_cond_timedwait(&hasWorkCond, &hasWorkMutex, &abs_timeout); } hasWork = false; pthread_mutex_unlock(&hasWorkMutex); } } // while (!stop) store->close(); } void StoreQueue::processFailedMessages(shared_ptr<logentry_vector_t> messages) { // If the store was not able to process these messages, we will either // requeue them or give up depending on the value of mustSucceed if (mustSucceed) { // Save failed messages failedMessages = messages; LOG_OPER("[%s] WARNING: Re-queueing %lu messages!", categoryHandled.c_str(), messages->size()); g_Handler->incCounter(categoryHandled, "requeue", messages->size()); } else { // record messages as being lost LOG_OPER("[%s] WARNING: Lost %lu messages!", categoryHandled.c_str(), messages->size()); g_Handler->incCounter(categoryHandled, "lost", messages->size()); } } void StoreQueue::storeInitCommon() { // model store doesn't need this stuff if (!isModel) { msgQueue = boost::shared_ptr<logentry_vector_t>(new logentry_vector_t); pthread_mutex_init(&cmdMutex, NULL); pthread_mutex_init(&msgMutex, NULL); pthread_mutex_init(&hasWorkMutex, NULL); pthread_cond_init(&hasWorkCond, NULL); pthread_create(&storeThread, NULL, threadStatic, (void*) this); } } void StoreQueue::configureInline(pStoreConf configuration) { // Constructor defaults are fine if these don't exist configuration->getUnsignedLongLong("target_write_size", targetWriteSize); configuration->getUnsigned("max_write_interval", (unsigned long&) maxWriteInterval); if (maxWriteInterval == 0) { maxWriteInterval = 1; } string tmp; if (configuration->getString("must_succeed", tmp) && tmp == "no") { LOG_OPER("[%s] Setting mustSucceed to false.", categoryHandled.c_str()); mustSucceed = false; } store->configure(configuration, pStoreConf()); } void StoreQueue::openInline() { if (store->isOpen()) { store->close(); } if (!isModel) { store->open(); } } <|endoftext|>
<commit_before>#include <QtGui> #include <QtSql/QSqlDatabase> #include <QtSql/QSqlQuery> #include <QtSql/QSqlError> #include <QtSvg/QSvgGenerator> #include <QMessageBox> #include <QTcpSocket> #include "mainwindow.h" #include "qsqlconnectiondialog.h" #include "propertyeditorproxymodel.h" #include "realrepomodel.h" #include "editorview.h" MainWindow::MainWindow() : model(0) { ui.setupUi(this); ui.minimapView->setScene(ui.view->scene()); ui.minimapView->setRenderHint(QPainter::Antialiasing, true); connect(ui.diagramExplorer, SIGNAL( activated( const QModelIndex & ) ), ui.view->mvIface(), SLOT( setRootIndex( const QModelIndex & ) ) ); connect(ui.diagramExplorer, SIGNAL( clicked( const QModelIndex & ) ), ui.view->mvIface(), SLOT( setRootIndex( const QModelIndex & ) ) ); connect(ui.actionConnect, SIGNAL( triggered() ), this, SLOT( connectRepo() ) ); connect(ui.actionDisconnect, SIGNAL( triggered() ), this, SLOT( closeRepo() ) ); connect(ui.actionQuit, SIGNAL( triggered() ), this, SLOT( close() ) ); connect(ui.actionZoom_In, SIGNAL( triggered() ), ui.view, SLOT( zoomIn() ) ); connect(ui.actionZoom_Out, SIGNAL( triggered() ), ui.view, SLOT( zoomOut() ) ); connect(ui.actionAntialiasing, SIGNAL( toggled(bool) ), ui.view, SLOT( toggleAntialiasing(bool) ) ); connect(ui.actionOpenGL_Renderer, SIGNAL( toggled(bool) ), ui.view, SLOT( toggleOpenGL(bool) ) ); connect(ui.actionPrint, SIGNAL( triggered() ), this, SLOT( print() ) ); connect(ui.actionMakeSvg, SIGNAL( triggered() ), this, SLOT( makeSvg() ) ); connect(ui.actionBeginTransaction, SIGNAL( triggered() ), this, SLOT( beginTransaction() ) ); connect(ui.actionCommitTransaction, SIGNAL( triggered() ), this, SLOT( commitTransaction() ) ); connect(ui.actionRollbackTransaction, SIGNAL( triggered() ), this, SLOT( rollbackTransaction() ) ); connect(ui.actionDeleteFromDiagram, SIGNAL( triggered() ), this, SLOT( deleteFromDiagram() ) ); connect(ui.actionHelp, SIGNAL( triggered() ), this, SLOT( showHelp() ) ); connect(ui.actionAbout, SIGNAL( triggered() ), this, SLOT( showAbout() ) ); connect(ui.actionAboutQt, SIGNAL( triggered() ), qApp, SLOT( aboutQt() ) ); connect(ui.minimapZoomSlider, SIGNAL( valueChanged(int) ), this, SLOT( adjustMinimapZoom(int) ) ); adjustMinimapZoom(ui.minimapZoomSlider->value()); // XXX: kludge... don't know how to do it in designer ui.diagramDock->setWidget(ui.diagramExplorer); // ui.objectDock->setWidget(ui.objectExplorer); ui.paletteDock->setWidget(ui.paletteToolbox); ui.propertyEditor->horizontalHeader()->setStretchLastSection(true); ui.propertyEditor->horizontalHeader()->hide(); ui.propertyEditor->setModel(&propertyModel); ui.diagramExplorer->addAction(ui.actionDeleteFromDiagram); connect(ui.diagramExplorer, SIGNAL( clicked( const QModelIndex & ) ), &propertyModel, SLOT( setIndex( const QModelIndex & ) ) ); show(); //showMaximized(); resize(1024,800); connectRepo(); } MainWindow::~MainWindow() { } void MainWindow::adjustMinimapZoom(int zoom) { ui.minimapView->resetMatrix(); ui.minimapView->scale(0.01*zoom,0.01*zoom); } void MainWindow::connectRepo() { closeRepo(); model = new RealRepoModel(this); if( model->getState() != QAbstractSocket::ConnectedState ){ qDebug() << "repo model creation failed"; QMessageBox::critical(0, "achtung!", "cannot reach repo server at 127.0.0.1:6666.\n" "make sure that it is running and restart qreal"); //qApp->exit(); closeRepo(); return; } ui.diagramExplorer->setModel(model); ui.diagramExplorer->setRootIndex(model->index(1,0,QModelIndex())); ui.objectExplorer->setModel(model); // ui.objectExplorer->setRowHidden(1,QModelIndex(),true); propertyModel.setSourceModel(model); ui.view->mvIface()->setModel(model); } void MainWindow::closeRepo() { ui.diagramExplorer->setModel(0); ui.objectExplorer->setModel(0); propertyModel.setSourceModel(0); ui.view->mvIface()->setModel(0); ui.actionBeginTransaction->setEnabled(false); ui.actionCommitTransaction->setEnabled(false); ui.actionRollbackTransaction->setEnabled(false); if( model ) delete model; model = 0; } void MainWindow::beginTransaction() { if ( model ) { model->beginTransaction(); ui.actionBeginTransaction->setEnabled(false); ui.actionCommitTransaction->setEnabled(true); ui.actionRollbackTransaction->setEnabled(true); } } void MainWindow::commitTransaction() { if ( model ) { model->commitTransaction(); ui.actionBeginTransaction->setEnabled(true); ui.actionCommitTransaction->setEnabled(false); ui.actionRollbackTransaction->setEnabled(false); } } void MainWindow::rollbackTransaction() { if ( model ) { model->rollbackTransaction(); ui.actionBeginTransaction->setEnabled(true); ui.actionCommitTransaction->setEnabled(false); ui.actionRollbackTransaction->setEnabled(false); ui.diagramExplorer->setRootIndex(model->index(1,0,QModelIndex())); } } void MainWindow::deleteFromDiagram() { if ( model ) { QModelIndex idx = ui.diagramExplorer->currentIndex(); model->removeRow( idx.row(), idx.parent() ); } } void MainWindow::print() { QPrinter printer(QPrinter::HighResolution); QPrintDialog dialog(&printer, this); if (dialog.exec() == QDialog::Accepted) { QPainter painter(&printer); // QRect allScene = pieChart->mapFromScene(pieChart->scene()->sceneRect()).boundingRect(); ui.view->scene()->render(&painter); } } void MainWindow::makeSvg() { QSvgGenerator newSvg; QString fileName = QFileDialog::getSaveFileName(this); if (fileName.isEmpty()) return; newSvg.setFileName(fileName); newSvg.setSize(QSize(800,600)); QPainter painter(&newSvg); ui.view->scene()->render(&painter); } void MainWindow::showAbout() { QMessageBox::about(this, tr("About QReal"), tr("This is <b>QReal</b><br>" "Just another CASE tool")); } void MainWindow::showHelp() { } <commit_msg>Fix crash when deleting diagram.<commit_after>#include <QtGui> #include <QtSql/QSqlDatabase> #include <QtSql/QSqlQuery> #include <QtSql/QSqlError> #include <QtSvg/QSvgGenerator> #include <QMessageBox> #include <QTcpSocket> #include "mainwindow.h" #include "qsqlconnectiondialog.h" #include "propertyeditorproxymodel.h" #include "realrepomodel.h" #include "editorview.h" MainWindow::MainWindow() : model(0) { ui.setupUi(this); ui.minimapView->setScene(ui.view->scene()); ui.minimapView->setRenderHint(QPainter::Antialiasing, true); connect(ui.diagramExplorer, SIGNAL( activated( const QModelIndex & ) ), ui.view->mvIface(), SLOT( setRootIndex( const QModelIndex & ) ) ); connect(ui.diagramExplorer, SIGNAL( clicked( const QModelIndex & ) ), ui.view->mvIface(), SLOT( setRootIndex( const QModelIndex & ) ) ); connect(ui.actionConnect, SIGNAL( triggered() ), this, SLOT( connectRepo() ) ); connect(ui.actionDisconnect, SIGNAL( triggered() ), this, SLOT( closeRepo() ) ); connect(ui.actionQuit, SIGNAL( triggered() ), this, SLOT( close() ) ); connect(ui.actionZoom_In, SIGNAL( triggered() ), ui.view, SLOT( zoomIn() ) ); connect(ui.actionZoom_Out, SIGNAL( triggered() ), ui.view, SLOT( zoomOut() ) ); connect(ui.actionAntialiasing, SIGNAL( toggled(bool) ), ui.view, SLOT( toggleAntialiasing(bool) ) ); connect(ui.actionOpenGL_Renderer, SIGNAL( toggled(bool) ), ui.view, SLOT( toggleOpenGL(bool) ) ); connect(ui.actionPrint, SIGNAL( triggered() ), this, SLOT( print() ) ); connect(ui.actionMakeSvg, SIGNAL( triggered() ), this, SLOT( makeSvg() ) ); connect(ui.actionBeginTransaction, SIGNAL( triggered() ), this, SLOT( beginTransaction() ) ); connect(ui.actionCommitTransaction, SIGNAL( triggered() ), this, SLOT( commitTransaction() ) ); connect(ui.actionRollbackTransaction, SIGNAL( triggered() ), this, SLOT( rollbackTransaction() ) ); connect(ui.actionDeleteFromDiagram, SIGNAL( triggered() ), this, SLOT( deleteFromDiagram() ) ); connect(ui.actionHelp, SIGNAL( triggered() ), this, SLOT( showHelp() ) ); connect(ui.actionAbout, SIGNAL( triggered() ), this, SLOT( showAbout() ) ); connect(ui.actionAboutQt, SIGNAL( triggered() ), qApp, SLOT( aboutQt() ) ); connect(ui.minimapZoomSlider, SIGNAL( valueChanged(int) ), this, SLOT( adjustMinimapZoom(int) ) ); adjustMinimapZoom(ui.minimapZoomSlider->value()); // XXX: kludge... don't know how to do it in designer ui.diagramDock->setWidget(ui.diagramExplorer); // ui.objectDock->setWidget(ui.objectExplorer); ui.paletteDock->setWidget(ui.paletteToolbox); ui.propertyEditor->horizontalHeader()->setStretchLastSection(true); ui.propertyEditor->horizontalHeader()->hide(); ui.propertyEditor->setModel(&propertyModel); ui.diagramExplorer->addAction(ui.actionDeleteFromDiagram); connect(ui.diagramExplorer, SIGNAL( clicked( const QModelIndex & ) ), &propertyModel, SLOT( setIndex( const QModelIndex & ) ) ); show(); //showMaximized(); resize(1024,800); connectRepo(); } MainWindow::~MainWindow() { } void MainWindow::adjustMinimapZoom(int zoom) { ui.minimapView->resetMatrix(); ui.minimapView->scale(0.01*zoom,0.01*zoom); } void MainWindow::connectRepo() { closeRepo(); model = new RealRepoModel(this); if( model->getState() != QAbstractSocket::ConnectedState ){ qDebug() << "repo model creation failed"; QMessageBox::critical(0, "achtung!", "cannot reach repo server at 127.0.0.1:6666.\n" "make sure that it is running and restart qreal"); //qApp->exit(); closeRepo(); return; } ui.diagramExplorer->setModel(model); ui.diagramExplorer->setRootIndex(model->index(1,0,QModelIndex())); ui.objectExplorer->setModel(model); // ui.objectExplorer->setRowHidden(1,QModelIndex(),true); propertyModel.setSourceModel(model); ui.view->mvIface()->setModel(model); } void MainWindow::closeRepo() { ui.diagramExplorer->setModel(0); ui.objectExplorer->setModel(0); propertyModel.setSourceModel(0); ui.view->mvIface()->setModel(0); ui.actionBeginTransaction->setEnabled(false); ui.actionCommitTransaction->setEnabled(false); ui.actionRollbackTransaction->setEnabled(false); if( model ) delete model; model = 0; } void MainWindow::beginTransaction() { if ( model ) { model->beginTransaction(); ui.actionBeginTransaction->setEnabled(false); ui.actionCommitTransaction->setEnabled(true); ui.actionRollbackTransaction->setEnabled(true); } } void MainWindow::commitTransaction() { if ( model ) { model->commitTransaction(); ui.actionBeginTransaction->setEnabled(true); ui.actionCommitTransaction->setEnabled(false); ui.actionRollbackTransaction->setEnabled(false); } } void MainWindow::rollbackTransaction() { if ( model ) { model->rollbackTransaction(); ui.actionBeginTransaction->setEnabled(true); ui.actionCommitTransaction->setEnabled(false); ui.actionRollbackTransaction->setEnabled(false); ui.diagramExplorer->setRootIndex(model->index(1,0,QModelIndex())); } } void MainWindow::deleteFromDiagram() { if ( model ) { QModelIndex idx = ui.diagramExplorer->currentIndex(); model->removeRow( idx.row(), idx.parent() ); /* Brutal, but right now we have no choice */ connectRepo(); } } void MainWindow::print() { QPrinter printer(QPrinter::HighResolution); QPrintDialog dialog(&printer, this); if (dialog.exec() == QDialog::Accepted) { QPainter painter(&printer); // QRect allScene = pieChart->mapFromScene(pieChart->scene()->sceneRect()).boundingRect(); ui.view->scene()->render(&painter); } } void MainWindow::makeSvg() { QSvgGenerator newSvg; QString fileName = QFileDialog::getSaveFileName(this); if (fileName.isEmpty()) return; newSvg.setFileName(fileName); newSvg.setSize(QSize(800,600)); QPainter painter(&newSvg); ui.view->scene()->render(&painter); } void MainWindow::showAbout() { QMessageBox::about(this, tr("About QReal"), tr("This is <b>QReal</b><br>" "Just another CASE tool")); } void MainWindow::showHelp() { } <|endoftext|>
<commit_before>//--------------------------------------------------------- // Copyright 2017 Ontario Institute for Cancer Research // Written by Jared Simpson (jared.simpson@oicr.on.ca) // // nanopolish index - build an index from FASTA/FASTQ file // and the associated signal-level data // //--------------------------------------------------------- // // // Getopt // #define SUBPROGRAM "index" #include <iostream> #include <fstream> #include <sstream> #include <getopt.h> #include <fast5.hpp> #include "nanopolish_index.h" #include "nanopolish_common.h" #include "nanopolish_read_db.h" #include "fs_support.hpp" #include "logger.hpp" #include "profiler.h" #include "nanopolish_fast5_io.h" static const char *INDEX_VERSION_MESSAGE = SUBPROGRAM " Version " PACKAGE_VERSION "\n" "Written by Jared Simpson.\n" "\n" "Copyright 2017 Ontario Institute for Cancer Research\n"; static const char *INDEX_USAGE_MESSAGE = "Usage: " PACKAGE_NAME " " SUBPROGRAM " [OPTIONS] -d nanopore_raw_file_directory reads.fastq\n" "Build an index mapping from basecalled reads to the signals measured by the sequencer\n" "\n" " --help display this help and exit\n" " --version display version\n" " -v, --verbose display verbose output\n" " -d, --directory path to the directory containing the raw ONT signal files. This option can be given multiple times.\n" " -s, --sequencing-summary the sequencing summary file from albacore, providing this option will make indexing much faster\n" " -f, --summary-fofn file containing the paths to the sequencing summary files (one per line)\n" "\nReport bugs to " PACKAGE_BUGREPORT "\n\n"; namespace opt { static unsigned int verbose = 0; static std::vector<std::string> raw_file_directories; static std::string reads_file; static std::vector<std::string> sequencing_summary_files; static std::string sequencing_summary_fofn; } static std::ostream* os_p; // void index_file_from_map(ReadDB& read_db, const std::string& fn, const std::map<std::string, std::string>& fast5_to_read_name_map) { PROFILE_FUNC("index_file_from_map") // Check if this fast5 file is in the map size_t last_dir_pos = fn.find_last_of("/"); std::string fast5_basename = last_dir_pos == std::string::npos ? fn : fn.substr(last_dir_pos + 1); const auto& iter = fast5_to_read_name_map.find(fast5_basename); if(iter != fast5_to_read_name_map.end()) { if(read_db.has_read(iter->second)) { read_db.add_signal_path(iter->second.c_str(), fn); } } else { if(opt::verbose > 0) { fprintf(stderr, "Could not find read %s in sequencing summary file\n", fn.c_str()); } } } // void index_file_from_fast5(ReadDB& read_db, const std::string& fn, const std::map<std::string, std::string>& fast5_to_read_name_map) { PROFILE_FUNC("index_file_from_fast5") fast5_file f5_file = fast5_open(fn); if(!fast5_is_open(f5_file)) { fprintf(stderr, "could not open fast5 file: %s\n", fn.c_str()); } if(f5_file.is_multi_fast5) { std::vector<std::string> read_groups = fast5_get_multi_read_groups(f5_file); std::string prefix = "read_"; for(size_t group_idx = 0; group_idx < read_groups.size(); ++group_idx) { std::string group_name = read_groups[group_idx]; if(group_name.find(prefix) == 0) { std::string read_id = group_name.substr(prefix.size()); read_db.add_signal_path(read_id, fn); } } } else { std::string read_id = fast5_get_read_id_single_fast5(f5_file); if(read_id != "") { read_db.add_signal_path(read_id, fn); } } fast5_close(f5_file); } // void index_path(ReadDB& read_db, const std::string& path, const std::map<std::string, std::string>& fast5_to_read_name_map) { fprintf(stderr, "[readdb] indexing %s\n", path.c_str()); if (is_directory(path)) { auto dir_list = list_directory(path); for (const auto& fn : dir_list) { if(fn == "." or fn == "..") { continue; } std::string full_fn = path + "/" + fn; if(is_directory(full_fn)) { // recurse index_path(read_db, full_fn, fast5_to_read_name_map); } else if (full_fn.find(".fast5") != -1) { if(!fast5_to_read_name_map.empty()) { index_file_from_map(read_db, full_fn, fast5_to_read_name_map); } else { index_file_from_fast5(read_db, full_fn, fast5_to_read_name_map); } } } } } // read sequencing summary files from the fofn and add them to the list void process_summary_fofn() { if(opt::sequencing_summary_fofn.empty()) { return; } // open std::ifstream in_file(opt::sequencing_summary_fofn.c_str()); if(in_file.bad()) { fprintf(stderr, "error: could not file %s\n", opt::sequencing_summary_fofn.c_str()); exit(EXIT_FAILURE); } // read std::string filename; while(getline(in_file, filename)) { opt::sequencing_summary_files.push_back(filename); } } // void exit_bad_header(const std::string& str, const std::string& filename) { fprintf(stderr, "Could not find %s column in the header of %s\n", str.c_str(), filename.c_str()); exit(EXIT_FAILURE); } // void parse_sequencing_summary(const std::string& filename, std::map<std::string, std::string>& out_map) { // open std::ifstream in_file(filename.c_str()); if(in_file.bad()) { fprintf(stderr, "error: could not file %s\n", filename.c_str()); exit(EXIT_FAILURE); } // read header to get the column index of the read and file name std::string header; getline(in_file, header); std::vector<std::string> fields = split(header, '\t'); const std::string READ_NAME_STR = "read_id"; const std::string FILENAME_STR = "filename"; size_t filename_idx = -1; size_t read_name_idx = -1; for(size_t i = 0; i < fields.size(); ++i) { if(fields[i] == READ_NAME_STR) { read_name_idx = i; } if(fields[i] == FILENAME_STR) { filename_idx = i; } } if(filename_idx == -1) { exit_bad_header(FILENAME_STR, filename); } if(read_name_idx == -1) { exit_bad_header(READ_NAME_STR, filename); } // read records and add to map std::string line; while(getline(in_file, line)) { fields = split(line, '\t'); std::string fast5_filename = fields[filename_idx]; std::string read_name = fields[read_name_idx]; out_map[fast5_filename] = read_name; } } static const char* shortopts = "vd:f:s:"; enum { OPT_HELP = 1, OPT_VERSION, OPT_LOG_LEVEL, }; static const struct option longopts[] = { { "help", no_argument, NULL, OPT_HELP }, { "version", no_argument, NULL, OPT_VERSION }, { "log-level", required_argument, NULL, OPT_LOG_LEVEL }, { "verbose", no_argument, NULL, 'v' }, { "directory", required_argument, NULL, 'd' }, { "sequencing-summary-file", required_argument, NULL, 's' }, { "summary-fofn", required_argument, NULL, 'f' }, { NULL, 0, NULL, 0 } }; void parse_index_options(int argc, char** argv) { bool die = false; std::vector< std::string> log_level; for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) { std::istringstream arg(optarg != NULL ? optarg : ""); switch (c) { case OPT_HELP: std::cout << INDEX_USAGE_MESSAGE; exit(EXIT_SUCCESS); case OPT_VERSION: std::cout << INDEX_VERSION_MESSAGE; exit(EXIT_SUCCESS); case OPT_LOG_LEVEL: log_level.push_back(arg.str()); break; case 'v': opt::verbose++; break; case 's': opt::sequencing_summary_files.push_back(arg.str()); break; case 'd': opt::raw_file_directories.push_back(arg.str()); break; case 'f': arg >> opt::sequencing_summary_fofn; break; } } // set log levels auto default_level = (int)logger::warning + opt::verbose; logger::Logger::set_default_level(default_level); logger::Logger::set_levels_from_options(log_level, &std::clog); if (argc - optind < 1) { std::cerr << SUBPROGRAM ": not enough arguments\n"; die = true; } if (argc - optind > 1) { std::cerr << SUBPROGRAM ": too many arguments\n"; die = true; } if (die) { std::cout << "\n" << INDEX_USAGE_MESSAGE; exit(EXIT_FAILURE); } opt::reads_file = argv[optind++]; } int index_main(int argc, char** argv) { parse_index_options(argc, argv); // Read a map from fast5 files to read name from the sequencing summary files (if any) process_summary_fofn(); std::map<std::string, std::string> fast5_to_read_name_map; for(const auto& ss_filename : opt::sequencing_summary_files) { if(opt::verbose > 2) { fprintf(stderr, "summary: %s\n", ss_filename.c_str()); } parse_sequencing_summary(ss_filename, fast5_to_read_name_map); } // import read names, and possibly fast5 paths, from the fasta/fastq file ReadDB read_db; read_db.build(opt::reads_file); bool all_reads_have_paths = read_db.check_signal_paths(); // if the input fastq did not contain a complete set of paths // use the fofn/directory provided to augment the index if(!all_reads_have_paths) { for(const auto& dir_name : opt::raw_file_directories) { index_path(read_db, dir_name, fast5_to_read_name_map); } } size_t num_with_path = read_db.get_num_reads_with_path(); if(num_with_path == 0) { fprintf(stderr, "Error: no fast5 files found\n"); exit(EXIT_FAILURE); } else { read_db.print_stats(); read_db.save(); } return 0; } <commit_msg>fix check for non-readable sequencing summary file<commit_after>//--------------------------------------------------------- // Copyright 2017 Ontario Institute for Cancer Research // Written by Jared Simpson (jared.simpson@oicr.on.ca) // // nanopolish index - build an index from FASTA/FASTQ file // and the associated signal-level data // //--------------------------------------------------------- // // // Getopt // #define SUBPROGRAM "index" #include <iostream> #include <fstream> #include <sstream> #include <getopt.h> #include <fast5.hpp> #include "nanopolish_index.h" #include "nanopolish_common.h" #include "nanopolish_read_db.h" #include "fs_support.hpp" #include "logger.hpp" #include "profiler.h" #include "nanopolish_fast5_io.h" static const char *INDEX_VERSION_MESSAGE = SUBPROGRAM " Version " PACKAGE_VERSION "\n" "Written by Jared Simpson.\n" "\n" "Copyright 2017 Ontario Institute for Cancer Research\n"; static const char *INDEX_USAGE_MESSAGE = "Usage: " PACKAGE_NAME " " SUBPROGRAM " [OPTIONS] -d nanopore_raw_file_directory reads.fastq\n" "Build an index mapping from basecalled reads to the signals measured by the sequencer\n" "\n" " --help display this help and exit\n" " --version display version\n" " -v, --verbose display verbose output\n" " -d, --directory path to the directory containing the raw ONT signal files. This option can be given multiple times.\n" " -s, --sequencing-summary the sequencing summary file from albacore, providing this option will make indexing much faster\n" " -f, --summary-fofn file containing the paths to the sequencing summary files (one per line)\n" "\nReport bugs to " PACKAGE_BUGREPORT "\n\n"; namespace opt { static unsigned int verbose = 0; static std::vector<std::string> raw_file_directories; static std::string reads_file; static std::vector<std::string> sequencing_summary_files; static std::string sequencing_summary_fofn; } static std::ostream* os_p; // void index_file_from_map(ReadDB& read_db, const std::string& fn, const std::map<std::string, std::string>& fast5_to_read_name_map) { PROFILE_FUNC("index_file_from_map") // Check if this fast5 file is in the map size_t last_dir_pos = fn.find_last_of("/"); std::string fast5_basename = last_dir_pos == std::string::npos ? fn : fn.substr(last_dir_pos + 1); const auto& iter = fast5_to_read_name_map.find(fast5_basename); if(iter != fast5_to_read_name_map.end()) { if(read_db.has_read(iter->second)) { read_db.add_signal_path(iter->second.c_str(), fn); } } else { if(opt::verbose > 0) { fprintf(stderr, "Could not find read %s in sequencing summary file\n", fn.c_str()); } } } // void index_file_from_fast5(ReadDB& read_db, const std::string& fn, const std::map<std::string, std::string>& fast5_to_read_name_map) { PROFILE_FUNC("index_file_from_fast5") fast5_file f5_file = fast5_open(fn); if(!fast5_is_open(f5_file)) { fprintf(stderr, "could not open fast5 file: %s\n", fn.c_str()); } if(f5_file.is_multi_fast5) { std::vector<std::string> read_groups = fast5_get_multi_read_groups(f5_file); std::string prefix = "read_"; for(size_t group_idx = 0; group_idx < read_groups.size(); ++group_idx) { std::string group_name = read_groups[group_idx]; if(group_name.find(prefix) == 0) { std::string read_id = group_name.substr(prefix.size()); read_db.add_signal_path(read_id, fn); } } } else { std::string read_id = fast5_get_read_id_single_fast5(f5_file); if(read_id != "") { read_db.add_signal_path(read_id, fn); } } fast5_close(f5_file); } // void index_path(ReadDB& read_db, const std::string& path, const std::map<std::string, std::string>& fast5_to_read_name_map) { fprintf(stderr, "[readdb] indexing %s\n", path.c_str()); if (is_directory(path)) { auto dir_list = list_directory(path); for (const auto& fn : dir_list) { if(fn == "." or fn == "..") { continue; } std::string full_fn = path + "/" + fn; if(is_directory(full_fn)) { // recurse index_path(read_db, full_fn, fast5_to_read_name_map); } else if (full_fn.find(".fast5") != -1) { if(!fast5_to_read_name_map.empty()) { index_file_from_map(read_db, full_fn, fast5_to_read_name_map); } else { index_file_from_fast5(read_db, full_fn, fast5_to_read_name_map); } } } } } // read sequencing summary files from the fofn and add them to the list void process_summary_fofn() { if(opt::sequencing_summary_fofn.empty()) { return; } // open std::ifstream in_file(opt::sequencing_summary_fofn.c_str()); if(in_file.bad()) { fprintf(stderr, "error: could not file %s\n", opt::sequencing_summary_fofn.c_str()); exit(EXIT_FAILURE); } // read std::string filename; while(getline(in_file, filename)) { opt::sequencing_summary_files.push_back(filename); } } // void exit_bad_header(const std::string& str, const std::string& filename) { fprintf(stderr, "Could not find %s column in the header of %s\n", str.c_str(), filename.c_str()); exit(EXIT_FAILURE); } // void parse_sequencing_summary(const std::string& filename, std::map<std::string, std::string>& out_map) { // open std::ifstream in_file(filename.c_str()); if(!in_file.good()) { fprintf(stderr, "error: could not read file %s\n", filename.c_str()); exit(EXIT_FAILURE); } // read header to get the column index of the read and file name std::string header; getline(in_file, header); std::vector<std::string> fields = split(header, '\t'); const std::string READ_NAME_STR = "read_id"; const std::string FILENAME_STR = "filename"; size_t filename_idx = -1; size_t read_name_idx = -1; for(size_t i = 0; i < fields.size(); ++i) { if(fields[i] == READ_NAME_STR) { read_name_idx = i; } if(fields[i] == FILENAME_STR) { filename_idx = i; } } if(filename_idx == -1) { exit_bad_header(FILENAME_STR, filename); } if(read_name_idx == -1) { exit_bad_header(READ_NAME_STR, filename); } // read records and add to map std::string line; while(getline(in_file, line)) { fields = split(line, '\t'); std::string fast5_filename = fields[filename_idx]; std::string read_name = fields[read_name_idx]; out_map[fast5_filename] = read_name; } } static const char* shortopts = "vd:f:s:"; enum { OPT_HELP = 1, OPT_VERSION, OPT_LOG_LEVEL, }; static const struct option longopts[] = { { "help", no_argument, NULL, OPT_HELP }, { "version", no_argument, NULL, OPT_VERSION }, { "log-level", required_argument, NULL, OPT_LOG_LEVEL }, { "verbose", no_argument, NULL, 'v' }, { "directory", required_argument, NULL, 'd' }, { "sequencing-summary-file", required_argument, NULL, 's' }, { "summary-fofn", required_argument, NULL, 'f' }, { NULL, 0, NULL, 0 } }; void parse_index_options(int argc, char** argv) { bool die = false; std::vector< std::string> log_level; for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) { std::istringstream arg(optarg != NULL ? optarg : ""); switch (c) { case OPT_HELP: std::cout << INDEX_USAGE_MESSAGE; exit(EXIT_SUCCESS); case OPT_VERSION: std::cout << INDEX_VERSION_MESSAGE; exit(EXIT_SUCCESS); case OPT_LOG_LEVEL: log_level.push_back(arg.str()); break; case 'v': opt::verbose++; break; case 's': opt::sequencing_summary_files.push_back(arg.str()); break; case 'd': opt::raw_file_directories.push_back(arg.str()); break; case 'f': arg >> opt::sequencing_summary_fofn; break; } } // set log levels auto default_level = (int)logger::warning + opt::verbose; logger::Logger::set_default_level(default_level); logger::Logger::set_levels_from_options(log_level, &std::clog); if (argc - optind < 1) { std::cerr << SUBPROGRAM ": not enough arguments\n"; die = true; } if (argc - optind > 1) { std::cerr << SUBPROGRAM ": too many arguments\n"; die = true; } if (die) { std::cout << "\n" << INDEX_USAGE_MESSAGE; exit(EXIT_FAILURE); } opt::reads_file = argv[optind++]; } int index_main(int argc, char** argv) { parse_index_options(argc, argv); // Read a map from fast5 files to read name from the sequencing summary files (if any) process_summary_fofn(); std::map<std::string, std::string> fast5_to_read_name_map; for(const auto& ss_filename : opt::sequencing_summary_files) { if(opt::verbose > 2) { fprintf(stderr, "summary: %s\n", ss_filename.c_str()); } parse_sequencing_summary(ss_filename, fast5_to_read_name_map); } // import read names, and possibly fast5 paths, from the fasta/fastq file ReadDB read_db; read_db.build(opt::reads_file); bool all_reads_have_paths = read_db.check_signal_paths(); // if the input fastq did not contain a complete set of paths // use the fofn/directory provided to augment the index if(!all_reads_have_paths) { for(const auto& dir_name : opt::raw_file_directories) { index_path(read_db, dir_name, fast5_to_read_name_map); } } size_t num_with_path = read_db.get_num_reads_with_path(); if(num_with_path == 0) { fprintf(stderr, "Error: no fast5 files found\n"); exit(EXIT_FAILURE); } else { read_db.print_stats(); read_db.save(); } return 0; } <|endoftext|>